jdk.internal.loader.BootLoader Java Examples

The following examples show how to use jdk.internal.loader.BootLoader. 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: Modules.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Updates module m to provide a service
 */
public static void addProvides(Module m, Class<?> service, Class<?> impl) {
    ModuleLayer layer = m.getLayer();

    PrivilegedAction<ClassLoader> pa = m::getClassLoader;
    ClassLoader loader = AccessController.doPrivileged(pa);

    ClassLoader platformClassLoader = ClassLoaders.platformClassLoader();
    if (layer == null || loader == null || loader == platformClassLoader) {
        // update ClassLoader catalog
        ServicesCatalog catalog;
        if (loader == null) {
            catalog = BootLoader.getServicesCatalog();
        } else {
            catalog = ServicesCatalog.getServicesCatalog(loader);
        }
        catalog.addProvider(m, service, impl);
    }

    if (layer != null) {
        // update Layer catalog
        JLA.getServicesCatalog(layer).addProvider(m, service, impl);
    }
}
 
Example #2
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 #3
Source File: Package.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
private Class<?> getPackageInfo() {
    if (packageInfo == null) {
        // find package-info.class defined by loader
        String cn = packageName() + ".package-info";
        Module module = module();
        PrivilegedAction<ClassLoader> pa = module::getClassLoader;
        ClassLoader loader = AccessController.doPrivileged(pa);
        Class<?> c;
        if (loader != null) {
            c = loader.loadClass(module, cn);
        } else {
            c = BootLoader.loadClass(module, cn);
        }

        if (c != null) {
            packageInfo = c;
        } else {
            // store a proxy for the package info that has no annotations
            class PackageInfoProxy {}
            packageInfo = PackageInfoProxy.class;
        }
    }
    return packageInfo;
}
 
Example #4
Source File: ResourceBundle.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method will find resource bundles using the legacy mechanism
 * if the caller is unnamed module or the given class loader is
 * not the class loader of the caller module getting the resource
 * bundle, i.e. find the class that is visible to the class loader
 * and properties from unnamed module.
 *
 * The module-aware resource bundle lookup mechanism will load
 * the service providers using the service loader mechanism
 * as well as properties local in the caller module.
 */
private static ResourceBundle getBundleImpl(String baseName,
                                            Locale locale,
                                            Class<?> caller,
                                            ClassLoader loader,
                                            Control control) {
    if (caller == null) {
        throw new InternalError("null caller");
    }
    Module callerModule = caller.getModule();

    // get resource bundles for a named module only if loader is the module's class loader
    if (callerModule.isNamed() && loader == getLoader(callerModule)) {
        return getBundleImpl(callerModule, callerModule, baseName, locale, control);
    }

    // find resource bundles from unnamed module of given class loader
    // Java agent can add to the bootclasspath e.g. via
    // java.lang.instrument.Instrumentation and load classes in unnamed module.
    // It may call RB::getBundle that will end up here with loader == null.
    Module unnamedModule = loader != null
        ? loader.getUnnamedModule()
        : BootLoader.getUnnamedModule();

    return getBundleImpl(callerModule, unnamedModule, baseName, locale, control);
}
 
Example #5
Source File: Package.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private Class<?> getPackageInfo() {
    if (packageInfo == null) {
        // find package-info.class defined by loader
        String cn = packageName() + ".package-info";
        Module module = module();
        PrivilegedAction<ClassLoader> pa = module::getClassLoader;
        ClassLoader loader = AccessController.doPrivileged(pa);
        Class<?> c;
        if (loader != null) {
            c = loader.loadClass(module, cn);
        } else {
            c = BootLoader.loadClass(module, cn);
        }

        if (c != null) {
            packageInfo = c;
        } else {
            // store a proxy for the package info that has no annotations
            class PackageInfoProxy {}
            packageInfo = PackageInfoProxy.class;
        }
    }
    return packageInfo;
}
 
Example #6
Source File: Modules.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Updates module m to provide a service
 */
public static void addProvides(Module m, Class<?> service, Class<?> impl) {
    ModuleLayer layer = m.getLayer();

    PrivilegedAction<ClassLoader> pa = m::getClassLoader;
    ClassLoader loader = AccessController.doPrivileged(pa);

    ClassLoader platformClassLoader = ClassLoaders.platformClassLoader();
    if (layer == null || loader == null || loader == platformClassLoader) {
        // update ClassLoader catalog
        ServicesCatalog catalog;
        if (loader == null) {
            catalog = BootLoader.getServicesCatalog();
        } else {
            catalog = ServicesCatalog.getServicesCatalog(loader);
        }
        catalog.addProvider(m, service, impl);
    }

    if (layer != null) {
        // update Layer catalog
        JLA.getServicesCatalog(layer).addProvider(m, service, impl);
    }
}
 
Example #7
Source File: ModuleBootstrap.java    From Bytecoder with Apache License 2.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 #8
Source File: ResourceBundle.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * This method will find resource bundles using the legacy mechanism
 * if the caller is unnamed module or the given class loader is
 * not the class loader of the caller module getting the resource
 * bundle, i.e. find the class that is visible to the class loader
 * and properties from unnamed module.
 *
 * The module-aware resource bundle lookup mechanism will load
 * the service providers using the service loader mechanism
 * as well as properties local in the caller module.
 */
private static ResourceBundle getBundleImpl(String baseName,
                                            Locale locale,
                                            Class<?> caller,
                                            ClassLoader loader,
                                            Control control) {
    if (caller == null) {
        throw new InternalError("null caller");
    }
    Module callerModule = caller.getModule();

    // get resource bundles for a named module only if loader is the module's class loader
    if (callerModule.isNamed() && loader == getLoader(callerModule)) {
        return getBundleImpl(callerModule, callerModule, baseName, locale, control);
    }

    // find resource bundles from unnamed module of given class loader
    // Java agent can add to the bootclasspath e.g. via
    // java.lang.instrument.Instrumentation and load classes in unnamed module.
    // It may call RB::getBundle that will end up here with loader == null.
    Module unnamedModule = loader != null
        ? loader.getUnnamedModule()
        : BootLoader.getUnnamedModule();

    return getBundleImpl(callerModule, unnamedModule, baseName, locale, control);
}
 
Example #9
Source File: ModuleBuilder.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
Module defineModule(String moduleName, ClassLoader classLoader, URL[] urls) {
    if (moduleName == null) {
        throw new NullPointerException("moduleName");
    }
    if (urls == null) {
        throw new NullPointerException("urls");
    }
    if (urls.length == 0) {
        throw new IllegalArgumentException("urls.length is 0");
    }
    logger.info("bootstrap unnamedModule:" +  BootLoader.getUnnamedModule());
    logger.info("platform unnamedModule:" + ClassLoader.getPlatformClassLoader().getUnnamedModule());
    logger.info("system unnamedModule:" + ClassLoader.getSystemClassLoader().getUnnamedModule());

    Module unnamedModule = classLoader.getUnnamedModule();
    logger.info("defineModule classLoader: " + classLoader);
    logger.info("defineModule classLoader-unnamedModule: " + unnamedModule);


    List<PackageInfo> packageInfos = parsePackageInfo(urls);
    Set<String> packages = mergePackageInfo(packageInfos);
    logger.info("packages:" + packages);
    Map<String, Set<String>> serviceInfoMap = mergeServiceInfo(packageInfos);
    logger.info("providers:" + serviceInfoMap);

    ModuleDescriptor.Builder builder = ModuleDescriptor.newModule(moduleName);
    builder.packages(packages);
    for (Map.Entry<String, Set<String>> entry : serviceInfoMap.entrySet()) {
        builder.provides(entry.getKey(), new ArrayList<>(entry.getValue()));
    }

    ModuleDescriptor moduleDescriptor = builder.build();
    URI url = getInformationURI(urls);

    Module module = Modules.defineModule(classLoader, moduleDescriptor , url);
    logger.info("defineModule module:" + module);
    return module;
}
 
Example #10
Source File: ResourceBundle.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Loads a {@code ResourceBundle} of the given {@code bundleName} local to
 * the given {@code module}. If not found, search the bundle class
 * that is visible from the module's class loader.
 *
 * The caller module is used for access check only.
 */
static ResourceBundle loadResourceBundle(Module callerModule,
                                         Module module,
                                         String baseName,
                                         Locale locale)
{
    String bundleName = Control.INSTANCE.toBundleName(baseName, locale);
    try {
        PrivilegedAction<Class<?>> pa = () -> Class.forName(module, bundleName);
        Class<?> c = AccessController.doPrivileged(pa, null, GET_CLASSLOADER_PERMISSION);
        trace("local in %s %s caller %s: %s%n", module, bundleName, callerModule, c);

        if (c == null) {
            // if not found from the given module, locate resource bundle
            // that is visible to the module's class loader
            ClassLoader loader = getLoader(module);
            if (loader != null) {
                c = Class.forName(bundleName, false, loader);
            } else {
                c = BootLoader.loadClassOrNull(bundleName);
            }
            trace("loader for %s %s caller %s: %s%n", module, bundleName, callerModule, c);
        }

        if (c != null && ResourceBundle.class.isAssignableFrom(c)) {
            @SuppressWarnings("unchecked")
            Class<ResourceBundle> bundleClass = (Class<ResourceBundle>) c;
            Module m = bundleClass.getModule();
            if (!isAccessible(callerModule, m, bundleClass.getPackageName())) {
                trace("   %s does not have access to %s/%s%n", callerModule,
                      m.getName(), bundleClass.getPackageName());
                return null;
            }

            return newResourceBundle(bundleClass);
        }
    } catch (ClassNotFoundException e) {}
    return null;
}
 
Example #11
Source File: ResourceBundle.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Loads a {@code ResourceBundle} of the given {@code bundleName} local to
 * the given {@code module}. If not found, search the bundle class
 * that is visible from the module's class loader.
 *
 * The caller module is used for access check only.
 */
static ResourceBundle loadResourceBundle(Module callerModule,
                                         Module module,
                                         String baseName,
                                         Locale locale)
{
    String bundleName = Control.INSTANCE.toBundleName(baseName, locale);
    try {
        PrivilegedAction<Class<?>> pa = () -> Class.forName(module, bundleName);
        Class<?> c = AccessController.doPrivileged(pa, null, GET_CLASSLOADER_PERMISSION);
        trace("local in %s %s caller %s: %s%n", module, bundleName, callerModule, c);

        if (c == null) {
            // if not found from the given module, locate resource bundle
            // that is visible to the module's class loader
            ClassLoader loader = getLoader(module);
            if (loader != null) {
                c = Class.forName(bundleName, false, loader);
            } else {
                c = BootLoader.loadClassOrNull(bundleName);
            }
            trace("loader for %s %s caller %s: %s%n", module, bundleName, callerModule, c);
        }

        if (c != null && ResourceBundle.class.isAssignableFrom(c)) {
            @SuppressWarnings("unchecked")
            Class<ResourceBundle> bundleClass = (Class<ResourceBundle>) c;
            Module m = bundleClass.getModule();
            if (!isAccessible(callerModule, m, bundleClass.getPackageName())) {
                trace("   %s does not have access to %s/%s%n", callerModule,
                      m.getName(), bundleClass.getPackageName());
                return null;
            }

            return newResourceBundle(bundleClass);
        }
    } catch (ClassNotFoundException e) {}
    return null;
}
 
Example #12
Source File: Class.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns the {@code Class} with the given <a href="ClassLoader.html#name">
 * binary name</a> in the given module.
 *
 * <p> This method attempts to locate, load, and link the class or interface.
 * It does not run the class initializer.  If the class is not found, this
 * method returns {@code null}. </p>
 *
 * <p> If the class loader of the given module defines other modules and
 * the given name is a class defined in a different module, this method
 * returns {@code null} after the class is loaded. </p>
 *
 * <p> This method does not check whether the requested class is
 * accessible to its caller. </p>
 *
 * @apiNote
 * This method returns {@code null} on failure rather than
 * throwing a {@link ClassNotFoundException}, as is done by
 * the {@link #forName(String, boolean, ClassLoader)} method.
 * The security check is a stack-based permission check if the caller
 * loads a class in another module.
 *
 * @param  module   A module
 * @param  name     The <a href="ClassLoader.html#name">binary name</a>
 *                  of the class
 * @return {@code Class} object of the given name defined in the given module;
 *         {@code null} if not found.
 *
 * @throws NullPointerException if the given module or name is {@code null}
 *
 * @throws LinkageError if the linkage fails
 *
 * @throws SecurityException
 *         <ul>
 *         <li> if the caller is not the specified module and
 *         {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
 *         <li> access to the module content is denied. For example,
 *         permission check will be performed when a class loader calls
 *         {@link ModuleReader#open(String)} to read the bytes of a class file
 *         in a module.</li>
 *         </ul>
 *
 * @since 9
 * @spec JPMS
 */
@CallerSensitive
public static Class<?> forName(Module module, String name) {
    Objects.requireNonNull(module);
    Objects.requireNonNull(name);

    Class<?> caller = Reflection.getCallerClass();
    if (caller != null && caller.getModule() != module) {
        // if caller is null, Class.forName is the last java frame on the stack.
        // java.base has all permissions
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
        }
    }

    PrivilegedAction<ClassLoader> pa = module::getClassLoader;
    ClassLoader cl = AccessController.doPrivileged(pa);
    if (cl != null) {
        return cl.loadClass(module, name);
    } else {
        return BootLoader.loadClass(module, name);
    }
}
 
Example #13
Source File: ClassLoader.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Finds the resource with the given name.  A resource is some data
 * (images, audio, text, etc) that can be accessed by class code in a way
 * that is independent of the location of the code.
 *
 * <p> The name of a resource is a '{@code /}'-separated path name that
 * identifies the resource. </p>
 *
 * <p> Resources in named modules are subject to the encapsulation rules
 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
 * Additionally, and except for the special case where the resource has a
 * name ending with "{@code .class}", this method will only find resources in
 * packages of named modules when the package is {@link Module#isOpen(String)
 * opened} unconditionally (even if the caller of this method is in the
 * same module as the resource). </p>
 *
 * @implSpec The default implementation will first search the parent class
 * loader for the resource; if the parent is {@code null} the path of the
 * class loader built into the virtual machine is searched. If not found,
 * this method will invoke {@link #findResource(String)} to find the resource.
 *
 * @apiNote Where several modules are defined to the same class loader,
 * and where more than one module contains a resource with the given name,
 * then the ordering that modules are searched is not specified and may be
 * very unpredictable.
 * When overriding this method it is recommended that an implementation
 * ensures that any delegation is consistent with the {@link
 * #getResources(java.lang.String) getResources(String)} method.
 *
 * @param  name
 *         The resource name
 *
 * @return  {@code URL} object for reading the resource; {@code null} if
 *          the resource could not be found, a {@code URL} could not be
 *          constructed to locate the resource, the resource is in a package
 *          that is not opened unconditionally, or access to the resource is
 *          denied by the security manager.
 *
 * @throws  NullPointerException If {@code name} is {@code null}
 *
 * @since  1.1
 * @revised 9
 * @spec JPMS
 */
public URL getResource(String name) {
    Objects.requireNonNull(name);
    URL url;
    if (parent != null) {
        url = parent.getResource(name);
    } else {
        url = BootLoader.findResource(name);
    }
    if (url == null) {
        url = findResource(name);
    }
    return url;
}
 
Example #14
Source File: Class.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Gets the package of this class.
 *
 * <p>If this class represents an array type, a primitive type or void,
 * this method returns {@code null}.
 *
 * @return the package of this class.
 * @revised 9
 * @spec JPMS
 */
public Package getPackage() {
    if (isPrimitive() || isArray()) {
        return null;
    }
    ClassLoader cl = getClassLoader0();
    return cl != null ? cl.definePackage(this)
                      : BootLoader.definePackage(this);
}
 
Example #15
Source File: Package.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Finds a package by name in the caller's class loader and its
 * ancestors.
 * <p>
 * If the caller's class loader defines a {@code Package} of the given name,
 * the {@code Package} is returned. Otherwise, the ancestors of the
 * caller's class loader are searched recursively (parent by parent)
 * for a {@code Package} of the given name.
 * <p>
 * Calling this method is equivalent to calling {@link ClassLoader#getPackage}
 * on a {@code ClassLoader} instance which is the caller's class loader.
 *
 * @param name A package name, such as "{@code java.lang}".
 * @return The {@code Package} of the given name defined by the caller's
 *         class loader or its ancestors, or {@code null} if not found.
 *
 * @throws NullPointerException
 *         if {@code name} is {@code null}.
 *
 * @deprecated
 * If multiple class loaders delegate to each other and define classes
 * with the same package name, and one such loader relies on the lookup
 * behavior of {@code getPackage} to return a {@code Package} from
 * a parent loader, then the properties exposed by the {@code Package}
 * may not be as expected in the rest of the program.
 * For example, the {@code Package} will only expose annotations from the
 * {@code package-info.class} file defined by the parent loader, even if
 * annotations exist in a {@code package-info.class} file defined by
 * a child loader.  A more robust approach is to use the
 * {@link ClassLoader#getDefinedPackage} method which returns
 * a {@code Package} for the specified class loader.
 *
 * @see ClassLoader#getDefinedPackage
 *
 * @revised 9
 * @spec JPMS
 */
@CallerSensitive
@Deprecated(since="9")
@SuppressWarnings("deprecation")
public static Package getPackage(String name) {
    ClassLoader l = ClassLoader.getClassLoader(Reflection.getCallerClass());
    return l != null ? l.getPackage(name) : BootLoader.getDefinedPackage(name);
}
 
Example #16
Source File: Package.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Construct a package instance for an unnamed module
 * with the specified version information.
 *
 * @apiNote
 * This method should not be called to define a Package for named module.
 *
 * @param name the name of the package
 * @param spectitle the title of the specification
 * @param specversion the version of the specification
 * @param specvendor the organization that maintains the specification
 * @param impltitle the title of the implementation
 * @param implversion the version of the implementation
 * @param implvendor the organization that maintains the implementation
 * @param sealbase code source where this Package comes from
 * @param loader defining class loader
 */
Package(String name,
        String spectitle, String specversion, String specvendor,
        String impltitle, String implversion, String implvendor,
        URL sealbase, ClassLoader loader)
{
    super(Objects.requireNonNull(name),
          loader != null ? loader.getUnnamedModule()
                         : BootLoader.getUnnamedModule());

    this.versionInfo = VersionInfo.getInstance(spectitle, specversion,
                                               specvendor, impltitle,
                                               implversion, implvendor,
                                               sealbase);
}
 
Example #17
Source File: ClassLoader.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Finds the resource with the given name.  A resource is some data
 * (images, audio, text, etc) that can be accessed by class code in a way
 * that is independent of the location of the code.
 *
 * <p> The name of a resource is a '{@code /}'-separated path name that
 * identifies the resource. </p>
 *
 * <p> Resources in named modules are subject to the encapsulation rules
 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
 * Additionally, and except for the special case where the resource has a
 * name ending with "{@code .class}", this method will only find resources in
 * packages of named modules when the package is {@link Module#isOpen(String)
 * opened} unconditionally (even if the caller of this method is in the
 * same module as the resource). </p>
 *
 * @implSpec The default implementation will first search the parent class
 * loader for the resource; if the parent is {@code null} the path of the
 * class loader built into the virtual machine is searched. If not found,
 * this method will invoke {@link #findResource(String)} to find the resource.
 *
 * @apiNote Where several modules are defined to the same class loader,
 * and where more than one module contains a resource with the given name,
 * then the ordering that modules are searched is not specified and may be
 * very unpredictable.
 * When overriding this method it is recommended that an implementation
 * ensures that any delegation is consistent with the {@link
 * #getResources(java.lang.String) getResources(String)} method.
 *
 * @param  name
 *         The resource name
 *
 * @return  {@code URL} object for reading the resource; {@code null} if
 *          the resource could not be found, a {@code URL} could not be
 *          constructed to locate the resource, the resource is in a package
 *          that is not opened unconditionally, or access to the resource is
 *          denied by the security manager.
 *
 * @throws  NullPointerException If {@code name} is {@code null}
 *
 * @since  1.1
 * @revised 9
 * @spec JPMS
 */
public URL getResource(String name) {
    Objects.requireNonNull(name);
    URL url;
    if (parent != null) {
        url = parent.getResource(name);
    } else {
        url = BootLoader.findResource(name);
    }
    if (url == null) {
        url = findResource(name);
    }
    return url;
}
 
Example #18
Source File: ClassLoader.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns all of the {@code Package}s defined by this class loader
 * and its ancestors.  The returned array may contain more than one
 * {@code Package} object of the same package name, each defined by
 * a different class loader in the class loader hierarchy.
 *
 * @apiNote The {@link #getPlatformClassLoader() platform class loader}
 * may delegate to the application class loader. In other words,
 * packages in modules defined to the application class loader may be
 * visible to the platform class loader.  On the other hand,
 * the application class loader is not its ancestor and hence
 * when invoked on the platform class loader, this method will not
 * return any packages defined to the application class loader.
 *
 * @return  The array of {@code Package} objects defined by this
 *          class loader and its ancestors
 *
 * @since  1.2
 * @revised 9
 * @spec JPMS
 */
protected Package[] getPackages() {
    Stream<Package> pkgs = packages();
    ClassLoader ld = parent;
    while (ld != null) {
        pkgs = Stream.concat(ld.packages(), pkgs);
        ld = ld.parent;
    }
    return Stream.concat(BootLoader.packages(), pkgs)
                 .toArray(Package[]::new);
}
 
Example #19
Source File: ClassLoader.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Finds a package by <a href="#name">name</a> in this class loader and its ancestors.
 * <p>
 * If this class loader defines a {@code Package} of the given name,
 * the {@code Package} is returned. Otherwise, the ancestors of
 * this class loader are searched recursively (parent by parent)
 * for a {@code Package} of the given name.
 *
 * @apiNote The {@link #getPlatformClassLoader() platform class loader}
 * may delegate to the application class loader but the application class
 * loader is not its ancestor.  When invoked on the platform class loader,
 * this method  will not find packages defined to the application
 * class loader.
 *
 * @param  name
 *         The <a href="#name">package name</a>
 *
 * @return The {@code Package} corresponding to the given name defined by
 *         this class loader or its ancestors, or {@code null} if not found.
 *
 * @throws  NullPointerException
 *          if {@code name} is {@code null}.
 *
 * @deprecated
 * If multiple class loaders delegate to each other and define classes
 * with the same package name, and one such loader relies on the lookup
 * behavior of {@code getPackage} to return a {@code Package} from
 * a parent loader, then the properties exposed by the {@code Package}
 * may not be as expected in the rest of the program.
 * For example, the {@code Package} will only expose annotations from the
 * {@code package-info.class} file defined by the parent loader, even if
 * annotations exist in a {@code package-info.class} file defined by
 * a child loader.  A more robust approach is to use the
 * {@link ClassLoader#getDefinedPackage} method which returns
 * a {@code Package} for the specified class loader.
 *
 * @since  1.2
 * @revised 9
 * @spec JPMS
 */
@Deprecated(since="9")
protected Package getPackage(String name) {
    Package pkg = getDefinedPackage(name);
    if (pkg == null) {
        if (parent != null) {
            pkg = parent.getPackage(name);
        } else {
            pkg = BootLoader.getDefinedPackage(name);
        }
    }
    return pkg;
}
 
Example #20
Source File: ClassLoader.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Finds all the resources with the given name. A resource is some data
 * (images, audio, text, etc) that can be accessed by class code in a way
 * that is independent of the location of the code.
 *
 * <p> The name of a resource is a {@code /}-separated path name that
 * identifies the resource. </p>
 *
 * <p> Resources in named modules are subject to the encapsulation rules
 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
 * Additionally, and except for the special case where the resource has a
 * name ending with "{@code .class}", this method will only find resources in
 * packages of named modules when the package is {@link Module#isOpen(String)
 * opened} unconditionally (even if the caller of this method is in the
 * same module as the resource). </p>
 *
 * @implSpec The default implementation will first search the parent class
 * loader for the resource; if the parent is {@code null} the path of the
 * class loader built into the virtual machine is searched. It then
 * invokes {@link #findResources(String)} to find the resources with the
 * name in this class loader. It returns an enumeration whose elements
 * are the URLs found by searching the parent class loader followed by
 * the elements found with {@code findResources}.
 *
 * @apiNote Where several modules are defined to the same class loader,
 * and where more than one module contains a resource with the given name,
 * then the ordering is not specified and may be very unpredictable.
 * When overriding this method it is recommended that an
 * implementation ensures that any delegation is consistent with the {@link
 * #getResource(java.lang.String) getResource(String)} method. This should
 * ensure that the first element returned by the Enumeration's
 * {@code nextElement} method is the same resource that the
 * {@code getResource(String)} method would return.
 *
 * @param  name
 *         The resource name
 *
 * @return  An enumeration of {@link java.net.URL URL} objects for
 *          the resource. If no resources could  be found, the enumeration
 *          will be empty. Resources for which a {@code URL} cannot be
 *          constructed, are in package that is not opened unconditionally,
 *          or access to the resource is denied by the security manager,
 *          are not returned in the enumeration.
 *
 * @throws  IOException
 *          If I/O errors occur
 * @throws  NullPointerException If {@code name} is {@code null}
 *
 * @since  1.2
 * @revised 9
 * @spec JPMS
 */
public Enumeration<URL> getResources(String name) throws IOException {
    Objects.requireNonNull(name);
    @SuppressWarnings("unchecked")
    Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
    if (parent != null) {
        tmp[0] = parent.getResources(name);
    } else {
        tmp[0] = BootLoader.findResources(name);
    }
    tmp[1] = findResources(name);

    return new CompoundEnumeration<>(tmp);
}
 
Example #21
Source File: Package.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Construct a package instance for an unnamed module
 * with the specified version information.
 *
 * @apiNote
 * This method should not be called to define a Package for named module.
 *
 * @param name the name of the package
 * @param spectitle the title of the specification
 * @param specversion the version of the specification
 * @param specvendor the organization that maintains the specification
 * @param impltitle the title of the implementation
 * @param implversion the version of the implementation
 * @param implvendor the organization that maintains the implementation
 * @param sealbase code source where this Package comes from
 * @param loader defining class loader
 */
Package(String name,
        String spectitle, String specversion, String specvendor,
        String impltitle, String implversion, String implvendor,
        URL sealbase, ClassLoader loader)
{
    super(Objects.requireNonNull(name),
          loader != null ? loader.getUnnamedModule()
                         : BootLoader.getUnnamedModule());

    this.versionInfo = VersionInfo.getInstance(spectitle, specversion,
                                               specvendor, impltitle,
                                               implversion, implvendor,
                                               sealbase);
}
 
Example #22
Source File: ClassLoader.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Finds all the resources with the given name. A resource is some data
 * (images, audio, text, etc) that can be accessed by class code in a way
 * that is independent of the location of the code.
 *
 * <p> The name of a resource is a {@code /}-separated path name that
 * identifies the resource. </p>
 *
 * <p> Resources in named modules are subject to the encapsulation rules
 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
 * Additionally, and except for the special case where the resource has a
 * name ending with "{@code .class}", this method will only find resources in
 * packages of named modules when the package is {@link Module#isOpen(String)
 * opened} unconditionally (even if the caller of this method is in the
 * same module as the resource). </p>
 *
 * @implSpec The default implementation will first search the parent class
 * loader for the resource; if the parent is {@code null} the path of the
 * class loader built into the virtual machine is searched. It then
 * invokes {@link #findResources(String)} to find the resources with the
 * name in this class loader. It returns an enumeration whose elements
 * are the URLs found by searching the parent class loader followed by
 * the elements found with {@code findResources}.
 *
 * @apiNote Where several modules are defined to the same class loader,
 * and where more than one module contains a resource with the given name,
 * then the ordering is not specified and may be very unpredictable.
 * When overriding this method it is recommended that an
 * implementation ensures that any delegation is consistent with the {@link
 * #getResource(java.lang.String) getResource(String)} method. This should
 * ensure that the first element returned by the Enumeration's
 * {@code nextElement} method is the same resource that the
 * {@code getResource(String)} method would return.
 *
 * @param  name
 *         The resource name
 *
 * @return  An enumeration of {@link java.net.URL URL} objects for the
 *          resource. If no resources could be found, the enumeration will
 *          be empty. Resources for which a {@code URL} cannot be
 *          constructed, are in a package that is not opened
 *          unconditionally, or access to the resource is denied by the
 *          security manager, are not returned in the enumeration.
 *
 * @throws  IOException
 *          If I/O errors occur
 * @throws  NullPointerException If {@code name} is {@code null}
 *
 * @since  1.2
 * @revised 9
 * @spec JPMS
 */
public Enumeration<URL> getResources(String name) throws IOException {
    Objects.requireNonNull(name);
    @SuppressWarnings("unchecked")
    Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
    if (parent != null) {
        tmp[0] = parent.getResources(name);
    } else {
        tmp[0] = BootLoader.findResources(name);
    }
    tmp[1] = findResources(name);

    return new CompoundEnumeration<>(tmp);
}
 
Example #23
Source File: Package.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Finds a package by name in the caller's class loader and its
 * ancestors.
 * <p>
 * If the caller's class loader defines a {@code Package} of the given name,
 * the {@code Package} is returned. Otherwise, the ancestors of the
 * caller's class loader are searched recursively (parent by parent)
 * for a {@code Package} of the given name.
 * <p>
 * Calling this method is equivalent to calling {@link ClassLoader#getPackage}
 * on a {@code ClassLoader} instance which is the caller's class loader.
 *
 * @param name A package name, such as "{@code java.lang}".
 * @return The {@code Package} of the given name defined by the caller's
 *         class loader or its ancestors, or {@code null} if not found.
 *
 * @throws NullPointerException
 *         if {@code name} is {@code null}.
 *
 * @deprecated
 * If multiple class loaders delegate to each other and define classes
 * with the same package name, and one such loader relies on the lookup
 * behavior of {@code getPackage} to return a {@code Package} from
 * a parent loader, then the properties exposed by the {@code Package}
 * may not be as expected in the rest of the program.
 * For example, the {@code Package} will only expose annotations from the
 * {@code package-info.class} file defined by the parent loader, even if
 * annotations exist in a {@code package-info.class} file defined by
 * a child loader.  A more robust approach is to use the
 * {@link ClassLoader#getDefinedPackage} method which returns
 * a {@code Package} for the specified class loader.
 *
 * @see ClassLoader#getDefinedPackage
 *
 * @revised 9
 * @spec JPMS
 */
@CallerSensitive
@Deprecated(since="9")
@SuppressWarnings("deprecation")
public static Package getPackage(String name) {
    ClassLoader l = ClassLoader.getClassLoader(Reflection.getCallerClass());
    return l != null ? l.getPackage(name) : BootLoader.getDefinedPackage(name);
}
 
Example #24
Source File: Class.java    From openjdk-jdk9 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Gets the package of this class.
 *
 * <p>If this class represents an array type, a primitive type or void,
 * this method returns {@code null}.
 *
 * @return the package of this class.
 * @revised 9
 * @spec JPMS
 */
public Package getPackage() {
    if (isPrimitive() || isArray()) {
        return null;
    }
    ClassLoader cl = getClassLoader0();
    return cl != null ? cl.definePackage(this)
                      : BootLoader.definePackage(this);
}
 
Example #25
Source File: Class.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
 * binary name</a> in the given module.
 *
 * <p> This method attempts to locate and load the class or interface.
 * It does not link the class, and does not run the class initializer.
 * If the class is not found, this method returns {@code null}. </p>
 *
 * <p> If the class loader of the given module defines other modules and
 * the given name is a class defined in a different module, this method
 * returns {@code null} after the class is loaded. </p>
 *
 * <p> This method does not check whether the requested class is
 * accessible to its caller. </p>
 *
 * @apiNote
 * This method returns {@code null} on failure rather than
 * throwing a {@link ClassNotFoundException}, as is done by
 * the {@link #forName(String, boolean, ClassLoader)} method.
 * The security check is a stack-based permission check if the caller
 * loads a class in another module.
 *
 * @param  module   A module
 * @param  name     The <a href="ClassLoader.html#binary-name">binary name</a>
 *                  of the class
 * @return {@code Class} object of the given name defined in the given module;
 *         {@code null} if not found.
 *
 * @throws NullPointerException if the given module or name is {@code null}
 *
 * @throws LinkageError if the linkage fails
 *
 * @throws SecurityException
 *         <ul>
 *         <li> if the caller is not the specified module and
 *         {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
 *         <li> access to the module content is denied. For example,
 *         permission check will be performed when a class loader calls
 *         {@link ModuleReader#open(String)} to read the bytes of a class file
 *         in a module.</li>
 *         </ul>
 *
 * @jls 12.2 Loading of Classes and Interfaces
 * @jls 12.3 Linking of Classes and Interfaces
 * @since 9
 * @spec JPMS
 */
@CallerSensitive
public static Class<?> forName(Module module, String name) {
    Objects.requireNonNull(module);
    Objects.requireNonNull(name);

    ClassLoader cl;
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Class<?> caller = Reflection.getCallerClass();
        if (caller != null && caller.getModule() != module) {
            // if caller is null, Class.forName is the last java frame on the stack.
            // java.base has all permissions
            sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
        }
        PrivilegedAction<ClassLoader> pa = module::getClassLoader;
        cl = AccessController.doPrivileged(pa);
    } else {
        cl = module.getClassLoader();
    }

    if (cl != null) {
        return cl.loadClass(module, name);
    } else {
        return BootLoader.loadClass(module, name);
    }
}
 
Example #26
Source File: ClassLoader.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Finds a package by <a href="#binary-name">name</a> in this class loader and its ancestors.
 * <p>
 * If this class loader defines a {@code Package} of the given name,
 * the {@code Package} is returned. Otherwise, the ancestors of
 * this class loader are searched recursively (parent by parent)
 * for a {@code Package} of the given name.
 *
 * @apiNote The {@link #getPlatformClassLoader() platform class loader}
 * may delegate to the application class loader but the application class
 * loader is not its ancestor.  When invoked on the platform class loader,
 * this method  will not find packages defined to the application
 * class loader.
 *
 * @param  name
 *         The <a href="#binary-name">package name</a>
 *
 * @return The {@code Package} of the given name that has been defined by
 *         this class loader or its ancestors, or {@code null} if not found.
 *
 * @throws  NullPointerException
 *          if {@code name} is {@code null}.
 *
 * @deprecated
 * If multiple class loaders delegate to each other and define classes
 * with the same package name, and one such loader relies on the lookup
 * behavior of {@code getPackage} to return a {@code Package} from
 * a parent loader, then the properties exposed by the {@code Package}
 * may not be as expected in the rest of the program.
 * For example, the {@code Package} will only expose annotations from the
 * {@code package-info.class} file defined by the parent loader, even if
 * annotations exist in a {@code package-info.class} file defined by
 * a child loader.  A more robust approach is to use the
 * {@link ClassLoader#getDefinedPackage} method which returns
 * a {@code Package} for the specified class loader.
 *
 * @see ClassLoader#getDefinedPackage(String)
 *
 * @since  1.2
 * @revised 9
 * @spec JPMS
 */
@Deprecated(since="9")
protected Package getPackage(String name) {
    Package pkg = getDefinedPackage(name);
    if (pkg == null) {
        if (parent != null) {
            pkg = parent.getPackage(name);
        } else {
            pkg = BootLoader.getDefinedPackage(name);
        }
    }
    return pkg;
}
 
Example #27
Source File: ClassLoader.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Returns all of the {@code Package}s that have been defined by
 * this class loader and its ancestors.  The returned array may contain
 * more than one {@code Package} object of the same package name, each
 * defined by a different class loader in the class loader hierarchy.
 *
 * @apiNote The {@link #getPlatformClassLoader() platform class loader}
 * may delegate to the application class loader. In other words,
 * packages in modules defined to the application class loader may be
 * visible to the platform class loader.  On the other hand,
 * the application class loader is not its ancestor and hence
 * when invoked on the platform class loader, this method will not
 * return any packages defined to the application class loader.
 *
 * @return  The array of {@code Package} objects that have been defined by
 *          this class loader and its ancestors
 *
 * @see ClassLoader#getDefinedPackages()
 *
 * @since  1.2
 * @revised 9
 * @spec JPMS
 */
protected Package[] getPackages() {
    Stream<Package> pkgs = packages();
    ClassLoader ld = parent;
    while (ld != null) {
        pkgs = Stream.concat(ld.packages(), pkgs);
        ld = ld.parent;
    }
    return Stream.concat(BootLoader.packages(), pkgs)
                 .toArray(Package[]::new);
}
 
Example #28
Source File: Module.java    From Bytecoder with Apache License 2.0 2 votes vote down vote up
/**
 * Returns an input stream for reading a resource in this module.
 * The {@code name} parameter is a {@code '/'}-separated path name that
 * identifies the resource. As with {@link Class#getResourceAsStream
 * Class.getResourceAsStream}, this method delegates to the module's class
 * loader {@link ClassLoader#findResource(String,String)
 * findResource(String,String)} method, invoking it with the module name
 * (or {@code null} when the module is unnamed) and the name of the
 * resource. If the resource name has a leading slash then it is dropped
 * before delegation.
 *
 * <p> A resource in a named module may be <em>encapsulated</em> so that
 * it cannot be located by code in other modules. Whether a resource can be
 * located or not is determined as follows: </p>
 *
 * <ul>
 *     <li> If the resource name ends with  "{@code .class}" then it is not
 *     encapsulated. </li>
 *
 *     <li> A <em>package name</em> is derived from the resource name. If
 *     the package name is a {@linkplain #getPackages() package} in the
 *     module then the resource can only be located by the caller of this
 *     method when the package is {@linkplain #isOpen(String,Module) open}
 *     to at least the caller's module. If the resource is not in a
 *     package in the module then the resource is not encapsulated. </li>
 * </ul>
 *
 * <p> In the above, the <em>package name</em> for a resource is derived
 * from the subsequence of characters that precedes the last {@code '/'} in
 * the name and then replacing each {@code '/'} character in the subsequence
 * with {@code '.'}. A leading slash is ignored when deriving the package
 * name. As an example, the package name derived for a resource named
 * "{@code a/b/c/foo.properties}" is "{@code a.b.c}". A resource name
 * with the name "{@code META-INF/MANIFEST.MF}" is never encapsulated
 * because "{@code META-INF}" is not a legal package name. </p>
 *
 * <p> This method returns {@code null} if the resource is not in this
 * module, the resource is encapsulated and cannot be located by the caller,
 * or access to the resource is denied by the security manager. </p>
 *
 * @param  name
 *         The resource name
 *
 * @return An input stream for reading the resource or {@code null}
 *
 * @throws IOException
 *         If an I/O error occurs
 *
 * @see Class#getResourceAsStream(String)
 */
@CallerSensitive
public InputStream getResourceAsStream(String name) throws IOException {
    if (name.startsWith("/")) {
        name = name.substring(1);
    }

    if (isNamed() && Resources.canEncapsulate(name)) {
        Module caller = getCallerModule(Reflection.getCallerClass());
        if (caller != this && caller != Object.class.getModule()) {
            String pn = Resources.toPackageName(name);
            if (getPackages().contains(pn)) {
                if (caller == null && !isOpen(pn)) {
                    // no caller, package not open
                    return null;
                }
                if (!isOpen(pn, caller)) {
                    // package not open to caller
                    return null;
                }
            }
        }
    }

    String mn = this.name;

    // special-case built-in class loaders to avoid URL connection
    if (loader == null) {
        return BootLoader.findResourceAsStream(mn, name);
    } else if (loader instanceof BuiltinClassLoader) {
        return ((BuiltinClassLoader) loader).findResourceAsStream(mn, name);
    }

    // locate resource in module
    URL url = loader.findResource(mn, name);
    if (url != null) {
        try {
            return url.openStream();
        } catch (SecurityException e) { }
    }

    return null;
}
 
Example #29
Source File: Package.java    From openjdk-jdk9 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns all of the {@code Package}s defined by the caller's class loader
 * and its ancestors.  The returned array may contain more than one
 * {@code Package} object of the same package name, each defined by
 * a different class loader in the class loader hierarchy.
 * <p>
 * Calling this method is equivalent to calling {@link ClassLoader#getPackages}
 * on a {@code ClassLoader} instance which is the caller's class loader.
 *
 * @return  The array of {@code Package} objects defined by this
 *          class loader and its ancestors
 *
 * @see ClassLoader#getDefinedPackages
 *
 * @revised 9
 * @spec JPMS
 */
@CallerSensitive
public static Package[] getPackages() {
    ClassLoader cl = ClassLoader.getClassLoader(Reflection.getCallerClass());
    return cl != null ? cl.getPackages() : BootLoader.packages().toArray(Package[]::new);
}
 
Example #30
Source File: Module.java    From openjdk-jdk9 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns an input stream for reading a resource in this module.
 * The {@code name} parameter is a {@code '/'}-separated path name that
 * identifies the resource. As with {@link Class#getResourceAsStream
 * Class.getResourceAsStream}, this method delegates to the module's class
 * loader {@link ClassLoader#findResource(String,String)
 * findResource(String,String)} method, invoking it with the module name
 * (or {@code null} when the module is unnamed) and the name of the
 * resource. If the resource name has a leading slash then it is dropped
 * before delegation.
 *
 * <p> A resource in a named module may be <em>encapsulated</em> so that
 * it cannot be located by code in other modules. Whether a resource can be
 * located or not is determined as follows: </p>
 *
 * <ul>
 *     <li> If the resource name ends with  "{@code .class}" then it is not
 *     encapsulated. </li>
 *
 *     <li> A <em>package name</em> is derived from the resource name. If
 *     the package name is a {@linkplain #getPackages() package} in the
 *     module then the resource can only be located by the caller of this
 *     method when the package is {@linkplain #isOpen(String,Module) open}
 *     to at least the caller's module. If the resource is not in a
 *     package in the module then the resource is not encapsulated. </li>
 * </ul>
 *
 * <p> In the above, the <em>package name</em> for a resource is derived
 * from the subsequence of characters that precedes the last {@code '/'} in
 * the name and then replacing each {@code '/'} character in the subsequence
 * with {@code '.'}. A leading slash is ignored when deriving the package
 * name. As an example, the package name derived for a resource named
 * "{@code a/b/c/foo.properties}" is "{@code a.b.c}". A resource name
 * with the name "{@code META-INF/MANIFEST.MF}" is never encapsulated
 * because "{@code META-INF}" is not a legal package name. </p>
 *
 * <p> This method returns {@code null} if the resource is not in this
 * module, the resource is encapsulated and cannot be located by the caller,
 * or access to the resource is denied by the security manager. </p>
 *
 * @param  name
 *         The resource name
 *
 * @return An input stream for reading the resource or {@code null}
 *
 * @throws IOException
 *         If an I/O error occurs
 *
 * @see Class#getResourceAsStream(String)
 */
@CallerSensitive
public InputStream getResourceAsStream(String name) throws IOException {
    if (name.startsWith("/")) {
        name = name.substring(1);
    }

    if (isNamed() && Resources.canEncapsulate(name)) {
        Module caller = getCallerModule(Reflection.getCallerClass());
        if (caller != this && caller != Object.class.getModule()) {
            String pn = Resources.toPackageName(name);
            if (getPackages().contains(pn)) {
                if (caller == null && !isOpen(pn)) {
                    // no caller, package not open
                    return null;
                }
                if (!isOpen(pn, caller)) {
                    // package not open to caller
                    return null;
                }
            }
        }
    }

    String mn = this.name;

    // special-case built-in class loaders to avoid URL connection
    if (loader == null) {
        return BootLoader.findResourceAsStream(mn, name);
    } else if (loader instanceof BuiltinClassLoader) {
        return ((BuiltinClassLoader) loader).findResourceAsStream(mn, name);
    }

    // locate resource in module
    URL url = loader.findResource(mn, name);
    if (url != null) {
        try {
            return url.openStream();
        } catch (SecurityException e) { }
    }

    return null;
}