< prev index next >

src/jdk.incubator.jpackage/share/classes/jdk/incubator/jpackage/internal/Arguments.java

Print this page




   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.jpackage.internal;
  26 
  27 import java.io.File;
  28 import java.io.FileInputStream;
  29 import java.io.IOException;
  30 import java.nio.file.Files;
  31 import java.nio.file.Path;

  32 import java.text.MessageFormat;
  33 import java.util.ArrayList;
  34 import java.util.Arrays;
  35 import java.util.Collection;
  36 import java.util.EnumSet;
  37 import java.util.HashMap;
  38 import java.util.HashSet;
  39 import java.util.List;
  40 import java.util.Map;
  41 import java.util.Set;
  42 import java.util.Properties;
  43 import java.util.ResourceBundle;
  44 import java.util.jar.Attributes;
  45 import java.util.jar.JarFile;
  46 import java.util.jar.Manifest;
  47 import java.util.stream.Stream;
  48 import java.util.regex.Matcher;
  49 import java.util.regex.Pattern;
  50 
  51 /**
  52  * Arguments
  53  *
  54  * This class encapsulates and processes the command line arguments,
  55  * in effect, implementing all the work of jpackage tool.
  56  *
  57  * The primary entry point, processArguments():
  58  * Processes and validates command line arguments, constructing DeployParams.
  59  * Validates the DeployParams, and generate the BundleParams.
  60  * Generates List of Bundlers from BundleParams valid for this platform.
  61  * Executes each Bundler in the list.
  62  */
  63 public class Arguments {
  64     private static final ResourceBundle I18N = ResourceBundle.getBundle(
  65             "jdk.jpackage.internal.resources.MainResources");
  66 
  67     private static final String APPIMAGE_MODE = "create-app-image";
  68     private static final String INSTALLER_MODE = "create-installer";
  69 
  70     private static final String FA_EXTENSIONS = "extension";
  71     private static final String FA_CONTENT_TYPE = "mime-type";
  72     private static final String FA_DESCRIPTION = "description";
  73     private static final String FA_ICON = "icon";
  74 
  75     public static final BundlerParamInfo<Boolean> CREATE_APP_IMAGE =
  76             new StandardBundlerParam<>(
  77                     APPIMAGE_MODE,
  78                     Boolean.class,
  79                     p -> Boolean.FALSE,
  80                     (s, p) -> (s == null || "null".equalsIgnoreCase(s)) ?
  81                             true : Boolean.valueOf(s));
  82 
  83     public static final BundlerParamInfo<Boolean> CREATE_INSTALLER =
  84             new StandardBundlerParam<>(
  85                     INSTALLER_MODE,
  86                     Boolean.class,
  87                     p -> Boolean.FALSE,
  88                     (s, p) -> (s == null || "null".equalsIgnoreCase(s)) ?
  89                             true : Boolean.valueOf(s));
  90 
  91     // regexp for parsing args (for example, for additional launchers)
  92     private static Pattern pattern = Pattern.compile(
  93           "(?:(?:([\"'])(?:\\\\\\1|.)*?(?:\\1|$))|(?:\\\\[\"'\\s]|[^\\s]))++");
  94 
  95     private DeployParams deployParams = null;
  96     private BundlerType bundleType = null;
  97 
  98     private int pos = 0;
  99     private List<String> argList = null;
 100 
 101     private List<CLIOptions> allOptions = null;
 102 
 103     private String input = null;
 104     private String output = null;
 105 
 106     private boolean hasMainJar = false;
 107     private boolean hasMainClass = false;
 108     private boolean hasMainModule = false;
 109     private boolean hasTargetFormat = false;
 110     private boolean hasAppImage = false;
 111     public boolean userProvidedBuildRoot = false;
 112 
 113     private String buildRoot = null;
 114     private String mainJarPath = null;
 115 
 116     private static boolean runtimeInstaller = false;
 117 
 118     private List<jdk.jpackage.internal.Bundler> platformBundlers = null;
 119 
 120     private List<AddLauncherArguments> addLaunchers = null;
 121 
 122     private static Map<String, CLIOptions> argIds = new HashMap<>();
 123     private static Map<String, CLIOptions> argShortIds = new HashMap<>();
 124 
 125     static {
 126         // init maps for parsing arguments
 127         (EnumSet.allOf(CLIOptions.class)).forEach(option -> {
 128             argIds.put(option.getIdWithPrefix(), option);
 129             if (option.getShortIdWithPrefix() != null) {
 130                 argShortIds.put(option.getShortIdWithPrefix(), option);
 131             }
 132         });
 133     }
 134 
 135     public Arguments(String[] args) throws PackagerException {
 136         argList = new ArrayList<String>(args.length);
 137         for (String arg : args) {
 138             argList.add(arg);
 139         }
 140         Log.debug ("\njpackage argument list: \n" + argList + "\n");
 141         pos = 0;
 142 
 143         deployParams = new DeployParams();
 144         bundleType = BundlerType.NONE;
 145 
 146         allOptions = new ArrayList<>();
 147 
 148         addLaunchers = new ArrayList<>();



 149     }
 150 
 151     // CLIOptions is public for DeployParamsTest
 152     public enum CLIOptions {
 153         CREATE_APP_IMAGE(APPIMAGE_MODE, OptionCategories.MODE, () -> {
 154             context().bundleType = BundlerType.IMAGE;
 155             context().deployParams.setTargetFormat("image");
 156             setOptionValue(APPIMAGE_MODE, true);
 157         }),
 158 
 159         CREATE_INSTALLER(INSTALLER_MODE, OptionCategories.MODE, () -> {
 160             setOptionValue(INSTALLER_MODE, true);
 161             context().bundleType = BundlerType.INSTALLER;
 162             String format = "installer";
 163             context().deployParams.setTargetFormat(format);
 164         }),
 165 
 166         INSTALLER_TYPE("installer-type", OptionCategories.PROPERTY, () -> {
 167             String type = popArg();
 168             if (BundlerType.INSTALLER.equals(context().bundleType)) {
 169                 context().deployParams.setTargetFormat(type);
 170                 context().hasTargetFormat = true;
 171             }
 172             setOptionValue("installer-type", type);
 173         }),
 174 
 175         INPUT ("input", "i", OptionCategories.PROPERTY, () -> {
 176             context().input = popArg();
 177             setOptionValue("input", context().input);
 178         }),
 179 
 180         OUTPUT ("output", "o", OptionCategories.PROPERTY, () -> {
 181             context().output = popArg();
 182             context().deployParams.setOutput(new File(context().output));
 183         }),
 184 
 185         DESCRIPTION ("description", "d", OptionCategories.PROPERTY),
 186 
 187         VENDOR ("vendor", OptionCategories.PROPERTY),
 188 
 189         APPCLASS ("main-class", OptionCategories.PROPERTY, () -> {
 190             context().hasMainClass = true;
 191             setOptionValue("main-class", popArg());
 192         }),
 193 
 194         NAME ("name", "n", OptionCategories.PROPERTY),
 195 
 196         IDENTIFIER ("identifier", OptionCategories.PROPERTY),
 197 
 198         VERBOSE ("verbose", OptionCategories.PROPERTY, () -> {
 199             setOptionValue("verbose", true);
 200             Log.setVerbose(true);
 201         }),
 202 
 203         RESOURCE_DIR("resource-dir",
 204                 OptionCategories.PROPERTY, () -> {
 205             String resourceDir = popArg();
 206             setOptionValue("resource-dir", resourceDir);
 207         }),
 208 
 209         ARGUMENTS ("arguments", OptionCategories.PROPERTY, () -> {
 210             List<String> arguments = getArgumentList(popArg());
 211             setOptionValue("arguments", arguments);
 212         }),
 213 
 214         ICON ("icon", OptionCategories.PROPERTY),
 215 
 216         COPYRIGHT ("copyright", OptionCategories.PROPERTY),
 217 
 218         LICENSE_FILE ("license-file", OptionCategories.PROPERTY),
 219 
 220         VERSION ("app-version", OptionCategories.PROPERTY),
 221 


 222         JAVA_OPTIONS ("java-options", OptionCategories.PROPERTY, () -> {
 223             List<String> args = getArgumentList(popArg());
 224             args.forEach(a -> setOptionValue("java-options", a));
 225         }),
 226 
 227         FILE_ASSOCIATIONS ("file-associations",
 228                 OptionCategories.PROPERTY, () -> {
 229             Map<String, ? super Object> args = new HashMap<>();
 230 
 231             // load .properties file
 232             Map<String, String> initialMap = getPropertiesFromFile(popArg());
 233 
 234             String ext = initialMap.get(FA_EXTENSIONS);
 235             if (ext != null) {
 236                 args.put(StandardBundlerParam.FA_EXTENSIONS.getID(), ext);
 237             }
 238 
 239             String type = initialMap.get(FA_CONTENT_TYPE);
 240             if (type != null) {
 241                 args.put(StandardBundlerParam.FA_CONTENT_TYPE.getID(), type);


 258 
 259             // check that we really add _another_ value to the list
 260             setOptionValue("file-associations", associationList);
 261 
 262         }),
 263 
 264         ADD_LAUNCHER ("add-launcher",
 265                     OptionCategories.PROPERTY, () -> {
 266             String spec = popArg();
 267             String name = null;
 268             String filename = spec;
 269             if (spec.contains("=")) {
 270                 String[] values = spec.split("=", 2);
 271                 name = values[0];
 272                 filename = values[1];
 273             }
 274             context().addLaunchers.add(
 275                 new AddLauncherArguments(name, filename));
 276         }),
 277 
 278         TEMP_ROOT ("temp-root", OptionCategories.PROPERTY, () -> {
 279             context().buildRoot = popArg();
 280             context().userProvidedBuildRoot = true;
 281             setOptionValue("temp-root", context().buildRoot);
 282         }),
 283 
 284         INSTALL_DIR ("install-dir", OptionCategories.PROPERTY),
 285 
 286         PREDEFINED_APP_IMAGE ("app-image", OptionCategories.PROPERTY, ()-> {
 287             setOptionValue("app-image", popArg());
 288             context().hasAppImage = true;
 289         }),
 290 
 291         PREDEFINED_RUNTIME_IMAGE ("runtime-image", OptionCategories.PROPERTY),
 292 
 293         MAIN_JAR ("main-jar",  OptionCategories.PROPERTY, () -> {
 294             context().mainJarPath = popArg();
 295             context().hasMainJar = true;
 296             setOptionValue("main-jar", context().mainJarPath);
 297         }),
 298 
 299         MODULE ("module", "m", OptionCategories.MODULAR, () -> {
 300             context().hasMainModule = true;
 301             setOptionValue("module", popArg());
 302         }),
 303 
 304         ADD_MODULES ("add-modules", OptionCategories.MODULAR),
 305 
 306         MODULE_PATH ("module-path", "p", OptionCategories.MODULAR),
 307 




 308         MAC_SIGN ("mac-sign", "s", OptionCategories.PLATFORM_MAC, () -> {
 309             setOptionValue("mac-sign", true);
 310         }),
 311 
 312         MAC_BUNDLE_NAME ("mac-bundle-name", OptionCategories.PLATFORM_MAC),
 313 
 314         MAC_BUNDLE_IDENTIFIER("mac-bundle-identifier",
 315                     OptionCategories.PLATFORM_MAC),
 316 
 317         MAC_APP_STORE_CATEGORY ("mac-app-store-category",
 318                     OptionCategories.PLATFORM_MAC),
 319 
 320         MAC_BUNDLE_SIGNING_PREFIX ("mac-bundle-signing-prefix",
 321                     OptionCategories.PLATFORM_MAC),
 322 
 323         MAC_SIGNING_KEY_NAME ("mac-signing-key-user-name",
 324                     OptionCategories.PLATFORM_MAC),
 325 
 326         MAC_SIGNING_KEYCHAIN ("mac-signing-keychain",
 327                     OptionCategories.PLATFORM_MAC),
 328 
 329         MAC_APP_STORE_ENTITLEMENTS ("mac-app-store-entitlements",
 330                     OptionCategories.PLATFORM_MAC),
 331 
 332         WIN_MENU_HINT ("win-menu", OptionCategories.PLATFORM_WIN, () -> {
 333             setOptionValue("win-menu", true);
 334         }),
 335 
 336         WIN_MENU_GROUP ("win-menu-group", OptionCategories.PLATFORM_WIN),
 337 
 338         WIN_SHORTCUT_HINT ("win-shortcut",
 339                 OptionCategories.PLATFORM_WIN, () -> {
 340             setOptionValue("win-shortcut", true);
 341         }),
 342 
 343         WIN_PER_USER_INSTALLATION ("win-per-user-install",
 344                 OptionCategories.PLATFORM_WIN, () -> {
 345             setOptionValue("win-per-user-install", false);
 346         }),
 347 
 348         WIN_DIR_CHOOSER ("win-dir-chooser",
 349                 OptionCategories.PLATFORM_WIN, () -> {
 350             setOptionValue("win-dir-chooser", true);
 351         }),
 352 
 353         WIN_REGISTRY_NAME ("win-registry-name", OptionCategories.PLATFORM_WIN),
 354 
 355         WIN_UPGRADE_UUID ("win-upgrade-uuid",
 356                 OptionCategories.PLATFORM_WIN),
 357 
 358         WIN_CONSOLE_HINT ("win-console", OptionCategories.PLATFORM_WIN, () -> {
 359             setOptionValue("win-console", true);
 360         }),
 361 
 362         LINUX_BUNDLE_NAME ("linux-bundle-name",
 363                 OptionCategories.PLATFORM_LINUX),
 364 
 365         LINUX_DEB_MAINTAINER ("linux-deb-maintainer",
 366                 OptionCategories.PLATFORM_LINUX),
 367 



 368         LINUX_RPM_LICENSE_TYPE ("linux-rpm-license-type",
 369                 OptionCategories.PLATFORM_LINUX),
 370 
 371         LINUX_PACKAGE_DEPENDENCIES ("linux-package-deps",
 372                 OptionCategories.PLATFORM_LINUX),
 373 





 374         LINUX_MENU_GROUP ("linux-menu-group", OptionCategories.PLATFORM_LINUX);
 375 
 376         private final String id;
 377         private final String shortId;
 378         private final OptionCategories category;
 379         private final ArgAction action;
 380         private static Arguments argContext;
 381 
 382         private CLIOptions(String id, OptionCategories category) {
 383             this(id, null, category, null);
 384         }
 385 
 386         private CLIOptions(String id, String shortId,
 387                            OptionCategories category) {
 388             this(id, shortId, category, null);
 389         }
 390 
 391         private CLIOptions(String id,
 392                 OptionCategories category, ArgAction action) {
 393             this(id, null, category, action);


 401             this.category = category;
 402         }
 403 
 404         static void setContext(Arguments context) {
 405             argContext = context;
 406         }
 407 
 408         public static Arguments context() {
 409             if (argContext != null) {
 410                 return argContext;
 411             } else {
 412                 throw new RuntimeException("Argument context is not set.");
 413             }
 414         }
 415 
 416         public String getId() {
 417             return this.id;
 418         }
 419 
 420         String getIdWithPrefix() {
 421             String prefix = isMode() ? "" : "--";
 422             return prefix + this.id;
 423         }
 424 
 425         String getShortIdWithPrefix() {
 426             return this.shortId == null ? null : "-" + this.shortId;
 427         }
 428 
 429         void execute() {
 430             if (action != null) {
 431                 action.execute();
 432             } else {
 433                 defaultAction();
 434             }
 435         }
 436 
 437         boolean isMode() {
 438             return category == OptionCategories.MODE;
 439         }
 440 
 441         OptionCategories getCategory() {
 442             return category;
 443         }
 444 
 445         private void defaultAction() {
 446             context().deployParams.addBundleArgument(id, popArg());
 447         }
 448 
 449         private static void setOptionValue(String option, Object value) {
 450             context().deployParams.addBundleArgument(option, value);
 451         }
 452 
 453         private static String popArg() {
 454             nextArg();
 455             return (context().pos >= context().argList.size()) ?
 456                             "" : context().argList.get(context().pos);
 457         }
 458 
 459         private static String getArg() {
 460             return (context().pos >= context().argList.size()) ?
 461                         "" : context().argList.get(context().pos);
 462         }
 463 
 464         private static void nextArg() {
 465             context().pos++;
 466         }
 467 
 468         private static void prevArg() {
 469             context().pos--;
 470         }
 471 
 472         private static boolean hasNextArg() {
 473             return context().pos < context().argList.size();
 474         }
 475     }
 476 
 477     enum OptionCategories {
 478         MODE,
 479         MODULAR,
 480         PROPERTY,
 481         PLATFORM_MAC,
 482         PLATFORM_WIN,
 483         PLATFORM_LINUX;
 484     }
 485 
 486     public boolean processArguments() throws Exception {
 487         try {
 488 
 489             // init context of arguments
 490             CLIOptions.setContext(this);
 491 
 492             // parse cmd line
 493             String arg;
 494             CLIOptions option;
 495             for (; CLIOptions.hasNextArg(); CLIOptions.nextArg()) {
 496                 arg = CLIOptions.getArg();
 497                 if ((option = toCLIOption(arg)) != null) {
 498                     // found a CLI option
 499                     allOptions.add(option);
 500                     option.execute();
 501                 } else {
 502                     throw new PackagerException("ERR_InvalidOption", arg);
 503                 }
 504             }
 505 
 506             if (allOptions.isEmpty() || !allOptions.get(0).isMode()) {
 507                 // first argument should always be a mode.
 508                 throw new PackagerException("ERR_MissingMode");
 509             }
 510 
 511             if (hasMainJar && !hasMainClass) {
 512                 // try to get main-class from manifest
 513                 String mainClass = getMainClassFromManifest();
 514                 if (mainClass != null) {
 515                     CLIOptions.setOptionValue(
 516                             CLIOptions.APPCLASS.getId(), mainClass);
 517                 }
 518             }
 519 
 520             // display warning for arguments that are not supported
 521             // for current configuration.
 522 
 523             validateArguments();
 524 
 525             addResources(deployParams, input);
 526 
 527             deployParams.setBundleType(bundleType);
 528 
 529             List<Map<String, ? super Object>> launchersAsMap =
 530                     new ArrayList<>();
 531 
 532             for (AddLauncherArguments sl : addLaunchers) {
 533                 launchersAsMap.add(sl.getLauncherMap());
 534             }
 535 
 536             deployParams.addBundleArgument(
 537                     StandardBundlerParam.ADD_LAUNCHERS.getID(),
 538                     launchersAsMap);
 539 
 540             // at this point deployParams should be already configured
 541 
 542             deployParams.validate();
 543 
 544             BundleParams bp = deployParams.getBundleParams();
 545 
 546             // validate name(s)
 547             ArrayList<String> usedNames = new ArrayList<String>();


 550             for (AddLauncherArguments sl : addLaunchers) {
 551                 Map<String, ? super Object> slMap = sl.getLauncherMap();
 552                 String slName =
 553                         (String) slMap.get(Arguments.CLIOptions.NAME.getId());
 554                 if (slName == null) {
 555                     throw new PackagerException("ERR_NoAddLauncherName");
 556                 }
 557                 // same rules apply to additional launcher names as app name
 558                 DeployParams.validateName(slName, false);
 559                 for (String usedName : usedNames) {
 560                     if (slName.equals(usedName)) {
 561                         throw new PackagerException("ERR_NoUniqueName");
 562                     }
 563                 }
 564                 usedNames.add(slName);
 565             }
 566             if (runtimeInstaller && bp.getName() == null) {
 567                 throw new PackagerException("ERR_NoJreInstallerName");
 568             }
 569 
 570             return generateBundle(bp.getBundleParamsAsMap());

 571         } catch (Exception e) {
 572             if (Log.isVerbose()) {
 573                 throw e;
 574             } else {
 575                 String msg1 = e.getMessage();
 576                 Log.error(msg1);
 577                 if (e.getCause() != null && e.getCause() != e) {
 578                     String msg2 = e.getCause().getMessage();
 579                     if (!msg1.contains(msg2)) {
 580                         Log.error(msg2);
 581                     }
 582                 }
 583                 return false;
 584             }

 585         }
 586     }
 587 
 588     private void validateArguments() throws PackagerException {
 589         CLIOptions mode = allOptions.get(0);
 590         boolean imageOnly = (mode == CLIOptions.CREATE_APP_IMAGE);

 591         boolean hasAppImage = allOptions.contains(
 592                 CLIOptions.PREDEFINED_APP_IMAGE);
 593         boolean hasRuntime = allOptions.contains(
 594                 CLIOptions.PREDEFINED_RUNTIME_IMAGE);
 595         boolean installerOnly = !imageOnly && hasAppImage;
 596         boolean runtimeInstall = !imageOnly && hasRuntime && !hasAppImage &&
 597                 !hasMainModule && !hasMainJar;
 598 
 599         for (CLIOptions option : allOptions) {
 600             if (!ValidOptions.checkIfSupported(option)) {
 601                 // includes option valid only on different platform
 602                 throw new PackagerException("ERR_UnsupportedOption",
 603                         option.getIdWithPrefix());
 604             }
 605             if (imageOnly) {
 606                 if (!ValidOptions.checkIfImageSupported(option)) {
 607                     throw new PackagerException("ERR_NotImageOption",
 608                         option.getIdWithPrefix());
 609                 }
 610             } else if (installerOnly || runtimeInstall) {
 611                 if (!ValidOptions.checkIfInstallerSupported(option)) {
 612                     String key = runtimeInstaller ?
 613                         "ERR_NoInstallerEntryPoint" : "ERR_NotInstallerOption";
 614                     throw new PackagerException(key, option.getIdWithPrefix());




 615                 }
 616             }
 617         }
 618         if (installerOnly && hasRuntime) {
 619             // note --runtime-image is only for image or runtime installer.
 620             throw new PackagerException("ERR_NotInstallerOption",
 621                     CLIOptions.PREDEFINED_RUNTIME_IMAGE.getIdWithPrefix());

 622         }
 623         if (hasMainJar && hasMainModule) {
 624             throw new PackagerException("ERR_BothMainJarAndModule");
 625         }
 626         if (imageOnly && !hasMainJar && !hasMainModule) {
 627             throw new PackagerException("ERR_NoEntryPoint");
 628         }
 629     }
 630 
 631     private List<jdk.jpackage.internal.Bundler> getPlatformBundlers() {
 632 
 633         if (platformBundlers != null) {
 634             return platformBundlers;







 635         }
 636 
 637         platformBundlers = new ArrayList<>();
 638         for (jdk.jpackage.internal.Bundler bundler :
 639                 Bundlers.createBundlersInstance().getBundlers(
 640                         bundleType.toString())) {
 641             if (hasTargetFormat && deployParams.getTargetFormat() != null &&
 642                     !deployParams.getTargetFormat().equalsIgnoreCase(
 643                     bundler.getID())) {
 644                 continue;
 645             }
 646             if (bundler.supported(runtimeInstaller)) {
 647                  platformBundlers.add(bundler);
 648             }
 649         }
 650 
 651         return platformBundlers;
 652     }
 653 
 654     private boolean generateBundle(Map<String,? super Object> params)
 655             throws PackagerException {
 656 
 657         boolean bundleCreated = false;
 658 
 659         // the temp-root needs to be fetched from the params early,
 660         // to prevent each copy of the params (such as may be used for
 661         // additional launchers) from generating a separate temp-root when
 662         // the default is used (the default is a new temp directory)
 663         // The bundler.cleanup() below would not otherwise be able to
 664         // clean these extra (and unneeded) temp directories.
 665         StandardBundlerParam.TEMP_ROOT.fetchFrom(params);
 666         List<jdk.jpackage.internal.Bundler> bundlers = getPlatformBundlers();
 667         if (bundlers.isEmpty()) {



 668             throw new PackagerException("ERR_InvalidInstallerType",
 669                     deployParams.getTargetFormat());
 670         }
 671         PackagerException pe = null;
 672         for (jdk.jpackage.internal.Bundler bundler : bundlers) {
 673             Map<String, ? super Object> localParams = new HashMap<>(params);
 674             try {
 675                 if (bundler.validate(localParams)) {
 676                     File result =
 677                             bundler.execute(localParams, deployParams.outdir);
 678                     if (!userProvidedBuildRoot) {
 679                         bundler.cleanup(localParams);
 680                     }
 681                     if (result == null) {
 682                         throw new PackagerException("MSG_BundlerFailed",
 683                                 bundler.getID(), bundler.getName());
 684                     }
 685                     bundleCreated = true; // at least one bundle was created
 686                 }
 687                 Log.verbose(MessageFormat.format(
 688                         I18N.getString("message.bundle-created"),
 689                         bundler.getName()));
 690             } catch (UnsupportedPlatformException upe) {
 691                 Log.debug(upe);
 692                 if (pe == null) {
 693                     pe = new PackagerException(upe,
 694                             "MSG_BundlerPlatformException", bundler.getName());
 695                 }
 696             } catch (ConfigException e) {
 697                 Log.debug(e);
 698                 if (pe == null) {
 699                     pe = (e.getAdvice() != null) ?
 700                             new PackagerException(e,
 701                             "MSG_BundlerConfigException",
 702                             bundler.getName(), e.getMessage(), e.getAdvice()) :
 703                             new PackagerException(e,
 704                            "MSG_BundlerConfigExceptionNoAdvice",
 705                             bundler.getName(), e.getMessage());
 706                 }
 707             } catch (RuntimeException re) {
 708                 Log.debug(re);
 709                 if (pe == null) {
 710                     pe = new PackagerException(re,
 711                             "MSG_BundlerRuntimeException",
 712                             bundler.getName(), re.toString());
 713                 }
 714             } finally {
 715                 if (userProvidedBuildRoot) {
 716                     Log.verbose(MessageFormat.format(
 717                             I18N.getString("message.debug-working-directory"),
 718                             (new File(buildRoot)).getAbsolutePath()));




 719                 }
 720             }
 721         }
 722         if (pe != null) {
 723             // throw packager exception only after trying all bundlers
 724             throw pe;
 725         }
 726         return bundleCreated;
 727     }
 728 
 729     private void addResources(DeployParams deployParams,
 730             String inputdir) throws PackagerException {
 731 
 732         if (inputdir == null || inputdir.isEmpty()) {
 733             return;
 734         }
 735 
 736         File baseDir = new File(inputdir);
 737 
 738         if (!baseDir.isDirectory()) {
 739             throw new PackagerException("ERR_InputNotDirectory", inputdir);
 740         }
 741         if (!baseDir.canRead()) {
 742             throw new PackagerException("ERR_CannotReadInputDir", inputdir);
 743         }
 744 
 745         List<String> fileNames;
 746         fileNames = new ArrayList<>();
 747         try (Stream<Path> files = Files.list(baseDir.toPath())) {
 748             files.forEach(file -> fileNames.add(
 749                     file.getFileName().toString()));
 750         } catch (IOException e) {
 751             Log.error("Unable to add resources: " + e.getMessage());
 752         }
 753         fileNames.forEach(file -> deployParams.addResource(baseDir, file));
 754 
 755         deployParams.setClasspath();
 756     }
 757 
 758     static boolean isCLIOption(String arg) {
 759         return toCLIOption(arg) != null;
 760     }
 761 
 762     static CLIOptions toCLIOption(String arg) {
 763         CLIOptions option;
 764         if ((option = argIds.get(arg)) == null) {
 765             option = argShortIds.get(arg);
 766         }
 767         return option;
 768     }
 769 
 770     static Map<String, String> getArgumentMap(String inputString) {
 771         Map<String, String> map = new HashMap<>();
 772         List<String> list = getArgumentList(inputString);
 773         for (String pair : list) {
 774             int equals = pair.indexOf("=");
 775             if (equals != -1) {
 776                 String key = pair.substring(0, equals);
 777                 String value = pair.substring(equals+1, pair.length());
 778                 map.put(key, value);
 779             }
 780         }
 781         return map;
 782     }
 783 
 784     static Map<String, String> getPropertiesFromFile(String filename) {
 785         Map<String, String> map = new HashMap<>();
 786         // load properties file
 787         File file = new File(filename);
 788         Properties properties = new Properties();
 789         try (FileInputStream in = new FileInputStream(file)) {
 790             properties.load(in);
 791         } catch (IOException e) {
 792             Log.error("Exception: " + e.getMessage());
 793         }
 794 
 795         for (final String name: properties.stringPropertyNames()) {
 796             map.put(name, properties.getProperty(name));
 797         }
 798 
 799         return map;
 800     }
 801 




   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.incubator.jpackage.internal;
  26 
  27 import java.io.File;
  28 import java.io.FileInputStream;
  29 import java.io.IOException;
  30 import java.nio.file.Files;
  31 import java.nio.file.Path;
  32 import java.nio.file.Paths;
  33 import java.text.MessageFormat;
  34 import java.util.ArrayList;
  35 import java.util.Arrays;
  36 import java.util.Collection;
  37 import java.util.EnumSet;
  38 import java.util.HashMap;
  39 import java.util.HashSet;
  40 import java.util.List;
  41 import java.util.Map;
  42 import java.util.Set;
  43 import java.util.Properties;
  44 import java.util.ResourceBundle;
  45 import java.util.jar.Attributes;
  46 import java.util.jar.JarFile;
  47 import java.util.jar.Manifest;
  48 import java.util.stream.Stream;
  49 import java.util.regex.Matcher;
  50 import java.util.regex.Pattern;
  51 
  52 /**
  53  * Arguments
  54  *
  55  * This class encapsulates and processes the command line arguments,
  56  * in effect, implementing all the work of jpackage tool.
  57  *
  58  * The primary entry point, processArguments():
  59  * Processes and validates command line arguments, constructing DeployParams.
  60  * Validates the DeployParams, and generate the BundleParams.
  61  * Generates List of Bundlers from BundleParams valid for this platform.
  62  * Executes each Bundler in the list.
  63  */
  64 public class Arguments {
  65     private static final ResourceBundle I18N = ResourceBundle.getBundle(
  66             "jdk.incubator.jpackage.internal.resources.MainResources");



  67 
  68     private static final String FA_EXTENSIONS = "extension";
  69     private static final String FA_CONTENT_TYPE = "mime-type";
  70     private static final String FA_DESCRIPTION = "description";
  71     private static final String FA_ICON = "icon";
  72 
















  73     // regexp for parsing args (for example, for additional launchers)
  74     private static Pattern pattern = Pattern.compile(
  75           "(?:(?:([\"'])(?:\\\\\\1|.)*?(?:\\1|$))|(?:\\\\[\"'\\s]|[^\\s]))++");
  76 
  77     private DeployParams deployParams = null;

  78 
  79     private int pos = 0;
  80     private List<String> argList = null;
  81 
  82     private List<CLIOptions> allOptions = null;
  83 
  84     private String input = null;
  85     private String output = null;
  86 
  87     private boolean hasMainJar = false;
  88     private boolean hasMainClass = false;
  89     private boolean hasMainModule = false;


  90     public boolean userProvidedBuildRoot = false;
  91 
  92     private String buildRoot = null;
  93     private String mainJarPath = null;
  94 
  95     private static boolean runtimeInstaller = false;
  96 


  97     private List<AddLauncherArguments> addLaunchers = null;
  98 
  99     private static Map<String, CLIOptions> argIds = new HashMap<>();
 100     private static Map<String, CLIOptions> argShortIds = new HashMap<>();
 101 
 102     static {
 103         // init maps for parsing arguments
 104         (EnumSet.allOf(CLIOptions.class)).forEach(option -> {
 105             argIds.put(option.getIdWithPrefix(), option);
 106             if (option.getShortIdWithPrefix() != null) {
 107                 argShortIds.put(option.getShortIdWithPrefix(), option);
 108             }
 109         });
 110     }
 111 
 112     public Arguments(String[] args) {
 113         argList = new ArrayList<String>(args.length);
 114         for (String arg : args) {
 115             argList.add(arg);
 116         }
 117         Log.verbose ("\njpackage argument list: \n" + argList + "\n");
 118         pos = 0;
 119 
 120         deployParams = new DeployParams();

 121 
 122         allOptions = new ArrayList<>();
 123 
 124         addLaunchers = new ArrayList<>();
 125 
 126         output = Paths.get("").toAbsolutePath().toString();
 127         deployParams.setOutput(new File(output));
 128     }
 129 
 130     // CLIOptions is public for DeployParamsTest
 131     public enum CLIOptions {
 132         PACKAGE_TYPE("type", "t", OptionCategories.PROPERTY, () -> {
 133             context().deployParams.setTargetFormat(popArg());


















 134         }),
 135 
 136         INPUT ("input", "i", OptionCategories.PROPERTY, () -> {
 137             context().input = popArg();
 138             setOptionValue("input", context().input);
 139         }),
 140 
 141         OUTPUT ("dest", "d", OptionCategories.PROPERTY, () -> {
 142             context().output = popArg();
 143             context().deployParams.setOutput(new File(context().output));
 144         }),
 145 
 146         DESCRIPTION ("description", OptionCategories.PROPERTY),
 147 
 148         VENDOR ("vendor", OptionCategories.PROPERTY),
 149 
 150         APPCLASS ("main-class", OptionCategories.PROPERTY, () -> {
 151             context().hasMainClass = true;
 152             setOptionValue("main-class", popArg());
 153         }),
 154 
 155         NAME ("name", "n", OptionCategories.PROPERTY),
 156 


 157         VERBOSE ("verbose", OptionCategories.PROPERTY, () -> {
 158             setOptionValue("verbose", true);
 159             Log.setVerbose();
 160         }),
 161 
 162         RESOURCE_DIR("resource-dir",
 163                 OptionCategories.PROPERTY, () -> {
 164             String resourceDir = popArg();
 165             setOptionValue("resource-dir", resourceDir);
 166         }),
 167 
 168         ARGUMENTS ("arguments", OptionCategories.PROPERTY, () -> {
 169             List<String> arguments = getArgumentList(popArg());
 170             setOptionValue("arguments", arguments);
 171         }),
 172 
 173         ICON ("icon", OptionCategories.PROPERTY),
 174 
 175         COPYRIGHT ("copyright", OptionCategories.PROPERTY),
 176 
 177         LICENSE_FILE ("license-file", OptionCategories.PROPERTY),
 178 
 179         VERSION ("app-version", OptionCategories.PROPERTY),
 180 
 181         RELEASE ("linux-app-release", OptionCategories.PROPERTY),
 182 
 183         JAVA_OPTIONS ("java-options", OptionCategories.PROPERTY, () -> {
 184             List<String> args = getArgumentList(popArg());
 185             args.forEach(a -> setOptionValue("java-options", a));
 186         }),
 187 
 188         FILE_ASSOCIATIONS ("file-associations",
 189                 OptionCategories.PROPERTY, () -> {
 190             Map<String, ? super Object> args = new HashMap<>();
 191 
 192             // load .properties file
 193             Map<String, String> initialMap = getPropertiesFromFile(popArg());
 194 
 195             String ext = initialMap.get(FA_EXTENSIONS);
 196             if (ext != null) {
 197                 args.put(StandardBundlerParam.FA_EXTENSIONS.getID(), ext);
 198             }
 199 
 200             String type = initialMap.get(FA_CONTENT_TYPE);
 201             if (type != null) {
 202                 args.put(StandardBundlerParam.FA_CONTENT_TYPE.getID(), type);


 219 
 220             // check that we really add _another_ value to the list
 221             setOptionValue("file-associations", associationList);
 222 
 223         }),
 224 
 225         ADD_LAUNCHER ("add-launcher",
 226                     OptionCategories.PROPERTY, () -> {
 227             String spec = popArg();
 228             String name = null;
 229             String filename = spec;
 230             if (spec.contains("=")) {
 231                 String[] values = spec.split("=", 2);
 232                 name = values[0];
 233                 filename = values[1];
 234             }
 235             context().addLaunchers.add(
 236                 new AddLauncherArguments(name, filename));
 237         }),
 238 
 239         TEMP_ROOT ("temp", OptionCategories.PROPERTY, () -> {
 240             context().buildRoot = popArg();
 241             context().userProvidedBuildRoot = true;
 242             setOptionValue("temp", context().buildRoot);
 243         }),
 244 
 245         INSTALL_DIR ("install-dir", OptionCategories.PROPERTY),
 246 
 247         PREDEFINED_APP_IMAGE ("app-image", OptionCategories.PROPERTY),



 248 
 249         PREDEFINED_RUNTIME_IMAGE ("runtime-image", OptionCategories.PROPERTY),
 250 
 251         MAIN_JAR ("main-jar",  OptionCategories.PROPERTY, () -> {
 252             context().mainJarPath = popArg();
 253             context().hasMainJar = true;
 254             setOptionValue("main-jar", context().mainJarPath);
 255         }),
 256 
 257         MODULE ("module", "m", OptionCategories.MODULAR, () -> {
 258             context().hasMainModule = true;
 259             setOptionValue("module", popArg());
 260         }),
 261 
 262         ADD_MODULES ("add-modules", OptionCategories.MODULAR),
 263 
 264         MODULE_PATH ("module-path", "p", OptionCategories.MODULAR),
 265 
 266         BIND_SERVICES ("bind-services", OptionCategories.PROPERTY, () -> {
 267             setOptionValue("bind-services", true);
 268         }),
 269 
 270         MAC_SIGN ("mac-sign", "s", OptionCategories.PLATFORM_MAC, () -> {
 271             setOptionValue("mac-sign", true);
 272         }),
 273 
 274         MAC_BUNDLE_NAME ("mac-package-name", OptionCategories.PLATFORM_MAC),
 275 
 276         MAC_BUNDLE_IDENTIFIER("mac-package-identifier",
 277                     OptionCategories.PLATFORM_MAC),
 278 
 279         MAC_BUNDLE_SIGNING_PREFIX ("mac-package-signing-prefix",



 280                     OptionCategories.PLATFORM_MAC),
 281 
 282         MAC_SIGNING_KEY_NAME ("mac-signing-key-user-name",
 283                     OptionCategories.PLATFORM_MAC),
 284 
 285         MAC_SIGNING_KEYCHAIN ("mac-signing-keychain",
 286                     OptionCategories.PLATFORM_MAC),
 287 
 288         MAC_APP_STORE_ENTITLEMENTS ("mac-app-store-entitlements",
 289                     OptionCategories.PLATFORM_MAC),
 290 
 291         WIN_MENU_HINT ("win-menu", OptionCategories.PLATFORM_WIN, () -> {
 292             setOptionValue("win-menu", true);
 293         }),
 294 
 295         WIN_MENU_GROUP ("win-menu-group", OptionCategories.PLATFORM_WIN),
 296 
 297         WIN_SHORTCUT_HINT ("win-shortcut",
 298                 OptionCategories.PLATFORM_WIN, () -> {
 299             setOptionValue("win-shortcut", true);
 300         }),
 301 
 302         WIN_PER_USER_INSTALLATION ("win-per-user-install",
 303                 OptionCategories.PLATFORM_WIN, () -> {
 304             setOptionValue("win-per-user-install", false);
 305         }),
 306 
 307         WIN_DIR_CHOOSER ("win-dir-chooser",
 308                 OptionCategories.PLATFORM_WIN, () -> {
 309             setOptionValue("win-dir-chooser", true);
 310         }),
 311 


 312         WIN_UPGRADE_UUID ("win-upgrade-uuid",
 313                 OptionCategories.PLATFORM_WIN),
 314 
 315         WIN_CONSOLE_HINT ("win-console", OptionCategories.PLATFORM_WIN, () -> {
 316             setOptionValue("win-console", true);
 317         }),
 318 
 319         LINUX_BUNDLE_NAME ("linux-package-name",
 320                 OptionCategories.PLATFORM_LINUX),
 321 
 322         LINUX_DEB_MAINTAINER ("linux-deb-maintainer",
 323                 OptionCategories.PLATFORM_LINUX),
 324 
 325         LINUX_CATEGORY ("linux-app-category",
 326                 OptionCategories.PLATFORM_LINUX),
 327 
 328         LINUX_RPM_LICENSE_TYPE ("linux-rpm-license-type",
 329                 OptionCategories.PLATFORM_LINUX),
 330 
 331         LINUX_PACKAGE_DEPENDENCIES ("linux-package-deps",
 332                 OptionCategories.PLATFORM_LINUX),
 333 
 334         LINUX_SHORTCUT_HINT ("linux-shortcut",
 335                 OptionCategories.PLATFORM_LINUX, () -> {
 336             setOptionValue("linux-shortcut", true);
 337         }),
 338 
 339         LINUX_MENU_GROUP ("linux-menu-group", OptionCategories.PLATFORM_LINUX);
 340 
 341         private final String id;
 342         private final String shortId;
 343         private final OptionCategories category;
 344         private final ArgAction action;
 345         private static Arguments argContext;
 346 
 347         private CLIOptions(String id, OptionCategories category) {
 348             this(id, null, category, null);
 349         }
 350 
 351         private CLIOptions(String id, String shortId,
 352                            OptionCategories category) {
 353             this(id, shortId, category, null);
 354         }
 355 
 356         private CLIOptions(String id,
 357                 OptionCategories category, ArgAction action) {
 358             this(id, null, category, action);


 366             this.category = category;
 367         }
 368 
 369         static void setContext(Arguments context) {
 370             argContext = context;
 371         }
 372 
 373         public static Arguments context() {
 374             if (argContext != null) {
 375                 return argContext;
 376             } else {
 377                 throw new RuntimeException("Argument context is not set.");
 378             }
 379         }
 380 
 381         public String getId() {
 382             return this.id;
 383         }
 384 
 385         String getIdWithPrefix() {
 386             return "--" + this.id;

 387         }
 388 
 389         String getShortIdWithPrefix() {
 390             return this.shortId == null ? null : "-" + this.shortId;
 391         }
 392 
 393         void execute() {
 394             if (action != null) {
 395                 action.execute();
 396             } else {
 397                 defaultAction();
 398             }
 399         }
 400 








 401         private void defaultAction() {
 402             context().deployParams.addBundleArgument(id, popArg());
 403         }
 404 
 405         private static void setOptionValue(String option, Object value) {
 406             context().deployParams.addBundleArgument(option, value);
 407         }
 408 
 409         private static String popArg() {
 410             nextArg();
 411             return (context().pos >= context().argList.size()) ?
 412                             "" : context().argList.get(context().pos);
 413         }
 414 
 415         private static String getArg() {
 416             return (context().pos >= context().argList.size()) ?
 417                         "" : context().argList.get(context().pos);
 418         }
 419 
 420         private static void nextArg() {
 421             context().pos++;
 422         }
 423 




 424         private static boolean hasNextArg() {
 425             return context().pos < context().argList.size();
 426         }
 427     }
 428 
 429     enum OptionCategories {

 430         MODULAR,
 431         PROPERTY,
 432         PLATFORM_MAC,
 433         PLATFORM_WIN,
 434         PLATFORM_LINUX;
 435     }
 436 
 437     public boolean processArguments() {
 438         try {
 439 
 440             // init context of arguments
 441             CLIOptions.setContext(this);
 442 
 443             // parse cmd line
 444             String arg;
 445             CLIOptions option;
 446             for (; CLIOptions.hasNextArg(); CLIOptions.nextArg()) {
 447                 arg = CLIOptions.getArg();
 448                 if ((option = toCLIOption(arg)) != null) {
 449                     // found a CLI option
 450                     allOptions.add(option);
 451                     option.execute();
 452                 } else {
 453                     throw new PackagerException("ERR_InvalidOption", arg);
 454                 }
 455             }
 456 





 457             if (hasMainJar && !hasMainClass) {
 458                 // try to get main-class from manifest
 459                 String mainClass = getMainClassFromManifest();
 460                 if (mainClass != null) {
 461                     CLIOptions.setOptionValue(
 462                             CLIOptions.APPCLASS.getId(), mainClass);
 463                 }
 464             }
 465 
 466             // display error for arguments that are not supported
 467             // for current configuration.
 468 
 469             validateArguments();
 470 
 471             addResources(deployParams, input, mainJarPath);


 472 
 473             List<Map<String, ? super Object>> launchersAsMap =
 474                     new ArrayList<>();
 475 
 476             for (AddLauncherArguments sl : addLaunchers) {
 477                 launchersAsMap.add(sl.getLauncherMap());
 478             }
 479 
 480             deployParams.addBundleArgument(
 481                     StandardBundlerParam.ADD_LAUNCHERS.getID(),
 482                     launchersAsMap);
 483 
 484             // at this point deployParams should be already configured
 485 
 486             deployParams.validate();
 487 
 488             BundleParams bp = deployParams.getBundleParams();
 489 
 490             // validate name(s)
 491             ArrayList<String> usedNames = new ArrayList<String>();


 494             for (AddLauncherArguments sl : addLaunchers) {
 495                 Map<String, ? super Object> slMap = sl.getLauncherMap();
 496                 String slName =
 497                         (String) slMap.get(Arguments.CLIOptions.NAME.getId());
 498                 if (slName == null) {
 499                     throw new PackagerException("ERR_NoAddLauncherName");
 500                 }
 501                 // same rules apply to additional launcher names as app name
 502                 DeployParams.validateName(slName, false);
 503                 for (String usedName : usedNames) {
 504                     if (slName.equals(usedName)) {
 505                         throw new PackagerException("ERR_NoUniqueName");
 506                     }
 507                 }
 508                 usedNames.add(slName);
 509             }
 510             if (runtimeInstaller && bp.getName() == null) {
 511                 throw new PackagerException("ERR_NoJreInstallerName");
 512             }
 513 
 514             generateBundle(bp.getBundleParamsAsMap());
 515             return true;
 516         } catch (Exception e) {
 517             if (Log.isVerbose()) {
 518                 Log.verbose(e);
 519             } else {
 520                 String msg1 = e.getMessage();
 521                 Log.error(msg1);
 522                 if (e.getCause() != null && e.getCause() != e) {
 523                     String msg2 = e.getCause().getMessage();
 524                     if (msg2 != null && !msg1.contains(msg2)) {
 525                         Log.error(msg2);
 526                     }
 527                 }

 528             }
 529             return false;
 530         }
 531     }
 532 
 533     private void validateArguments() throws PackagerException {
 534         String type = deployParams.getTargetFormat();
 535         String ptype = (type != null) ? type : "default";
 536         boolean imageOnly = deployParams.isTargetAppImage();
 537         boolean hasAppImage = allOptions.contains(
 538                 CLIOptions.PREDEFINED_APP_IMAGE);
 539         boolean hasRuntime = allOptions.contains(
 540                 CLIOptions.PREDEFINED_RUNTIME_IMAGE);
 541         boolean installerOnly = !imageOnly && hasAppImage;
 542         runtimeInstaller = !imageOnly && hasRuntime && !hasAppImage &&
 543                 !hasMainModule && !hasMainJar;
 544 
 545         for (CLIOptions option : allOptions) {
 546             if (!ValidOptions.checkIfSupported(option)) {
 547                 // includes option valid only on different platform
 548                 throw new PackagerException("ERR_UnsupportedOption",
 549                         option.getIdWithPrefix());
 550             }
 551             if (imageOnly) {
 552                 if (!ValidOptions.checkIfImageSupported(option)) {
 553                     throw new PackagerException("ERR_InvalidTypeOption",
 554                         option.getIdWithPrefix(), type);
 555                 }
 556             } else if (installerOnly || runtimeInstaller) {
 557                 if (!ValidOptions.checkIfInstallerSupported(option)) {
 558                     if (runtimeInstaller) {
 559                         throw new PackagerException("ERR_NoInstallerEntryPoint",
 560                             option.getIdWithPrefix());
 561                     } else {
 562                         throw new PackagerException("ERR_InvalidTypeOption",
 563                             option.getIdWithPrefix(), ptype);
 564                    }
 565                 }
 566             }
 567         }
 568         if (installerOnly && hasRuntime) {
 569             // note --runtime-image is only for image or runtime installer.
 570             throw new PackagerException("ERR_InvalidTypeOption",
 571                     CLIOptions.PREDEFINED_RUNTIME_IMAGE.getIdWithPrefix(),
 572                     ptype);
 573         }
 574         if (hasMainJar && hasMainModule) {
 575             throw new PackagerException("ERR_BothMainJarAndModule");
 576         }
 577         if (imageOnly && !hasMainJar && !hasMainModule) {
 578             throw new PackagerException("ERR_NoEntryPoint");
 579         }
 580     }
 581 
 582     private jdk.incubator.jpackage.internal.Bundler getPlatformBundler() {
 583         boolean appImage = deployParams.isTargetAppImage();
 584         String type = deployParams.getTargetFormat();
 585         String bundleType = (appImage ?  "IMAGE" : "INSTALLER");
 586 
 587         for (jdk.incubator.jpackage.internal.Bundler bundler :
 588                 Bundlers.createBundlersInstance().getBundlers(bundleType)) {
 589             if (type == null) {
 590                  if (bundler.isDefault()
 591                          && bundler.supported(runtimeInstaller)) {
 592                      return bundler;
 593                  }
 594             } else {
 595                  if ((appImage || type.equalsIgnoreCase(bundler.getID()))
 596                          && bundler.supported(runtimeInstaller)) {
 597                      return bundler;





 598                  }


 599             }
 600         }
 601         return null;

 602     }
 603 
 604     private void generateBundle(Map<String,? super Object> params)
 605             throws PackagerException {
 606 
 607         boolean bundleCreated = false;
 608 
 609         // the temp dir needs to be fetched from the params early,
 610         // to prevent each copy of the params (such as may be used for
 611         // additional launchers) from generating a separate temp dir when
 612         // the default is used (the default is a new temp directory)
 613         // The bundler.cleanup() below would not otherwise be able to
 614         // clean these extra (and unneeded) temp directories.
 615         StandardBundlerParam.TEMP_ROOT.fetchFrom(params);
 616 
 617         // determine what bundler to run
 618         jdk.incubator.jpackage.internal.Bundler bundler = getPlatformBundler();
 619 
 620         if (bundler == null) {
 621             throw new PackagerException("ERR_InvalidInstallerType",
 622                       deployParams.getTargetFormat());
 623         }
 624 

 625         Map<String, ? super Object> localParams = new HashMap<>(params);
 626         try {
 627             bundler.validate(localParams);
 628             File result = bundler.execute(localParams, deployParams.outdir);




 629             if (result == null) {
 630                 throw new PackagerException("MSG_BundlerFailed",
 631                         bundler.getID(), bundler.getName());
 632             }


 633             Log.verbose(MessageFormat.format(
 634                     I18N.getString("message.bundle-created"),
 635                     bundler.getName()));






 636         } catch (ConfigException e) {
 637             Log.verbose(e);
 638             if (e.getAdvice() != null)  {
 639                 throw new PackagerException(e, "MSG_BundlerConfigException",
 640                         bundler.getName(), e.getMessage(), e.getAdvice());
 641             } else {
 642                 throw new PackagerException(e,

 643                        "MSG_BundlerConfigExceptionNoAdvice",
 644                         bundler.getName(), e.getMessage());
 645             }
 646         } catch (RuntimeException re) {
 647             Log.verbose(re);
 648             throw new PackagerException(re, "MSG_BundlerRuntimeException",


 649                     bundler.getName(), re.toString());

 650         } finally {
 651             if (userProvidedBuildRoot) {
 652                 Log.verbose(MessageFormat.format(
 653                         I18N.getString("message.debug-working-directory"),
 654                         (new File(buildRoot)).getAbsolutePath()));
 655             } else {
 656                 // always clean up the temporary directory created
 657                 // when --temp option not used.
 658                 bundler.cleanup(localParams);
 659             }
 660         }
 661     }






 662 
 663     private void addResources(DeployParams deployParams,
 664             String inputdir, String mainJar) throws PackagerException {
 665 
 666         if (inputdir == null || inputdir.isEmpty()) {
 667             return;
 668         }
 669 
 670         File baseDir = new File(inputdir);
 671 
 672         if (!baseDir.isDirectory()) {
 673             throw new PackagerException("ERR_InputNotDirectory", inputdir);
 674         }
 675         if (!baseDir.canRead()) {
 676             throw new PackagerException("ERR_CannotReadInputDir", inputdir);
 677         }
 678 
 679         List<String> fileNames;
 680         fileNames = new ArrayList<>();
 681         try (Stream<Path> files = Files.list(baseDir.toPath())) {
 682             files.forEach(file -> fileNames.add(
 683                     file.getFileName().toString()));
 684         } catch (IOException e) {
 685             Log.error("Unable to add resources: " + e.getMessage());
 686         }
 687         fileNames.forEach(file -> deployParams.addResource(baseDir, file));
 688 
 689         deployParams.setClasspath(mainJar);




 690     }
 691 
 692     static CLIOptions toCLIOption(String arg) {
 693         CLIOptions option;
 694         if ((option = argIds.get(arg)) == null) {
 695             option = argShortIds.get(arg);
 696         }
 697         return option;














 698     }
 699 
 700     static Map<String, String> getPropertiesFromFile(String filename) {
 701         Map<String, String> map = new HashMap<>();
 702         // load properties file
 703         File file = new File(filename);
 704         Properties properties = new Properties();
 705         try (FileInputStream in = new FileInputStream(file)) {
 706             properties.load(in);
 707         } catch (IOException e) {
 708             Log.error("Exception: " + e.getMessage());
 709         }
 710 
 711         for (final String name: properties.stringPropertyNames()) {
 712             map.put(name, properties.getProperty(name));
 713         }
 714 
 715         return map;
 716     }
 717 


< prev index next >