1 /*
   2  * Copyright (c) 2011, 2018, 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.jpackager.internal;
  27 
  28 import jdk.jpackager.internal.bundlers.BundlerType;
  29 import jdk.jpackager.internal.bundlers.BundleParams;
  30 
  31 import java.io.File;
  32 import java.nio.file.Files;
  33 import java.util.ArrayList;
  34 import java.util.Arrays;
  35 import java.util.Collection;
  36 import java.util.LinkedHashMap;
  37 import java.util.LinkedHashSet;
  38 import java.util.LinkedList;
  39 import java.util.List;
  40 import java.util.Map;
  41 import java.util.Set;
  42 import java.util.TreeMap;
  43 import java.util.TreeSet;
  44 
  45 /**
  46  * DeployParams
  47  *
  48  * This class is generated and used in Arguments.processArguments() as
  49  * intermediate step in generating the BundleParams and ultimately the Bundles
  50  */
  51 public class DeployParams {
  52 
  53     final List<RelativeFileSet> resources = new ArrayList<>();
  54 
  55     String id;
  56     String title;
  57     String vendor;
  58     String email;
  59     String description;
  60     String category;
  61     String licenseType;
  62     String copyright;
  63     String version;
  64     Boolean systemWide;
  65     Boolean serviceHint;
  66     Boolean signBundle;
  67     Boolean installdirChooser;
  68     Boolean singleton;
  69 
  70     String applicationClass;
  71 
  72     List<Param> params;
  73     List<String> arguments; //unnamed arguments
  74 
  75     // Java 9 modules support
  76     String addModules = null;
  77     String limitModules = null;
  78     Boolean stripNativeCommands = null;
  79     String modulePath = null;
  80     String module = null;
  81     String debugPort = null;
  82 
  83     boolean jreInstaller = false;
  84 
  85     File outdir = null;
  86 
  87     String appId = null;
  88 
  89     // list of jvm args
  90     // (in theory string can contain spaces and need to be escaped
  91     List<String> jvmargs = new LinkedList<>();
  92 
  93     // list of jvm properties (can also be passed as VM args
  94     // but keeping them separate make it a bit more convinient
  95     Map<String, String> properties = new LinkedHashMap<>();
  96 
  97     // raw arguments to the bundler
  98     Map<String, ? super Object> bundlerArguments = new LinkedHashMap<>();
  99 
 100     public void setId(String id) {
 101         this.id = id;
 102     }
 103 
 104     public void setCategory(String category) {
 105         this.category = category;
 106     }
 107 
 108     public void setLicenseType(String licenseType) {
 109         this.licenseType = licenseType;
 110     }
 111 
 112     public void setCopyright(String copyright) {
 113         this.copyright = copyright;
 114     }
 115 
 116     public void setVersion(String version) {
 117         this.version = version;
 118     }
 119 
 120     public void setSystemWide(Boolean systemWide) {
 121         this.systemWide = systemWide;
 122     }
 123 
 124     public void setServiceHint(Boolean serviceHint) {
 125         this.serviceHint = serviceHint;
 126     }
 127 
 128     public void setInstalldirChooser(Boolean installdirChooser) {
 129         this.installdirChooser = installdirChooser;
 130     }
 131 
 132     public void setSingleton(Boolean singleton) {
 133         this.singleton = singleton;
 134     }
 135 
 136     public void setSignBundle(Boolean signBundle) {
 137         this.signBundle = signBundle;
 138     }
 139 
 140     public void addJvmArg(String v) {
 141         jvmargs.add(v);
 142     }
 143 
 144     public void addJvmProperty(String n, String v) {
 145         properties.put(n, v);
 146     }
 147 
 148     public void setArguments(List<String> args) {
 149         this.arguments = args;
 150     }
 151 
 152     public List<String> getArguments() {
 153         return this.arguments;
 154     }
 155 
 156     public void addArgument(String arg) {
 157         this.arguments.add(arg);
 158     }
 159 
 160     public void addAddModule(String value) {
 161         if (addModules == null) {
 162             addModules = value;
 163         }
 164         else {
 165             addModules += "," + value;
 166         }
 167     }
 168 
 169     public void addLimitModule(String value) {
 170         if (limitModules == null) {
 171             limitModules = value;
 172         }
 173         else {
 174             limitModules += "," + value;
 175         }
 176     }
 177 
 178     public String getModulePath() {
 179         return this.modulePath;
 180     }
 181 
 182     public void setModulePath(String value) {
 183         this.modulePath = value;
 184     }
 185 
 186     public void setModule(String value) {
 187         this.module = value;
 188     }
 189 
 190     public void setDebug(String value) {
 191         this.debugPort = value;
 192     }
 193 
 194     public void setStripNativeCommands(boolean value) {
 195         this.stripNativeCommands = value;
 196     }
 197 
 198     public void setDescription(String description) {
 199         this.description = description;
 200     }
 201 
 202     public void setAppId(String id) {
 203         appId = id;
 204     }
 205 
 206     public void setParams(List<Param> params) {
 207         this.params = params;
 208     }
 209 
 210     public void setTitle(String title) {
 211         this.title = title;
 212     }
 213 
 214     public void setVendor(String vendor) {
 215         this.vendor = vendor;
 216     }
 217 
 218     public void setEmail(String email) {
 219         this.email = email;
 220     }
 221 
 222     public void setApplicationClass(String applicationClass) {
 223         this.applicationClass = applicationClass;
 224     }
 225 
 226     public void setJreInstaller(boolean value) {
 227         jreInstaller = value;
 228     }
 229 
 230     public File getOutput() {
 231         return outdir;
 232     }
 233 
 234     public void setOutput(File output) {
 235         outdir = output;
 236     }
 237 
 238     static class Template {
 239         File in;
 240         File out;
 241 
 242         Template(File in, File out) {
 243             this.in = in;
 244             this.out = out;
 245         }
 246     }
 247 
 248     // we need to expand as in some cases
 249     // (most notably jpackager)
 250     // we may get "." as filename and assumption is we include
 251     // everything in the given folder
 252     // (IOUtils.copyfiles() have recursive behavior)
 253     List<File> expandFileset(File root) {
 254         List<File> files = new LinkedList<>();
 255         if (!Files.isSymbolicLink(root.toPath())) {
 256             if (root.isDirectory()) {
 257                 File[] children = root.listFiles();
 258                 if (children != null) {
 259                     for (File f : children) {
 260                         files.addAll(expandFileset(f));
 261                     }
 262                 }
 263             } else {
 264                 files.add(root);
 265             }
 266         }
 267         return files;
 268     }
 269 
 270     public void addResource(File baseDir, String path) {
 271         File file = new File(baseDir, path);
 272         // normalize top level dir
 273         // to strip things like "." in the path
 274         // or it can confuse symlink detection logic
 275         file = file.getAbsoluteFile();
 276 
 277         if (baseDir == null) {
 278             baseDir = file.getParentFile();
 279         }
 280         resources.add(new RelativeFileSet(
 281                 baseDir, new LinkedHashSet<>(expandFileset(file))));
 282     }
 283 
 284     public void addResource(File baseDir, File file) {
 285         // normalize initial file
 286         // to strip things like "." in the path
 287         // or it can confuse symlink detection logic
 288         file = file.getAbsoluteFile();
 289 
 290         if (baseDir == null) {
 291             baseDir = file.getParentFile();
 292         }
 293         resources.add(new RelativeFileSet(
 294                 baseDir, new LinkedHashSet<>(expandFileset(file))));
 295     }
 296 
 297     private static File createFile(final File baseDir, final String path) {
 298         final File testFile = new File(path);
 299         return testFile.isAbsolute() ?
 300                 testFile : new File(baseDir == null ?
 301                         null : baseDir.getAbsolutePath(), path);
 302     }
 303 
 304     public static void validateAppName(String s) throws PackagerException {
 305         if (s == null || s.length() == 0) {
 306             // empty or null string - there is no unsupported char
 307             return;
 308         }
 309 
 310         int last = s.length() - 1;
 311 
 312         char fc = s.charAt(0);
 313         char lc = s.charAt(last);
 314 
 315         // illegal to end in backslash escape char
 316         if (lc == '\\') {
 317             throw new PackagerException("ERR_InvalidCharacterInArgument", "--name");
 318         }
 319 
 320         for (int i = 0; i < s.length(); i++) {
 321             char a = s.charAt(i);
 322             // We check for ASCII codes first which we accept. If check fails,
 323             // then check if it is acceptable extended ASCII or unicode character.
 324             if (a < ' ' || a > '~' || a == '%') {
 325                 // Reject '%', whitespaces and ISO Control.
 326                 // Accept anything else including special characters like copyright
 327                 // symbols. Note: space will be included by ASCII check above,
 328                 // but other whitespace like tabs or new line will be ignored.
 329                 if (Character.isISOControl(a) || Character.isWhitespace(a) || a == '%') {
 330                     throw new PackagerException("ERR_InvalidCharacterInArgument", "--name");
 331                 }
 332             }
 333             if (a == '"') {
 334                 throw new PackagerException("ERR_InvalidCharacterInArgument", "--name");
 335             }
 336         }
 337     }
 338 
 339     public void validate() throws PackagerException {
 340         if (outdir == null) {
 341             throw new PackagerException("ERR_MissingArgument", "--output");
 342         }
 343 
 344         if (getBundleType() == BundlerType.IMAGE) {
 345             String input = (String)bundlerArguments.get(Arguments.CLIOptions.INPUT.getId());
 346             if (input == null) {
 347                 throw new PackagerException("ERR_MissingArgument", "--input");
 348             }
 349         } else if (getBundleType() == BundlerType.INSTALLER) {
 350             if (!Arguments.isJreInstaller()) {
 351                 String input = (String)bundlerArguments.get(Arguments.CLIOptions.INPUT.getId());
 352                 String appImage = (String)bundlerArguments.get(
 353                     Arguments.CLIOptions.PREDEFINED_APP_IMAGE.getId());
 354                 if (input == null && appImage == null) {
 355                     throw new PackagerException("ERR_MissingArgument", "--input or --app-image");
 356                 }
 357             }
 358         }
 359 
 360         boolean hasModule = (bundlerArguments.get(
 361                 Arguments.CLIOptions.MODULE.getId()) != null);
 362         boolean hasImage = (bundlerArguments.get(
 363                 Arguments.CLIOptions.PREDEFINED_APP_IMAGE.getId()) != null);
 364         boolean hasClass = (bundlerArguments.get(
 365                 Arguments.CLIOptions.APPCLASS.getId()) != null);
 366         boolean hasMain = (bundlerArguments.get(
 367                 Arguments.CLIOptions.MAIN_JAR.getId()) != null);
 368 
 369         // if bundling non-modular image, or installer without app-image
 370         // then we need some resources and a main class
 371         if (!hasModule && !hasImage && !jreInstaller) {
 372             if (resources.isEmpty()) {
 373                 throw new PackagerException("ERR_MissingAppResources");
 374             }
 375             if (!hasClass) {
 376                 throw new PackagerException("ERR_MissingArgument", "--class");
 377             }
 378             if (!hasMain) {
 379                 throw new PackagerException("ERR_MissingArgument",
 380                         "--main-jar");
 381             }
 382         }
 383 
 384         String name = (String)bundlerArguments.get(Arguments.CLIOptions.NAME.getId());
 385         validateAppName(name);
 386 
 387         // Validate app image if set
 388         String appImage = (String)bundlerArguments.get(
 389                 Arguments.CLIOptions.PREDEFINED_APP_IMAGE.getId());
 390         if (appImage != null) {
 391             File appImageDir = new File(appImage);
 392             if (!appImageDir.exists()) {
 393                 throw new PackagerException("ERR_AppImageNotExist", appImage);
 394             }
 395 
 396             File appImageAppDir = new File(appImage + File.separator + "app");
 397             File appImageRuntimeDir = new File(appImage
 398                     + File.separator + "runtime");
 399             if (!appImageAppDir.exists() || !appImageRuntimeDir.exists()) {
 400                 throw new PackagerException("ERR_AppImageInvalid", appImage);
 401             }
 402         }
 403     }
 404 
 405     public boolean validateForBundle() {
 406         boolean result = false;
 407 
 408         // Success
 409         if (((applicationClass != null && !applicationClass.isEmpty()) ||
 410             (module != null && !module.isEmpty()))) {
 411             result = true;
 412         }
 413 
 414         return result;
 415     }
 416 
 417     BundlerType bundleType = BundlerType.NONE;
 418     String targetFormat = null; //means any
 419 
 420     public void setBundleType(BundlerType type) {
 421         bundleType = type;
 422     }
 423 
 424     public BundlerType getBundleType() {
 425         return bundleType;
 426     }
 427 
 428     public void setTargetFormat(String t) {
 429         targetFormat = t;
 430     }
 431 
 432     public String getTargetFormat() {
 433         return targetFormat;
 434     }
 435 
 436     private String getArch() {
 437         String arch = System.getProperty("os.arch").toLowerCase();
 438 
 439         if ("x86".equals(arch) || "i386".equals(arch) || "i486".equals(arch)
 440                 || "i586".equals(arch) || "i686".equals(arch)) {
 441             arch = "x86";
 442         } else if ("x86_64".equals(arch) || "amd64".equals("arch")) {
 443             arch = "x86_64";
 444         }
 445 
 446         return arch;
 447     }
 448 
 449     static final Set<String> multi_args = new TreeSet<>(Arrays.asList(
 450             StandardBundlerParam.JVM_PROPERTIES.getID(),
 451             StandardBundlerParam.JVM_OPTIONS.getID(),
 452             StandardBundlerParam.ARGUMENTS.getID(),
 453             StandardBundlerParam.MODULE_PATH.getID(),
 454             StandardBundlerParam.ADD_MODULES.getID(),
 455             StandardBundlerParam.LIMIT_MODULES.getID(),
 456             StandardBundlerParam.FILE_ASSOCIATIONS.getID()
 457     ));
 458 
 459     @SuppressWarnings("unchecked")
 460     public void addBundleArgument(String key, Object value) {
 461         // special hack for multi-line arguments
 462         if (multi_args.contains(key)) {
 463             Object existingValue = bundlerArguments.get(key);
 464             if (existingValue instanceof String && value instanceof String) {
 465                 bundlerArguments.put(key, existingValue + "\n\n" + value);
 466             } else if (existingValue instanceof List && value instanceof List) {
 467                 ((List)existingValue).addAll((List)value);
 468             } else if (existingValue instanceof Map &&
 469                 value instanceof String && ((String)value).contains("=")) {
 470                 String[] mapValues = ((String)value).split("=", 2);
 471                 ((Map)existingValue).put(mapValues[0], mapValues[1]);
 472             } else {
 473                 bundlerArguments.put(key, value);
 474             }
 475         } else {
 476             bundlerArguments.put(key, value);
 477         }
 478     }
 479 
 480     public BundleParams getBundleParams() {
 481         BundleParams bundleParams = new BundleParams();
 482 
 483         //construct app resources
 484         //  relative to output folder!
 485         String currentOS = System.getProperty("os.name").toLowerCase();
 486         String currentArch = getArch();
 487 
 488         bundleParams.setAppResourcesList(resources);
 489 
 490         bundleParams.setIdentifier(id);
 491 
 492         bundleParams.setApplicationClass(applicationClass);
 493         bundleParams.setAppVersion(version);
 494         bundleParams.setType(bundleType);
 495         bundleParams.setBundleFormat(targetFormat);
 496         bundleParams.setVendor(vendor);
 497         bundleParams.setEmail(email);
 498         bundleParams.setServiceHint(serviceHint);
 499         bundleParams.setInstalldirChooser(installdirChooser);
 500         bundleParams.setSingleton(singleton);
 501         bundleParams.setCopyright(copyright);
 502         bundleParams.setApplicationCategory(category);
 503         bundleParams.setDescription(description);
 504         bundleParams.setTitle(title);
 505 
 506         bundleParams.setJvmProperties(properties);
 507         bundleParams.setJvmargs(jvmargs);
 508         bundleParams.setArguments(arguments);
 509 
 510         if (addModules != null && !addModules.isEmpty()) {
 511             bundleParams.setAddModules(addModules);
 512         }
 513 
 514         if (limitModules != null && !limitModules.isEmpty()) {
 515             bundleParams.setLimitModules(limitModules);
 516         }
 517 
 518         if (stripNativeCommands != null) {
 519             bundleParams.setStripNativeCommands(stripNativeCommands);
 520         }
 521 
 522         if (modulePath != null && !modulePath.isEmpty()) {
 523             bundleParams.setModulePath(modulePath);
 524         }
 525 
 526         if (module != null && !module.isEmpty()) {
 527             bundleParams.setMainModule(module);
 528         }
 529 
 530         if (debugPort != null && !debugPort.isEmpty()) {
 531             bundleParams.setDebug(debugPort);
 532         }
 533 
 534         Map<String, String> paramsMap = new TreeMap<>();
 535         if (params != null) {
 536             for (Param p : params) {
 537                 paramsMap.put(p.name, p.value);
 538             }
 539         }
 540 
 541         Map<String, String> unescapedHtmlParams = new TreeMap<>();
 542         Map<String, String> escapedHtmlParams = new TreeMap<>();
 543 
 544         // check for collisions
 545         TreeSet<String> keys = new TreeSet<>(bundlerArguments.keySet());
 546         keys.retainAll(bundleParams.getBundleParamsAsMap().keySet());
 547 
 548         if (!keys.isEmpty()) {
 549             throw new RuntimeException("Deploy Params and Bundler Arguments "
 550                     + "overlap in the following values:" + keys.toString());
 551         }
 552 
 553         bundleParams.addAllBundleParams(bundlerArguments);
 554 
 555         return bundleParams;
 556     }
 557 
 558     public Map<String, ? super Object> getBundlerArguments() {
 559         return this.bundlerArguments;
 560     }
 561 
 562     public void putUnlessNull(String param, Object value) {
 563         if (value != null) {
 564             bundlerArguments.put(param, value);
 565         }
 566     }
 567 
 568     public void putUnlessNullOrEmpty(String param, Map<?, ?> value) {
 569         if (value != null && !value.isEmpty()) {
 570             bundlerArguments.put(param, value);
 571         }
 572     }
 573 
 574     public void putUnlessNullOrEmpty(String param, Collection<?> value) {
 575         if (value != null && !value.isEmpty()) {
 576             bundlerArguments.put(param, value);
 577         }
 578     }
 579 
 580     @Override
 581     public String toString() {
 582         return "DeployParams{" + "outdir=" + outdir + '}';
 583     }
 584 
 585 }