1 /*
   2  * Copyright (c) 2015, 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 
  26 package jdk.jpackage.internal;
  27 
  28 import java.io.BufferedWriter;
  29 import java.io.File;
  30 import java.io.FileInputStream;
  31 import java.io.FileOutputStream;
  32 import java.io.FileWriter;
  33 import java.io.IOException;
  34 import java.io.InputStream;
  35 import java.io.OutputStream;
  36 import java.io.OutputStreamWriter;
  37 import java.io.UncheckedIOException;
  38 import java.io.Writer;
  39 import java.math.BigInteger;
  40 import java.nio.file.Files;
  41 import java.nio.file.Path;
  42 import java.nio.file.StandardCopyOption;
  43 import java.nio.file.attribute.PosixFilePermission;
  44 import java.text.MessageFormat;
  45 import java.util.ArrayList;
  46 import java.util.Arrays;
  47 import java.util.EnumSet;
  48 import java.util.HashMap;
  49 import java.util.List;
  50 import java.util.Map;
  51 import java.util.Objects;
  52 import java.util.Optional;
  53 import java.util.ResourceBundle;
  54 import java.util.Set;
  55 import java.util.concurrent.atomic.AtomicReference;
  56 import java.util.function.Consumer;
  57 
  58 import static jdk.jpackage.internal.StandardBundlerParam.*;
  59 import static jdk.jpackage.internal.MacBaseInstallerBundler.*;
  60 import static jdk.jpackage.internal.MacAppBundler.*;
  61 
  62 public class MacAppImageBuilder extends AbstractAppImageBuilder {
  63 
  64     private static final ResourceBundle I18N = ResourceBundle.getBundle(
  65             "jdk.jpackage.internal.resources.MacResources");
  66 
  67     private static final String LIBRARY_NAME = "libapplauncher.dylib";
  68     private static final String TEMPLATE_BUNDLE_ICON = "GenericApp.icns";
  69     private static final String OS_TYPE_CODE = "APPL";
  70     private static final String TEMPLATE_INFO_PLIST_LITE =
  71             "Info-lite.plist.template";
  72     private static final String TEMPLATE_RUNTIME_INFO_PLIST =
  73             "Runtime-Info.plist.template";
  74 
  75     private final Path root;
  76     private final Path contentsDir;
  77     private final Path javaDir;
  78     private final Path javaModsDir;
  79     private final Path resourcesDir;
  80     private final Path macOSDir;
  81     private final Path runtimeDir;
  82     private final Path runtimeRoot;
  83     private final Path mdir;
  84 
  85     private final Map<String, ? super Object> params;
  86 
  87     private static List<String> keyChains;
  88 
  89     public static final BundlerParamInfo<Boolean>
  90             MAC_CONFIGURE_LAUNCHER_IN_PLIST = new StandardBundlerParam<>(
  91                     "mac.configure-launcher-in-plist",
  92                     Boolean.class,
  93                     params -> Boolean.FALSE,
  94                     (s, p) -> Boolean.valueOf(s));
  95 
  96     public static final EnumeratedBundlerParam<String> MAC_CATEGORY =
  97             new EnumeratedBundlerParam<>(
  98                     Arguments.CLIOptions.MAC_APP_STORE_CATEGORY.getId(),
  99                     String.class,
 100                     params -> "Unknown",
 101                     (s, p) -> s,
 102                     MacAppBundler.getMacCategories(),
 103                     false //strict - for MacStoreBundler this should be strict
 104             );
 105 
 106     public static final BundlerParamInfo<String> MAC_CF_BUNDLE_NAME =
 107             new StandardBundlerParam<>(
 108                     Arguments.CLIOptions.MAC_BUNDLE_NAME.getId(),
 109                     String.class,
 110                     params -> null,
 111                     (s, p) -> s);
 112 
 113     public static final BundlerParamInfo<String> MAC_CF_BUNDLE_IDENTIFIER =
 114             new StandardBundlerParam<>(
 115                     Arguments.CLIOptions.MAC_BUNDLE_IDENTIFIER.getId(),
 116                     String.class,
 117                     IDENTIFIER::fetchFrom,
 118                     (s, p) -> s);
 119 
 120     public static final BundlerParamInfo<String> MAC_CF_BUNDLE_VERSION =
 121             new StandardBundlerParam<>(
 122                     "mac.CFBundleVersion",
 123                     String.class,
 124                     p -> {
 125                         String s = VERSION.fetchFrom(p);
 126                         if (validCFBundleVersion(s)) {
 127                             return s;
 128                         } else {
 129                             return "100";
 130                         }
 131                     },
 132                     (s, p) -> s);
 133 
 134     public static final BundlerParamInfo<String> DEFAULT_ICNS_ICON =
 135             new StandardBundlerParam<>(
 136             ".mac.default.icns",
 137             String.class,
 138             params -> TEMPLATE_BUNDLE_ICON,
 139             (s, p) -> s);
 140 
 141     public static final BundlerParamInfo<File> ICON_ICNS =
 142             new StandardBundlerParam<>(
 143             "icon.icns",
 144             File.class,
 145             params -> {
 146                 File f = ICON.fetchFrom(params);
 147                 if (f != null && !f.getName().toLowerCase().endsWith(".icns")) {
 148                     Log.error(MessageFormat.format(
 149                             I18N.getString("message.icon-not-icns"), f));
 150                     return null;
 151                 }
 152                 return f;
 153             },
 154             (s, p) -> new File(s));
 155 
 156     public static final StandardBundlerParam<Boolean> SIGN_BUNDLE  =
 157             new StandardBundlerParam<>(
 158             Arguments.CLIOptions.MAC_SIGN.getId(),
 159             Boolean.class,
 160             params -> false,
 161             // valueOf(null) is false, we actually do want null in some cases
 162             (s, p) -> (s == null || "null".equalsIgnoreCase(s)) ?
 163                     null : Boolean.valueOf(s)
 164         );
 165 
 166     public MacAppImageBuilder(Map<String, Object> config, Path imageOutDir)
 167             throws IOException {
 168         super(config, imageOutDir.resolve(APP_NAME.fetchFrom(config)
 169                 + ".app/Contents/runtime/Contents/Home"));
 170 
 171         Objects.requireNonNull(imageOutDir);
 172 
 173         this.params = config;
 174         this.root = imageOutDir.resolve(APP_NAME.fetchFrom(params) + ".app");
 175         this.contentsDir = root.resolve("Contents");
 176         this.javaDir = contentsDir.resolve("Java");
 177         this.javaModsDir = javaDir.resolve("mods");
 178         this.resourcesDir = contentsDir.resolve("Resources");
 179         this.macOSDir = contentsDir.resolve("MacOS");
 180         this.runtimeDir = contentsDir.resolve("runtime");
 181         this.runtimeRoot = runtimeDir.resolve("Contents/Home");
 182         this.mdir = runtimeRoot.resolve("lib");
 183         Files.createDirectories(javaDir);
 184         Files.createDirectories(resourcesDir);
 185         Files.createDirectories(macOSDir);
 186         Files.createDirectories(runtimeDir);
 187     }
 188 
 189     public MacAppImageBuilder(Map<String, Object> config, String jreName,
 190             Path imageOutDir) throws IOException {
 191         super(null, imageOutDir.resolve(jreName + "/Contents/Home"));
 192 
 193         Objects.requireNonNull(imageOutDir);
 194 
 195         this.params = config;
 196         this.root = imageOutDir.resolve(jreName );
 197         this.contentsDir = root.resolve("Contents");
 198         this.javaDir = null;
 199         this.javaModsDir = null;
 200         this.resourcesDir = null;
 201         this.macOSDir = null;
 202         this.runtimeDir = this.root;
 203         this.runtimeRoot = runtimeDir.resolve("Contents/Home");
 204         this.mdir = runtimeRoot.resolve("lib");
 205 
 206         Files.createDirectories(runtimeDir);
 207     }
 208 
 209     private void writeEntry(InputStream in, Path dstFile) throws IOException {
 210         Files.createDirectories(dstFile.getParent());
 211         Files.copy(in, dstFile);
 212     }
 213 
 214     public static boolean validCFBundleVersion(String v) {
 215         // CFBundleVersion (String - iOS, OS X) specifies the build version
 216         // number of the bundle, which identifies an iteration (released or
 217         // unreleased) of the bundle. The build version number should be a
 218         // string comprised of three non-negative, period-separated integers
 219         // with the first integer being greater than zero. The string should
 220         // only contain numeric (0-9) and period (.) characters. Leading zeros
 221         // are truncated from each integer and will be ignored (that is,
 222         // 1.02.3 is equivalent to 1.2.3). This key is not localizable.
 223 
 224         if (v == null) {
 225             return false;
 226         }
 227 
 228         String p[] = v.split("\\.");
 229         if (p.length > 3 || p.length < 1) {
 230             Log.verbose(I18N.getString(
 231                     "message.version-string-too-many-components"));
 232             return false;
 233         }
 234 
 235         try {
 236             BigInteger n = new BigInteger(p[0]);
 237             if (BigInteger.ONE.compareTo(n) > 0) {
 238                 Log.verbose(I18N.getString(
 239                         "message.version-string-first-number-not-zero"));
 240                 return false;
 241             }
 242             if (p.length > 1) {
 243                 n = new BigInteger(p[1]);
 244                 if (BigInteger.ZERO.compareTo(n) > 0) {
 245                     Log.verbose(I18N.getString(
 246                             "message.version-string-no-negative-numbers"));
 247                     return false;
 248                 }
 249             }
 250             if (p.length > 2) {
 251                 n = new BigInteger(p[2]);
 252                 if (BigInteger.ZERO.compareTo(n) > 0) {
 253                     Log.verbose(I18N.getString(
 254                             "message.version-string-no-negative-numbers"));
 255                     return false;
 256                 }
 257             }
 258         } catch (NumberFormatException ne) {
 259             Log.verbose(I18N.getString("message.version-string-numbers-only"));
 260             Log.verbose(ne);
 261             return false;
 262         }
 263 
 264         return true;
 265     }
 266 
 267     @Override
 268     public Path getAppDir() {
 269         return javaDir;
 270     }
 271 
 272     @Override
 273     public Path getAppModsDir() {
 274         return javaModsDir;
 275     }
 276 
 277     @Override
 278     public void prepareApplicationFiles() throws IOException {
 279         Map<String, ? super Object> originalParams = new HashMap<>(params);
 280         // Generate PkgInfo
 281         File pkgInfoFile = new File(contentsDir.toFile(), "PkgInfo");
 282         pkgInfoFile.createNewFile();
 283         writePkgInfo(pkgInfoFile);
 284 
 285         Path executable = macOSDir.resolve(getLauncherName(params));
 286 
 287         // create the main app launcher
 288         try (InputStream is_launcher =
 289                 getResourceAsStream("jpackageapplauncher");
 290             InputStream is_lib = getResourceAsStream(LIBRARY_NAME)) {
 291             // Copy executable and library to MacOS folder
 292             writeEntry(is_launcher, executable);
 293             writeEntry(is_lib, macOSDir.resolve(LIBRARY_NAME));
 294         }
 295         executable.toFile().setExecutable(true, false);
 296         // generate main app launcher config file
 297         File cfg = new File(root.toFile(), getLauncherCfgName(params));
 298         writeCfgFile(params, cfg);
 299 
 300         // create additional app launcher(s) and config file(s)
 301         List<Map<String, ? super Object>> entryPoints =
 302                 StandardBundlerParam.ADD_LAUNCHERS.fetchFrom(params);
 303         for (Map<String, ? super Object> entryPoint : entryPoints) {
 304             Map<String, ? super Object> tmp =
 305                     AddLauncherArguments.merge(originalParams, entryPoint);
 306 
 307             // add executable for add launcher
 308             Path addExecutable = macOSDir.resolve(getLauncherName(tmp));
 309             try (InputStream is = getResourceAsStream("jpackageapplauncher");) {
 310                 writeEntry(is, addExecutable);
 311             }
 312             addExecutable.toFile().setExecutable(true, false);
 313 
 314             // add config file for add launcher
 315             cfg = new File(root.toFile(), getLauncherCfgName(tmp));
 316             writeCfgFile(tmp, cfg);
 317         }
 318 
 319         // Copy class path entries to Java folder
 320         copyClassPathEntries(javaDir);
 321 
 322         /*********** Take care of "config" files *******/
 323         File icon = ICON_ICNS.fetchFrom(params);
 324 
 325         InputStream in = locateResource(
 326                 APP_NAME.fetchFrom(params) + ".icns",
 327                 "icon",
 328                 DEFAULT_ICNS_ICON.fetchFrom(params),
 329                 icon,
 330                 VERBOSE.fetchFrom(params),
 331                 RESOURCE_DIR.fetchFrom(params));
 332         Files.copy(in,
 333                 resourcesDir.resolve(APP_NAME.fetchFrom(params) + ".icns"),
 334                 StandardCopyOption.REPLACE_EXISTING);
 335 
 336         // copy file association icons
 337         for (Map<String, ?
 338                 super Object> fa : FILE_ASSOCIATIONS.fetchFrom(params)) {
 339             File f = FA_ICON.fetchFrom(fa);
 340             if (f != null && f.exists()) {
 341                 try (InputStream in2 = new FileInputStream(f)) {
 342                     Files.copy(in2, resourcesDir.resolve(f.getName()));
 343                 }
 344 
 345             }
 346         }
 347 
 348         copyRuntimeFiles();
 349         sign();
 350     }
 351 
 352     @Override
 353     public void prepareJreFiles() throws IOException {
 354         copyRuntimeFiles();
 355         sign();
 356     }
 357 
 358     private void copyRuntimeFiles() throws IOException {
 359         // Generate Info.plist
 360         writeInfoPlist(contentsDir.resolve("Info.plist").toFile());
 361 
 362         // generate java runtime info.plist
 363         writeRuntimeInfoPlist(
 364                 runtimeDir.resolve("Contents/Info.plist").toFile());
 365 
 366         // copy library
 367         Path runtimeMacOSDir = Files.createDirectories(
 368                 runtimeDir.resolve("Contents/MacOS"));
 369 
 370         // JDK 9, 10, and 11 have extra '/jli/' subdir
 371         Path jli = runtimeRoot.resolve("lib/libjli.dylib");
 372         if (!Files.exists(jli)) {
 373             jli = runtimeRoot.resolve("lib/jli/libjli.dylib");
 374         }
 375 
 376         Files.copy(jli, runtimeMacOSDir.resolve("libjli.dylib"));
 377     }
 378 
 379     private void sign() throws IOException {
 380         if (Optional.ofNullable(
 381                 SIGN_BUNDLE.fetchFrom(params)).orElse(Boolean.TRUE)) {
 382             try {
 383                 addNewKeychain(params);
 384             } catch (InterruptedException e) {
 385                 Log.error(e.getMessage());
 386             }
 387             String signingIdentity =
 388                     DEVELOPER_ID_APP_SIGNING_KEY.fetchFrom(params);
 389             if (signingIdentity != null) {
 390                 signAppBundle(params, root, signingIdentity,
 391                         BUNDLE_ID_SIGNING_PREFIX.fetchFrom(params), null, null);
 392             }
 393             restoreKeychainList(params);
 394         }
 395     }
 396 
 397     private String getLauncherName(Map<String, ? super Object> params) {
 398         if (APP_NAME.fetchFrom(params) != null) {
 399             return APP_NAME.fetchFrom(params);
 400         } else {
 401             return MAIN_CLASS.fetchFrom(params);
 402         }
 403     }
 404 
 405     public static String getLauncherCfgName(
 406             Map<String, ? super Object> params) {
 407         return "Contents/Java/" + APP_NAME.fetchFrom(params) + ".cfg";
 408     }
 409 
 410     private void copyClassPathEntries(Path javaDirectory) throws IOException {
 411         List<RelativeFileSet> resourcesList =
 412                 APP_RESOURCES_LIST.fetchFrom(params);
 413         if (resourcesList == null) {
 414             throw new RuntimeException(
 415                     I18N.getString("message.null-classpath"));
 416         }
 417 
 418         for (RelativeFileSet classPath : resourcesList) {
 419             File srcdir = classPath.getBaseDirectory();
 420             for (String fname : classPath.getIncludedFiles()) {
 421                 copyEntry(javaDirectory, srcdir, fname);
 422             }
 423         }
 424     }
 425 
 426     private String getBundleName(Map<String, ? super Object> params) {
 427         if (MAC_CF_BUNDLE_NAME.fetchFrom(params) != null) {
 428             String bn = MAC_CF_BUNDLE_NAME.fetchFrom(params);
 429             if (bn.length() > 16) {
 430                 Log.error(MessageFormat.format(I18N.getString(
 431                         "message.bundle-name-too-long-warning"),
 432                         MAC_CF_BUNDLE_NAME.getID(), bn));
 433             }
 434             return MAC_CF_BUNDLE_NAME.fetchFrom(params);
 435         } else if (APP_NAME.fetchFrom(params) != null) {
 436             return APP_NAME.fetchFrom(params);
 437         } else {
 438             String nm = MAIN_CLASS.fetchFrom(params);
 439             if (nm.length() > 16) {
 440                 nm = nm.substring(0, 16);
 441             }
 442             return nm;
 443         }
 444     }
 445 
 446     private void writeRuntimeInfoPlist(File file) throws IOException {
 447         Map<String, String> data = new HashMap<>();
 448         String identifier = StandardBundlerParam.isRuntimeInstaller(params) ?
 449                 MAC_CF_BUNDLE_IDENTIFIER.fetchFrom(params) :
 450                 "com.oracle.java." + MAC_CF_BUNDLE_IDENTIFIER.fetchFrom(params);
 451         data.put("CF_BUNDLE_IDENTIFIER", identifier);
 452         String name = StandardBundlerParam.isRuntimeInstaller(params) ?
 453                 getBundleName(params): "Java Runtime Image";
 454         data.put("CF_BUNDLE_NAME", name);
 455         data.put("CF_BUNDLE_VERSION", VERSION.fetchFrom(params));
 456         data.put("CF_BUNDLE_SHORT_VERSION_STRING", VERSION.fetchFrom(params));
 457 
 458         try (Writer w = Files.newBufferedWriter(file.toPath())) {
 459             w.write(preprocessTextResource("Runtime-Info.plist",
 460                     I18N.getString("resource.runtime-info-plist"),
 461                     TEMPLATE_RUNTIME_INFO_PLIST,
 462                     data,
 463                     VERBOSE.fetchFrom(params),
 464                     RESOURCE_DIR.fetchFrom(params)));
 465         }
 466     }
 467 
 468     private void writeInfoPlist(File file) throws IOException {
 469         Log.verbose(MessageFormat.format(I18N.getString(
 470                 "message.preparing-info-plist"), file.getAbsolutePath()));
 471 
 472         //prepare config for exe
 473         //Note: do not need CFBundleDisplayName if we don't support localization
 474         Map<String, String> data = new HashMap<>();
 475         data.put("DEPLOY_ICON_FILE", APP_NAME.fetchFrom(params) + ".icns");
 476         data.put("DEPLOY_BUNDLE_IDENTIFIER",
 477                 MAC_CF_BUNDLE_IDENTIFIER.fetchFrom(params));
 478         data.put("DEPLOY_BUNDLE_NAME",
 479                 getBundleName(params));
 480         data.put("DEPLOY_BUNDLE_COPYRIGHT",
 481                 COPYRIGHT.fetchFrom(params) != null ?
 482                 COPYRIGHT.fetchFrom(params) : "Unknown");
 483         data.put("DEPLOY_LAUNCHER_NAME", getLauncherName(params));
 484         data.put("DEPLOY_JAVA_RUNTIME_NAME", getCfgRuntimeDir());
 485         data.put("DEPLOY_BUNDLE_SHORT_VERSION",
 486                 VERSION.fetchFrom(params) != null ?
 487                 VERSION.fetchFrom(params) : "1.0.0");
 488         data.put("DEPLOY_BUNDLE_CFBUNDLE_VERSION",
 489                 MAC_CF_BUNDLE_VERSION.fetchFrom(params) != null ?
 490                 MAC_CF_BUNDLE_VERSION.fetchFrom(params) : "100");
 491         data.put("DEPLOY_BUNDLE_CATEGORY", MAC_CATEGORY.fetchFrom(params));
 492 
 493         boolean hasMainJar = MAIN_JAR.fetchFrom(params) != null;
 494         boolean hasMainModule =
 495                 StandardBundlerParam.MODULE.fetchFrom(params) != null;
 496 
 497         if (hasMainJar) {
 498             data.put("DEPLOY_MAIN_JAR_NAME", MAIN_JAR.fetchFrom(params).
 499                     getIncludedFiles().iterator().next());
 500         }
 501         else if (hasMainModule) {
 502             data.put("DEPLOY_MODULE_NAME",
 503                     StandardBundlerParam.MODULE.fetchFrom(params));
 504         }
 505 
 506         StringBuilder sb = new StringBuilder();
 507         List<String> jvmOptions = JAVA_OPTIONS.fetchFrom(params);
 508 
 509         String newline = ""; //So we don't add extra line after last append
 510         for (String o : jvmOptions) {
 511             sb.append(newline).append(
 512                     "    <string>").append(o).append("</string>");
 513             newline = "\n";
 514         }
 515 
 516         data.put("DEPLOY_JAVA_OPTIONS", sb.toString());
 517 
 518         sb = new StringBuilder();
 519         List<String> args = ARGUMENTS.fetchFrom(params);
 520         newline = "";
 521         // So we don't add unneccessary extra line after last append
 522 
 523         for (String o : args) {
 524             sb.append(newline).append("    <string>").append(o).append(
 525                     "</string>");
 526             newline = "\n";
 527         }
 528         data.put("DEPLOY_ARGUMENTS", sb.toString());
 529 
 530         newline = "";
 531 
 532         data.put("DEPLOY_LAUNCHER_CLASS", MAIN_CLASS.fetchFrom(params));
 533 
 534         data.put("DEPLOY_APP_CLASSPATH",
 535                   getCfgClassPath(CLASSPATH.fetchFrom(params)));
 536 
 537         StringBuilder bundleDocumentTypes = new StringBuilder();
 538         StringBuilder exportedTypes = new StringBuilder();
 539         for (Map<String, ? super Object>
 540                 fileAssociation : FILE_ASSOCIATIONS.fetchFrom(params)) {
 541 
 542             List<String> extensions = FA_EXTENSIONS.fetchFrom(fileAssociation);
 543 
 544             if (extensions == null) {
 545                 Log.verbose(I18N.getString(
 546                         "message.creating-association-with-null-extension"));
 547             }
 548 
 549             List<String> mimeTypes = FA_CONTENT_TYPE.fetchFrom(fileAssociation);
 550             String itemContentType = MAC_CF_BUNDLE_IDENTIFIER.fetchFrom(params)
 551                     + "." + ((extensions == null || extensions.isEmpty())
 552                     ? "mime" : extensions.get(0));
 553             String description = FA_DESCRIPTION.fetchFrom(fileAssociation);
 554             File icon = FA_ICON.fetchFrom(fileAssociation);
 555 
 556             bundleDocumentTypes.append("    <dict>\n")
 557                     .append("      <key>LSItemContentTypes</key>\n")
 558                     .append("      <array>\n")
 559                     .append("        <string>")
 560                     .append(itemContentType)
 561                     .append("</string>\n")
 562                     .append("      </array>\n")
 563                     .append("\n")
 564                     .append("      <key>CFBundleTypeName</key>\n")
 565                     .append("      <string>")
 566                     .append(description)
 567                     .append("</string>\n")
 568                     .append("\n")
 569                     .append("      <key>LSHandlerRank</key>\n")
 570                     .append("      <string>Owner</string>\n")
 571                             // TODO make a bundler arg
 572                     .append("\n")
 573                     .append("      <key>CFBundleTypeRole</key>\n")
 574                     .append("      <string>Editor</string>\n")
 575                             // TODO make a bundler arg
 576                     .append("\n")
 577                     .append("      <key>LSIsAppleDefaultForType</key>\n")
 578                     .append("      <true/>\n")
 579                             // TODO make a bundler arg
 580                     .append("\n");
 581 
 582             if (icon != null && icon.exists()) {
 583                 bundleDocumentTypes
 584                         .append("      <key>CFBundleTypeIconFile</key>\n")
 585                         .append("      <string>")
 586                         .append(icon.getName())
 587                         .append("</string>\n");
 588             }
 589             bundleDocumentTypes.append("    </dict>\n");
 590 
 591             exportedTypes.append("    <dict>\n")
 592                     .append("      <key>UTTypeIdentifier</key>\n")
 593                     .append("      <string>")
 594                     .append(itemContentType)
 595                     .append("</string>\n")
 596                     .append("\n")
 597                     .append("      <key>UTTypeDescription</key>\n")
 598                     .append("      <string>")
 599                     .append(description)
 600                     .append("</string>\n")
 601                     .append("      <key>UTTypeConformsTo</key>\n")
 602                     .append("      <array>\n")
 603                     .append("          <string>public.data</string>\n")
 604                             //TODO expose this?
 605                     .append("      </array>\n")
 606                     .append("\n");
 607 
 608             if (icon != null && icon.exists()) {
 609                 exportedTypes.append("      <key>UTTypeIconFile</key>\n")
 610                         .append("      <string>")
 611                         .append(icon.getName())
 612                         .append("</string>\n")
 613                         .append("\n");
 614             }
 615 
 616             exportedTypes.append("\n")
 617                     .append("      <key>UTTypeTagSpecification</key>\n")
 618                     .append("      <dict>\n")
 619                             // TODO expose via param? .append(
 620                             // "        <key>com.apple.ostype</key>\n");
 621                             // TODO expose via param? .append(
 622                             // "        <string>ABCD</string>\n")
 623                     .append("\n");
 624 
 625             if (extensions != null && !extensions.isEmpty()) {
 626                 exportedTypes.append(
 627                         "        <key>public.filename-extension</key>\n")
 628                         .append("        <array>\n");
 629 
 630                 for (String ext : extensions) {
 631                     exportedTypes.append("          <string>")
 632                             .append(ext)
 633                             .append("</string>\n");
 634                 }
 635                 exportedTypes.append("        </array>\n");
 636             }
 637             if (mimeTypes != null && !mimeTypes.isEmpty()) {
 638                 exportedTypes.append("        <key>public.mime-type</key>\n")
 639                         .append("        <array>\n");
 640 
 641                 for (String mime : mimeTypes) {
 642                     exportedTypes.append("          <string>")
 643                             .append(mime)
 644                             .append("</string>\n");
 645                 }
 646                 exportedTypes.append("        </array>\n");
 647             }
 648             exportedTypes.append("      </dict>\n")
 649                     .append("    </dict>\n");
 650         }
 651         String associationData;
 652         if (bundleDocumentTypes.length() > 0) {
 653             associationData =
 654                     "\n  <key>CFBundleDocumentTypes</key>\n  <array>\n"
 655                     + bundleDocumentTypes.toString()
 656                     + "  </array>\n\n"
 657                     + "  <key>UTExportedTypeDeclarations</key>\n  <array>\n"
 658                     + exportedTypes.toString()
 659                     + "  </array>\n";
 660         } else {
 661             associationData = "";
 662         }
 663         data.put("DEPLOY_FILE_ASSOCIATIONS", associationData);
 664 
 665 
 666         try (Writer w = Files.newBufferedWriter(file.toPath())) {
 667             w.write(preprocessTextResource(
 668                     // getConfig_InfoPlist(params).getName(),
 669                     "Info.plist",
 670                     I18N.getString("resource.app-info-plist"),
 671                     TEMPLATE_INFO_PLIST_LITE,
 672                     data, VERBOSE.fetchFrom(params),
 673                     RESOURCE_DIR.fetchFrom(params)));
 674         }
 675     }
 676 
 677     private void writePkgInfo(File file) throws IOException {
 678         //hardcoded as it does not seem we need to change it ever
 679         String signature = "????";
 680 
 681         try (Writer out = Files.newBufferedWriter(file.toPath())) {
 682             out.write(OS_TYPE_CODE + signature);
 683             out.flush();
 684         }
 685     }
 686 
 687     public static void addNewKeychain(Map<String, ? super Object> params)
 688                                     throws IOException, InterruptedException {
 689         if (Platform.getMajorVersion() < 10 ||
 690                 (Platform.getMajorVersion() == 10 &&
 691                 Platform.getMinorVersion() < 12)) {
 692             // we need this for OS X 10.12+
 693             return;
 694         }
 695 
 696         String keyChain = SIGNING_KEYCHAIN.fetchFrom(params);
 697         if (keyChain == null || keyChain.isEmpty()) {
 698             return;
 699         }
 700 
 701         // get current keychain list
 702         String keyChainPath = new File (keyChain).getAbsolutePath().toString();
 703         List<String> keychainList = new ArrayList<>();
 704         int ret = IOUtils.getProcessOutput(
 705                 keychainList, "security", "list-keychains");
 706         if (ret != 0) {
 707             Log.error(I18N.getString("message.keychain.error"));
 708             return;
 709         }
 710 
 711         boolean contains = keychainList.stream().anyMatch(
 712                     str -> str.trim().equals("\""+keyChainPath.trim()+"\""));
 713         if (contains) {
 714             // keychain is already added in the search list
 715             return;
 716         }
 717 
 718         keyChains = new ArrayList<>();
 719         // remove "
 720         keychainList.forEach((String s) -> {
 721             String path = s.trim();
 722             if (path.startsWith("\"") && path.endsWith("\"")) {
 723                 path = path.substring(1, path.length()-1);
 724             }
 725             keyChains.add(path);
 726         });
 727 
 728         List<String> args = new ArrayList<>();
 729         args.add("security");
 730         args.add("list-keychains");
 731         args.add("-s");
 732 
 733         args.addAll(keyChains);
 734         args.add(keyChain);
 735 
 736         ProcessBuilder  pb = new ProcessBuilder(args);
 737         IOUtils.exec(pb);
 738     }
 739 
 740     public static void restoreKeychainList(Map<String, ? super Object> params)
 741             throws IOException{
 742         if (Platform.getMajorVersion() < 10 ||
 743                 (Platform.getMajorVersion() == 10 &&
 744                 Platform.getMinorVersion() < 12)) {
 745             // we need this for OS X 10.12+
 746             return;
 747         }
 748 
 749         if (keyChains == null || keyChains.isEmpty()) {
 750             return;
 751         }
 752 
 753         List<String> args = new ArrayList<>();
 754         args.add("security");
 755         args.add("list-keychains");
 756         args.add("-s");
 757 
 758         args.addAll(keyChains);
 759 
 760         ProcessBuilder  pb = new ProcessBuilder(args);
 761         IOUtils.exec(pb);
 762     }
 763 
 764     public static void signAppBundle(
 765             Map<String, ? super Object> params, Path appLocation,
 766             String signingIdentity, String identifierPrefix,
 767             String entitlementsFile, String inheritedEntitlements)
 768             throws IOException {
 769         AtomicReference<IOException> toThrow = new AtomicReference<>();
 770         String appExecutable = "/Contents/MacOS/" + APP_NAME.fetchFrom(params);
 771         String keyChain = SIGNING_KEYCHAIN.fetchFrom(params);
 772 
 773         // sign all dylibs and jars
 774         Files.walk(appLocation)
 775                 // fix permissions
 776                 .peek(path -> {
 777                     try {
 778                         Set<PosixFilePermission> pfp =
 779                             Files.getPosixFilePermissions(path);
 780                         if (!pfp.contains(PosixFilePermission.OWNER_WRITE)) {
 781                             pfp = EnumSet.copyOf(pfp);
 782                             pfp.add(PosixFilePermission.OWNER_WRITE);
 783                             Files.setPosixFilePermissions(path, pfp);
 784                         }
 785                     } catch (IOException e) {
 786                         Log.debug(e);
 787                     }
 788                 })
 789                 .filter(p -> Files.isRegularFile(p) &&
 790                         !(p.toString().contains("/Contents/MacOS/libjli.dylib")
 791                         || p.toString().endsWith(appExecutable))
 792                 ).forEach(p -> {
 793             //noinspection ThrowableResultOfMethodCallIgnored
 794             if (toThrow.get() != null) return;
 795 
 796             // If p is a symlink then skip the signing process.
 797             if (Files.isSymbolicLink(p)) {
 798                 if (VERBOSE.fetchFrom(params)) {
 799                     Log.verbose(MessageFormat.format(I18N.getString(
 800                             "message.ignoring.symlink"), p.toString()));
 801                 }
 802             }
 803             else {
 804                 List<String> args = new ArrayList<>();
 805                 args.addAll(Arrays.asList("codesign",
 806                         "-s", signingIdentity, // sign with this key
 807                         "--prefix", identifierPrefix,
 808                                 // use the identifier as a prefix
 809                         "-vvvv"));
 810                 if (entitlementsFile != null &&
 811                         (p.toString().endsWith(".jar")
 812                                 || p.toString().endsWith(".dylib"))) {
 813                     args.add("--entitlements");
 814                     args.add(entitlementsFile); // entitlements
 815                 } else if (inheritedEntitlements != null &&
 816                         Files.isExecutable(p)) {
 817                     args.add("--entitlements");
 818                     args.add(inheritedEntitlements);
 819                             // inherited entitlements for executable processes
 820                 }
 821                 if (keyChain != null && !keyChain.isEmpty()) {
 822                     args.add("--keychain");
 823                     args.add(keyChain);
 824                 }
 825                 args.add(p.toString());
 826 
 827                 try {
 828                     Set<PosixFilePermission> oldPermissions =
 829                             Files.getPosixFilePermissions(p);
 830                     File f = p.toFile();
 831                     f.setWritable(true, true);
 832 
 833                     ProcessBuilder pb = new ProcessBuilder(args);
 834                     IOUtils.exec(pb);
 835 
 836                     Files.setPosixFilePermissions(p, oldPermissions);
 837                 } catch (IOException ioe) {
 838                     toThrow.set(ioe);
 839                 }
 840             }
 841         });
 842 
 843         IOException ioe = toThrow.get();
 844         if (ioe != null) {
 845             throw ioe;
 846         }
 847 
 848         // sign all runtime and frameworks
 849         Consumer<? super Path> signIdentifiedByPList = path -> {
 850             //noinspection ThrowableResultOfMethodCallIgnored
 851             if (toThrow.get() != null) return;
 852 
 853             try {
 854                 List<String> args = new ArrayList<>();
 855                 args.addAll(Arrays.asList("codesign",
 856                         "-s", signingIdentity, // sign with this key
 857                         "--prefix", identifierPrefix,
 858                                 // use the identifier as a prefix
 859                         "-vvvv"));
 860                 if (keyChain != null && !keyChain.isEmpty()) {
 861                     args.add("--keychain");
 862                     args.add(keyChain);
 863                 }
 864                 args.add(path.toString());
 865                 ProcessBuilder pb = new ProcessBuilder(args);
 866                 IOUtils.exec(pb);
 867 
 868                 args = new ArrayList<>();
 869                 args.addAll(Arrays.asList("codesign",
 870                         "-s", signingIdentity, // sign with this key
 871                         "--prefix", identifierPrefix,
 872                                 // use the identifier as a prefix
 873                         "-vvvv"));
 874                 if (keyChain != null && !keyChain.isEmpty()) {
 875                     args.add("--keychain");
 876                     args.add(keyChain);
 877                 }
 878                 args.add(path.toString()
 879                         + "/Contents/_CodeSignature/CodeResources");
 880                 pb = new ProcessBuilder(args);
 881                 IOUtils.exec(pb);
 882             } catch (IOException e) {
 883                 toThrow.set(e);
 884             }
 885         };
 886 
 887         Path javaPath = appLocation.resolve("Contents/runtime");
 888         if (Files.isDirectory(javaPath)) {
 889             signIdentifiedByPList.accept(javaPath);
 890 
 891             ioe = toThrow.get();
 892             if (ioe != null) {
 893                 throw ioe;
 894             }
 895         }
 896         Path frameworkPath = appLocation.resolve("Contents/Frameworks");
 897         if (Files.isDirectory(frameworkPath)) {
 898             Files.list(frameworkPath)
 899                     .forEach(signIdentifiedByPList);
 900 
 901             ioe = toThrow.get();
 902             if (ioe != null) {
 903                 throw ioe;
 904             }
 905         }
 906 
 907         // sign the app itself
 908         List<String> args = new ArrayList<>();
 909         args.addAll(Arrays.asList("codesign",
 910                 "-s", signingIdentity, // sign with this key
 911                 "-vvvv")); // super verbose output
 912         if (entitlementsFile != null) {
 913             args.add("--entitlements");
 914             args.add(entitlementsFile); // entitlements
 915         }
 916         if (keyChain != null && !keyChain.isEmpty()) {
 917             args.add("--keychain");
 918             args.add(keyChain);
 919         }
 920         args.add(appLocation.toString());
 921 
 922         ProcessBuilder pb =
 923                 new ProcessBuilder(args.toArray(new String[args.size()]));
 924         IOUtils.exec(pb);
 925     }
 926 
 927 }