1 /*
   2  * Copyright (c) 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package jdk.jpackage.test;
  24 
  25 import java.io.IOException;
  26 import java.nio.file.Files;
  27 import java.nio.file.Path;
  28 import java.util.HashMap;
  29 import java.util.Map;
  30 import java.util.Optional;
  31 import java.util.stream.Collectors;
  32 import java.util.stream.Stream;
  33 
  34 public class WindowsHelper {
  35 
  36     static String getBundleName(JPackageCommand cmd) {
  37         cmd.verifyIsOfType(PackageType.WINDOWS);
  38         return String.format("%s-%s%s", cmd.name(), cmd.version(),
  39                 cmd.packageType().getSuffix());
  40     }
  41 
  42     static Path getInstallationDirectory(JPackageCommand cmd) {
  43         cmd.verifyIsOfType(PackageType.WINDOWS);
  44         Path installDir = Path.of(
  45                 cmd.getArgumentValue("--install-dir", () -> cmd.name()));
  46         if (isUserLocalInstall(cmd)) {
  47             return USER_LOCAL.resolve(installDir);
  48         }
  49         return PROGRAM_FILES.resolve(installDir);
  50     }
  51 
  52     private static boolean isUserLocalInstall(JPackageCommand cmd) {
  53         return cmd.hasArgument("--win-per-user-install");
  54     }
  55 
  56     static class AppVerifier {
  57 
  58         AppVerifier(JPackageCommand cmd) {
  59             cmd.verifyIsOfType(PackageType.WINDOWS);
  60             this.cmd = cmd;
  61             verifyStartMenuShortcut();
  62             verifyDesktopShortcut();
  63             verifyFileAssociationsRegistry();
  64         }
  65 
  66         private void verifyDesktopShortcut() {
  67             boolean appInstalled = cmd.launcherInstallationPath().toFile().exists();
  68             if (cmd.hasArgument("--win-shortcut")) {
  69                 if (isUserLocalInstall(cmd)) {
  70                     verifyUserLocalDesktopShortcut(appInstalled);
  71                     verifySystemDesktopShortcut(false);
  72                 } else {
  73                     verifySystemDesktopShortcut(appInstalled);
  74                     verifyUserLocalDesktopShortcut(false);
  75                 }
  76             } else {
  77                 verifySystemDesktopShortcut(false);
  78                 verifyUserLocalDesktopShortcut(false);
  79             }
  80         }
  81 
  82         private Path desktopShortcutPath() {
  83             return Path.of(cmd.name() + ".lnk");
  84         }
  85 
  86         private void verifySystemDesktopShortcut(boolean exists) {
  87             Path dir = Path.of(queryRegistryValueCache(
  88                     SYSTEM_SHELL_FOLDERS_REGKEY, "Common Desktop"));
  89             Test.assertFileExists(dir.resolve(desktopShortcutPath()), exists);
  90         }
  91 
  92         private void verifyUserLocalDesktopShortcut(boolean exists) {
  93             Path dir = Path.of(
  94                     queryRegistryValueCache(USER_SHELL_FOLDERS_REGKEY, "Desktop"));
  95             Test.assertFileExists(dir.resolve(desktopShortcutPath()), exists);
  96         }
  97 
  98         private void verifyStartMenuShortcut() {
  99             boolean appInstalled = cmd.launcherInstallationPath().toFile().exists();
 100             if (cmd.hasArgument("--win-menu") || !cmd.hasArgument("--win-shortcut")) {
 101                 if (isUserLocalInstall(cmd)) {
 102                     verifyUserLocalStartMenuShortcut(appInstalled);
 103                     verifySystemStartMenuShortcut(false);
 104                 } else {
 105                     verifySystemStartMenuShortcut(appInstalled);
 106                     verifyUserLocalStartMenuShortcut(false);
 107                 }
 108             } else {
 109                 verifySystemStartMenuShortcut(false);
 110                 verifyUserLocalStartMenuShortcut(false);
 111             }
 112         }
 113 
 114         private Path startMenuShortcutPath() {
 115             return Path.of(cmd.getArgumentValue("--win-menu-group",
 116                     () -> "Unknown"), cmd.name() + ".lnk");
 117         }
 118 
 119         private void verifySystemStartMenuShortcut(boolean exists) {
 120             Path dir = Path.of(queryRegistryValueCache(
 121                     SYSTEM_SHELL_FOLDERS_REGKEY, "Common Programs"));
 122             Test.assertFileExists(dir.resolve(startMenuShortcutPath()), exists);
 123         }
 124 
 125         private void verifyUserLocalStartMenuShortcut(boolean exists) {
 126             Path dir = Path.of(queryRegistryValueCache(
 127                     USER_SHELL_FOLDERS_REGKEY, "Programs"));
 128             Test.assertFileExists(dir.resolve(startMenuShortcutPath()), exists);
 129         }
 130 
 131         private void verifyFileAssociationsRegistry() {
 132             Path faFile = cmd.getArgumentValue("--file-associations",
 133                     () -> (Path) null, Path::of);
 134             if (faFile == null) {
 135                 return;
 136             }
 137 
 138             boolean appInstalled = cmd.launcherInstallationPath().toFile().exists();
 139             try {
 140                 Test.trace(String.format(
 141                         "Get file association properties from [%s] file",
 142                         faFile));
 143                 Map<String, String> faProps = Files.readAllLines(faFile).stream().filter(
 144                         line -> line.trim().startsWith("extension=") || line.trim().startsWith(
 145                         "mime-type=")).map(
 146                                 line -> {
 147                                     String[] keyValue = line.trim().split("=", 2);
 148                                     return Map.entry(keyValue[0], keyValue[1]);
 149                                 }).collect(Collectors.toMap(
 150                                 entry -> entry.getKey(),
 151                                 entry -> entry.getValue()));
 152                 String suffix = faProps.get("extension");
 153                 String contentType = faProps.get("mime-type");
 154                 Test.assertNotNull(suffix, String.format(
 155                         "Check file association suffix [%s] is found in [%s] property file",
 156                         suffix, faFile));
 157                 Test.assertNotNull(contentType, String.format(
 158                         "Check file association content type [%s] is found in [%s] property file",
 159                         contentType, faFile));
 160                 verifyFileAssociations(appInstalled, "." + suffix, contentType);
 161             } catch (IOException ex) {
 162                 throw new RuntimeException(ex);
 163             }
 164         }
 165 
 166         private void verifyFileAssociations(boolean exists, String suffix,
 167                 String contentType) {
 168             String contentTypeFromRegistry = queryRegistryValue(Path.of(
 169                     "HKLM\\Software\\Classes", suffix).toString(),
 170                     "Content Type");
 171             String suffixFromRegistry = queryRegistryValue(
 172                     "HKLM\\Software\\Classes\\MIME\\Database\\Content Type\\" + contentType,
 173                     "Extension");
 174 
 175             if (exists) {
 176                 Test.assertEquals(suffix, suffixFromRegistry,
 177                         "Check suffix in registry is as expected");
 178                 Test.assertEquals(contentType, contentTypeFromRegistry,
 179                         "Check content type in registry is as expected");
 180             } else {
 181                 Test.assertNull(suffixFromRegistry,
 182                         "Check suffix in registry not found");
 183                 Test.assertNull(contentTypeFromRegistry,
 184                         "Check content type in registry not found");
 185             }
 186         }
 187 
 188         private final JPackageCommand cmd;
 189     }
 190 
 191     private static String queryRegistryValue(String keyPath, String valueName) {
 192         Executor.Result status = new Executor()
 193                 .setExecutable("reg")
 194                 .saveOutput()
 195                 .addArguments("query", keyPath, "/v", valueName)
 196                 .execute();
 197         if (status.exitCode == 1) {
 198             // Should be the case of no such registry value or key
 199             String lookupString = "ERROR: The system was unable to find the specified registry key or value.";
 200             status.getOutput().stream().filter(line -> line.equals(lookupString)).findFirst().orElseThrow(
 201                     () -> new RuntimeException(String.format(
 202                             "Failed to find [%s] string in the output",
 203                             lookupString)));
 204             Test.trace(String.format(
 205                     "Registry value [%s] at [%s] path not found", valueName,
 206                     keyPath));
 207             return null;
 208         }
 209 
 210         String value = status.assertExitCodeIsZero().getOutput().stream().skip(2).findFirst().orElseThrow();
 211         // Extract the last field from the following line:
 212         //     Common Desktop    REG_SZ    C:\Users\Public\Desktop
 213         value = value.split("    REG_SZ    ")[1];
 214 
 215         Test.trace(String.format("Registry value [%s] at [%s] path is [%s]",
 216                 valueName, keyPath, value));
 217 
 218         return value;
 219     }
 220 
 221     private static String queryRegistryValueCache(String keyPath,
 222             String valueName) {
 223         String key = String.format("[%s][%s]", keyPath, valueName);
 224         String value = REGISTRY_VALUES.get(key);
 225         if (value == null) {
 226             value = queryRegistryValue(keyPath, valueName);
 227             REGISTRY_VALUES.put(key, value);
 228         }
 229 
 230         return value;
 231     }
 232 
 233     // jtreg resets %ProgramFiles% environment variable by some reason.
 234     private final static Path PROGRAM_FILES = Path.of(Optional.ofNullable(
 235             System.getenv("ProgramFiles")).orElse("C:\\Program Files"));
 236 
 237     private final static Path USER_LOCAL = Path.of(System.getProperty(
 238             "user.home"),
 239             "AppData", "Local");
 240 
 241     private final static String SYSTEM_SHELL_FOLDERS_REGKEY = "HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";
 242     private final static String USER_SHELL_FOLDERS_REGKEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";
 243 
 244     private static final Map<String, String> REGISTRY_VALUES = new HashMap<>();
 245 }