java.lang.module.ModuleReference Java Examples

The following examples show how to use java.lang.module.ModuleReference. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AddPackagesAttribute.java    From openjdk-jdk9 with GNU General Public License v2.0 7 votes vote down vote up
public static void main(String[] args) throws IOException {

        if (args.length != 1) {
            System.err.println("Usage AddPackagesAttribute exploded-java-home");
            System.exit(-1);
        }

        String home = args[0];
        Path dir = Paths.get(home, "modules");

        ModuleFinder finder = ModuleFinder.of(dir);

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            for (Path entry : stream) {
                Path mi = entry.resolve("module-info.class");
                if (Files.isRegularFile(mi)) {
                    String mn = entry.getFileName().toString();
                    Optional<ModuleReference> omref = finder.find(mn);
                    if (omref.isPresent()) {
                        Set<String> packages = omref.get().descriptor().packages();
                        addPackagesAttribute(mi, packages);
                    }
                }
            }
        }
    }
 
Example #2
Source File: ResolverPlugin.java    From pro with GNU General Public License v3.0 6 votes vote down vote up
private static Optional<ModuleReference> validateModuleReferenceFromArtifact(Log log, ArtifactDescriptor resolvedArtifact) {
  var finder = ModuleFinder.of(resolvedArtifact.getPath());
  Set<ModuleReference> moduleReferences;
  try {
    moduleReferences = finder.findAll();
  } catch (FindException e) {
    log.info(null, __ -> "WARNING! finding " + resolvedArtifact + " failed: " + e);
    return Optional.empty();
  }
  var referenceOpt = moduleReferences.stream().findFirst();
  if (!referenceOpt.isPresent()) {
    log.info(null, __ -> "WARNING! artifact " + resolvedArtifact + " is not a valid jar");
    return Optional.empty();
  }
  return referenceOpt;
}
 
Example #3
Source File: BuiltinClassLoader.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the URL to a resource in a module or {@code null} if not found.
 */
private URL findResource(ModuleReference mref, String name) throws IOException {
    URI u;
    if (System.getSecurityManager() == null) {
        u = moduleReaderFor(mref).find(name).orElse(null);
    } else {
        try {
            u = AccessController.doPrivileged(new PrivilegedExceptionAction<> () {
                @Override
                public URI run() throws IOException {
                    return moduleReaderFor(mref).find(name).orElse(null);
                }
            });
        } catch (PrivilegedActionException pae) {
            throw (IOException) pae.getCause();
        }
    }
    if (u != null) {
        try {
            return u.toURL();
        } catch (MalformedURLException | IllegalArgumentException e) { }
    }
    return null;
}
 
Example #4
Source File: ModulePatcher.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates the ModuleReader to reads resources in a patched module.
 */
PatchedModuleReader(List<Path> patches, ModuleReference mref) {
    List<ResourceFinder> finders = new ArrayList<>();
    boolean initialized = false;
    try {
        for (Path file : patches) {
            if (Files.isRegularFile(file)) {
                finders.add(new JarResourceFinder(file));
            } else {
                finders.add(new ExplodedResourceFinder(file));
            }
        }
        initialized = true;
    } catch (IOException ioe) {
        throw new UncheckedIOException(ioe);
    } finally {
        // close all ResourceFinder in the event of an error
        if (!initialized) closeAll(finders);
    }

    this.finders = finders;
    this.mref = mref;
    this.delegateCodeSourceURL = codeSourceURL(mref);
}
 
Example #5
Source File: ModuleReferences.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a ModuleReference to a possibly-patched module
 */
private static ModuleReference newModule(ModuleInfo.Attributes attrs,
                                         URI uri,
                                         Supplier<ModuleReader> supplier,
                                         ModulePatcher patcher,
                                         HashSupplier hasher) {
    ModuleReference mref = new ModuleReferenceImpl(attrs.descriptor(),
                                                   uri,
                                                   supplier,
                                                   null,
                                                   attrs.target(),
                                                   attrs.recordedHashes(),
                                                   hasher,
                                                   attrs.moduleResolution());
    if (patcher != null)
        mref = patcher.patchIfNeeded(mref);

    return mref;
}
 
Example #6
Source File: RunnerPlugin.java    From pro with GNU General Public License v3.0 6 votes vote down vote up
private static Optional<String> findMainModule(List<Path> modulePath, Log log) {
  for(var path: modulePath) {
    var finder = ModuleFinder.of(path);
    
    var mainClasses = finder.findAll().stream()
      .map(ModuleReference::descriptor)
      .flatMap(desc -> desc.mainClass().map(mainClass -> desc.name() + '/' + mainClass).stream())
      .collect(toUnmodifiableSet());
    
    switch(mainClasses.size()) {
    case 0:
      break;
    case 1:
      return Optional.of(mainClasses.iterator().next());
    default:
      log.error(mainClasses, _mainClasses -> "several main classes found " + String.join(", ", _mainClasses));
      return Optional.empty();
    }
  }
  
  log.error(modulePath, _modulePath -> "no main class found in " + _modulePath.stream().map(Path::toString).collect(joining(":")));
  return Optional.empty();
}
 
Example #7
Source File: BuiltinClassLoader.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the ModuleReader for the given module, creating it if needed.
 */
private ModuleReader moduleReaderFor(ModuleReference mref) {
    ModuleReader reader = moduleToReader.get(mref);
    if (reader == null) {
        // avoid method reference during startup
        Function<ModuleReference, ModuleReader> create = new Function<>() {
            public ModuleReader apply(ModuleReference moduleReference) {
                try {
                    return mref.open();
                } catch (IOException e) {
                    // Return a null module reader to avoid a future class
                    // load attempting to open the module again.
                    return new NullModuleReader();
                }
            }
        };
        reader = moduleToReader.computeIfAbsent(mref, create);
    }
    return reader;
}
 
Example #8
Source File: ModuleLibrary.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void add(ModuleDescriptor... descriptors) {
    for (ModuleDescriptor descriptor: descriptors) {
        String name = descriptor.name();
        if (!namesToReference.containsKey(name)) {
            //modules.add(descriptor);

            URI uri = URI.create("module:/" + descriptor.name());

            ModuleReference mref = new ModuleReference(descriptor, uri) {
                @Override
                public ModuleReader open() {
                    throw new UnsupportedOperationException();
                }
            };

            namesToReference.put(name, mref);
        }
    }
}
 
Example #9
Source File: AutomaticModulesTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test JAR file with META-INF/services configuration file with bad
 * values or names.
 */
@Test(dataProvider = "badservices")
public void testBadServicesNames(String service, String provider)
    throws IOException
{
    Path tmpdir = Files.createTempDirectory(USER_DIR, "tmp");
    Path services = tmpdir.resolve("META-INF").resolve("services");
    Files.createDirectories(services);
    Files.write(services.resolve(service), Set.of(provider));
    Path dir = Files.createTempDirectory(USER_DIR, "mods");
    JarUtils.createJarFile(dir.resolve("m.jar"), tmpdir);

    Optional<ModuleReference> omref = ModuleFinder.of(dir).find("m");
    assertTrue(omref.isPresent());
    ModuleDescriptor descriptor = omref.get().descriptor();
    assertTrue(descriptor.provides().isEmpty());
}
 
Example #10
Source File: BuiltinClassLoader.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the URL to a resource in a module or {@code null} if not found.
 */
private URL findResource(ModuleReference mref, String name) throws IOException {
    URI u;
    if (System.getSecurityManager() == null) {
        u = moduleReaderFor(mref).find(name).orElse(null);
    } else {
        try {
            u = AccessController.doPrivileged(new PrivilegedExceptionAction<> () {
                @Override
                public URI run() throws IOException {
                    return moduleReaderFor(mref).find(name).orElse(null);
                }
            });
        } catch (PrivilegedActionException pae) {
            throw (IOException) pae.getCause();
        }
    }
    if (u != null) {
        try {
            return u.toURL();
        } catch (MalformedURLException | IllegalArgumentException e) { }
    }
    return null;
}
 
Example #11
Source File: LauncherHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prints the module location and name, checks if the module is
 * shadowed by a previously seen module, and finally checks for
 * package conflicts with previously seen modules.
 */
void process(ModuleReference mref) {
    printModule(mref);

    String name = mref.descriptor().name();
    ModuleReference previous = nameToModule.putIfAbsent(name, mref);
    if (previous != null) {
        ostream.print(INDENT + "shadowed by ");
        printModule(previous);
    } else {
        // check for package conflicts when not shadowed
        for (String pkg :  mref.descriptor().packages()) {
            previous = packageToModule.putIfAbsent(pkg, mref);
            if (previous != null) {
                String mn = previous.descriptor().name();
                ostream.println(INDENT + "contains " + pkg
                                + " conflicts with module " + mn);
                errorFound = true;
            }
        }
    }
}
 
Example #12
Source File: ModuleBootstrap.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Load/register the modules to the built-in class loaders.
 */
private static void loadModules(Configuration cf,
                                Function<String, ClassLoader> clf) {
    for (ResolvedModule resolvedModule : cf.modules()) {
        ModuleReference mref = resolvedModule.reference();
        String name = resolvedModule.name();
        ClassLoader loader = clf.apply(name);
        if (loader == null) {
            // skip java.base as it is already loaded
            if (!name.equals(JAVA_BASE)) {
                BootLoader.loadModule(mref);
            }
        } else if (loader instanceof BuiltinClassLoader) {
            ((BuiltinClassLoader) loader).loadModule(mref);
        }
    }
}
 
Example #13
Source File: ModulePath.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Scans the next entry on the module path. A no-op if all entries have
 * already been scanned.
 *
 * @throws FindException if an error occurs scanning the next entry
 */
private void scanNextEntry() {
    if (hasNextEntry()) {

        long t0 = System.nanoTime();

        Path entry = entries[next];
        Map<String, ModuleReference> modules = scan(entry);
        next++;

        // update cache, ignoring duplicates
        int initialSize = cachedModules.size();
        for (Map.Entry<String, ModuleReference> e : modules.entrySet()) {
            cachedModules.putIfAbsent(e.getKey(), e.getValue());
        }

        // update counters
        int added = cachedModules.size() - initialSize;
        moduleCount.add(added);

        scanTime.addElapsedTimeFrom(t0);
    }
}
 
Example #14
Source File: LauncherHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Scan a JAR file or exploded module.
 */
private Optional<ModuleReference> scanModule(Path entry) {
    ModuleFinder finder = ModuleFinder.of(entry);
    try {
        return finder.findAll().stream().findFirst();
    } catch (FindException e) {
        ostream.println(entry);
        ostream.println(INDENT + e.getMessage());
        Throwable cause = e.getCause();
        if (cause != null) {
            ostream.println(INDENT + cause);
        }
        errorFound = true;
        return Optional.empty();
    }
}
 
Example #15
Source File: AutomaticModulesTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test that a JAR file with a Main-Class attribute that is not a qualified
 * type name.
 */
@Test(dataProvider = "badmainclass")
public void testBadMainClass(String mainClass, String ignore) throws IOException {
    Manifest man = new Manifest();
    Attributes attrs = man.getMainAttributes();
    attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
    attrs.put(Attributes.Name.MAIN_CLASS, mainClass);

    Path dir = Files.createTempDirectory(USER_DIR, "mods");
    String entry = mainClass.replace('.', '/') + ".class";
    createDummyJarFile(dir.resolve("m.jar"), man, entry);

    // bad Main-Class value should be ignored
    Optional<ModuleReference> omref = ModuleFinder.of(dir).find("m");
    assertTrue(omref.isPresent());
    ModuleDescriptor descriptor = omref.get().descriptor();
    assertFalse(descriptor.mainClass().isPresent());
}
 
Example #16
Source File: AutomaticModulesTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test all packages are exported
 */
public void testPackages() throws IOException {
    Path dir = Files.createTempDirectory(USER_DIR, "mods");
    createDummyJarFile(dir.resolve("m.jar"),
                       "p/C1.class", "p/C2.class", "q/C1.class");

    ModuleFinder finder = ModuleFinder.of(dir);
    Optional<ModuleReference> mref = finder.find("m");
    assertTrue(mref.isPresent(), "m not found");

    ModuleDescriptor descriptor = mref.get().descriptor();
    assertTrue(descriptor.isAutomatic());

    assertTrue(descriptor.packages().size() == 2);
    assertTrue(descriptor.packages().contains("p"));
    assertTrue(descriptor.packages().contains("q"));

    assertTrue(descriptor.exports().isEmpty());
    assertTrue(descriptor.opens().isEmpty());
}
 
Example #17
Source File: Loader.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@code Loader} in a loader pool that loads classes/resources
 * from one module.
 */
public Loader(ResolvedModule resolvedModule,
              LoaderPool pool,
              ClassLoader parent)
{
    super("Loader-" + resolvedModule.name(), parent);

    this.pool = pool;
    this.parent = parent;

    ModuleReference mref = resolvedModule.reference();
    ModuleDescriptor descriptor = mref.descriptor();
    String mn = descriptor.name();
    this.nameToModule = Map.of(mn, mref);

    Map<String, LoadedModule> localPackageToModule = new HashMap<>();
    LoadedModule lm = new LoadedModule(mref);
    descriptor.packages().forEach(pn -> localPackageToModule.put(pn, lm));
    this.localPackageToModule = localPackageToModule;

    this.acc = AccessController.getContext();
}
 
Example #18
Source File: AutomaticModulesTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test class files in JAR file where the entry does not correspond to a
 * legal package name.
 */
public void testBadPackage() throws IOException {
    Path dir = Files.createTempDirectory(USER_DIR, "mods");
    createDummyJarFile(dir.resolve("m.jar"), "p/C1.class", "p-/C2.class");

    ModuleFinder finder = ModuleFinder.of(dir);
    Optional<ModuleReference> mref = finder.find("m");
    assertTrue(mref.isPresent(), "m not found");

    ModuleDescriptor descriptor = mref.get().descriptor();
    assertTrue(descriptor.isAutomatic());

    assertTrue(descriptor.packages().size() == 1);
    assertTrue(descriptor.packages().contains("p"));

    assertTrue(descriptor.exports().isEmpty());
    assertTrue(descriptor.opens().isEmpty());
}
 
Example #19
Source File: ModuleFinderWithSecurityManager.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    boolean allow = args[0].equals("allow");

    // set security policy to allow access
    if (allow) {
        String testSrc = System.getProperty("test.src");
        if (testSrc == null)
            testSrc = ".";
        Path policyFile = Paths.get(testSrc, "java.policy");
        System.setProperty("java.security.policy", policyFile.toString());
    }

    System.setSecurityManager(new SecurityManager());

    ModuleFinder finder = null;
    try {
        finder = ModuleFinder.ofSystem();
        if (!allow) throw new RuntimeException("SecurityException expected");
    } catch (SecurityException e) {
        if (allow) throw new RuntimeException("SecurityException not expected");
    }

    // no additional permissions should be required to locate modules
    if (finder != null) {
        ModuleReference base = finder.find("java.base").orElse(null);
        if (base == null)
            throw new RuntimeException("java.base not found");
        Set<ModuleReference> allModules = finder.findAll();
        if (!allModules.contains(base))
            throw new RuntimeException("java.base not in all modules");
    }
}
 
Example #20
Source File: Loader.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true if the given module opens the given package
 * unconditionally.
 *
 * @implNote This method currently iterates over each of the open
 * packages. This will be replaced once the ModuleDescriptor.Opens
 * API is updated.
 */
private boolean isOpen(ModuleReference mref, String pn) {
    ModuleDescriptor descriptor = mref.descriptor();
    if (descriptor.isOpen() || descriptor.isAutomatic())
        return true;
    for (ModuleDescriptor.Opens opens : descriptor.opens()) {
        String source = opens.source();
        if (!opens.isQualified() && source.equals(pn)) {
            return true;
        }
    }
    return false;
}
 
Example #21
Source File: WithSecurityManager.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a module layer that contains the given system module.
 */
static Module loadModuleInChildLayer(String mn) {
    Optional<ModuleReference> omref = ModuleFinder.ofSystem().find(mn);
    assertTrue("module " + mn + " not a system module", omref.isPresent());

    // create a ModuleFinder that only finds this module
    ModuleReference mref = omref.get();
    ModuleFinder finder = new ModuleFinder() {
        @Override
        public Optional<ModuleReference> find(String name) {
            if (name.equals(mn))
                return Optional.of(mref);
            else
                return Optional.empty();
        }

        @Override
        public Set<ModuleReference> findAll() {
            return Collections.singleton(mref);
        }
    };

    // create a child configuration and layer with this module
    ModuleLayer bootLayer = ModuleLayer.boot();
    Configuration cf = bootLayer
        .configuration()
        .resolve(finder, ModuleFinder.of(), Set.of(ANOTHER_MODULE));
    ModuleLayer layer = bootLayer.defineModulesWithOneLoader(cf, null);

    Optional<Module> om = layer.findModule(mn);
    assertTrue("module " + mn + " not in child layer", om.isPresent());
    return om.get();
}
 
Example #22
Source File: JdepsConfiguration.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void initProfiles() {
    // other system modules are not observed and not added in nameToModule map
    Map<String, Module> systemModules =
        system.moduleNames()
            .collect(toMap(Function.identity(), (mn) -> {
                Module m = nameToModule.get(mn);
                if (m == null) {
                    ModuleReference mref = finder.find(mn).get();
                    m = toModule(mref);
                }
                return m;
            }));
    Profile.init(systemModules);
}
 
Example #23
Source File: ModuleReferenceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testNullLocation() {
    ModuleDescriptor descriptor
        = ModuleDescriptor.newModule("m")
            .exports("p")
            .build();
    ModuleReference mref = newModuleReference(descriptor, null);
    assertTrue(!mref.location().isPresent());
}
 
Example #24
Source File: Loader.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
LoadedModule(ModuleReference mref) {
    URL url = null;
    if (mref.location().isPresent()) {
        try {
            url = mref.location().get().toURL();
        } catch (MalformedURLException | IllegalArgumentException e) { }
    }
    this.mref = mref;
    this.url = url;
    this.cs = new CodeSource(url, (CodeSigner[]) null);
}
 
Example #25
Source File: LauncherHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prints a single line with the module name, version and modifiers
 */
private static void showModule(ModuleReference mref) {
    ModuleDescriptor md = mref.descriptor();
    ostream.print(md.toNameAndVersion());
    mref.location()
            .filter(uri -> !isJrt(uri))
            .ifPresent(uri -> ostream.format(" %s", uri));
    if (md.isOpen())
        ostream.print(" open");
    if (md.isAutomatic())
        ostream.print(" automatic");
    ostream.println();
}
 
Example #26
Source File: ModulesInCustomFileSystem.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * List all modules that the finder finds and the resources in the module.
 */
private void listAllModules(ModuleFinder finder) throws Exception {
    for (ModuleReference mref : finder.findAll()) {
        System.out.println(mref.descriptor());
        try (ModuleReader reader = mref.open()) {
            reader.list().forEach(name -> System.out.format("  %s%n", name));
        }
    }
}
 
Example #27
Source File: FileUtils.java    From update4j with Apache License 2.0 5 votes vote down vote up
private static ModuleDescriptor primitiveModuleDescriptor(Path jar, String filename) throws IOException {
    String tempName = "a" + jar.getFileName();
    Path temp = Paths.get(System.getProperty("user.home"), tempName + ".jar");
    ModuleDescriptor mod;
    try {
        Files.copy(jar, temp);
        mod = ModuleFinder.of(temp) //
                        .findAll()
                        .stream()
                        .map(ModuleReference::descriptor)
                        .findAny()
                        .orElseThrow(IllegalStateException::new);

    } finally {
        Files.deleteIfExists(temp);
    }

    if (tempName.equals(mod.name())) {
        String newModuleName = StringUtils.deriveModuleName(filename);
        if (!StringUtils.isModuleName(newModuleName)) {
            Warning.illegalModule(jar.getFileName().toString());
            throw new IllegalStateException("Automatic module name '" + newModuleName + "' for file '"
                            + jar.getFileName() + "' is not valid.");
        }

        return ModuleDescriptor.newAutomaticModule(newModuleName).packages(mod.packages()).build();

    }

    return mod;
}
 
Example #28
Source File: ModuleHelper.java    From pro with GNU General Public License v3.0 5 votes vote down vote up
private static void deepFirst(String name, Map<String, ModuleReference> map, LinkedHashSet<ModuleReference> order) {
  var moduleRef = map.get(name);
  if (moduleRef == null) {
    return;
  }
  map.remove(name);  // visited

  for(var requires: moduleRef.descriptor().requires()) {
    deepFirst(requires.name(), map, order);
  }
  order.add(moduleRef);
}
 
Example #29
Source File: ModulePath.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a string with the file name of the module if possible.
 * If the module location is not a file URI then return the URI
 * as a string.
 */
private String fileName(ModuleReference mref) {
    URI uri = mref.location().orElse(null);
    if (uri != null) {
        if (uri.getScheme().equalsIgnoreCase("file")) {
            Path file = Paths.get(uri);
            return file.getFileName().toString();
        } else {
            return uri.toString();
        }
    } else {
        return "<unknown>";
    }
}
 
Example #30
Source File: ModuleLocationFactory.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
ModuleClassFileSource(
        ModuleReference moduleReference,
        NormalizedResourceName resourceName,
        ImportOptions importOptions) {

    Set<String> entries = loadEntries(moduleReference, resourceName);
    locations = entries.stream()
            .map(entry -> new ModuleClassFileLocation(moduleReference, entry))
            .filter(classFileLocation -> classFileLocation.isIncludedBy(importOptions))
            .map(Function.identity()); // thanks Java type system :-(
}