Java Code Examples for java.lang.module.ModuleReader

Following code examples demonstrate how to use java.lang.module.ModuleReaderfrom java. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use java.lang.module.ModuleReaderand various code implementation of this class.

            public ModuleReader open() throws IOException {
                ModuleReader moduleReader = new ModuleReader() {
                    @Override
                    public Optional<URI> find(String name) throws IOException {
                        throw new UnsupportedOperationException("Not supported yet.");
                    }

                    @Override
                    public Stream<String> list() throws IOException {
                        throw new UnsupportedOperationException("Not supported yet.");
                    }

                    @Override
                    public void close() throws IOException {
                        throw new UnsupportedOperationException("Not supported yet.");
                    }
                };
                return moduleReader;
            } 


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try (ModuleReader reader = createReader()) {
            Optional<InputStream> optionalStream = reader.open(BASE_PATH + request.getPathInfo());
            reader.list().collect(toList());
            if (optionalStream.isPresent()) {
                try (InputStream is = optionalStream.get()) {
                    is.transferTo(response.getOutputStream());

                    response.setStatus(HttpServletResponse.SC_OK);
                    response.setContentType("text/html");
                }
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
                response.setContentType("text/html");
            }
        }
    } 

    private ModuleReader createReader() throws IOException {
        String webAppModule = getServletContext().getInitParameter(ServletContextImpl.InitParams.WEBAPP_MODULE);
        return getClass().
                getModule().
                getLayer().
                configuration().
                findModule(webAppModule).
                get().
                reference().
                open();
    } 

    public ModuleReader open(){
        if(descriptor().name().equals("minecraft")){
            return new MinecraftModuleReader(location, jar);
        }

        return new BasicModuleReader(jar, location);
    } 

    public static void main(String[] args) {
        ModuleFinder finder = ModuleFinder.ofSystem();

        Optional<ModuleReference> omr = finder.find("java.base");
        ModuleReference moduleRef = omr.get();

        try (ModuleReader reader = moduleRef.open()) {
            Optional<ByteBuffer> bb = reader.read("java/lang/Object.class");

            bb.ifPresent(
                buffer -> {System.out.println("Object.class Size: " + buffer.limit());

                reader.release(buffer);
            });

            System.out.println("\nFive resources in the java.base module:");
            reader.list()
                  .limit(5)
                  .forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 

    protected ModuleReference(ModuleDescriptor descriptor, URI location) {
        super(descriptor,location);
        this.descriptor = Objects.requireNonNull(descriptor);
        this.location = location;
    } 

    public static Set<String> getRedistributableModules(List<Path> modulePath) {
        Set<String> result = null;

        Set<String> addModules = new HashSet<>();
        Set<String> limitModules = new HashSet<>();
        ModuleFinder finder = AppRuntimeImageBuilder.moduleFinder(modulePath, addModules, limitModules);
        Optional<ModuleReference> mref = finder.find(JDK_PACKAGER_MODULE);

        if (mref.isPresent()) {
            ModuleReader reader = null;

            try {
                reader = mref.get().open();
            } catch (IOException ex) {
            }

            if (reader != null) {
                Optional<InputStream> stream = null;

                try {
                    stream = reader.open(LEGACY_JRE_MODULES_FILENAME);
                } catch (IOException ex) {
                }

                if (stream != null) {
                    if (stream.isPresent()) {
                        BufferedReader br = null;

                        try {
                            br = new BufferedReader(new InputStreamReader(stream.get(), "UTF-8"));
                        } catch (UnsupportedEncodingException ex) {
                        }

                        if (br != null) {
                            result = new LinkedHashSet();
                            String line;

                            try {
                                while ((line = br.readLine()) != null) {
                                    String module = stripComments(line);

                                    if (!module.isEmpty()) {
                                        result.add(line);
                                    }
                                }
                            } catch (IOException ex) {
                            }
                        }
                    }
                }
            }
        }

        return result;
    } 

    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();
        }
    } 

    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 (name.endsWith("/")) {
                    testFindUnchecked(name.substring(0, name.length() - 1));
                }
            });
        }
    } 

    public static void main(String[] args) {
        ModuleFinder moduleFinder = ModuleFinder.ofSystem();
        Optional<ModuleReference> omr = moduleFinder.find("java.base");
        ModuleReference moduleReference = omr.get();

        try (ModuleReader reader = moduleReference.open()) {
            Optional<ByteBuffer> bb = reader.read("java/lang/Object.class");
            bb.ifPresent(byteBuffer -> {
                System.out.println("Object.class Size: "+byteBuffer.limit());

                reader.release(byteBuffer);
            });

            System.out.println("\nFive resources in java.base module: ");
            reader.list().limit(5).forEach(System.out::println);
        } catch (IOException ex){
            System.out.println(ex.getMessage());
        }
    } 

    @Override
    public ModuleReader open() throws IOException
    {
        return reader.get();
    } 

    
    void testOpen(ModuleReader reader, String name, byte[] expectedBytes)
        throws Exception
    {
        Optional<InputStream> oin = reader.open(name);
        assertTrue(oin.isPresent());

        InputStream in = oin.get();
        try (in) {
            byte[] bytes = in.readAllBytes();
            assertTrue(Arrays.equals(bytes, expectedBytes));
        }
    } 

    
    void testFind(ModuleReader reader, String name, byte[] expectedBytes)
        throws Exception
    {
        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));
            }
        }
    } 

    
    void testRead(ModuleReader reader, String name, byte[] expectedBytes)
        throws Exception
    {
        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);
        }
    } 

    public static void main(String[] arr) {
        ModuleFinder finder = ModuleFinder.ofSystem();
        Optional<ModuleReference> omr = finder.find("java.base");
        ModuleReference ref = omr.get();
        System.out.println(ref.location().orElse(null));
        System.out.println(ref.descriptor().name());

        try (ModuleReader reader = ref.open()) {

            Optional<ByteBuffer> bb = reader.read("java/lang/Object.class");
            bb.ifPresent(buffer -> {
                System.out.println("Object.class Size: " + buffer.limit());
                reader.release(buffer);
            });

            System.out.println("\nFive resources in the java.base module:");
            reader.list()
                    .limit(5)
                    .forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    } 

Advertisement
Javadoc
Provides access to the content of a module.

A module reader is intended for cases where

access to the resources in a module is required, regardless of whether the module has been loaded. A framework that scans a collection of packaged modules on the file system, for example, may use a module reader to access a specific resource in each module. A module reader is also intended to be used by ClassLoader implementations that load classes and resources from modules.

A resource in a module is identified by an abstract name that is a '/'-separated path string. For example, module java.base may have a resource "java/lang/Object.class" that, by convention, is the class file for java.lang.Object. A module reader may treat directories in the module content as resources (whether it does or not is module reader specific). Where the module content contains a directory that can be located as a resource then its name ends with a slash ('/'). The directory can also be located with a name that drops the trailing slash.

A ModuleReader is {@linkplain ModuleReference#open open upon creation and is closed by invoking the #close close method. Failure to close a module reader may result in a resource leak. The try-with-resources statement provides a useful construct to ensure that module readers are closed.

A ModuleReader implementation may require permissions to access resources in the module. Consequently the #find find, #open open, #read read, and #list list methods may throw SecurityException if access is denied by the security manager. @implSpec Implementations of ModuleReader should take great care when translating an abstract resource name to the location of a resource in a packaged module or on the file system. Implementations are advised to treat resource names with elements such as '., '..', elements containing file separators, or empty elements as "not found". More generally, if the resource name is not in the stream of elements that the list method returns then the resource should be treated as "not found" to avoid inconsistencies. @see ModuleReference @since 9 @spec JPMS

Read More
Advertisement