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.
   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 
  24 /*
  25  * @test
  26  * @bug 8144355 8144062 8176709 8194070 8193802
  27  * @summary Test aliasing additions to ZipFileSystem for multi-release jar files
  28  * @library /lib/testlibrary/java/util/jar
  29  * @modules jdk.compiler
  30  *          jdk.jartool
  31  *          jdk.zipfs
  32  * @build Compiler JarBuilder CreateMultiReleaseTestJars
  33  * @run testng MultiReleaseJarTest
  34  */
  35 
  36 import java.io.IOException;
  37 import java.lang.invoke.MethodHandle;
  38 import java.lang.invoke.MethodHandles;
  39 import java.lang.invoke.MethodType;
  40 import java.lang.Runtime.Version;
  41 import java.net.URI;
  42 import java.nio.file.*;
  43 import java.util.HashMap;
  44 import java.util.Map;
  45 import java.util.concurrent.atomic.AtomicInteger;
  46 
  47 import org.testng.Assert;
  48 import org.testng.annotations.*;
  49 
  50 public class MultiReleaseJarTest {
  51     final private int MAJOR_VERSION = Runtime.version().feature();
  52 
  53     final private String userdir = System.getProperty("user.dir",".");
  54     final private CreateMultiReleaseTestJars creator =  new CreateMultiReleaseTestJars();
  55     final private Map<String,String> stringEnv = new HashMap<>();
  56     final private Map<String,Integer> integerEnv = new HashMap<>();
  57     final private Map<String,Version> versionEnv = new HashMap<>();
  58     final private String className = "version.Version";
  59     final private MethodType mt = MethodType.methodType(int.class);
  60 
  61     private String entryName;
  62     private URI uvuri;
  63     private URI mruri;
  64     private URI smruri;
  65 
  66     @BeforeClass
  67     public void initialize() throws Exception {
  68         creator.compileEntries();
  69         creator.buildUnversionedJar();
  70         creator.buildMultiReleaseJar();
  71         creator.buildShortMultiReleaseJar();
  72         String ssp = Paths.get(userdir, "unversioned.jar").toUri().toString();
  73         uvuri = new URI("jar", ssp , null);
  74         ssp = Paths.get(userdir, "multi-release.jar").toUri().toString();
  75         mruri = new URI("jar", ssp, null);
  76         ssp = Paths.get(userdir, "short-multi-release.jar").toUri().toString();
  77         smruri = new URI("jar", ssp, null);
  78         entryName = className.replace('.', '/') + ".class";
  79     }
  80 
  81     public void close() throws IOException {
  82         Files.delete(Paths.get(userdir, "unversioned.jar"));
  83         Files.delete(Paths.get(userdir, "multi-release.jar"));
  84         Files.delete(Paths.get(userdir, "short-multi-release.jar"));
  85     }
  86 
  87     @DataProvider(name="strings")
  88     public Object[][] createStrings() {
  89         return new Object[][]{
  90                 {"runtime", MAJOR_VERSION},
  91                 {"9.0.1", 9},
  92                 {MAJOR_VERSION + ".0.1", MAJOR_VERSION},
  93                 {"8", 8},
  94                 {"9", 9},
  95                 {Integer.toString(MAJOR_VERSION), MAJOR_VERSION},
  96                 {Integer.toString(MAJOR_VERSION+1), MAJOR_VERSION},
  97                 {"50", MAJOR_VERSION}
  98         };
  99     }
 100 
 101     @DataProvider(name="integers")
 102     public Object[][] createIntegers() {
 103         return new Object[][] {
 104                 {Integer.valueOf(8), 8},
 105                 {Integer.valueOf(9), 9},
 106                 {Integer.valueOf(MAJOR_VERSION), MAJOR_VERSION},
 107                 {Integer.valueOf(MAJOR_VERSION + 1), MAJOR_VERSION},
 108                 {Integer.valueOf(100), MAJOR_VERSION}
 109         };
 110     }
 111 
 112     @DataProvider(name="versions")
 113     public Object[][] createVersions() {
 114         return new Object[][] {
 115                 {Version.parse("8"),    8},
 116                 {Version.parse("9"),    9},
 117                 {Version.parse(Integer.toString(MAJOR_VERSION)),  MAJOR_VERSION},
 118                 {Version.parse(Integer.toString(MAJOR_VERSION) + 1),  MAJOR_VERSION},
 119                 {Version.parse("100"), MAJOR_VERSION}
 120         };
 121     }
 122 
 123     @DataProvider(name="invalidVersions")
 124     public Object[][] invalidVersions() {
 125         return new Object[][] {
 126                 {Map.of("releaseVersion", "0")},
 127                 {Map.of("releaseVersion", "-1")},
 128                 {Map.of("releaseVersion",Integer.valueOf(-5))}
 129         };
 130     }
 131 
 132     // Not the best test but all I can do since ZipFileSystem and JarFileSystem
 133     // are not public, so I can't use (fs instanceof ...)
 134     @Test
 135     public void testNewFileSystem() throws Exception {
 136         Map<String,String> env = new HashMap<>();
 137         // no configuration, treat multi-release jar as unversioned
 138         try (FileSystem fs = FileSystems.newFileSystem(mruri, env)) {
 139             Assert.assertTrue(readAndCompare(fs, 8));
 140         }
 141         env.put("releaseVersion", "runtime");
 142         // a configuration and jar file is multi-release
 143         try (FileSystem fs = FileSystems.newFileSystem(mruri, env)) {
 144             Assert.assertTrue(readAndCompare(fs, MAJOR_VERSION));
 145         }
 146         // a configuration but jar file is unversioned
 147         try (FileSystem fs = FileSystems.newFileSystem(uvuri, env)) {
 148             Assert.assertTrue(readAndCompare(fs, 8));
 149         }
 150     }
 151 
 152     private boolean readAndCompare(FileSystem fs, int expected) throws IOException {
 153         Path path = fs.getPath("version/Version.java");
 154         String src = new String(Files.readAllBytes(path));
 155         return src.contains("return " + expected);
 156     }
 157 
 158     @Test(dataProvider="strings")
 159     public void testStrings(String value, int expected) throws Throwable {
 160         stringEnv.put("releaseVersion", value);
 161         runTest(stringEnv, expected);
 162     }
 163 
 164     @Test(dataProvider="integers")
 165     public void testIntegers(Integer value, int expected) throws Throwable {
 166         integerEnv.put("releaseVersion", value);
 167         runTest(integerEnv, expected);
 168     }
 169 
 170     @Test(dataProvider="versions")
 171     public void testVersions(Version value, int expected) throws Throwable {
 172         versionEnv.put("releaseVersion", value);
 173         runTest(versionEnv, expected);
 174     }
 175 
 176     @Test
 177     public void testShortJar() throws Throwable {
 178         integerEnv.put("releaseVersion", Integer.valueOf(MAJOR_VERSION));
 179         runTest(smruri, integerEnv, MAJOR_VERSION);
 180         integerEnv.put("releaseVersion", Integer.valueOf(9));
 181         runTest(smruri, integerEnv, 8);
 182     }
 183 
 184     @Test(dataProvider="invalidVersions")
 185     public void testInvalidVersions(Map<String,?> env) throws Throwable {
 186         Assert.assertThrows(IllegalArgumentException.class, () ->
 187                 FileSystems.newFileSystem(Path.of(userdir,
 188                         "multi-release.jar"), env));
 189     }
 190 
 191     // The following tests are for backwards compatibility to validate that
 192     // the original property still works
 193     @Test(dataProvider="strings")
 194     public void testMRStrings(String value, int expected) throws Throwable {
 195         runTest(Map.of("multi-release", value), expected);
 196     }
 197 
 198     @Test(dataProvider="integers")
 199     public void testMRIntegers(Integer value, int expected) throws Throwable {
 200         runTest(Map.of("multi-release", value), expected);
 201     }
 202 
 203     @Test(dataProvider="versions")
 204     public void testMRVersions(Version value, int expected) throws Throwable {
 205         runTest(Map.of("multi-release", value), expected);
 206     }
 207 
 208     private void runTest(Map<String,?> env, int expected) throws Throwable {
 209         runTest(mruri, env, expected);
 210     }
 211 
 212     private void runTest(URI uri, Map<String,?> env, int expected) throws Throwable {
 213         try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
 214             Path version = fs.getPath(entryName);
 215             byte [] bytes = Files.readAllBytes(version);
 216             Class<?> vcls = (new ByteArrayClassLoader(fs)).defineClass(className, bytes);
 217             MethodHandle mh = MethodHandles.lookup().findVirtual(vcls, "getVersion", mt);
 218             Assert.assertEquals((int)mh.invoke(vcls.getDeclaredConstructor().newInstance()), expected);
 219         }
 220     }
 221 
 222     @Test
 223     public void testIsMultiReleaseJar() throws Exception {
 224         // Re-examine commented out tests as part of JDK-8176843
 225         testCustomMultiReleaseValue("true", true);
 226         testCustomMultiReleaseValue("true\r\nOther: value", true);
 227         testCustomMultiReleaseValue("true\nOther: value", true);
 228         //testCustomMultiReleaseValue("true\rOther: value", true);
 229 
 230         testCustomMultiReleaseValue("false", false);
 231         testCustomMultiReleaseValue(" true", false);
 232         testCustomMultiReleaseValue("true ", false);
 233         //testCustomMultiReleaseValue("true\n ", false);
 234         //testCustomMultiReleaseValue("true\r ", false);
 235         //testCustomMultiReleaseValue("true\n true", false);
 236         //testCustomMultiReleaseValue("true\r\n true", false);
 237     }
 238 
 239     @Test
 240     public void testMultiReleaseJarWithNonVersionDir() throws Exception {
 241         String jfname = "multi-release-non-ver.jar";
 242         Path jfpath = Paths.get(jfname);
 243         URI uri = new URI("jar", jfpath.toUri().toString() , null);
 244         JarBuilder jb = new JarBuilder(jfname);
 245         jb.addAttribute("Multi-Release", "true");
 246         jb.build();
 247         Map<String,String> env = Map.of("releaseVersion", "runtime");
 248         try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
 249             Assert.assertTrue(true);
 250         }
 251         Files.delete(jfpath);
 252     }
 253 
 254     private static final AtomicInteger JAR_COUNT = new AtomicInteger(0);
 255 
 256     private void testCustomMultiReleaseValue(String value, boolean expected)
 257             throws Exception {
 258         String fileName = "custom-mr" + JAR_COUNT.incrementAndGet() + ".jar";
 259         creator.buildCustomMultiReleaseJar(fileName, value, Map.of(),
 260                 /*addEntries*/true);
 261 
 262         Map<String,String> env = Map.of("releaseVersion", "runtime");
 263         Path filePath = Paths.get(userdir, fileName);
 264         String ssp = filePath.toUri().toString();
 265         URI customJar = new URI("jar", ssp , null);
 266         try (FileSystem fs = FileSystems.newFileSystem(customJar, env)) {
 267             if (expected) {
 268                 Assert.assertTrue(readAndCompare(fs, MAJOR_VERSION));
 269             } else {
 270                 Assert.assertTrue(readAndCompare(fs, 8));
 271             }
 272         }
 273         Files.delete(filePath);
 274     }
 275 
 276     private static class ByteArrayClassLoader extends ClassLoader {
 277         final private FileSystem fs;
 278 
 279         ByteArrayClassLoader(FileSystem fs) {
 280             super(null);
 281             this.fs = fs;
 282         }
 283 
 284         @Override
 285         public Class<?> loadClass(String name) throws ClassNotFoundException {
 286             try {
 287                 return super.loadClass(name);
 288             } catch (ClassNotFoundException x) {}
 289             Path cls = fs.getPath(name.replace('.', '/') + ".class");
 290             try {
 291                 byte[] bytes = Files.readAllBytes(cls);
 292                 return defineClass(name, bytes);
 293             } catch (IOException x) {
 294                 throw new ClassNotFoundException(x.getMessage());
 295             }
 296         }
 297 
 298         public Class<?> defineClass(String name, byte[] bytes) throws ClassNotFoundException {
 299             if (bytes == null) throw new ClassNotFoundException("No bytes for " + name);
 300             return defineClass(name, bytes, 0, bytes.length);
 301         }
 302     }
 303 }