下面列出了怎么用java.lang.module.InvalidModuleDescriptorException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Maps the name of an entry in a JAR or ZIP file to a package name.
*
* @throws InvalidModuleDescriptorException
* if the name is a class file in the top-level directory of the
* JAR/ZIP file (and it's not module-info.class)
*/
private static Optional<String> toPackageName(String name) {
int index = name.lastIndexOf("/");
if (index == -1) {
if (name.endsWith(".class") && !name.equals("module-info.class")) {
String msg = name + " found in top-level directory" + " (unnamed package not allowed in module)";
throw new InvalidModuleDescriptorException(msg);
}
return Optional.empty();
}
String pn = name.substring(0, index).replace('/', '.');
if (StringUtils.isClassName(pn)) {
return Optional.of(pn);
} else {
// not a valid package name
return Optional.empty();
}
}
private boolean checkModuleInfo(byte[] moduleInfoBytes, Set<String> entries)
throws IOException
{
boolean ok = true;
if (moduleInfoBytes != null) { // no root module-info.class if null
try {
// ModuleDescriptor.read() checks open/exported pkgs vs packages
ModuleDescriptor md = ModuleDescriptor.read(ByteBuffer.wrap(moduleInfoBytes));
// A module must have the implementation class of the services it 'provides'.
if (md.provides().stream().map(Provides::providers).flatMap(List::stream)
.filter(p -> !entries.contains(toBinaryName(p)))
.peek(p -> fatalError(formatMsg("error.missing.provider", p)))
.count() != 0) {
ok = false;
}
} catch (InvalidModuleDescriptorException x) {
fatalError(x.getMessage());
ok = false;
}
}
return ok;
}
@Test(dataProvider = "illegalModuleNames",
expectedExceptions = InvalidModuleDescriptorException.class)
public void testIllegalModuleName(String mn, String ignore) throws Exception {
ModuleDescriptor md = newBuilder(mn).requires("java.base").build();
ByteBuffer bb = toBuffer(md);
ModuleDescriptor.read(bb); // throws InvalidModuleDescriptorException
}
@Test(dataProvider = "illegalModuleNames",
expectedExceptions = InvalidModuleDescriptorException.class)
public void testIllegalRequires(String mn, String ignore) throws Exception {
ModuleDescriptor md = newBuilder("m").requires("java.base").requires(mn).build();
ByteBuffer bb = toBuffer(md);
ModuleDescriptor.read(bb); // throws InvalidModuleDescriptorException
}
@Test(dataProvider = "illegalModuleNames",
expectedExceptions = InvalidModuleDescriptorException.class)
public void testIllegalExports(String mn, String ignore) throws Exception {
ModuleDescriptor md = newBuilder("m")
.requires("java.base")
.exports("p", Set.of(mn))
.build();
ByteBuffer bb = toBuffer(md);
ModuleDescriptor.read(bb); // throws InvalidModuleDescriptorException
}
@Test(dataProvider = "illegalModuleNames",
expectedExceptions = InvalidModuleDescriptorException.class)
public void testIllegalOpens(String mn, String ignore) throws Exception {
ModuleDescriptor md = newBuilder("m")
.requires("java.base")
.opens("p", Set.of(mn))
.build();
ByteBuffer bb = toBuffer(md);
ModuleDescriptor.read(bb); // throws InvalidModuleDescriptorException
}
/**
* Test ModuleDescriptor with a packager finder that doesn't return the
* complete set of packages.
*/
@Test(expectedExceptions = InvalidModuleDescriptorException.class)
public void testReadsWithBadPackageFinder() throws Exception {
ModuleDescriptor descriptor = ModuleDescriptor.newModule("foo")
.requires("java.base")
.exports("p")
.build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ModuleInfoWriter.write(descriptor, baos);
ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
// package finder returns a set that doesn't include p
ModuleDescriptor.read(bb, () -> Set.of("q"));
}
@Test(expectedExceptions = InvalidModuleDescriptorException.class)
public void testReadOfJavaBaseWithRequires() {
ModuleDescriptor descriptor
= ModuleDescriptor.newModule("java.base")
.requires("other")
.build();
ByteBuffer bb = ModuleInfoWriter.toByteBuffer(descriptor);
ModuleDescriptor.read(bb);
}
@Test(expectedExceptions = InvalidModuleDescriptorException.class)
public void testReadWithEmptyRequires() {
ModuleDescriptor descriptor = SharedSecrets.getJavaLangModuleAccess()
.newModuleBuilder("m1", false, Set.of()).build();
ByteBuffer bb = ModuleInfoWriter.toByteBuffer(descriptor);
ModuleDescriptor.read(bb);
}
@Test(expectedExceptions = InvalidModuleDescriptorException.class)
public void testReadWithNoRequiresBase() {
ModuleDescriptor descriptor = SharedSecrets.getJavaLangModuleAccess()
.newModuleBuilder("m1", false, Set.of()).requires("m2").build();
ByteBuffer bb = ModuleInfoWriter.toByteBuffer(descriptor);
ModuleDescriptor.read(bb);
}
private static void checkBootConflicts(FileMetadata file, Path download) throws IOException {
String filename = file.getPath().getFileName().toString();
if (!FileUtils.isZipFile(download)) {
Warning.nonZip(filename);
throw new IllegalStateException(
"File '" + filename + "' is not a valid zip file.");
}
Set<Module> modules = ModuleLayer.boot().modules();
Set<String> moduleNames = modules.stream().map(Module::getName).collect(Collectors.toSet());
Set<String> sysMods = ModuleFinder.ofSystem()
.findAll()
.stream()
.map(mr -> mr.descriptor().name())
.collect(Collectors.toSet());
ModuleDescriptor newMod = null;
try {
newMod = FileUtils.deriveModuleDescriptor(download, filename, sysMods.contains("jdk.zipfs"));
} catch (IllegalArgumentException | InvalidModuleDescriptorException | FindException e) {
Warning.illegalModule(filename);
throw e;
}
if (moduleNames.contains(newMod.name())) {
Warning.moduleConflict(newMod.name());
throw new IllegalStateException(
"Module '" + newMod.name() + "' conflicts with a module in the boot modulepath");
}
Set<String> packages = modules.stream().flatMap(m -> m.getPackages().stream()).collect(Collectors.toSet());
for (String p : newMod.packages()) {
if (packages.contains(p)) {
Warning.packageConflict(p);
throw new IllegalStateException("Package '" + p + "' in module '" + newMod.name()
+ "' conflicts with a package in the boot modulepath");
}
}
for (Requires require : newMod.requires()) {
// static requires are not mandatory
if (require.modifiers().contains(Requires.Modifier.STATIC))
continue;
String reqName = require.name();
if (StringUtils.isSystemModule(reqName)) {
if (!sysMods.contains(reqName)) {
Warning.missingSysMod(reqName);
throw new IllegalStateException("System module '" + reqName
+ "' is missing from JVM image, required by '" + newMod.name() + "'");
}
}
}
}
/**
* Returns an InvalidModuleDescriptorException with the given detail
* message
*/
private static InvalidModuleDescriptorException
invalidModuleDescriptor(String msg) {
return new InvalidModuleDescriptorException(msg);
}
/**
* Reads a packaged or exploded module, returning a {@code ModuleReference}
* to the module. Returns {@code null} if the entry is not recognized.
*
* @throws IOException if an I/O error occurs
* @throws FindException if an error occurs parsing its module descriptor
*/
private ModuleReference readModule(Path entry, BasicFileAttributes attrs)
throws IOException
{
try {
// exploded module
if (attrs.isDirectory()) {
return readExplodedModule(entry); // may return null
}
// JAR or JMOD file
if (attrs.isRegularFile()) {
String fn = entry.getFileName().toString();
boolean isDefaultFileSystem = isDefaultFileSystem(entry);
// JAR file
if (fn.endsWith(".jar")) {
if (isDefaultFileSystem) {
return readJar(entry);
} else {
// the JAR file is in a custom file system so
// need to copy it to the local file system
Path tmpdir = Files.createTempDirectory("mlib");
Path target = Files.copy(entry, tmpdir.resolve(fn));
return readJar(target);
}
}
// JMOD file
if (isDefaultFileSystem && isLinkPhase && fn.endsWith(".jmod")) {
return readJMod(entry);
}
}
return null;
} catch (InvalidModuleDescriptorException e) {
throw new FindException("Error reading module: " + entry, e);
}
}
/**
* Returns an InvalidModuleDescriptorException with the given detail
* message
*/
private static InvalidModuleDescriptorException
invalidModuleDescriptor(String msg) {
return new InvalidModuleDescriptorException(msg);
}
/**
* Reads a packaged or exploded module, returning a {@code ModuleReference}
* to the module. Returns {@code null} if the entry is not recognized.
*
* @throws IOException if an I/O error occurs
* @throws FindException if an error occurs parsing its module descriptor
*/
private ModuleReference readModule(Path entry, BasicFileAttributes attrs)
throws IOException
{
try {
// exploded module
if (attrs.isDirectory()) {
return readExplodedModule(entry); // may return null
}
// JAR or JMOD file
if (attrs.isRegularFile()) {
String fn = entry.getFileName().toString();
boolean isDefaultFileSystem = isDefaultFileSystem(entry);
// JAR file
if (fn.endsWith(".jar")) {
if (isDefaultFileSystem) {
return readJar(entry);
} else {
// the JAR file is in a custom file system so
// need to copy it to the local file system
Path tmpdir = Files.createTempDirectory("mlib");
Path target = Files.copy(entry, tmpdir.resolve(fn));
return readJar(target);
}
}
// JMOD file
if (isDefaultFileSystem && isLinkPhase && fn.endsWith(".jmod")) {
return readJMod(entry);
}
}
return null;
} catch (InvalidModuleDescriptorException e) {
throw new FindException("Error reading module: " + entry, e);
}
}
@Test(expectedExceptions = InvalidModuleDescriptorException.class)
public void testReadFromEmptyInputStream() throws Exception {
ModuleDescriptor.read(EMPTY_INPUT_STREAM);
}
@Test(expectedExceptions = InvalidModuleDescriptorException.class)
public void testReadFromEmptyBuffer() {
ByteBuffer bb = ByteBuffer.allocate(0);
ModuleDescriptor.read(bb);
}
/**
* Returns an InvalidModuleDescriptorException with a detail message to
* indicate that the class file is truncated.
*/
private static InvalidModuleDescriptorException truncatedModuleDescriptor() {
return invalidModuleDescriptor("Truncated module-info.class");
}
/**
* Returns an InvalidModuleDescriptorException with a detail message to
* indicate that the class file is truncated.
*/
private static InvalidModuleDescriptorException truncatedModuleDescriptor() {
return invalidModuleDescriptor("Truncated module-info.class");
}