Path: blob/master/test/jdk/tools/jar/modularJar/Basic.java
41149 views
/*1* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.*;24import java.lang.module.ModuleDescriptor;25import java.lang.reflect.Method;26import java.nio.file.Files;27import java.nio.file.Path;28import java.nio.file.Paths;29import java.util.*;30import java.util.function.Consumer;31import java.util.jar.JarEntry;32import java.util.jar.JarFile;33import java.util.jar.JarInputStream;34import java.util.jar.Manifest;35import java.util.regex.Pattern;36import java.util.spi.ToolProvider;37import java.util.stream.Collectors;38import java.util.stream.Stream;3940import jdk.test.lib.util.FileUtils;41import jdk.test.lib.JDKToolFinder;42import org.testng.annotations.BeforeTest;43import org.testng.annotations.DataProvider;44import org.testng.annotations.Test;4546import static java.lang.String.format;47import static java.lang.System.out;4849/*50* @test51* @bug 8167328 8171830 8165640 8174248 8176772 8196748 8191533 821045452* @library /test/lib53* @modules jdk.compiler54* jdk.jartool55* @build jdk.test.lib.Platform56* jdk.test.lib.util.FileUtils57* jdk.test.lib.JDKToolFinder58* @compile Basic.java59* @run testng Basic60* @summary Tests for plain Modular jars & Multi-Release Modular jars61*/6263public class Basic {6465private static final ToolProvider JAR_TOOL = ToolProvider.findFirst("jar")66.orElseThrow(()67-> new RuntimeException("jar tool not found")68);69private static final ToolProvider JAVAC_TOOL = ToolProvider.findFirst("javac")70.orElseThrow(()71-> new RuntimeException("javac tool not found")72);7374static final Path TEST_SRC = Paths.get(System.getProperty("test.src", "."));75static final Path TEST_CLASSES = Paths.get(System.getProperty("test.classes", "."));76static final Path MODULE_CLASSES = TEST_CLASSES.resolve("build");77static final Path MRJAR_DIR = MODULE_CLASSES.resolve("mrjar");7879static final String VM_OPTIONS = System.getProperty("test.vm.opts", "");80static final String TOOL_VM_OPTIONS = System.getProperty("test.tool.vm.opts", "");81static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "");8283// Details based on the checked in module source84static TestModuleData FOO = new TestModuleData("foo",85"1.123",86"jdk.test.foo.Foo",87"Hello World!!!",88null, // no hashes89Set.of("java.base"),90Set.of("jdk.test.foo"),91null, // no uses92null, // no provides93Set.of("jdk.test.foo.internal",94"jdk.test.foo.resources"));95static TestModuleData BAR = new TestModuleData("bar",96"4.5.6.7",97"jdk.test.bar.Bar",98"Hello from Bar!",99null, // no hashes100Set.of("java.base", "foo"),101null, // no exports102null, // no uses103null, // no provides104Set.of("jdk.test.bar",105"jdk.test.bar.internal"));106107static class TestModuleData {108final String moduleName;109final Set<String> requires;110final Set<String> exports;111final Set<String> uses;112final Set<String> provides;113final String mainClass;114final String version;115final String message;116final String hashes;117final Set<String> packages;118119TestModuleData(String mn, String v, String mc, String m, String h,120Set<String> requires, Set<String> exports, Set<String> uses,121Set<String> provides, Set<String> contains) {122moduleName = mn; mainClass = mc; version = v; message = m; hashes = h;123this.requires = requires != null ? requires : Collections.emptySet();124this.exports = exports != null ? exports : Collections.emptySet();125this.uses = uses != null ? uses : Collections.emptySet();;126this.provides = provides != null ? provides : Collections.emptySet();127this.packages = Stream.concat(this.exports.stream(), contains.stream())128.collect(Collectors.toSet());129}130static TestModuleData from(String s) {131try {132BufferedReader reader = new BufferedReader(new StringReader(s));133String line;134String message = null;135String name = null, version = null, mainClass = null;136String hashes = null;137Set<String> requires, exports, uses, provides, conceals;138requires = exports = uses = provides = conceals = null;139while ((line = reader.readLine()) != null) {140if (line.startsWith("message:")) {141message = line.substring("message:".length());142} else if (line.startsWith("nameAndVersion:")) {143line = line.substring("nameAndVersion:".length());144int i = line.indexOf('@');145if (i != -1) {146name = line.substring(0, i);147version = line.substring(i + 1, line.length());148} else {149name = line;150}151} else if (line.startsWith("mainClass:")) {152mainClass = line.substring("mainClass:".length());153} else if (line.startsWith("requires:")) {154line = line.substring("requires:".length());155requires = stringToSet(line);156} else if (line.startsWith("exports:")) {157line = line.substring("exports:".length());158exports = stringToSet(line);159} else if (line.startsWith("uses:")) {160line = line.substring("uses:".length());161uses = stringToSet(line);162} else if (line.startsWith("provides:")) {163line = line.substring("provides:".length());164provides = stringToSet(line);165} else if (line.startsWith("hashes:")) {166hashes = line.substring("hashes:".length());167} else if (line.startsWith("contains:")) {168line = line.substring("contains:".length());169conceals = stringToSet(line);170} else if (line.contains("VM warning:")) {171continue; // ignore server vm warning see#8196748172} else if (line.contains("WARNING: JNI access from module not specified in --enable-native-access:")) {173continue;174} else {175throw new AssertionError("Unknown value " + line);176}177}178179return new TestModuleData(name, version, mainClass, message,180hashes, requires, exports, uses,181provides, conceals);182} catch (IOException x) {183throw new UncheckedIOException(x);184}185}186static Set<String> stringToSet(String commaList) {187Set<String> s = new HashSet<>();188int i = commaList.indexOf(',');189if (i != -1) {190String[] p = commaList.split(",");191Stream.of(p).forEach(s::add);192} else {193s.add(commaList);194}195return s;196}197}198199static void assertModuleData(Result r, TestModuleData expected) {200//out.printf("%s%n", r.output);201TestModuleData received = TestModuleData.from(r.output);202if (expected.message != null)203assertTrue(expected.message.equals(received.message),204"Expected message:", expected.message, ", got:", received.message);205assertTrue(expected.moduleName.equals(received.moduleName),206"Expected moduleName: ", expected.moduleName, ", got:", received.moduleName);207assertTrue(expected.version.equals(received.version),208"Expected version: ", expected.version, ", got:", received.version);209assertTrue(expected.mainClass.equals(received.mainClass),210"Expected mainClass: ", expected.mainClass, ", got:", received.mainClass);211assertSetsEqual(expected.requires, received.requires);212assertSetsEqual(expected.exports, received.exports);213assertSetsEqual(expected.uses, received.uses);214assertSetsEqual(expected.provides, received.provides);215assertSetsEqual(expected.packages, received.packages);216}217218static void assertSetsEqual(Set<String> s1, Set<String> s2) {219if (!s1.equals(s2)) {220org.testng.Assert.assertTrue(false, s1 + " vs " + s2);221}222}223224@BeforeTest225public void compileModules() throws Exception {226compileModule(FOO.moduleName);227compileModule(BAR.moduleName, MODULE_CLASSES);228compileModule("baz"); // for service provider consistency checking229230// copy resources231copyResource(TEST_SRC.resolve("src").resolve(FOO.moduleName),232MODULE_CLASSES.resolve(FOO.moduleName),233"jdk/test/foo/resources/foo.properties");234235setupMRJARModuleInfo(FOO.moduleName);236setupMRJARModuleInfo(BAR.moduleName);237setupMRJARModuleInfo("baz");238}239240@Test241public void createFoo() throws IOException {242Path mp = Paths.get("createFoo");243createTestDir(mp);244Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);245Path modularJar = mp.resolve(FOO.moduleName + ".jar");246247jar("--create",248"--file=" + modularJar.toString(),249"--main-class=" + FOO.mainClass,250"--module-version=" + FOO.version,251"--no-manifest",252"-C", modClasses.toString(), ".")253.assertSuccess();254255assertSetsEqual(readPackagesAttribute(modularJar),256Set.of("jdk.test.foo",257"jdk.test.foo.resources",258"jdk.test.foo.internal"));259260java(mp, FOO.moduleName + "/" + FOO.mainClass)261.assertSuccess()262.resultChecker(r -> assertModuleData(r, FOO));263try (InputStream fis = Files.newInputStream(modularJar);264JarInputStream jis = new JarInputStream(fis)) {265assertTrue(!jarContains(jis, "./"),266"Unexpected ./ found in ", modularJar.toString());267}268}269270/** Similar to createFoo, but with a Multi-Release Modular jar. */271@Test272public void createMRMJarFoo() throws IOException {273Path mp = Paths.get("createMRMJarFoo");274createTestDir(mp);275Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);276Path mrjarDir = MRJAR_DIR.resolve(FOO.moduleName);277Path modularJar = mp.resolve(FOO.moduleName + ".jar");278279// Positive test, create280jar("--create",281"--file=" + modularJar.toString(),282"--main-class=" + FOO.mainClass,283"--module-version=" + FOO.version,284"-m", mrjarDir.resolve("META-INF/MANIFEST.MF").toRealPath().toString(),285"-C", mrjarDir.toString(), "META-INF/versions/9/module-info.class",286"-C", modClasses.toString(), ".")287.assertSuccess();288java(mp, FOO.moduleName + "/" + FOO.mainClass)289.assertSuccess()290.resultChecker(r -> assertModuleData(r, FOO));291}292293294@Test295public void updateFoo() throws IOException {296Path mp = Paths.get("updateFoo");297createTestDir(mp);298Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);299Path modularJar = mp.resolve(FOO.moduleName + ".jar");300301jar("--create",302"--file=" + modularJar.toString(),303"--no-manifest",304"-C", modClasses.toString(), "jdk")305.assertSuccess();306jar("--update",307"--file=" + modularJar.toString(),308"--main-class=" + FOO.mainClass,309"--module-version=" + FOO.version,310"--no-manifest",311"-C", modClasses.toString(), "module-info.class")312.assertSuccess();313java(mp, FOO.moduleName + "/" + FOO.mainClass)314.assertSuccess()315.resultChecker(r -> assertModuleData(r, FOO));316}317318@Test319public void updateMRMJarFoo() throws IOException {320Path mp = Paths.get("updateMRMJarFoo");321createTestDir(mp);322Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);323Path mrjarDir = MRJAR_DIR.resolve(FOO.moduleName);324Path modularJar = mp.resolve(FOO.moduleName + ".jar");325326jar("--create",327"--file=" + modularJar.toString(),328"--no-manifest",329"-C", modClasses.toString(), "jdk")330.assertSuccess();331jar("--update",332"--file=" + modularJar.toString(),333"--main-class=" + FOO.mainClass,334"--module-version=" + FOO.version,335"-m", mrjarDir.resolve("META-INF/MANIFEST.MF").toRealPath().toString(),336"-C", mrjarDir.toString(), "META-INF/versions/9/module-info.class",337"-C", modClasses.toString(), "module-info.class")338.assertSuccess();339java(mp, FOO.moduleName + "/" + FOO.mainClass)340.assertSuccess()341.resultChecker(r -> assertModuleData(r, FOO));342}343344@Test345public void partialUpdateFooMainClass() throws IOException {346Path mp = Paths.get("partialUpdateFooMainClass");347createTestDir(mp);348Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);349Path modularJar = mp.resolve(FOO.moduleName + ".jar");350351// A "bad" main class in first create ( and no version )352jar("--create",353"--file=" + modularJar.toString(),354"--main-class=" + "jdk.test.foo.IAmNotTheEntryPoint",355"--no-manifest",356"-C", modClasses.toString(), ".") // includes module-info.class357.assertSuccess();358jar("--update",359"--file=" + modularJar.toString(),360"--main-class=" + FOO.mainClass,361"--module-version=" + FOO.version,362"--no-manifest")363.assertSuccess();364java(mp, FOO.moduleName + "/" + FOO.mainClass)365.assertSuccess()366.resultChecker(r -> assertModuleData(r, FOO));367}368369@Test370public void partialUpdateFooVersion() throws IOException {371Path mp = Paths.get("partialUpdateFooVersion");372createTestDir(mp);373Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);374Path modularJar = mp.resolve(FOO.moduleName + ".jar");375376// A "bad" version in first create ( and no main class )377jar("--create",378"--file=" + modularJar.toString(),379"--module-version=" + "100000000",380"--no-manifest",381"-C", modClasses.toString(), ".") // includes module-info.class382.assertSuccess();383jar("--update",384"--file=" + modularJar.toString(),385"--main-class=" + FOO.mainClass,386"--module-version=" + FOO.version,387"--no-manifest")388.assertSuccess();389java(mp, FOO.moduleName + "/" + FOO.mainClass)390.assertSuccess()391.resultChecker(r -> assertModuleData(r, FOO));392}393394@Test395public void partialUpdateFooNotAllFiles() throws IOException {396Path mp = Paths.get("partialUpdateFooNotAllFiles");397createTestDir(mp);398Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);399Path modularJar = mp.resolve(FOO.moduleName + ".jar");400401// Not all files, and none from non-exported packages,402// i.e. no concealed list in first create403jar("--create",404"--file=" + modularJar.toString(),405"--no-manifest",406"-C", modClasses.toString(), "module-info.class",407"-C", modClasses.toString(), "jdk/test/foo/Foo.class",408"-C", modClasses.toString(), "jdk/test/foo/resources/foo.properties")409.assertSuccess();410jar("--update",411"--file=" + modularJar.toString(),412"--main-class=" + FOO.mainClass,413"--module-version=" + FOO.version,414"--no-manifest",415"-C", modClasses.toString(), "jdk/test/foo/internal/Message.class")416.assertSuccess();417java(mp, FOO.moduleName + "/" + FOO.mainClass)418.assertSuccess()419.resultChecker(r -> assertModuleData(r, FOO));420}421422@Test423public void partialUpdateMRMJarFooNotAllFiles() throws IOException {424Path mp = Paths.get("partialUpdateMRMJarFooNotAllFiles");425createTestDir(mp);426Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);427Path mrjarDir = MRJAR_DIR.resolve(FOO.moduleName);428Path modularJar = mp.resolve(FOO.moduleName + ".jar");429430jar("--create",431"--file=" + modularJar.toString(),432"--module-version=" + FOO.version,433"-C", modClasses.toString(), ".")434.assertSuccess();435jar("--update",436"--file=" + modularJar.toString(),437"--main-class=" + FOO.mainClass,438"--module-version=" + FOO.version,439"-m", mrjarDir.resolve("META-INF/MANIFEST.MF").toRealPath().toString(),440"-C", mrjarDir.toString(), "META-INF/versions/9/module-info.class")441.assertSuccess();442java(mp, FOO.moduleName + "/" + FOO.mainClass)443.assertSuccess()444.resultChecker(r -> assertModuleData(r, FOO));445}446447@Test448public void partialUpdateFooAllFilesAndAttributes() throws IOException {449Path mp = Paths.get("partialUpdateFooAllFilesAndAttributes");450createTestDir(mp);451Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);452Path modularJar = mp.resolve(FOO.moduleName + ".jar");453454// all attributes and files455jar("--create",456"--file=" + modularJar.toString(),457"--main-class=" + FOO.mainClass,458"--module-version=" + FOO.version,459"--no-manifest",460"-C", modClasses.toString(), ".")461.assertSuccess();462jar("--update",463"--file=" + modularJar.toString(),464"--main-class=" + FOO.mainClass,465"--module-version=" + FOO.version,466"--no-manifest",467"-C", modClasses.toString(), ".")468.assertSuccess();469java(mp, FOO.moduleName + "/" + FOO.mainClass)470.assertSuccess()471.resultChecker(r -> assertModuleData(r, FOO));472}473474@Test475public void partialUpdateFooModuleInfo() throws IOException {476Path mp = Paths.get("partialUpdateFooModuleInfo");477createTestDir(mp);478Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);479Path modularJar = mp.resolve(FOO.moduleName + ".jar");480Path barModInfo = MODULE_CLASSES.resolve(BAR.moduleName);481482jar("--create",483"--file=" + modularJar.toString(),484"--main-class=" + FOO.mainClass,485"--module-version=" + FOO.version,486"--no-manifest",487"-C", modClasses.toString(), ".")488.assertSuccess();489jar("--update",490"--file=" + modularJar.toString(),491"--no-manifest",492"-C", barModInfo.toString(), "module-info.class") // stuff in bar's info493.assertSuccess();494jar("-d",495"--file=" + modularJar.toString())496.assertSuccess()497.resultChecker(r -> {498// Expect "bar jar:file:/...!/module-info.class"499// conceals jdk.test.foo, conceals jdk.test.foo.internal"500String uri = "jar:" + modularJar.toUri().toString() + "!/module-info.class";501assertTrue(r.output.contains("bar " + uri),502"Expecting to find \"bar " + uri + "\"",503"in output, but did not: [" + r.output + "]");504Pattern p = Pattern.compile(505"contains\\s+jdk.test.foo\\s+contains\\s+jdk.test.foo.internal");506assertTrue(p.matcher(r.output).find(),507"Expecting to find \"contains jdk.test.foo,...\"",508"in output, but did not: [" + r.output + "]");509});510}511512513@Test514public void partialUpdateFooPackagesAttribute() throws IOException {515Path mp = Paths.get("partialUpdateFooPackagesAttribute");516createTestDir(mp);517Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);518Path modularJar = mp.resolve(FOO.moduleName + ".jar");519520// Not all files, and none from non-exported packages,521// i.e. no concealed list in first create522jar("--create",523"--file=" + modularJar.toString(),524"--no-manifest",525"-C", modClasses.toString(), "module-info.class",526"-C", modClasses.toString(), "jdk/test/foo/Foo.class")527.assertSuccess();528529assertSetsEqual(readPackagesAttribute(modularJar),530Set.of("jdk.test.foo"));531532jar("--update",533"--file=" + modularJar.toString(),534"-C", modClasses.toString(), "jdk/test/foo/resources/foo.properties")535.assertSuccess();536537assertSetsEqual(readPackagesAttribute(modularJar),538Set.of("jdk.test.foo", "jdk.test.foo.resources"));539540jar("--update",541"--file=" + modularJar.toString(),542"--main-class=" + FOO.mainClass,543"--module-version=" + FOO.version,544"--no-manifest",545"-C", modClasses.toString(), "jdk/test/foo/internal/Message.class")546.assertSuccess();547548assertSetsEqual(readPackagesAttribute(modularJar),549Set.of("jdk.test.foo",550"jdk.test.foo.resources",551"jdk.test.foo.internal"));552553java(mp, FOO.moduleName + "/" + FOO.mainClass)554.assertSuccess()555.resultChecker(r -> assertModuleData(r, FOO));556}557558private Set<String> readPackagesAttribute(Path jar) {559return getModuleDescriptor(jar).packages();560}561562@Test563public void hashBarInFooModule() throws IOException {564Path mp = Paths.get("dependencesFooBar");565createTestDir(mp);566567Path modClasses = MODULE_CLASSES.resolve(BAR.moduleName);568Path modularJar = mp.resolve(BAR.moduleName + ".jar");569jar("--create",570"--file=" + modularJar.toString(),571"--main-class=" + BAR.mainClass,572"--module-version=" + BAR.version,573"--no-manifest",574"-C", modClasses.toString(), ".")575.assertSuccess();576577modClasses = MODULE_CLASSES.resolve(FOO.moduleName);578modularJar = mp.resolve(FOO.moduleName + ".jar");579jar("--create",580"--file=" + modularJar.toString(),581"--main-class=" + FOO.mainClass,582"--module-version=" + FOO.version,583"--module-path=" + mp.toString(),584"--hash-modules=" + "bar",585"--no-manifest",586"-C", modClasses.toString(), ".")587.assertSuccess();588589java(mp, BAR.moduleName + "/" + BAR.mainClass,590"--add-exports", "java.base/jdk.internal.misc=bar",591"--add-exports", "java.base/jdk.internal.module=bar")592.assertSuccess()593.resultChecker(r -> {594assertModuleData(r, BAR);595TestModuleData received = TestModuleData.from(r.output);596assertTrue(received.hashes != null, "Expected non-null hashes value.");597});598}599600@Test601public void invalidHashInFooModule() throws IOException {602Path mp = Paths.get("badDependencyFooBar");603createTestDir(mp);604605Path barClasses = MODULE_CLASSES.resolve(BAR.moduleName);606Path barJar = mp.resolve(BAR.moduleName + ".jar");607jar("--create",608"--file=" + barJar.toString(),609"--main-class=" + BAR.mainClass,610"--module-version=" + BAR.version,611"--no-manifest",612"-C", barClasses.toString(), ".").assertSuccess();613614Path fooClasses = MODULE_CLASSES.resolve(FOO.moduleName);615Path fooJar = mp.resolve(FOO.moduleName + ".jar");616jar("--create",617"--file=" + fooJar.toString(),618"--main-class=" + FOO.mainClass,619"--module-version=" + FOO.version,620"-p", mp.toString(), // test short-form621"--hash-modules=" + "bar",622"--no-manifest",623"-C", fooClasses.toString(), ".").assertSuccess();624625// Rebuild bar.jar with a change that will cause its hash to be different626FileUtils.deleteFileWithRetry(barJar);627jar("--create",628"--file=" + barJar.toString(),629"--main-class=" + BAR.mainClass,630"--module-version=" + BAR.version + ".1", // a newer version631"--no-manifest",632"-C", barClasses.toString(), ".").assertSuccess();633634java(mp, BAR.moduleName + "/" + BAR.mainClass,635"--add-exports", "java.base/jdk.internal.misc=bar",636"--add-exports", "java.base/jdk.internal.module=bar")637.assertFailure()638.resultChecker(r -> {639// Expect similar output: "java.lang.module.ResolutionException: Hash640// of bar (WdktSIQSkd4+CEacpOZoeDrCosMATNrIuNub9b5yBeo=) differs to641// expected hash (iepvdv8xTeVrFgMtUhcFnmetSub6qQHCHc92lSaSEg0=)"642Pattern p = Pattern.compile(".*Hash of bar.*differs to expected hash.*");643assertTrue(p.matcher(r.output).find(),644"Expecting error message containing \"Hash of bar ... differs to"645+ " expected hash...\" but got: [", r.output + "]");646});647}648649@Test650public void badOptionsFoo() throws IOException {651Path mp = Paths.get("badOptionsFoo");652createTestDir(mp);653Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);654Path modularJar = mp.resolve(FOO.moduleName + ".jar");655656jar("--create",657"--file=" + modularJar.toString(),658"--module-version=" + 1.1, // no module-info.class659"-C", modClasses.toString(), "jdk")660.assertFailure(); // TODO: expected failure message661662jar("--create",663"--file=" + modularJar.toString(),664"--hash-modules=" + ".*", // no module-info.class665"-C", modClasses.toString(), "jdk")666.assertFailure(); // TODO: expected failure message667}668669@Test670public void servicesCreateWithoutFailure() throws IOException {671Path mp = Paths.get("servicesCreateWithoutFailure");672createTestDir(mp);673Path modClasses = MODULE_CLASSES.resolve("baz");674Path modularJar = mp.resolve("baz" + ".jar");675676// Positive test, create677jar("--create",678"--file=" + modularJar.toString(),679"-C", modClasses.toString(), "module-info.class",680"-C", modClasses.toString(), "jdk/test/baz/BazService.class",681"-C", modClasses.toString(), "jdk/test/baz/internal/BazServiceImpl.class")682.assertSuccess();683684for (String option : new String[] {"--describe-module", "-d" }) {685jar(option,686"--file=" + modularJar.toString())687.assertSuccess()688.resultChecker(r ->689assertTrue(r.output.contains("provides jdk.test.baz.BazService with jdk.test.baz.internal.BazServiceImpl"),690"Expected to find ", "provides jdk.test.baz.BazService with jdk.test.baz.internal.BazServiceImpl",691" in [", r.output, "]")692);693}694}695696@Test697public void servicesCreateWithoutServiceImpl() throws IOException {698Path mp = Paths.get("servicesWithoutServiceImpl");699createTestDir(mp);700Path modClasses = MODULE_CLASSES.resolve("baz");701Path modularJar = mp.resolve("baz" + ".jar");702703// Omit service impl704jar("--create",705"--file=" + modularJar.toString(),706"-C", modClasses.toString(), "module-info.class",707"-C", modClasses.toString(), "jdk/test/baz/BazService.class")708.assertFailure();709}710711@Test712public void servicesUpdateWithoutFailure() throws IOException {713Path mp = Paths.get("servicesUpdateWithoutFailure");714createTestDir(mp);715Path modClasses = MODULE_CLASSES.resolve("baz");716Path modularJar = mp.resolve("baz" + ".jar");717718// Positive test, update719jar("--create",720"--file=" + modularJar.toString(),721"-C", modClasses.toString(), "jdk/test/baz/BazService.class",722"-C", modClasses.toString(), "jdk/test/baz/internal/BazServiceImpl.class")723.assertSuccess();724jar("--update",725"--file=" + modularJar.toString(),726"-C", modClasses.toString(), "module-info.class")727.assertSuccess();728}729730@Test731public void servicesUpdateWithoutServiceImpl() throws IOException {732Path mp = Paths.get("servicesUpdateWithoutServiceImpl");733createTestDir(mp);734Path modClasses = MODULE_CLASSES.resolve("baz");735Path modularJar = mp.resolve("baz" + ".jar");736737// Omit service impl738jar("--create",739"--file=" + modularJar.toString(),740"-C", modClasses.toString(), "jdk/test/baz/BazService.class")741.assertSuccess();742jar("--update",743"--file=" + modularJar.toString(),744"-C", modClasses.toString(), "module-info.class")745.assertFailure();746}747748@Test749public void servicesCreateWithoutFailureMRMJAR() throws IOException {750Path mp = Paths.get("servicesCreateWithoutFailureMRMJAR");751createTestDir(mp);752Path modClasses = MODULE_CLASSES.resolve("baz");753Path mrjarDir = MRJAR_DIR.resolve("baz");754Path modularJar = mp.resolve("baz" + ".jar");755756jar("--create",757"--file=" + modularJar.toString(),758"-m", mrjarDir.resolve("META-INF/MANIFEST.MF").toRealPath().toString(),759"-C", modClasses.toString(), "module-info.class",760"-C", mrjarDir.toString(), "META-INF/versions/9/module-info.class",761"-C", modClasses.toString(), "jdk/test/baz/BazService.class",762"-C", modClasses.toString(), "jdk/test/baz/internal/BazServiceImpl.class")763.assertSuccess();764}765766@Test767public void servicesCreateWithoutFailureNonRootMRMJAR() throws IOException {768// without a root module-info.class769Path mp = Paths.get("servicesCreateWithoutFailureNonRootMRMJAR");770createTestDir(mp);771Path modClasses = MODULE_CLASSES.resolve("baz");772Path mrjarDir = MRJAR_DIR.resolve("baz");773Path modularJar = mp.resolve("baz.jar");774775jar("--create",776"--file=" + modularJar.toString(),777"--main-class=" + "jdk.test.baz.Baz",778"-m", mrjarDir.resolve("META-INF/MANIFEST.MF").toRealPath().toString(),779"-C", mrjarDir.toString(), "META-INF/versions/9/module-info.class",780"-C", modClasses.toString(), "jdk/test/baz/BazService.class",781"-C", modClasses.toString(), "jdk/test/baz/Baz.class",782"-C", modClasses.toString(), "jdk/test/baz/internal/BazServiceImpl.class")783.assertSuccess();784785786for (String option : new String[] {"--describe-module", "-d" }) {787788jar(option,789"--file=" + modularJar.toString(),790"--release", "9")791.assertSuccess()792.resultChecker(r ->793assertTrue(r.output.contains("main-class jdk.test.baz.Baz"),794"Expected to find ", "main-class jdk.test.baz.Baz",795" in [", r.output, "]"));796797jarWithStdin(modularJar.toFile(), option, "--release", "9")798.assertSuccess()799.resultChecker(r ->800assertTrue(r.output.contains("main-class jdk.test.baz.Baz"),801"Expected to find ", "main-class jdk.test.baz.Baz",802" in [", r.output, "]"));803804}805// run module main class806java(mp, "baz/jdk.test.baz.Baz")807.assertSuccess()808.resultChecker(r ->809assertTrue(r.output.contains("mainClass:jdk.test.baz.Baz"),810"Expected to find ", "mainClass:jdk.test.baz.Baz",811" in [", r.output, "]"));812}813814@Test815public void exportCreateWithMissingPkg() throws IOException {816817Path foobar = TEST_SRC.resolve("src").resolve("foobar");818Path dst = Files.createDirectories(MODULE_CLASSES.resolve("foobar"));819javac(dst, null, sourceList(foobar));820821Path mp = Paths.get("exportWithMissingPkg");822createTestDir(mp);823Path modClasses = dst;824Path modularJar = mp.resolve("foofoo.jar");825826jar("--create",827"--file=" + modularJar.toString(),828"-C", modClasses.toString(), "module-info.class",829"-C", modClasses.toString(), "jdk/test/foo/Foo.class")830.assertFailure();831}832833@Test834public void describeModuleFoo() throws IOException {835Path mp = Paths.get("describeModuleFoo");836createTestDir(mp);837Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);838Path modularJar = mp.resolve(FOO.moduleName + ".jar");839840jar("--create",841"--file=" + modularJar.toString(),842"--main-class=" + FOO.mainClass,843"--module-version=" + FOO.version,844"--no-manifest",845"-C", modClasses.toString(), ".")846.assertSuccess();847848for (String option : new String[] {"--describe-module", "-d" }) {849jar(option,850"--file=" + modularJar.toString())851.assertSuccess()852.resultChecker(r -> {853assertTrue(r.output.contains(FOO.moduleName + "@" + FOO.version),854"Expected to find ", FOO.moduleName + "@" + FOO.version,855" in [", r.output, "]");856assertTrue(r.output.contains(modularJar.toUri().toString()),857"Expected to find ", modularJar.toUri().toString(),858" in [", r.output, "]");859}860);861862jar(option,863"--file=" + modularJar.toString(),864modularJar.toString())865.assertFailure();866867jar(option, modularJar.toString())868.assertFailure();869}870}871872@Test873public void describeModuleFooFromStdin() throws IOException {874Path mp = Paths.get("describeModuleFooFromStdin");875createTestDir(mp);876Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);877Path modularJar = mp.resolve(FOO.moduleName + ".jar");878879jar("--create",880"--file=" + modularJar.toString(),881"--main-class=" + FOO.mainClass,882"--module-version=" + FOO.version,883"--no-manifest",884"-C", modClasses.toString(), ".")885.assertSuccess();886887for (String option : new String[] {"--describe-module", "-d" }) {888jarWithStdin(modularJar.toFile(),889option)890.assertSuccess()891.resultChecker(r ->892assertTrue(r.output.contains(FOO.moduleName + "@" + FOO.version),893"Expected to find ", FOO.moduleName + "@" + FOO.version,894" in [", r.output, "]")895);896}897}898899/**900* Validate that you can update a jar only specifying --module-version901* @throws IOException902*/903@Test904public void updateFooModuleVersion() throws IOException {905Path mp = Paths.get("updateFooModuleVersion");906createTestDir(mp);907Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName);908Path modularJar = mp.resolve(FOO.moduleName + ".jar");909String newFooVersion = "87.0";910911jar("--create",912"--file=" + modularJar.toString(),913"--main-class=" + FOO.mainClass,914"--module-version=" + FOO.version,915"--no-manifest",916"-C", modClasses.toString(), ".")917.assertSuccess();918919jarWithStdin(modularJar.toFile(), "--describe-module")920.assertSuccess()921.resultChecker(r ->922assertTrue(r.output.contains(FOO.moduleName + "@" + FOO.version),923"Expected to find ", FOO.moduleName + "@" + FOO.version,924" in [", r.output, "]")925);926927jar("--update",928"--file=" + modularJar.toString(),929"--module-version=" + newFooVersion)930.assertSuccess();931932for (String option : new String[] {"--describe-module", "-d" }) {933jarWithStdin(modularJar.toFile(),934option)935.assertSuccess()936.resultChecker(r ->937assertTrue(r.output.contains(FOO.moduleName + "@" + newFooVersion),938"Expected to find ", FOO.moduleName + "@" + newFooVersion,939" in [", r.output, "]")940);941}942}943944@DataProvider(name = "autoNames")945public Object[][] autoNames() {946return new Object[][] {947// JAR file name module-name[@version]948{ "foo.jar", "foo" },949{ "foo1.jar", "foo1" },950{ "foo4j.jar", "foo4j", },951{ "foo-1.2.3.4.jar", "[email protected]" },952{ "foo-bar.jar", "foo.bar" },953{ "foo-1.2-SNAPSHOT.jar", "[email protected]" },954};955}956957@Test(dataProvider = "autoNames")958public void describeAutomaticModule(String jarName, String mid)959throws IOException960{961Path mp = Paths.get("describeAutomaticModule");962createTestDir(mp);963Path regularJar = mp.resolve(jarName);964Path t = Paths.get("t");965if (Files.notExists(t))966Files.createFile(t);967968jar("--create",969"--file=" + regularJar.toString(),970t.toString())971.assertSuccess();972973for (String option : new String[] {"--describe-module", "-d" }) {974jar(option,975"--file=" + regularJar.toString())976.assertSuccess()977.resultChecker(r -> {978assertTrue(r.output.contains("No module descriptor found"));979assertTrue(r.output.contains("Derived automatic module"));980assertTrue(r.output.contains(mid + " automatic"),981"Expected [", "module " + mid,"] in [", r.output, "]");982}983);984}985}986987// -- Infrastructure988989static Result jarWithStdin(File stdinSource, String... args) {990String jar = getJDKTool("jar");991List<String> commands = new ArrayList<>();992commands.add(jar);993if (!TOOL_VM_OPTIONS.isEmpty()) {994commands.addAll(Arrays.asList(TOOL_VM_OPTIONS.split("\\s+", -1)));995}996Stream.of(args).forEach(commands::add);997ProcessBuilder p = new ProcessBuilder(commands);998if (stdinSource != null) {999p.redirectInput(stdinSource);1000}1001return run(p);1002}10031004static Result jar(String... args) {1005return run(JAR_TOOL, args);1006}10071008static Path compileModule(String mn) throws IOException {1009return compileModule(mn, null);1010}10111012static Path compileModule(String mn, Path mp)1013throws IOException1014{1015Path sourcePath = TEST_SRC.resolve("src").resolve(mn);1016Path build = Files.createDirectories(MODULE_CLASSES.resolve(mn));1017javac(build, mp, sourceList(sourcePath));1018return build;1019}10201021static void copyResource(Path srcDir, Path dir, String resource)1022throws IOException1023{1024Path dest = dir.resolve(resource);1025Files.deleteIfExists(dest);10261027Files.createDirectories(dest.getParent());1028Files.copy(srcDir.resolve(resource), dest);1029}10301031static void setupMRJARModuleInfo(String moduleName) throws IOException {1032Path modClasses = MODULE_CLASSES.resolve(moduleName);1033Path metaInfDir = MRJAR_DIR.resolve(moduleName).resolve("META-INF");1034Path versionSection = metaInfDir.resolve("versions").resolve("9");1035createTestDir(versionSection);10361037Path versionModuleInfo = versionSection.resolve("module-info.class");1038System.out.println("copying " + modClasses.resolve("module-info.class") + " to " + versionModuleInfo);1039Files.copy(modClasses.resolve("module-info.class"), versionModuleInfo);10401041Manifest manifest = new Manifest();1042manifest.getMainAttributes().putValue("Manifest-Version", "1.0");1043manifest.getMainAttributes().putValue("Multi-Release", "true");1044try (OutputStream os = Files.newOutputStream(metaInfDir.resolve("MANIFEST.MF"))) {1045manifest.write(os);1046}1047}10481049static ModuleDescriptor getModuleDescriptor(Path jar) {1050ClassLoader cl = ClassLoader.getSystemClassLoader();1051try (JarFile jf = new JarFile(jar.toFile())) {1052JarEntry entry = jf.getJarEntry("module-info.class");1053try (InputStream in = jf.getInputStream(entry)) {1054return ModuleDescriptor.read(in);1055}1056} catch (IOException ioe) {1057throw new UncheckedIOException(ioe);1058}1059}10601061// Re-enable when there is support in javax.tools for module path1062// static void javac(Path dest, Path... sourceFiles) throws IOException {1063// out.printf("Compiling %d source files %s%n", sourceFiles.length,1064// Arrays.asList(sourceFiles));1065// JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();1066// try (StandardJavaFileManager fileManager =1067// compiler.getStandardFileManager(null, null, null)) {1068//1069// List<File> files = Stream.of(sourceFiles)1070// .map(p -> p.toFile())1071// .collect(Collectors.toList());1072// List<File> dests = Stream.of(dest)1073// .map(p -> p.toFile())1074// .collect(Collectors.toList());1075// Iterable<? extends JavaFileObject> compilationUnits =1076// fileManager.getJavaFileObjectsFromFiles(files);1077// fileManager.setLocation(StandardLocation.CLASS_OUTPUT, dests);1078// JavaCompiler.CompilationTask task =1079// compiler.getTask(null, fileManager, null, null, null, compilationUnits);1080// boolean passed = task.call();1081// if (!passed)1082// throw new RuntimeException("Error compiling " + files);1083// }1084// }10851086static void javac(Path dest, Path... sourceFiles) throws IOException {1087javac(dest, null, sourceFiles);1088}10891090static void javac(Path dest, Path modulePath, Path... sourceFiles)1091throws IOException1092{10931094List<String> commands = new ArrayList<>();1095if (!TOOL_VM_OPTIONS.isEmpty()) {1096commands.addAll(Arrays.asList(TOOL_VM_OPTIONS.split("\\s+", -1)));1097}1098commands.add("-d");1099commands.add(dest.toString());1100if (dest.toString().contains("bar")) {1101commands.add("--add-exports");1102commands.add("java.base/jdk.internal.misc=bar");1103commands.add("--add-exports");1104commands.add("java.base/jdk.internal.module=bar");1105}1106if (modulePath != null) {1107commands.add("--module-path");1108commands.add(modulePath.toString());1109}1110Stream.of(sourceFiles).map(Object::toString).forEach(x -> commands.add(x));11111112StringWriter sw = new StringWriter();1113try (PrintWriter pw = new PrintWriter(sw)) {1114int rc = JAVAC_TOOL.run(pw, pw, commands.toArray(new String[0]));1115if(rc != 0) {1116throw new RuntimeException(sw.toString());1117}1118}1119}11201121static Result java(Path modulePath, String entryPoint, String... args) {1122String java = getJDKTool("java");11231124List<String> commands = new ArrayList<>();1125commands.add(java);1126if (!VM_OPTIONS.isEmpty()) {1127commands.addAll(Arrays.asList(VM_OPTIONS.split("\\s+", -1)));1128}1129if (!JAVA_OPTIONS.isEmpty()) {1130commands.addAll(Arrays.asList(JAVA_OPTIONS.split("\\s+", -1)));1131}1132Stream.of(args).forEach(x -> commands.add(x));1133commands.add("--module-path");1134commands.add(modulePath.toString());1135commands.add("-m");1136commands.add(entryPoint);11371138return run(new ProcessBuilder(commands));1139}11401141static Path[] sourceList(Path directory) throws IOException {1142return Files.find(directory, Integer.MAX_VALUE,1143(file, attrs) -> (file.toString().endsWith(".java")))1144.toArray(Path[]::new);1145}11461147static void createTestDir(Path p) throws IOException{1148if (Files.exists(p))1149FileUtils.deleteFileTreeWithRetry(p);1150Files.createDirectories(p);1151}11521153static boolean jarContains(JarInputStream jis, String entryName)1154throws IOException1155{1156JarEntry e;1157while((e = jis.getNextJarEntry()) != null) {1158if (e.getName().equals(entryName))1159return true;1160}1161return false;1162}11631164static Result run(ToolProvider tp, String[] commands) {1165int rc = 0;1166StringWriter sw = new StringWriter();1167try (PrintWriter pw = new PrintWriter(sw)) {1168rc = tp.run(pw, pw, commands);1169}1170return new Result(rc, sw.toString());1171}11721173static Result run(ProcessBuilder pb) {1174Process p;1175out.printf("Running: %s%n", pb.command());1176try {1177p = pb.start();1178} catch (IOException e) {1179throw new RuntimeException(1180format("Couldn't start process '%s'", pb.command()), e);1181}11821183String output;1184try {1185output = toString(p.getInputStream(), p.getErrorStream());1186} catch (IOException e) {1187throw new RuntimeException(1188format("Couldn't read process output '%s'", pb.command()), e);1189}11901191try {1192p.waitFor();1193} catch (InterruptedException e) {1194throw new RuntimeException(1195format("Process hasn't finished '%s'", pb.command()), e);1196}1197return new Result(p.exitValue(), output);1198}11991200static final String DEFAULT_IMAGE_BIN = System.getProperty("java.home")1201+ File.separator + "bin" + File.separator;12021203static String getJDKTool(String name) {1204try {1205return JDKToolFinder.getJDKTool(name);1206} catch (Exception x) {1207return DEFAULT_IMAGE_BIN + name;1208}1209}12101211static String toString(InputStream in1, InputStream in2) throws IOException {1212try (ByteArrayOutputStream dst = new ByteArrayOutputStream();1213InputStream concatenated = new SequenceInputStream(in1, in2)) {1214concatenated.transferTo(dst);1215return new String(dst.toByteArray(), "UTF-8");1216}1217}12181219static class Result {1220final int ec;1221final String output;12221223private Result(int ec, String output) {1224this.ec = ec;1225this.output = output;1226}1227Result assertSuccess() {1228assertTrue(ec == 0, "Expected ec 0, got: ", ec, " , output [", output, "]");1229return this;1230}1231Result assertFailure() {1232assertTrue(ec != 0, "Expected ec != 0, got:", ec, " , output [", output, "]");1233return this;1234}1235Result resultChecker(Consumer<Result> r) { r.accept(this); return this; }1236}12371238static void assertTrue(boolean cond, Object ... failedArgs) {1239if (cond)1240return;1241StringBuilder sb = new StringBuilder();1242for (Object o : failedArgs)1243sb.append(o);1244org.testng.Assert.assertTrue(false, sb.toString());1245}12461247// Standalone entry point.1248public static void main(String[] args) throws Throwable {1249Basic test = new Basic();1250test.compileModules();1251for (Method m : Basic.class.getDeclaredMethods()) {1252if (m.getAnnotation(Test.class) != null) {1253System.out.println("Invoking " + m.getName());1254m.invoke(test);1255}1256}1257}1258}125912601261