java.lang.module.ModuleReader Java Examples

The following examples show how to use java.lang.module.ModuleReader. 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: ModuleReferences.java    From openjdk-jdk9 with GNU General Public License v2.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 #2
Source File: ModuleReaderTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test ModuleReader#read
 */
void testRead(ModuleReader reader, String name, byte[] expectedBytes)
    throws IOException
{
    Optional<ByteBuffer> obb = reader.read(name);
    assertTrue(obb.isPresent());

    ByteBuffer bb = obb.get();
    try {
        int rem = bb.remaining();
        assertTrue(rem == expectedBytes.length);
        byte[] bytes = new byte[rem];
        bb.get(bytes);
        assertTrue(Arrays.equals(bytes, expectedBytes));
    } finally {
        reader.release(bb);
    }
}
 
Example #3
Source File: Loader.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Defines the given binary class name to the VM, loading the class
 * bytes from the given module.
 *
 * @return the resulting Class or {@code null} if an I/O error occurs
 */
private Class<?> defineClass(String cn, LoadedModule loadedModule) {
    ModuleReader reader = moduleReaderFor(loadedModule.mref());

    try {
        // read class file
        String rn = cn.replace('.', '/').concat(".class");
        ByteBuffer bb = reader.read(rn).orElse(null);
        if (bb == null) {
            // class not found
            return null;
        }

        try {
            return defineClass(cn, bb, loadedModule.codeSource());
        } finally {
            reader.release(bb);
        }

    } catch (IOException ioe) {
        // TBD on how I/O errors should be propagated
        return null;
    }
}
 
Example #4
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 #5
Source File: ModuleReaderTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test ModuleReader#find
 */
void testFind(ModuleReader reader, String name, byte[] expectedBytes)
    throws IOException
{
    Optional<URI> ouri = reader.find(name);
    assertTrue(ouri.isPresent());

    URL url = ouri.get().toURL();
    if (!url.getProtocol().equalsIgnoreCase("jmod")) {
        URLConnection uc = url.openConnection();
        uc.setUseCaches(false);
        try (InputStream in = uc.getInputStream()) {
            byte[] bytes = in.readAllBytes();
            assertTrue(Arrays.equals(bytes, expectedBytes));
        }
    }
}
 
Example #6
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String mn = args[0];

    ModuleReference mref = ModuleLayer.boot()
            .configuration()
            .findModule(mn)
            .map(ResolvedModule::reference)
            .orElseThrow(() -> new RuntimeException(mn + " not resolved!!"));

    try (ModuleReader reader = mref.open()) {
        reader.list().forEach(name -> {
            testFindUnchecked(name);

            // if the resource is a directory then find without trailing slash
            if (name.endsWith("/")) {
                testFindUnchecked(name.substring(0, name.length() - 1));
            }
        });
    }
}
 
Example #7
Source File: ModuleReferenceImpl.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a new instance of this class.
 */
public ModuleReferenceImpl(ModuleDescriptor descriptor,
                           URI location,
                           Supplier<ModuleReader> readerSupplier,
                           ModulePatcher patcher,
                           ModuleTarget target,
                           ModuleHashes recordedHashes,
                           ModuleHashes.HashSupplier hasher,
                           ModuleResolution moduleResolution)
{
    super(descriptor, Objects.requireNonNull(location));
    this.location = location;
    this.readerSupplier = readerSupplier;
    this.patcher = patcher;
    this.target = target;
    this.recordedHashes = recordedHashes;
    this.hasher = hasher;
    this.moduleResolution = moduleResolution;
}
 
Example #8
Source File: Loader.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Defines the given binary class name to the VM, loading the class
 * bytes from the given module.
 *
 * @return the resulting Class or {@code null} if an I/O error occurs
 */
private Class<?> defineClass(String cn, LoadedModule loadedModule) {
    ModuleReader reader = moduleReaderFor(loadedModule.mref());

    try {
        // read class file
        String rn = cn.replace('.', '/').concat(".class");
        ByteBuffer bb = reader.read(rn).orElse(null);
        if (bb == null) {
            // class not found
            return null;
        }

        try {
            return defineClass(cn, bb, loadedModule.codeSource());
        } finally {
            reader.release(bb);
        }

    } catch (IOException ioe) {
        // TBD on how I/O errors should be propagated
        return null;
    }
}
 
Example #9
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 #10
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 #11
Source File: ModuleFixerPlugin.java    From pro with GNU General Public License v3.0 6 votes vote down vote up
private static void scanManifest(String resource, ModuleReader reader, Map<String, Object> propertyMap) throws IOException {
  try(var input = reader.open(resource).orElseThrow(() -> new IOException("resource unavailable " + resource));
      var isr = new InputStreamReader(input, StandardCharsets.UTF_8);
      var lineReader = new BufferedReader(isr)) {

    lineReader.lines()
    .flatMap(line -> {
      int index = line.indexOf(':');
      if (index == -1) {
        return Stream.empty();
      }
      String key = line.substring(0, index);
      String value = line.substring(index + 1).trim();
      return extractManifestValue(key, value).map(object -> Map.entry(key, object)).stream();
    })
    .forEach(entry -> propertyMap.put(entry.getKey(), entry.getValue()));

  }
}
 
Example #12
Source File: ModuleFixerPlugin.java    From pro with GNU General Public License v3.0 6 votes vote down vote up
private static void scanJavaClass(String resource, ModuleReader reader, Set<String> requirePackages, Set<String> exports, Set<String> uses) throws IOException {
try(var input = reader.open(resource).orElseThrow(() -> new IOException("resource unavailable " + resource))) {
  var classReader = new ClassReader(input);
  var className = classReader.getClassName();
  if (className.equals("module-info")) {
    return;  // skip module-info
  }
  var packageName = packageOf(className);
  exports.add(packageName);

  classReader.accept(new ClassRemapper(EmptyClassVisitor.getInstance(), new Remapper() {
    @Override
    public String map(String typeName) {
      String packageName = packageOf(typeName);
      requirePackages.add(packageName);
      return typeName;
    }
  }) {
    String owner;
 
Example #13
Source File: ModuleReferenceImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs a new instance of this class.
 */
ModuleReferenceImpl(ModuleDescriptor descriptor,
                    URI location,
                    Supplier<ModuleReader> readerSupplier,
                    ModulePatcher patcher,
                    ModuleTarget target,
                    ModuleHashes recordedHashes,
                    ModuleHashes.HashSupplier hasher,
                    ModuleResolution moduleResolution)
{
    super(descriptor, Objects.requireNonNull(location));
    this.location = location;
    this.readerSupplier = readerSupplier;
    this.patcher = patcher;
    this.target = target;
    this.recordedHashes = recordedHashes;
    this.hasher = hasher;
    this.moduleResolution = moduleResolution;
}
 
Example #14
Source File: ModuleReaderTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test ModuleReader#list
 */
void testList(ModuleReader reader, String name) throws IOException {
    List<String> list = reader.list().collect(Collectors.toList());
    Set<String> names = new HashSet<>(list);
    assertTrue(names.size() == list.size()); // no duplicates

    assertTrue(names.contains("module-info.class"));
    assertTrue(names.contains(name));

    // all resources should be locatable via find
    for (String e : names) {
        assertTrue(reader.find(e).isPresent());
    }
}
 
Example #15
Source File: ModuleReferenceImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ModuleReader open() throws IOException {
    try {
        return readerSupplier.get();
    } catch (UncheckedIOException e) {
        throw e.getCause();
    }
}
 
Example #16
Source File: ModulePatcher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the ModuleReader to delegate to when the resource is not
 * found in a patch location.
 */
private ModuleReader delegate() throws IOException {
    ModuleReader r = delegate;
    if (r == null) {
        synchronized (this) {
            r = delegate;
            if (r == null) {
                delegate = r = mref.open();
            }
        }
    }
    return r;
}
 
Example #17
Source File: ResourcePoolConfiguration.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static ModuleReference moduleReference(ModuleDescriptor desc) {
    return new ModuleReference(desc, null) {
        @Override
        public ModuleReader open() {
            throw new UnsupportedOperationException();
        }
    };
}
 
Example #18
Source File: ModuleReaderTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test ModuleReader#open
 */
void testOpen(ModuleReader reader, String name, byte[] expectedBytes)
    throws IOException
{
    Optional<InputStream> oin = reader.open(name);
    assertTrue(oin.isPresent());

    InputStream in = oin.get();
    try (in) {
        byte[] bytes = in.readAllBytes();
        assertTrue(Arrays.equals(bytes, expectedBytes));
    }
}
 
Example #19
Source File: ModuleReferences.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a ModuleReference to a possibly-patched module in a modular JAR.
 */
static ModuleReference newJarModule(ModuleInfo.Attributes attrs,
                                    ModulePatcher patcher,
                                    Path file) {
    URI uri = file.toUri();
    Supplier<ModuleReader> supplier = () -> new JarModuleReader(file, uri);
    HashSupplier hasher = (a) -> ModuleHashes.computeHash(file, a);
    return newModule(attrs, uri, supplier, patcher, hasher);
}
 
Example #20
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 #21
Source File: ModuleReferenceTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private ModuleReference newModuleReference(ModuleDescriptor descriptor, URI uri) {
    return new ModuleReference(descriptor, uri) {
        @Override
        public ModuleReader open() {
            throw new UnsupportedOperationException();
        }
    };
}
 
Example #22
Source File: ModuleTargetHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static ModuleTarget read(ModuleReference modRef) throws IOException {
    ModuleReader reader = modRef.open();
    try (InputStream in = reader.open("module-info.class").get()) {
        return read(in);
    } finally {
        reader.close();
    }
}
 
Example #23
Source File: ModuleLocationFactory.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static <T> T doWithModuleReader(ModuleReference moduleReference, ModuleReaderProcessor<T> readerProcessor) {
    try (ModuleReader moduleReader = moduleReference.open()) {
        return readerProcessor.process(moduleReader);
    } catch (IOException e) {
        String message = String.format("Unexpected error while processing module %s", moduleReference);
        throw new RuntimeException(message, e);
    }
}
 
Example #24
Source File: ModuleHelper.java    From pro with GNU General Public License v3.0 5 votes vote down vote up
private static ModuleReference moduleReference(ModuleDescriptor descriptor, URI uri, ModuleReader moduleReader) {
  return new ModuleReference(descriptor, uri) {
    @Override
    public ModuleReader open() {
      return moduleReader;
    }

    @Override
    public String toString() {
      return descriptor.name() + " at " + uri;
    }
  };
}
 
Example #25
Source File: ModuleFixerPlugin.java    From pro with GNU General Public License v3.0 5 votes vote down vote up
private static void scanServiceFile(String resource, ModuleReader reader, Map<String, Set<String>> provides) throws IOException {
  var service = resource.substring("META-INF/services/".length());
  try(var input = reader.open(resource).orElseThrow(() -> new IOException("resource unavailable " + resource));
      var isr = new InputStreamReader(input, StandardCharsets.UTF_8);
      var lineReader = new BufferedReader(isr)) {

    var providers = lineReader.lines()
        .map(ModuleFixerPlugin::parseProviderLine)
        .filter(provider -> !provider.isEmpty())  // skip empty line
        .collect(Collectors.toSet());
    provides.put(service, providers);
  }
}
 
Example #26
Source File: AutocompleteClasspathScanner.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private void scanClassesFromModulePath() {
  ModuleLayer.boot().configuration().modules().stream()
          .map(ResolvedModule::reference)
          .forEach(mref -> {
            try (ModuleReader reader = mref.open()) {
              reader.list().forEach( x -> addClass(x));
            } catch (IOException ioe) {
              throw new UncheckedIOException(ioe);
            }
          });
}
 
Example #27
Source File: ModuleReferences.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a ModuleReference to a module in a JMOD file.
 */
static ModuleReference newJModModule(ModuleInfo.Attributes attrs, Path file) {
    URI uri = file.toUri();
    Supplier<ModuleReader> supplier = () -> new JModModuleReader(file, uri);
    HashSupplier hasher = (a) -> ModuleHashes.computeHash(file, a);
    return newModule(attrs, uri, supplier, null, hasher);
}
 
Example #28
Source File: Loader.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a ModuleReader for the given module.
 */
private ModuleReader createModuleReader(ModuleReference mref) {
    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();
    }
}
 
Example #29
Source File: ModuleReferences.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a ModuleReference to a possibly-patched module in a modular JAR.
 */
static ModuleReference newJarModule(ModuleInfo.Attributes attrs,
                                    ModulePatcher patcher,
                                    Path file) {
    URI uri = file.toUri();
    Supplier<ModuleReader> supplier = () -> new JarModuleReader(file, uri);
    HashSupplier hasher = (a) -> ModuleHashes.computeHash(file, a);
    return newModule(attrs, uri, supplier, patcher, hasher);
}
 
Example #30
Source File: ModuleReferences.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a ModuleReference to a module in a JMOD file.
 */
static ModuleReference newJModModule(ModuleInfo.Attributes attrs, Path file) {
    URI uri = file.toUri();
    Supplier<ModuleReader> supplier = () -> new JModModuleReader(file, uri);
    HashSupplier hasher = (a) -> ModuleHashes.computeHash(file, a);
    return newModule(attrs, uri, supplier, null, hasher);
}