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.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);
 203             }
 204 
 205             String desc = initialMap.get(FA_DESCRIPTION);
 206             if (desc != null) {
 207                 args.put(StandardBundlerParam.FA_DESCRIPTION.getID(), desc);
 208             }
 209 
 210             String icon = initialMap.get(FA_ICON);
 211             if (icon != null) {
 212                 args.put(StandardBundlerParam.FA_ICON.getID(), icon);
 213             }
 214 
 215             ArrayList<Map<String, ? super Object>> associationList =
 216                 new ArrayList<Map<String, ? super Object>>();
 217 
 218             associationList.add(args);
 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);
 359         }
 360 
 361         private CLIOptions(String id, String shortId,
 362                            OptionCategories category, ArgAction action) {
 363             this.id = id;
 364             this.shortId = shortId;
 365             this.action = 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>();
 492             usedNames.add(bp.getName()); // add main app name
 493 
 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 (hasRuntime) {
 569             if (hasAppImage) {
 570                 // note --runtime-image is only for image or runtime installer.
 571                 throw new PackagerException("ERR_MutuallyExclusiveOptions",
 572                         CLIOptions.PREDEFINED_RUNTIME_IMAGE.getIdWithPrefix(),
 573                         CLIOptions.PREDEFINED_APP_IMAGE.getIdWithPrefix());
 574             }
 575             if (allOptions.contains(CLIOptions.ADD_MODULES)) {
 576                 throw new PackagerException("ERR_MutuallyExclusiveOptions",
 577                         CLIOptions.PREDEFINED_RUNTIME_IMAGE.getIdWithPrefix(),
 578                         CLIOptions.ADD_MODULES.getIdWithPrefix());
 579             }
 580             if (allOptions.contains(CLIOptions.BIND_SERVICES)) {
 581                 throw new PackagerException("ERR_MutuallyExclusiveOptions",
 582                         CLIOptions.PREDEFINED_RUNTIME_IMAGE.getIdWithPrefix(),
 583                         CLIOptions.BIND_SERVICES.getIdWithPrefix());
 584             }
 585 
 586         }
 587         if (hasMainJar && hasMainModule) {
 588             throw new PackagerException("ERR_BothMainJarAndModule");
 589         }
 590         if (imageOnly && !hasMainJar && !hasMainModule) {
 591             throw new PackagerException("ERR_NoEntryPoint");
 592         }
 593     }
 594 
 595     private jdk.incubator.jpackage.internal.Bundler getPlatformBundler() {
 596         boolean appImage = deployParams.isTargetAppImage();
 597         String type = deployParams.getTargetFormat();
 598         String bundleType = (appImage ?  "IMAGE" : "INSTALLER");
 599 
 600         for (jdk.incubator.jpackage.internal.Bundler bundler :
 601                 Bundlers.createBundlersInstance().getBundlers(bundleType)) {
 602             if (type == null) {
 603                  if (bundler.isDefault()
 604                          && bundler.supported(runtimeInstaller)) {
 605                      return bundler;
 606                  }
 607             } else {
 608                  if ((appImage || type.equalsIgnoreCase(bundler.getID()))
 609                          && bundler.supported(runtimeInstaller)) {
 610                      return bundler;
 611                  }
 612             }
 613         }
 614         return null;
 615     }
 616 
 617     private void generateBundle(Map<String,? super Object> params)
 618             throws PackagerException {
 619 
 620         boolean bundleCreated = false;
 621 
 622         // the temp dir needs to be fetched from the params early,
 623         // to prevent each copy of the params (such as may be used for
 624         // additional launchers) from generating a separate temp dir when
 625         // the default is used (the default is a new temp directory)
 626         // The bundler.cleanup() below would not otherwise be able to
 627         // clean these extra (and unneeded) temp directories.
 628         StandardBundlerParam.TEMP_ROOT.fetchFrom(params);
 629 
 630         // determine what bundler to run
 631         jdk.incubator.jpackage.internal.Bundler bundler = getPlatformBundler();
 632 
 633         if (bundler == null) {
 634             throw new PackagerException("ERR_InvalidInstallerType",
 635                       deployParams.getTargetFormat());
 636         }
 637 
 638         Map<String, ? super Object> localParams = new HashMap<>(params);
 639         try {
 640             bundler.validate(localParams);
 641             File result = bundler.execute(localParams, deployParams.outdir);
 642             if (result == null) {
 643                 throw new PackagerException("MSG_BundlerFailed",
 644                         bundler.getID(), bundler.getName());
 645             }
 646             Log.verbose(MessageFormat.format(
 647                     I18N.getString("message.bundle-created"),
 648                     bundler.getName()));
 649         } catch (ConfigException e) {
 650             Log.verbose(e);
 651             if (e.getAdvice() != null)  {
 652                 throw new PackagerException(e, "MSG_BundlerConfigException",
 653                         bundler.getName(), e.getMessage(), e.getAdvice());
 654             } else {
 655                 throw new PackagerException(e,
 656                        "MSG_BundlerConfigExceptionNoAdvice",
 657                         bundler.getName(), e.getMessage());
 658             }
 659         } catch (RuntimeException re) {
 660             Log.verbose(re);
 661             throw new PackagerException(re, "MSG_BundlerRuntimeException",
 662                     bundler.getName(), re.toString());
 663         } finally {
 664             if (userProvidedBuildRoot) {
 665                 Log.verbose(MessageFormat.format(
 666                         I18N.getString("message.debug-working-directory"),
 667                         (new File(buildRoot)).getAbsolutePath()));
 668             } else {
 669                 // always clean up the temporary directory created
 670                 // when --temp option not used.
 671                 bundler.cleanup(localParams);
 672             }
 673         }
 674     }
 675 
 676     private void addResources(DeployParams deployParams,
 677             String inputdir, String mainJar) throws PackagerException {
 678 
 679         if (inputdir == null || inputdir.isEmpty()) {
 680             return;
 681         }
 682 
 683         File baseDir = new File(inputdir);
 684 
 685         if (!baseDir.isDirectory()) {
 686             throw new PackagerException("ERR_InputNotDirectory", inputdir);
 687         }
 688         if (!baseDir.canRead()) {
 689             throw new PackagerException("ERR_CannotReadInputDir", inputdir);
 690         }
 691 
 692         List<String> fileNames;
 693         fileNames = new ArrayList<>();
 694         try (Stream<Path> files = Files.list(baseDir.toPath())) {
 695             files.forEach(file -> fileNames.add(
 696                     file.getFileName().toString()));
 697         } catch (IOException e) {
 698             Log.error("Unable to add resources: " + e.getMessage());
 699         }
 700         fileNames.forEach(file -> deployParams.addResource(baseDir, file));
 701 
 702         deployParams.setClasspath(mainJar);
 703     }
 704 
 705     static CLIOptions toCLIOption(String arg) {
 706         CLIOptions option;
 707         if ((option = argIds.get(arg)) == null) {
 708             option = argShortIds.get(arg);
 709         }
 710         return option;
 711     }
 712 
 713     static Map<String, String> getPropertiesFromFile(String filename) {
 714         Map<String, String> map = new HashMap<>();
 715         // load properties file
 716         File file = new File(filename);
 717         Properties properties = new Properties();
 718         try (FileInputStream in = new FileInputStream(file)) {
 719             properties.load(in);
 720         } catch (IOException e) {
 721             Log.error("Exception: " + e.getMessage());
 722         }
 723 
 724         for (final String name: properties.stringPropertyNames()) {
 725             map.put(name, properties.getProperty(name));
 726         }
 727 
 728         return map;
 729     }
 730 
 731     static List<String> getArgumentList(String inputString) {
 732         List<String> list = new ArrayList<>();
 733         if (inputString == null || inputString.isEmpty()) {
 734              return list;
 735         }
 736 
 737         // The "pattern" regexp attempts to abide to the rule that
 738         // strings are delimited by whitespace unless surrounded by
 739         // quotes, then it is anything (including spaces) in the quotes.
 740         Matcher m = pattern.matcher(inputString);
 741         while (m.find()) {
 742             String s = inputString.substring(m.start(), m.end()).trim();
 743             // Ensure we do not have an empty string. trim() will take care of
 744             // whitespace only strings. The regex preserves quotes and escaped
 745             // chars so we need to clean them before adding to the List
 746             if (!s.isEmpty()) {
 747                 list.add(unquoteIfNeeded(s));
 748             }
 749         }
 750         return list;
 751     }
 752 
 753     private static String unquoteIfNeeded(String in) {
 754         if (in == null) {
 755             return null;
 756         }
 757 
 758         if (in.isEmpty()) {
 759             return "";
 760         }
 761 
 762         // Use code points to preserve non-ASCII chars
 763         StringBuilder sb = new StringBuilder();
 764         int codeLen = in.codePointCount(0, in.length());
 765         int quoteChar = -1;
 766         for (int i = 0; i < codeLen; i++) {
 767             int code = in.codePointAt(i);
 768             if (code == '"' || code == '\'') {
 769                 // If quote is escaped make sure to copy it
 770                 if (i > 0 && in.codePointAt(i - 1) == '\\') {
 771                     sb.deleteCharAt(sb.length() - 1);
 772                     sb.appendCodePoint(code);
 773                     continue;
 774                 }
 775                 if (quoteChar != -1) {
 776                     if (code == quoteChar) {
 777                         // close quote, skip char
 778                         quoteChar = -1;
 779                     } else {
 780                         sb.appendCodePoint(code);
 781                     }
 782                 } else {
 783                     // opening quote, skip char
 784                     quoteChar = code;
 785                 }
 786             } else {
 787                 sb.appendCodePoint(code);
 788             }
 789         }
 790         return sb.toString();
 791     }
 792 
 793     private String getMainClassFromManifest() {
 794         if (mainJarPath == null ||
 795             input == null ) {
 796             return null;
 797         }
 798 
 799         JarFile jf;
 800         try {
 801             File file = new File(input, mainJarPath);
 802             if (!file.exists()) {
 803                 return null;
 804             }
 805             jf = new JarFile(file);
 806             Manifest m = jf.getManifest();
 807             Attributes attrs = (m != null) ? m.getMainAttributes() : null;
 808             if (attrs != null) {
 809                 return attrs.getValue(Attributes.Name.MAIN_CLASS);
 810             }
 811         } catch (IOException ignore) {}
 812         return null;
 813     }
 814 
 815 }