1 /*
   2  * Copyright (c) 2018, 2019, 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.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.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("package-type", 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         IDENTIFIER ("identifier", OptionCategories.PROPERTY),
 158 
 159         VERBOSE ("verbose", OptionCategories.PROPERTY, () -> {
 160             setOptionValue("verbose", true);
 161             Log.setVerbose();
 162         }),
 163 
 164         RESOURCE_DIR("resource-dir",
 165                 OptionCategories.PROPERTY, () -> {
 166             String resourceDir = popArg();
 167             setOptionValue("resource-dir", resourceDir);
 168         }),
 169 
 170         ARGUMENTS ("arguments", OptionCategories.PROPERTY, () -> {
 171             List<String> arguments = getArgumentList(popArg());
 172             setOptionValue("arguments", arguments);
 173         }),
 174 
 175         ICON ("icon", OptionCategories.PROPERTY),
 176 
 177         COPYRIGHT ("copyright", OptionCategories.PROPERTY),
 178 
 179         LICENSE_FILE ("license-file", OptionCategories.PROPERTY),
 180 
 181         VERSION ("app-version", OptionCategories.PROPERTY),
 182 
 183         RELEASE ("linux-app-release", OptionCategories.PROPERTY),
 184 
 185         JAVA_OPTIONS ("java-options", OptionCategories.PROPERTY, () -> {
 186             List<String> args = getArgumentList(popArg());
 187             args.forEach(a -> setOptionValue("java-options", a));
 188         }),
 189 
 190         FILE_ASSOCIATIONS ("file-associations",
 191                 OptionCategories.PROPERTY, () -> {
 192             Map<String, ? super Object> args = new HashMap<>();
 193 
 194             // load .properties file
 195             Map<String, String> initialMap = getPropertiesFromFile(popArg());
 196 
 197             String ext = initialMap.get(FA_EXTENSIONS);
 198             if (ext != null) {
 199                 args.put(StandardBundlerParam.FA_EXTENSIONS.getID(), ext);
 200             }
 201 
 202             String type = initialMap.get(FA_CONTENT_TYPE);
 203             if (type != null) {
 204                 args.put(StandardBundlerParam.FA_CONTENT_TYPE.getID(), type);
 205             }
 206 
 207             String desc = initialMap.get(FA_DESCRIPTION);
 208             if (desc != null) {
 209                 args.put(StandardBundlerParam.FA_DESCRIPTION.getID(), desc);
 210             }
 211 
 212             String icon = initialMap.get(FA_ICON);
 213             if (icon != null) {
 214                 args.put(StandardBundlerParam.FA_ICON.getID(), icon);
 215             }
 216 
 217             ArrayList<Map<String, ? super Object>> associationList =
 218                 new ArrayList<Map<String, ? super Object>>();
 219 
 220             associationList.add(args);
 221 
 222             // check that we really add _another_ value to the list
 223             setOptionValue("file-associations", associationList);
 224 
 225         }),
 226 
 227         ADD_LAUNCHER ("add-launcher",
 228                     OptionCategories.PROPERTY, () -> {
 229             String spec = popArg();
 230             String name = null;
 231             String filename = spec;
 232             if (spec.contains("=")) {
 233                 String[] values = spec.split("=", 2);
 234                 name = values[0];
 235                 filename = values[1];
 236             }
 237             context().addLaunchers.add(
 238                 new AddLauncherArguments(name, filename));
 239         }),
 240 
 241         TEMP_ROOT ("temp", OptionCategories.PROPERTY, () -> {
 242             context().buildRoot = popArg();
 243             context().userProvidedBuildRoot = true;
 244             setOptionValue("temp", context().buildRoot);
 245         }),
 246 
 247         INSTALL_DIR ("install-dir", OptionCategories.PROPERTY),
 248 
 249         PREDEFINED_APP_IMAGE ("app-image", OptionCategories.PROPERTY),
 250 
 251         PREDEFINED_RUNTIME_IMAGE ("runtime-image", OptionCategories.PROPERTY),
 252 
 253         MAIN_JAR ("main-jar",  OptionCategories.PROPERTY, () -> {
 254             context().mainJarPath = popArg();
 255             context().hasMainJar = true;
 256             setOptionValue("main-jar", context().mainJarPath);
 257         }),
 258 
 259         MODULE ("module", "m", OptionCategories.MODULAR, () -> {
 260             context().hasMainModule = true;
 261             setOptionValue("module", popArg());
 262         }),
 263 
 264         ADD_MODULES ("add-modules", OptionCategories.MODULAR),
 265 
 266         MODULE_PATH ("module-path", "p", OptionCategories.MODULAR),
 267 
 268         MAC_SIGN ("mac-sign", "s", OptionCategories.PLATFORM_MAC, () -> {
 269             setOptionValue("mac-sign", true);
 270         }),
 271 
 272         MAC_BUNDLE_NAME ("mac-package-name", OptionCategories.PLATFORM_MAC),
 273 
 274         MAC_BUNDLE_IDENTIFIER("mac-package-identifier",
 275                     OptionCategories.PLATFORM_MAC),
 276 
 277         MAC_APP_STORE_CATEGORY ("mac-app-store-category",
 278                     OptionCategories.PLATFORM_MAC),
 279 
 280         MAC_BUNDLE_SIGNING_PREFIX ("mac-package-signing-prefix",
 281                     OptionCategories.PLATFORM_MAC),
 282 
 283         MAC_SIGNING_KEY_NAME ("mac-signing-key-user-name",
 284                     OptionCategories.PLATFORM_MAC),
 285 
 286         MAC_SIGNING_KEYCHAIN ("mac-signing-keychain",
 287                     OptionCategories.PLATFORM_MAC),
 288 
 289         MAC_APP_STORE_ENTITLEMENTS ("mac-app-store-entitlements",
 290                     OptionCategories.PLATFORM_MAC),
 291 
 292         WIN_MENU_HINT ("win-menu", OptionCategories.PLATFORM_WIN, () -> {
 293             setOptionValue("win-menu", true);
 294         }),
 295 
 296         WIN_MENU_GROUP ("win-menu-group", OptionCategories.PLATFORM_WIN),
 297 
 298         WIN_SHORTCUT_HINT ("win-shortcut",
 299                 OptionCategories.PLATFORM_WIN, () -> {
 300             setOptionValue("win-shortcut", true);
 301         }),
 302 
 303         WIN_PER_USER_INSTALLATION ("win-per-user-install",
 304                 OptionCategories.PLATFORM_WIN, () -> {
 305             setOptionValue("win-per-user-install", false);
 306         }),
 307 
 308         WIN_DIR_CHOOSER ("win-dir-chooser",
 309                 OptionCategories.PLATFORM_WIN, () -> {
 310             setOptionValue("win-dir-chooser", true);
 311         }),
 312 
 313         WIN_UPGRADE_UUID ("win-upgrade-uuid",
 314                 OptionCategories.PLATFORM_WIN),
 315 
 316         WIN_CONSOLE_HINT ("win-console", OptionCategories.PLATFORM_WIN, () -> {
 317             setOptionValue("win-console", true);
 318         }),
 319 
 320         LINUX_BUNDLE_NAME ("linux-package-name",
 321                 OptionCategories.PLATFORM_LINUX),
 322 
 323         LINUX_DEB_MAINTAINER ("linux-deb-maintainer",
 324                 OptionCategories.PLATFORM_LINUX),
 325 
 326         LINUX_DEB_COPYRIGHT_FILE ("linux-deb-copyright-file",
 327                 OptionCategories.PLATFORM_LINUX),
 328 
 329         LINUX_CATEGORY ("linux-app-category",
 330                 OptionCategories.PLATFORM_LINUX),
 331 
 332         LINUX_RPM_LICENSE_TYPE ("linux-rpm-license-type",
 333                 OptionCategories.PLATFORM_LINUX),
 334 
 335         LINUX_PACKAGE_DEPENDENCIES ("linux-package-deps",
 336                 OptionCategories.PLATFORM_LINUX),
 337 
 338         LINUX_SHORTCUT_HINT ("linux-shortcut",
 339                 OptionCategories.PLATFORM_LINUX, () -> {
 340             setOptionValue("linux-shortcut", true);
 341         }),
 342 
 343         LINUX_MENU_GROUP ("linux-menu-group", OptionCategories.PLATFORM_LINUX);
 344 
 345         private final String id;
 346         private final String shortId;
 347         private final OptionCategories category;
 348         private final ArgAction action;
 349         private static Arguments argContext;
 350 
 351         private CLIOptions(String id, OptionCategories category) {
 352             this(id, null, category, null);
 353         }
 354 
 355         private CLIOptions(String id, String shortId,
 356                            OptionCategories category) {
 357             this(id, shortId, category, null);
 358         }
 359 
 360         private CLIOptions(String id,
 361                 OptionCategories category, ArgAction action) {
 362             this(id, null, category, action);
 363         }
 364 
 365         private CLIOptions(String id, String shortId,
 366                            OptionCategories category, ArgAction action) {
 367             this.id = id;
 368             this.shortId = shortId;
 369             this.action = action;
 370             this.category = category;
 371         }
 372 
 373         static void setContext(Arguments context) {
 374             argContext = context;
 375         }
 376 
 377         public static Arguments context() {
 378             if (argContext != null) {
 379                 return argContext;
 380             } else {
 381                 throw new RuntimeException("Argument context is not set.");
 382             }
 383         }
 384 
 385         public String getId() {
 386             return this.id;
 387         }
 388 
 389         String getIdWithPrefix() {
 390             return "--" + this.id;
 391         }
 392 
 393         String getShortIdWithPrefix() {
 394             return this.shortId == null ? null : "-" + this.shortId;
 395         }
 396 
 397         void execute() {
 398             if (action != null) {
 399                 action.execute();
 400             } else {
 401                 defaultAction();
 402             }
 403         }
 404 
 405         private void defaultAction() {
 406             context().deployParams.addBundleArgument(id, popArg());
 407         }
 408 
 409         private static void setOptionValue(String option, Object value) {
 410             context().deployParams.addBundleArgument(option, value);
 411         }
 412 
 413         private static String popArg() {
 414             nextArg();
 415             return (context().pos >= context().argList.size()) ?
 416                             "" : context().argList.get(context().pos);
 417         }
 418 
 419         private static String getArg() {
 420             return (context().pos >= context().argList.size()) ?
 421                         "" : context().argList.get(context().pos);
 422         }
 423 
 424         private static void nextArg() {
 425             context().pos++;
 426         }
 427 
 428         private static boolean hasNextArg() {
 429             return context().pos < context().argList.size();
 430         }
 431     }
 432 
 433     enum OptionCategories {
 434         MODULAR,
 435         PROPERTY,
 436         PLATFORM_MAC,
 437         PLATFORM_WIN,
 438         PLATFORM_LINUX;
 439     }
 440 
 441     public boolean processArguments() {
 442         try {
 443 
 444             // init context of arguments
 445             CLIOptions.setContext(this);
 446 
 447             // parse cmd line
 448             String arg;
 449             CLIOptions option;
 450             for (; CLIOptions.hasNextArg(); CLIOptions.nextArg()) {
 451                 arg = CLIOptions.getArg();
 452                 if ((option = toCLIOption(arg)) != null) {
 453                     // found a CLI option
 454                     allOptions.add(option);
 455                     option.execute();
 456                 } else {
 457                     throw new PackagerException("ERR_InvalidOption", arg);
 458                 }
 459             }
 460 
 461             if (hasMainJar && !hasMainClass) {
 462                 // try to get main-class from manifest
 463                 String mainClass = getMainClassFromManifest();
 464                 if (mainClass != null) {
 465                     CLIOptions.setOptionValue(
 466                             CLIOptions.APPCLASS.getId(), mainClass);
 467                 }
 468             }
 469 
 470             // display error for arguments that are not supported
 471             // for current configuration.
 472 
 473             validateArguments();
 474 
 475             addResources(deployParams, input, mainJarPath);
 476 
 477             List<Map<String, ? super Object>> launchersAsMap =
 478                     new ArrayList<>();
 479 
 480             for (AddLauncherArguments sl : addLaunchers) {
 481                 launchersAsMap.add(sl.getLauncherMap());
 482             }
 483 
 484             deployParams.addBundleArgument(
 485                     StandardBundlerParam.ADD_LAUNCHERS.getID(),
 486                     launchersAsMap);
 487 
 488             // at this point deployParams should be already configured
 489 
 490             deployParams.validate();
 491 
 492             BundleParams bp = deployParams.getBundleParams();
 493 
 494             // validate name(s)
 495             ArrayList<String> usedNames = new ArrayList<String>();
 496             usedNames.add(bp.getName()); // add main app name
 497 
 498             for (AddLauncherArguments sl : addLaunchers) {
 499                 Map<String, ? super Object> slMap = sl.getLauncherMap();
 500                 String slName =
 501                         (String) slMap.get(Arguments.CLIOptions.NAME.getId());
 502                 if (slName == null) {
 503                     throw new PackagerException("ERR_NoAddLauncherName");
 504                 }
 505                 // same rules apply to additional launcher names as app name
 506                 DeployParams.validateName(slName, false);
 507                 for (String usedName : usedNames) {
 508                     if (slName.equals(usedName)) {
 509                         throw new PackagerException("ERR_NoUniqueName");
 510                     }
 511                 }
 512                 usedNames.add(slName);
 513             }
 514             if (runtimeInstaller && bp.getName() == null) {
 515                 throw new PackagerException("ERR_NoJreInstallerName");
 516             }
 517 
 518             generateBundle(bp.getBundleParamsAsMap());
 519             return true;
 520         } catch (Exception e) {
 521             if (Log.isVerbose()) {
 522                 Log.verbose(e);
 523             } else {
 524                 String msg1 = e.getMessage();
 525                 Log.error(msg1);
 526                 if (e.getCause() != null && e.getCause() != e) {
 527                     String msg2 = e.getCause().getMessage();
 528                     if (msg2 != null && !msg1.contains(msg2)) {
 529                         Log.error(msg2);
 530                     }
 531                 }
 532             }
 533             return false;
 534         }
 535     }
 536 
 537     private void validateArguments() throws PackagerException {
 538         String type = deployParams.getTargetFormat();
 539         String ptype = (type != null) ? type : "default";
 540         boolean imageOnly = deployParams.isTargetAppImage();
 541         boolean hasAppImage = allOptions.contains(
 542                 CLIOptions.PREDEFINED_APP_IMAGE);
 543         boolean hasRuntime = allOptions.contains(
 544                 CLIOptions.PREDEFINED_RUNTIME_IMAGE);
 545         boolean installerOnly = !imageOnly && hasAppImage;
 546         runtimeInstaller = !imageOnly && hasRuntime && !hasAppImage &&
 547                 !hasMainModule && !hasMainJar;
 548 
 549         for (CLIOptions option : allOptions) {
 550             if (!ValidOptions.checkIfSupported(option)) {
 551                 // includes option valid only on different platform
 552                 throw new PackagerException("ERR_UnsupportedOption",
 553                         option.getIdWithPrefix());
 554             }
 555             if (imageOnly) {
 556                 if (!ValidOptions.checkIfImageSupported(option)) {
 557                     throw new PackagerException("ERR_InvalidTypeOption",
 558                         option.getIdWithPrefix(), type);
 559                 }
 560             } else if (installerOnly || runtimeInstaller) {
 561                 if (!ValidOptions.checkIfInstallerSupported(option)) {
 562                     if (runtimeInstaller) {
 563                         throw new PackagerException("ERR_NoInstallerEntryPoint",
 564                             option.getIdWithPrefix());
 565                     } else {
 566                         throw new PackagerException("ERR_InvalidTypeOption",
 567                             option.getIdWithPrefix(), ptype);
 568                    }
 569                 }
 570             }
 571         }
 572         if (installerOnly && hasRuntime) {
 573             // note --runtime-image is only for image or runtime installer.
 574             throw new PackagerException("ERR_InvalidTypeOption",
 575                     CLIOptions.PREDEFINED_RUNTIME_IMAGE.getIdWithPrefix(),
 576                     ptype);
 577         }
 578         if (hasMainJar && hasMainModule) {
 579             throw new PackagerException("ERR_BothMainJarAndModule");
 580         }
 581         if (imageOnly && !hasMainJar && !hasMainModule) {
 582             throw new PackagerException("ERR_NoEntryPoint");
 583         }
 584     }
 585 
 586     private jdk.jpackage.internal.Bundler getPlatformBundler() {
 587         boolean appImage = deployParams.isTargetAppImage();
 588         String type = deployParams.getTargetFormat();
 589         String bundleType = (appImage ?  "IMAGE" : "INSTALLER");
 590 
 591         for (jdk.jpackage.internal.Bundler bundler :
 592                 Bundlers.createBundlersInstance().getBundlers(bundleType)) {
 593             if (type == null) {
 594                  if (bundler.isDefault()
 595                          && bundler.supported(runtimeInstaller)) {
 596                      return bundler;
 597                  }
 598             } else {
 599                  if ((appImage || type.equalsIgnoreCase(bundler.getID()))
 600                          && bundler.supported(runtimeInstaller)) {
 601                      return bundler;
 602                  }
 603             }
 604         }
 605         return null;
 606     }
 607 
 608     private void generateBundle(Map<String,? super Object> params)
 609             throws PackagerException {
 610 
 611         boolean bundleCreated = false;
 612 
 613         // the temp dir needs to be fetched from the params early,
 614         // to prevent each copy of the params (such as may be used for
 615         // additional launchers) from generating a separate temp dir when
 616         // the default is used (the default is a new temp directory)
 617         // The bundler.cleanup() below would not otherwise be able to
 618         // clean these extra (and unneeded) temp directories.
 619         StandardBundlerParam.TEMP_ROOT.fetchFrom(params);
 620 
 621         // determine what bundler to run
 622         jdk.jpackage.internal.Bundler bundler = getPlatformBundler();
 623 
 624         if (bundler == null) {
 625             throw new PackagerException("ERR_InvalidInstallerType",
 626                       deployParams.getTargetFormat());
 627         }
 628 
 629         Map<String, ? super Object> localParams = new HashMap<>(params);
 630         try {
 631             bundler.validate(localParams);
 632             File result = bundler.execute(localParams, deployParams.outdir);
 633             if (result == null) {
 634                 throw new PackagerException("MSG_BundlerFailed",
 635                         bundler.getID(), bundler.getName());
 636             }
 637             Log.verbose(MessageFormat.format(
 638                     I18N.getString("message.bundle-created"),
 639                     bundler.getName()));
 640         } catch (ConfigException e) {
 641             Log.verbose(e);
 642             if (e.getAdvice() != null)  {
 643                 throw new PackagerException(e, "MSG_BundlerConfigException",
 644                         bundler.getName(), e.getMessage(), e.getAdvice());
 645             } else {
 646                 throw new PackagerException(e,
 647                        "MSG_BundlerConfigExceptionNoAdvice",
 648                         bundler.getName(), e.getMessage());
 649             }
 650         } catch (RuntimeException re) {
 651             Log.verbose(re);
 652             throw new PackagerException(re, "MSG_BundlerRuntimeException",
 653                     bundler.getName(), re.toString());
 654         } finally {
 655             if (userProvidedBuildRoot) {
 656                 Log.verbose(MessageFormat.format(
 657                         I18N.getString("message.debug-working-directory"),
 658                         (new File(buildRoot)).getAbsolutePath()));
 659             } else {
 660                 // always clean up the temporary directory created
 661                 // when --temp option not used.
 662                 bundler.cleanup(localParams);
 663             }
 664         }
 665     }
 666 
 667     private void addResources(DeployParams deployParams,
 668             String inputdir, String mainJar) throws PackagerException {
 669 
 670         if (inputdir == null || inputdir.isEmpty()) {
 671             return;
 672         }
 673 
 674         File baseDir = new File(inputdir);
 675 
 676         if (!baseDir.isDirectory()) {
 677             throw new PackagerException("ERR_InputNotDirectory", inputdir);
 678         }
 679         if (!baseDir.canRead()) {
 680             throw new PackagerException("ERR_CannotReadInputDir", inputdir);
 681         }
 682 
 683         List<String> fileNames;
 684         fileNames = new ArrayList<>();
 685         try (Stream<Path> files = Files.list(baseDir.toPath())) {
 686             files.forEach(file -> fileNames.add(
 687                     file.getFileName().toString()));
 688         } catch (IOException e) {
 689             Log.error("Unable to add resources: " + e.getMessage());
 690         }
 691         fileNames.forEach(file -> deployParams.addResource(baseDir, file));
 692 
 693         deployParams.setClasspath(mainJar);
 694     }
 695 
 696     static CLIOptions toCLIOption(String arg) {
 697         CLIOptions option;
 698         if ((option = argIds.get(arg)) == null) {
 699             option = argShortIds.get(arg);
 700         }
 701         return option;
 702     }
 703 
 704     static Map<String, String> getPropertiesFromFile(String filename) {
 705         Map<String, String> map = new HashMap<>();
 706         // load properties file
 707         File file = new File(filename);
 708         Properties properties = new Properties();
 709         try (FileInputStream in = new FileInputStream(file)) {
 710             properties.load(in);
 711         } catch (IOException e) {
 712             Log.error("Exception: " + e.getMessage());
 713         }
 714 
 715         for (final String name: properties.stringPropertyNames()) {
 716             map.put(name, properties.getProperty(name));
 717         }
 718 
 719         return map;
 720     }
 721 
 722     static List<String> getArgumentList(String inputString) {
 723         List<String> list = new ArrayList<>();
 724         if (inputString == null || inputString.isEmpty()) {
 725              return list;
 726         }
 727 
 728         // The "pattern" regexp attempts to abide to the rule that
 729         // strings are delimited by whitespace unless surrounded by
 730         // quotes, then it is anything (including spaces) in the quotes.
 731         Matcher m = pattern.matcher(inputString);
 732         while (m.find()) {
 733             String s = inputString.substring(m.start(), m.end()).trim();
 734             // Ensure we do not have an empty string. trim() will take care of
 735             // whitespace only strings. The regex preserves quotes and escaped
 736             // chars so we need to clean them before adding to the List
 737             if (!s.isEmpty()) {
 738                 list.add(unquoteIfNeeded(s));
 739             }
 740         }
 741         return list;
 742     }
 743 
 744     private static String unquoteIfNeeded(String in) {
 745         if (in == null) {
 746             return null;
 747         }
 748 
 749         if (in.isEmpty()) {
 750             return "";
 751         }
 752 
 753         // Use code points to preserve non-ASCII chars
 754         StringBuilder sb = new StringBuilder();
 755         int codeLen = in.codePointCount(0, in.length());
 756         int quoteChar = -1;
 757         for (int i = 0; i < codeLen; i++) {
 758             int code = in.codePointAt(i);
 759             if (code == '"' || code == '\'') {
 760                 // If quote is escaped make sure to copy it
 761                 if (i > 0 && in.codePointAt(i - 1) == '\\') {
 762                     sb.deleteCharAt(sb.length() - 1);
 763                     sb.appendCodePoint(code);
 764                     continue;
 765                 }
 766                 if (quoteChar != -1) {
 767                     if (code == quoteChar) {
 768                         // close quote, skip char
 769                         quoteChar = -1;
 770                     } else {
 771                         sb.appendCodePoint(code);
 772                     }
 773                 } else {
 774                     // opening quote, skip char
 775                     quoteChar = code;
 776                 }
 777             } else {
 778                 sb.appendCodePoint(code);
 779             }
 780         }
 781         return sb.toString();
 782     }
 783 
 784     private String getMainClassFromManifest() {
 785         if (mainJarPath == null ||
 786             input == null ) {
 787             return null;
 788         }
 789 
 790         JarFile jf;
 791         try {
 792             File file = new File(input, mainJarPath);
 793             if (!file.exists()) {
 794                 return null;
 795             }
 796             jf = new JarFile(file);
 797             Manifest m = jf.getManifest();
 798             Attributes attrs = (m != null) ? m.getMainAttributes() : null;
 799             if (attrs != null) {
 800                 return attrs.getValue(Attributes.Name.MAIN_CLASS);
 801             }
 802         } catch (IOException ignore) {}
 803         return null;
 804     }
 805 
 806 }