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.packager.internal;
  27 
  28 import jdk.packager.internal.bundlers.BundlerType;
  29 import jdk.packager.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         boolean hasModule = (bundlerArguments.get(
 345                 Arguments.CLIOptions.MODULE.getId()) != null);
 346         boolean hasImage = (bundlerArguments.get(
 347                 Arguments.CLIOptions.PREDEFINED_APP_IMAGE.getId()) != null);
 348         boolean hasClass = (bundlerArguments.get(
 349                 Arguments.CLIOptions.APPCLASS.getId()) != null);
 350         boolean hasMain = (bundlerArguments.get(
 351                 Arguments.CLIOptions.MAIN_JAR.getId()) != null);
 352 
 353         // if bundling non-modular image, or installer without app-image
 354         // then we need some resources and a main class
 355         if (!hasModule && !hasImage && !jreInstaller) {
 356             if (resources.isEmpty()) {
 357                 throw new PackagerException("ERR_MissingAppResources");
 358             }
 359             if (!hasClass) {
 360                 throw new PackagerException("ERR_MissingArgument", "--class");
 361             }
 362             if (!hasMain) {
 363                 throw new PackagerException("ERR_MissingArgument",
 364                         "--main-jar");
 365             }
 366         }
 367 
 368         String name = (String)bundlerArguments.get(Arguments.CLIOptions.NAME.getId());
 369         validateAppName(name);
 370 
 371         // Validate app image if set
 372         String appImage = (String)bundlerArguments.get(
 373                 Arguments.CLIOptions.PREDEFINED_APP_IMAGE.getId());
 374         if (appImage != null) {
 375             File appImageDir = new File(appImage);
 376             if (!appImageDir.exists()) {
 377                 throw new PackagerException("ERR_AppImageNotExist", appImage);
 378             }
 379 
 380             File appImageAppDir = new File(appImage + File.separator + "app");
 381             File appImageRuntimeDir = new File(appImage
 382                     + File.separator + "runtime");
 383             if (!appImageAppDir.exists() || !appImageRuntimeDir.exists()) {
 384                 throw new PackagerException("ERR_AppImageInvalid", appImage);
 385             }
 386         }
 387     }
 388 
 389     public boolean validateForBundle() {
 390         boolean result = false;
 391 
 392         // Success
 393         if (((applicationClass != null && !applicationClass.isEmpty()) ||
 394             (module != null && !module.isEmpty()))) {
 395             result = true;
 396         }
 397 
 398         return result;
 399     }
 400 
 401     BundlerType bundleType = BundlerType.NONE;
 402     String targetFormat = null; //means any
 403 
 404     public void setBundleType(BundlerType type) {
 405         bundleType = type;
 406     }
 407 
 408     public BundlerType getBundleType() {
 409         return bundleType;
 410     }
 411 
 412     public void setTargetFormat(String t) {
 413         targetFormat = t;
 414     }
 415 
 416     public String getTargetFormat() {
 417         return targetFormat;
 418     }
 419 
 420     private String getArch() {
 421         String arch = System.getProperty("os.arch").toLowerCase();
 422 
 423         if ("x86".equals(arch) || "i386".equals(arch) || "i486".equals(arch)
 424                 || "i586".equals(arch) || "i686".equals(arch)) {
 425             arch = "x86";
 426         } else if ("x86_64".equals(arch) || "amd64".equals("arch")) {
 427             arch = "x86_64";
 428         }
 429 
 430         return arch;
 431     }
 432 
 433     static final Set<String> multi_args = new TreeSet<>(Arrays.asList(
 434             StandardBundlerParam.JVM_PROPERTIES.getID(),
 435             StandardBundlerParam.JVM_OPTIONS.getID(),
 436             StandardBundlerParam.ARGUMENTS.getID(),
 437             StandardBundlerParam.MODULE_PATH.getID(),
 438             StandardBundlerParam.ADD_MODULES.getID(),
 439             StandardBundlerParam.LIMIT_MODULES.getID(),
 440             StandardBundlerParam.FILE_ASSOCIATIONS.getID()
 441     ));
 442 
 443     @SuppressWarnings("unchecked")
 444     public void addBundleArgument(String key, Object value) {
 445         // special hack for multi-line arguments
 446         if (multi_args.contains(key)) {
 447             Object existingValue = bundlerArguments.get(key);
 448             if (existingValue instanceof String && value instanceof String) {
 449                 bundlerArguments.put(key, existingValue + "\n\n" + value);
 450             } else if (existingValue instanceof List && value instanceof List) {
 451                 ((List)existingValue).addAll((List)value);
 452             } else if (existingValue instanceof Map &&
 453                 value instanceof String && ((String)value).contains("=")) {
 454                 String[] mapValues = ((String)value).split("=", 2);
 455                 ((Map)existingValue).put(mapValues[0], mapValues[1]);
 456             } else {
 457                 bundlerArguments.put(key, value);
 458             }
 459         } else {
 460             bundlerArguments.put(key, value);
 461         }
 462     }
 463 
 464     public BundleParams getBundleParams() {
 465         BundleParams bundleParams = new BundleParams();
 466 
 467         //construct app resources
 468         //  relative to output folder!
 469         String currentOS = System.getProperty("os.name").toLowerCase();
 470         String currentArch = getArch();
 471 
 472         bundleParams.setAppResourcesList(resources);
 473 
 474         bundleParams.setIdentifier(id);
 475 
 476         bundleParams.setApplicationClass(applicationClass);
 477         bundleParams.setAppVersion(version);
 478         bundleParams.setType(bundleType);
 479         bundleParams.setBundleFormat(targetFormat);
 480         bundleParams.setVendor(vendor);
 481         bundleParams.setEmail(email);
 482         bundleParams.setServiceHint(serviceHint);
 483         bundleParams.setInstalldirChooser(installdirChooser);
 484         bundleParams.setSingleton(singleton);
 485         bundleParams.setCopyright(copyright);
 486         bundleParams.setApplicationCategory(category);
 487         bundleParams.setDescription(description);
 488         bundleParams.setTitle(title);
 489 
 490         bundleParams.setJvmProperties(properties);
 491         bundleParams.setJvmargs(jvmargs);
 492         bundleParams.setArguments(arguments);
 493 
 494         if (addModules != null && !addModules.isEmpty()) {
 495             bundleParams.setAddModules(addModules);
 496         }
 497 
 498         if (limitModules != null && !limitModules.isEmpty()) {
 499             bundleParams.setLimitModules(limitModules);
 500         }
 501 
 502         if (stripNativeCommands != null) {
 503             bundleParams.setStripNativeCommands(stripNativeCommands);
 504         }
 505 
 506         if (modulePath != null && !modulePath.isEmpty()) {
 507             bundleParams.setModulePath(modulePath);
 508         }
 509 
 510         if (module != null && !module.isEmpty()) {
 511             bundleParams.setMainModule(module);
 512         }
 513 
 514         if (debugPort != null && !debugPort.isEmpty()) {
 515             bundleParams.setDebug(debugPort);
 516         }
 517 
 518         Map<String, String> paramsMap = new TreeMap<>();
 519         if (params != null) {
 520             for (Param p : params) {
 521                 paramsMap.put(p.name, p.value);
 522             }
 523         }
 524 
 525         Map<String, String> unescapedHtmlParams = new TreeMap<>();
 526         Map<String, String> escapedHtmlParams = new TreeMap<>();
 527 
 528         // check for collisions
 529         TreeSet<String> keys = new TreeSet<>(bundlerArguments.keySet());
 530         keys.retainAll(bundleParams.getBundleParamsAsMap().keySet());
 531 
 532         if (!keys.isEmpty()) {
 533             throw new RuntimeException("Deploy Params and Bundler Arguments "
 534                     + "overlap in the following values:" + keys.toString());
 535         }
 536 
 537         bundleParams.addAllBundleParams(bundlerArguments);
 538 
 539         return bundleParams;
 540     }
 541 
 542     public Map<String, ? super Object> getBundlerArguments() {
 543         return this.bundlerArguments;
 544     }
 545 
 546     public void putUnlessNull(String param, Object value) {
 547         if (value != null) {
 548             bundlerArguments.put(param, value);
 549         }
 550     }
 551 
 552     public void putUnlessNullOrEmpty(String param, Map<?, ?> value) {
 553         if (value != null && !value.isEmpty()) {
 554             bundlerArguments.put(param, value);
 555         }
 556     }
 557 
 558     public void putUnlessNullOrEmpty(String param, Collection<?> value) {
 559         if (value != null && !value.isEmpty()) {
 560             bundlerArguments.put(param, value);
 561         }
 562     }
 563 
 564     @Override
 565     public String toString() {
 566         return "DeployParams{" + "outdir=" + outdir + '}';
 567     }
 568 
 569 }