1 /*
   2  * Copyright (c) 2015, 2016, 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 
  29 import com.oracle.tools.packager.StandardBundlerParam;
  30 import com.oracle.tools.packager.BundlerParamInfo;
  31 import com.oracle.tools.packager.RelativeFileSet;
  32 import com.oracle.tools.packager.Log;
  33 import com.oracle.tools.packager.Platform;
  34 
  35 import java.io.ByteArrayOutputStream;
  36 import java.io.File;
  37 import java.io.FileInputStream;
  38 import java.io.FileNotFoundException;
  39 import java.io.IOException;
  40 import java.io.InputStream;
  41 import java.io.PrintWriter;
  42 import java.io.StringReader;
  43 import java.net.URI;
  44 import java.nio.file.Files;
  45 import java.nio.file.Path;
  46 import java.nio.file.Paths;
  47 import java.text.MessageFormat;
  48 import java.util.ArrayList;
  49 import java.util.Arrays;
  50 import java.util.Collection;
  51 import java.util.Collections;
  52 import java.util.EnumSet;
  53 import java.util.HashMap;
  54 import java.util.HashSet;
  55 import java.util.Iterator;
  56 import java.util.LinkedHashMap;
  57 import java.util.LinkedHashSet;
  58 import java.util.List;
  59 import java.util.Map;
  60 import java.util.Optional;
  61 import java.util.Properties;
  62 import java.util.ResourceBundle;
  63 import java.util.Set;
  64 import java.util.TreeSet;
  65 import java.util.function.Supplier;
  66 import java.util.logging.Level;
  67 import java.util.logging.Logger;
  68 import java.util.stream.Collectors;
  69 import java.util.stream.Stream;
  70 import java.util.zip.ZipEntry;
  71 import java.util.zip.ZipInputStream;
  72 
  73 import jdk.packager.builders.AbstractAppImageBuilder;
  74 import jdk.packager.internal.Module;
  75 import jdk.tools.jlink.internal.packager.AppRuntimeImageBuilder;
  76 
  77 
  78 public final class JLinkBundlerHelper {
  79 
  80     private static final ResourceBundle I18N =
  81             ResourceBundle.getBundle(JLinkBundlerHelper.class.getName());
  82 
  83     private JLinkBundlerHelper() {}
  84 
  85     @SuppressWarnings("unchecked")
  86     public static final BundlerParamInfo<Boolean> DETECT_MODULES =
  87             new StandardBundlerParam<>(
  88                     I18N.getString("param.detect-modules.name"),
  89                     I18N.getString("param.detect-modules.description"),
  90                     "detect-modules",
  91                     Boolean.class,
  92                     p -> Boolean.FALSE,
  93                     (s, p) -> Boolean.valueOf(s));
  94 
  95     @SuppressWarnings("unchecked")
  96     public static final BundlerParamInfo<Map<String, String>> JLINK_OPTIONS =
  97             new StandardBundlerParam<>(
  98                     I18N.getString("param.jlink-options.name"),
  99                     I18N.getString("param.jlink-options.description"),
 100                     "jlinkOptions",
 101                     (Class<Map<String, String>>) (Object) Map.class,
 102                     p -> Collections.emptyMap(),
 103                     (s, p) -> {
 104                         try {
 105                             Properties props = new Properties();
 106                             props.load(new StringReader(s));
 107                             return new LinkedHashMap<>((Map)props);
 108                         } catch (IOException e) {
 109                             return new LinkedHashMap<>();
 110                         }
 111                     });
 112 
 113     @SuppressWarnings("unchecked")
 114     public static final BundlerParamInfo<String> JLINK_BUILDER =
 115             new StandardBundlerParam<>(
 116                     I18N.getString("param.jlink-builder.name"),
 117                     I18N.getString("param.jlink-builder.description"),
 118                     "jlink.builder",
 119                     String.class,
 120                     null,
 121                     (s, p) -> s);
 122 
 123     @SuppressWarnings("unchecked")
 124     public static final BundlerParamInfo<Integer> DEBUG =
 125             new StandardBundlerParam<>(
 126                     "",
 127                     "",
 128                     "-J-Xdebug",
 129                     Integer.class,
 130                     p -> null,
 131                     (s, p) -> {
 132                         return Integer.valueOf(s);
 133                     });
 134 
 135     public static String listOfPathToString(List<Path> value) {
 136         String result = "";
 137 
 138         for (Path path : value) {
 139             if (result.length() > 0) {
 140                 result += File.pathSeparator;
 141             }
 142 
 143             result += path.toString();
 144         }
 145 
 146         return result;
 147     }
 148 
 149     public static String setOfStringToString(Set<String> value) {
 150         String result = "";
 151 
 152         for (String element : value) {
 153             if (result.length() > 0) {
 154                 result += ",";
 155             }
 156 
 157             result += element;
 158         }
 159 
 160         return result;
 161     }
 162 
 163     public static File getMainJar(Map<String, ? super Object> params) {
 164         File result = null;
 165         RelativeFileSet fileset = StandardBundlerParam.MAIN_JAR.fetchFrom(params);
 166 
 167         if (fileset != null) {
 168             String filename = fileset.getIncludedFiles().iterator().next();
 169             result = fileset.getBaseDirectory().toPath().resolve(filename).toFile();
 170 
 171             if (result == null || !result.exists()) {
 172                 String srcdir = StandardBundlerParam.SOURCE_DIR.fetchFrom(params);
 173 
 174                 if (srcdir != null) {
 175                     result = new File(srcdir + File.separator + filename);
 176                 }
 177             }
 178         }
 179 
 180         return result;
 181     }
 182 
 183     public static String getMainClass(Map<String, ? super Object> params) {
 184         String result = "";
 185         File mainJar = getMainJar(params);
 186 
 187         if (mainJar != null) {
 188             result = StandardBundlerParam.MAIN_CLASS.fetchFrom(params);
 189         }
 190         else {
 191             String mainModule = StandardBundlerParam.MODULE.fetchFrom(params);
 192 
 193             if (mainModule != null) {
 194                 int index = mainModule.indexOf("/");
 195 
 196                 if (index > 0) {
 197                     result = mainModule.substring(index + 1);
 198                 }
 199             }
 200         }
 201 
 202         return result;
 203     }
 204 
 205     public static String getMainModule(Map<String, ? super Object> params) {
 206         String result = "";
 207         String mainModule = StandardBundlerParam.MODULE.fetchFrom(params);
 208 
 209         if (mainModule != null) {
 210             int index = mainModule.indexOf("/");
 211 
 212             if (index > 0) {
 213                 result = mainModule.substring(0, index);
 214             }
 215             else {
 216                 result = mainModule;
 217             }
 218         }
 219 
 220         return result;
 221     }
 222 
 223     public static String getJDKVersion(Map<String, ? super Object> params) {
 224         String result = "";
 225         List<Path> modulePath = StandardBundlerParam.MODULE_PATH.fetchFrom(params);
 226         Path javaBasePath = findPathOfModule(modulePath, "java.base.jmod");
 227 
 228         if (javaBasePath != null && javaBasePath.toFile().exists()) {
 229             result = RedistributableModules.getModuleVersion(javaBasePath.toFile(),
 230                         modulePath, StandardBundlerParam.ADD_MODULES.fetchFrom(params),
 231                         StandardBundlerParam.LIMIT_MODULES.fetchFrom(params));
 232         }
 233 
 234         return result;
 235     }
 236 
 237     public static Path getJDKHome(Map<String, ? super Object> params) {
 238         Path result = null;
 239         List<Path> modulePath = StandardBundlerParam.MODULE_PATH.fetchFrom(params);
 240         Path javaBasePath = findPathOfModule(modulePath, "java.base.jmod");
 241 
 242         if (javaBasePath != null && javaBasePath.toFile().exists()) {
 243             result = javaBasePath.getParent();
 244 
 245             // On a developer build the JDK Home isn't where we expect it
 246             // relative to the jmods directory. Do some extra
 247             // processing to find it.
 248             if (result != null) {
 249                 boolean found = false;
 250                 Path bin = result.resolve("bin");
 251 
 252                 if (Files.exists(bin)) {
 253                     final String exe = (Platform.getPlatform() == Platform.WINDOWS) ? ".exe" : "";
 254                     Path javaExe = bin.resolve("java" + exe);
 255 
 256                     if (Files.exists(javaExe)) {
 257                         found = true;
 258                     }
 259                 }
 260 
 261                 if (!found) {
 262                     result = result.resolve("..\\jdk");
 263                 }
 264             }
 265         }
 266 
 267         return result;
 268     }
 269 
 270     public static void execute(Map<String, ? super Object> params, AbstractAppImageBuilder imageBuilder) throws IOException, Exception {
 271         List<Path> modulePath = StandardBundlerParam.MODULE_PATH.fetchFrom(params);
 272         Set<String> addModules = StandardBundlerParam.ADD_MODULES.fetchFrom(params);
 273         Set<String> limitModules = StandardBundlerParam.LIMIT_MODULES.fetchFrom(params);
 274         boolean stripNativeCommands = StandardBundlerParam.STRIP_NATIVE_COMMANDS.fetchFrom(params);
 275         Map<String, String> userArguments = JLINK_OPTIONS.fetchFrom(params);
 276         Path outputDir = imageBuilder.getRoot();
 277         String excludeFileList = imageBuilder.getExcludeFileList();
 278         Set<String> jars = getResourceFileJarList(params, Module.JarType.UnnamedJar);
 279         File mainJar = getMainJar(params);
 280         Module.ModuleType mainJarType = Module.ModuleType.Unknown;
 281 
 282         if (mainJar != null) {
 283             mainJarType = new Module(mainJar).getModuleType();
 284         }
 285 
 286         //--------------------------------------------------------------------
 287         // Modules
 288 
 289         boolean detectModules = DETECT_MODULES.fetchFrom(params);
 290 
 291         // The default for an unnamed jar is ALL_DEFAULT with the
 292         // non-redistributable modules removed.
 293         if (mainJarType == Module.ModuleType.UnnamedJar && !detectModules) {
 294             addModules.add(ModuleHelper.ALL_RUNTIME);
 295         }
 296         else if (mainJarType == Module.ModuleType.Unknown || mainJarType == Module.ModuleType.ModularJar) {
 297             String mainModule = getMainModule(params);
 298             addModules.add(mainModule);
 299 
 300             // Error if any of the srcfiles are modular jars.
 301             Set<String> modularJars = getResourceFileJarList(params, Module.JarType.ModularJar);
 302 
 303             if (!modularJars.isEmpty()) {
 304                 throw new Exception(MessageFormat.format(I18N.getString("error.srcfiles.contain.modules"), modularJars.toString()));
 305             }
 306         }
 307 
 308         ModuleHelper moduleHelper = new ModuleHelper(modulePath, addModules, limitModules);
 309         addModules.addAll(moduleHelper.modules());
 310 
 311         //--------------------------------------------------------------------
 312         // Jars
 313 
 314         // Bundle with minimum dependencies that unnamed jars depend on.
 315         if (detectModules && !jars.isEmpty()) {
 316             Log.info(MessageFormat.format(I18N.getString("using.experimental.feature"), "--" + DETECT_MODULES.getID()));
 317             Collection<String> detectedModules = JDepHelper.calculateModules(jars, modulePath);
 318 
 319             if (!detectedModules.isEmpty()) {
 320                 addModules.addAll(detectedModules);
 321             }
 322         }
 323 
 324         Log.info(MessageFormat.format(I18N.getString("message.modules"), addModules.toString()));
 325 
 326         AppRuntimeImageBuilder appRuntimeBuilder = new AppRuntimeImageBuilder();
 327         appRuntimeBuilder.setOutputDir(outputDir);
 328         appRuntimeBuilder.setModulePath(modulePath);
 329         appRuntimeBuilder.setAddModules(addModules);
 330         appRuntimeBuilder.setLimitModules(limitModules);
 331         appRuntimeBuilder.setExcludeFileList(excludeFileList);
 332         appRuntimeBuilder.setStripNativeCommands(stripNativeCommands);
 333         appRuntimeBuilder.setUserArguments(userArguments);
 334 
 335         appRuntimeBuilder.build();
 336         imageBuilder.prepareApplicationFiles();
 337     }
 338 
 339     // Returns the path to the JDK modules in the user defined module path.
 340     public static Path findPathOfModule(List<Path> modulePath, String moduleName) {
 341         Path result = null;
 342 
 343         for (Path path : modulePath) {
 344             Path moduleNamePath = path.resolve(moduleName);
 345 
 346             if (Files.exists(moduleNamePath)) {
 347                 result = path;
 348                 break;
 349             }
 350         }
 351 
 352         return result;
 353     }
 354 
 355     private static Set<String> getResourceFileJarList(Map<String, ? super Object> params, Module.JarType Query) {
 356         Set<String> files = new LinkedHashSet();
 357 
 358         String srcdir = StandardBundlerParam.SOURCE_DIR.fetchFrom(params);
 359 
 360         for (RelativeFileSet appResources : StandardBundlerParam.APP_RESOURCES_LIST.fetchFrom(params)) {
 361             for (String resource : appResources.getIncludedFiles()) {
 362                 if (resource.endsWith(".jar")) {
 363                     String filename = srcdir + File.separator + resource;
 364 
 365                     switch (Query) {
 366                         case All: {
 367                             files.add(filename);
 368                             break;
 369                         }
 370                         case ModularJar: {
 371                             Module module = new Module(new File(filename));
 372 
 373                             if (module.getModuleType() == Module.ModuleType.ModularJar) {
 374                                 files.add(filename);
 375                             }
 376                             break;
 377                         }
 378                         case UnnamedJar: {
 379                             Module module = new Module(new File(filename));
 380 
 381                             if (module.getModuleType() == Module.ModuleType.UnnamedJar) {
 382                                 files.add(filename);
 383                             }
 384                             break;
 385                         }
 386                     }
 387                 }
 388             }
 389         }
 390 
 391         return files;
 392     }
 393 
 394     private static class ModuleHelper {
 395         // The token for "all modules on the module path".
 396         private static final String ALL_MODULE_PATH = "ALL-MODULE-PATH";
 397 
 398         // The token for "all redistributable runtime modules".
 399         public static final String ALL_RUNTIME = "ALL-RUNTIME";
 400 
 401         private final Set<String> modules = new HashSet<>();
 402         private enum Macros {None, AllModulePath, AllRuntime}
 403 
 404         public ModuleHelper(List<Path> paths, Set<String> roots, Set<String> limitMods) {
 405             Set<String> lroots = new HashSet<>();
 406             Macros macro = Macros.None;
 407 
 408             for (Iterator<String> iterator = roots.iterator(); iterator.hasNext();) {
 409                 String module = iterator.next();
 410 
 411                 switch (module) {
 412                     case ALL_MODULE_PATH:
 413                         iterator.remove();
 414                         macro = Macros.AllModulePath;
 415                         break;
 416                     case ALL_RUNTIME:
 417                         iterator.remove();
 418                         macro = Macros.AllRuntime;
 419                         break;
 420                     default:
 421                         lroots.add(module);
 422                 }
 423             }
 424 
 425             switch (macro) {
 426                 case AllModulePath:
 427                     this.modules.addAll(getModuleNamesFromPath(paths));
 428                     break;
 429                 case AllRuntime:
 430                     Set<String> m = RedistributableModules.getRedistributableModules(paths);
 431 
 432                     if (m != null) {
 433                         this.modules.addAll(m);
 434                     }
 435 
 436                     break;
 437             }
 438 
 439             this.modules.addAll(lroots);
 440         }
 441 
 442         public Set<String> modules() {
 443             return modules;
 444         }
 445 
 446         private static Set<String> getModuleNamesFromPath(List<Path> Value) {
 447                 Set<String> result = new LinkedHashSet();
 448                 ModuleManager mm = new ModuleManager(Value);
 449                 List<Module> modules = mm.getModules(EnumSet.of(ModuleManager.SearchType.ModularJar,
 450                                                      ModuleManager.SearchType.Jmod,
 451                                                      ModuleManager.SearchType.ExplodedModule));
 452 
 453                 for (Module module : modules) {
 454                     result.add(module.getModuleName());
 455                 }
 456 
 457                 return result;
 458         }
 459     }
 460 }