public static ModuleClassLoader createAggregate(String identifier, List<String> dependencies)
      throws ModuleLoadException {

    List<ModuleIdentifier> depModuleIdentifiers =
        new ArrayList<ModuleIdentifier>(dependencies.size());
    for (String dependencySpec : dependencies) {
      depModuleIdentifiers.add(ModuleIdentifier.fromString(dependencySpec));
    }
    return InitialModuleLoader.INSTANCE
        .createAggregate(ModuleIdentifier.fromString(identifier), depModuleIdentifiers)
        .getClassLoader();
  }
 private Module loadModule(final String name, final ModuleLoader loader) {
   try {
     final Module module = loader.findLoadedModuleLocal(ModuleIdentifier.fromString(name));
     if (module == null) {
       throw new IllegalArgumentException("Module " + name + " not found");
     }
     return module;
   } catch (ModuleLoadError e) {
     throw new IllegalArgumentException("Error loading module " + name + ": " + e.toString());
   }
 }
 public boolean unloadModule(final String name) {
   final SecurityManager sm = System.getSecurityManager();
   if (sm != null) {
     sm.checkPermission(MODULE_UNLOAD_ANY_PERM);
   }
   final ModuleLoader loader = getModuleLoader();
   final Module module = loader.findLoadedModuleLocal(ModuleIdentifier.fromString(name));
   if (module == null) {
     return false;
   } else {
     loader.unloadModuleLocal(module);
     return true;
   }
 }
Exemple #4
0
  /**
   * Run JBoss Modules.
   *
   * @param args the command-line arguments
   * @throws Throwable if an error occurs
   */
  public static void main(String[] args) throws Throwable {
    final int argsLen = args.length;
    String deps = null;
    String[] moduleArgs = NO_STRINGS;
    String modulePath = null;
    String classpath = null;
    boolean jar = false;
    boolean classpathDefined = false;
    boolean classDefined = false;
    boolean depTree = false;
    String nameArgument = null;
    ModuleIdentifier jaxpModuleIdentifier = null;
    boolean defaultSecMgr = false;
    String secMgrModule = null;
    boolean addIndex = false;
    boolean modifyInPlace = false;
    for (int i = 0, argsLength = argsLen; i < argsLength; i++) {
      final String arg = args[i];
      try {
        if (arg.charAt(0) == '-') {
          // it's an option
          if ("-version".equals(arg)) {
            System.out.println("JBoss Modules version " + getVersionString());
            return;
          } else if ("-help".equals(arg)) {
            usage();
            return;
          } else if ("-addindex".equals(arg)) {
            addIndex = true;
          } else if ("-modify".equals(arg)) {
            modifyInPlace = true;
          } else if ("-modulepath".equals(arg) || "-mp".equals(arg)) {
            if (modulePath != null) {
              System.err.println("Module path may only be specified once");
              System.exit(1);
            }
            modulePath = args[++i];
            System.setProperty("module.path", modulePath);
          } else if ("-config".equals(arg)) {
            System.err.println("Config files are no longer supported.  Use the -mp option instead");
            System.exit(1);
          } else if ("-deptree".equals(arg)) {
            if (depTree) {
              System.err.println("-deptree may only be specified once");
              System.exit(1);
            }
            if (jar) {
              System.err.println("-deptree may not be specified with -jar");
              System.exit(1);
            }
            if (classDefined) {
              System.err.println("-deptree may not be specified with -class");
              System.exit(1);
            }
            if (classpathDefined) {
              System.err.println("-deptree may not be specified with -classpath");
              System.exit(1);
            }
            depTree = true;
          } else if ("-jaxpmodule".equals(arg)) {
            jaxpModuleIdentifier = ModuleIdentifier.fromString(args[++i]);
          } else if ("-jar".equals(arg)) {
            if (jar) {
              System.err.println("-jar flag may only be specified once");
              System.exit(1);
            }
            if (classpathDefined) {
              System.err.println("-cp/-classpath may not be specified with -jar");
              System.exit(1);
            }
            if (classDefined) {
              System.err.println("-class may not be specified with -jar");
              System.exit(1);
            }
            if (depTree) {
              System.err.println("-deptree may not be specified with -jar");
              System.exit(1);
            }
            jar = true;
          } else if ("-cp".equals(arg) || "-classpath".equals(arg)) {
            if (classpathDefined) {
              System.err.println("-cp or -classpath may only be specified once.");
              System.exit(1);
            }
            if (classDefined) {
              System.err.println("-class may not be specified with -cp/classpath");
              System.exit(1);
            }
            if (jar) {
              System.err.println("-cp/-classpath may not be specified with -jar");
              System.exit(1);
            }
            if (depTree) {
              System.err.println("-deptree may not be specified with -classpath");
              System.exit(1);
            }
            classpathDefined = true;
            classpath = args[++i];
            doPrivileged(new PropertyWriteAction("java.class.path", classpath));
          } else if ("-dep".equals(arg) || "-dependencies".equals(arg)) {
            if (deps != null) {
              System.err.println("-dep or -dependencies may only be specified once.");
              System.exit(1);
            }
            deps = args[++i];
          } else if ("-class".equals(arg)) {
            if (classDefined) {
              System.err.println("-class flag may only be specified once");
              System.exit(1);
            }
            if (classpathDefined) {
              System.err.println("-class may not be specified with -cp/classpath");
              System.exit(1);
            }
            if (jar) {
              System.err.println("-class may not be specified with -jar");
              System.exit(1);
            }
            if (depTree) {
              System.err.println("-deptree may not be specified with -class");
              System.exit(1);
            }
            classDefined = true;
          } else if ("-logmodule".equals(arg)) {
            System.err.println(
                "WARNING: -logmodule is deprecated. Please use the system property 'java.util.logging.manager' or the 'java.util.logging.LogManager' service loader.");
            i++;
          } else if ("-secmgr".equals(arg)) {
            if (defaultSecMgr) {
              System.err.println("-secmgr may only be specified once");
              System.exit(1);
            }
            if (secMgrModule != null) {
              System.err.println("-secmgr may not be specified when -secmgrmodule is given");
              System.exit(1);
            }
            defaultSecMgr = true;
          } else if ("-secmgrmodule".equals(arg)) {
            if (secMgrModule != null) {
              System.err.println("-secmgrmodule may only be specified once");
              System.exit(1);
            }
            if (defaultSecMgr) {
              System.err.println("-secmgrmodule may not be specified when -secmgr is given");
              System.exit(1);
            }
            secMgrModule = args[++i];
          } else {
            System.err.printf("Invalid option '%s'\n", arg);
            usage();
            System.exit(1);
          }
        } else {
          // it's the module specification
          nameArgument = arg;
          int cnt = argsLen - i - 1;
          moduleArgs = new String[cnt];
          System.arraycopy(args, i + 1, moduleArgs, 0, cnt);
          break;
        }
      } catch (IndexOutOfBoundsException e) {
        System.err.printf("Argument expected for option %s\n", arg);
        usage();
        System.exit(1);
      }
    }

    if (modifyInPlace && !addIndex) {
      System.err.println("-modify requires -addindex");
      usage();
      System.exit(1);
    }

    if (addIndex) {
      if (nameArgument == null) {
        System.err.println("-addindex requires a target JAR name");
        usage();
        System.exit(1);
      }
      if (modulePath != null) {
        System.err.println("-mp may not be used with -addindex");
        usage();
        System.exit(1);
      }
      if (jaxpModuleIdentifier != null) {
        System.err.println("-jaxpModuleIdentifier may not be used with -addindex");
        usage();
        System.exit(1);
      }
      if (classpathDefined) {
        System.err.println("-cp or -classpath may not be used with -addindex");
        usage();
        System.exit(1);
      }
      if (classDefined) {
        System.err.println("-class may not be used with -addindex");
        usage();
        System.exit(1);
      }
      if (jar) {
        System.err.println("-jar may not be used with -addindex");
        usage();
        System.exit(1);
      }
      if (deps != null) {
        System.err.println("-deps may not be used with -addindex");
        usage();
        System.exit(1);
      }
      if (defaultSecMgr) {
        System.err.println("-secmgr may not be used with -addindex");
        usage();
        System.exit(1);
      }
      if (secMgrModule != null) {
        System.err.println("-secmgrmodule may not be used with -addindex");
        usage();
        System.exit(1);
      }
      if (depTree) {
        System.err.println("-deptree may not be used with -addindex");
        usage();
        System.exit(1);
      }

      JarFileResourceLoader.addInternalIndex(new File(nameArgument), modifyInPlace);
      return;
    }

    if (deps != null && !classDefined && !classpathDefined) {
      System.err.println("-deps may only be specified when -cp/-classpath or -class is in use");
      System.exit(1);
    }

    // run the module
    if (nameArgument == null) {
      if (classDefined || classpathDefined) {
        System.err.println("No class name specified");
      } else if (jar) {
        System.err.println("No JAR specified");
      } else {
        System.err.println("No module specified");
      }
      usage();
      System.exit(1);
    }

    if (depTree) {
      DependencyTreeViewer.print(
          new PrintWriter(System.out),
          ModuleIdentifier.fromString(nameArgument),
          LocalModuleFinder.getRepoRoots(true));
      System.exit(0);
    }

    final ModuleLoader loader;
    final ModuleLoader environmentLoader;
    environmentLoader = DefaultBootModuleLoaderHolder.INSTANCE;
    final ModuleIdentifier moduleIdentifier;
    if (jar) {
      loader = new JarModuleLoader(environmentLoader, new JarFile(nameArgument));
      moduleIdentifier = ((JarModuleLoader) loader).getMyIdentifier();
    } else if (classpathDefined || classDefined) {
      loader = new ClassPathModuleLoader(environmentLoader, nameArgument, classpath, deps);
      moduleIdentifier = ModuleIdentifier.CLASSPATH;
    } else {
      loader = environmentLoader;
      moduleIdentifier = ModuleIdentifier.fromString(nameArgument);
    }
    Module.initBootModuleLoader(loader);

    final Module module;
    try {
      module = loader.loadModule(moduleIdentifier);
    } catch (ModuleNotFoundException e) {
      e.printStackTrace(System.err);
      System.exit(1);
      return;
    }
    final String ourJavaVersion =
        doPrivileged(new PropertyReadAction("java.specification.version", "1.6"));
    final String requireJavaVersion =
        module.getProperty("jboss.require-java-version", ourJavaVersion);
    final Pattern versionPattern = Pattern.compile("1\\.(\\d+)");
    final Matcher requireMatcher = versionPattern.matcher(requireJavaVersion);
    final Matcher ourMatcher = versionPattern.matcher(ourJavaVersion);
    if (requireMatcher.matches()
        && ourMatcher.matches()
        && Integer.valueOf(requireMatcher.group(1)) > Integer.valueOf(ourMatcher.group(1))) {
      System.err.printf(
          "This application requires Java specification version %s or later to run (this Java virtual machine implements specification version %s)%n",
          requireJavaVersion, ourJavaVersion);
      System.exit(1);
    }

    ModularURLStreamHandlerFactory.addHandlerModule(module);
    ModularContentHandlerFactory.addHandlerModule(module);

    // at this point, having a security manager already installed will prevent correct operation.

    final SecurityManager existingSecMgr = System.getSecurityManager();
    if (existingSecMgr != null) {
      System.err.println(
          "An existing security manager was detected.  You must use the -secmgr switch to start with a security manager.");
      System.exit(1);
      return; // not reached
    }

    try {
      final Iterator<Policy> iterator = module.loadService(Policy.class).iterator();
      if (iterator.hasNext()) {
        Policy.setPolicy(iterator.next());
      }
    } catch (Exception ignored) {
    }

    // configure policy so that if SM is enabled, modules can still function
    final ModulesPolicy policy = new ModulesPolicy(Policy.getPolicy());
    Policy.setPolicy(policy);

    if (secMgrModule != null) {
      final Module loadedModule;
      try {
        loadedModule = loader.loadModule(ModuleIdentifier.fromString(secMgrModule));
      } catch (ModuleNotFoundException e) {
        e.printStackTrace(System.err);
        System.exit(1);
        return;
      }
      final Iterator<SecurityManager> iterator =
          ServiceLoader.load(SecurityManager.class, loadedModule.getClassLoaderPrivate())
              .iterator();
      if (iterator.hasNext()) {
        System.setSecurityManager(iterator.next());
      } else {
        System.err.println("No security manager found in module " + secMgrModule);
        System.exit(1);
      }
    }

    if (defaultSecMgr) {
      final Iterator<SecurityManager> iterator =
          module.loadService(SecurityManager.class).iterator();
      if (iterator.hasNext()) {
        System.setSecurityManager(iterator.next());
      } else {
        System.setSecurityManager(new SecurityManager());
      }
    }

    final ModuleClassLoader bootClassLoader = module.getClassLoaderPrivate();
    setContextClassLoader(bootClassLoader);

    final String serviceName =
        getServiceName(bootClassLoader, "java.util.prefs.PreferencesFactory");
    if (serviceName != null) {
      final String old = System.setProperty("java.util.prefs.PreferencesFactory", serviceName);
      try {
        Preferences.systemRoot();
      } finally {
        if (old == null) {
          System.clearProperty("java.util.prefs.PreferencesFactory");
        } else {
          System.setProperty("java.util.prefs.PreferencesFactory", old);
        }
      }
    }

    final String logManagerName = getServiceName(bootClassLoader, "java.util.logging.LogManager");
    if (logManagerName != null) {
      System.setProperty("java.util.logging.manager", logManagerName);
      if (LogManager.getLogManager().getClass() == LogManager.class) {
        System.err.println(
            "WARNING: Failed to load the specified log manager class " + logManagerName);
      } else {
        Module.setModuleLogger(new JDKModuleLogger());
      }
    }

    final String mbeanServerBuilderName =
        getServiceName(bootClassLoader, "javax.management.MBeanServerBuilder");
    if (mbeanServerBuilderName != null) {
      System.setProperty("javax.management.builder.initial", mbeanServerBuilderName);
      // Initialize the platform mbean server
      ManagementFactory.getPlatformMBeanServer();
    }

    ModuleLoader.installMBeanServer();

    try {
      module.run(moduleArgs);
    } catch (InvocationTargetException e) {
      throw e.getCause();
    }
    return;
  }
 public ModuleSpec findModule(final ModuleIdentifier identifier, final ModuleLoader delegateLoader)
     throws ModuleLoadException {
   if (identifier.equals(myIdentifier)) {
     // special root JAR module
     Manifest manifest;
     try {
       manifest = jarFile.getManifest();
     } catch (IOException e) {
       throw new ModuleLoadException("Failed to load MANIFEST from JAR", e);
     }
     ModuleSpec.Builder builder = ModuleSpec.build(identifier);
     Attributes mainAttributes = manifest.getMainAttributes();
     String mainClass = mainAttributes.getValue(Attributes.Name.MAIN_CLASS);
     if (mainClass != null) {
       builder.setMainClass(mainClass);
     }
     String classPath = mainAttributes.getValue(Attributes.Name.CLASS_PATH);
     String dependencies = mainAttributes.getValue("Dependencies");
     MultiplePathFilterBuilder pathFilterBuilder = PathFilters.multiplePathFilterBuilder(true);
     pathFilterBuilder.addFilter(PathFilters.is("modules"), false);
     pathFilterBuilder.addFilter(PathFilters.isChildOf("modules"), false);
     builder.addResourceRoot(
         ResourceLoaderSpec.createResourceLoaderSpec(
             new JarFileResourceLoader("", jarFile), pathFilterBuilder.create()));
     String[] classPathEntries =
         classPath == null ? JarModuleLoader.NO_STRINGS : classPath.split("\\s+");
     for (String entry : classPathEntries) {
       if (!entry.isEmpty()) {
         if (entry.startsWith("../")
             || entry.startsWith("./")
             || entry.startsWith("/")
             || entry.contains("/../")) {
           // invalid
           continue;
         }
         if (entry.endsWith("/")) {
           // directory reference
           File root = new File(jarFile.getName(), entry);
           FileResourceLoader resourceLoader = new FileResourceLoader(entry, root);
           builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(resourceLoader));
         } else {
           // assume a JAR
           File root = new File(jarFile.getName(), entry);
           JarFile childJarFile;
           try {
             childJarFile = new JarFile(root, true);
           } catch (IOException e) {
             // ignore and continue
             continue;
           }
           builder.addResourceRoot(
               ResourceLoaderSpec.createResourceLoaderSpec(
                   new JarFileResourceLoader(entry, childJarFile)));
         }
       }
     }
     String[] dependencyEntries =
         dependencies == null ? JarModuleLoader.NO_STRINGS : dependencies.split("\\s*,\\s*");
     for (String dependencyEntry : dependencyEntries) {
       boolean optional = false;
       boolean export = false;
       dependencyEntry = dependencyEntry.trim();
       if (!dependencyEntry.isEmpty()) {
         String[] fields = dependencyEntry.split("\\s+");
         if (fields.length < 1) {
           continue;
         }
         String moduleName = fields[0];
         for (int i = 1; i < fields.length; i++) {
           String field = fields[i];
           if (field.equals("optional")) {
             optional = true;
           } else if (field.equals("export")) {
             export = true;
           }
           // else ignored
         }
         builder.addDependency(
             DependencySpec.createModuleDependencySpec(
                 ModuleIdentifier.fromString(moduleName), export, optional));
       }
     }
     builder.addDependency(DependencySpec.createSystemDependencySpec(JDKPaths.JDK));
     builder.addDependency(DependencySpec.createLocalDependencySpec());
     return builder.create();
   } else {
     String namePath = identifier.getName().replace('.', '/');
     String basePath = "modules/" + namePath + "/" + identifier.getSlot();
     JarEntry moduleXmlEntry = jarFile.getJarEntry(basePath + "/module.xml");
     if (moduleXmlEntry == null) {
       return null;
     }
     ModuleSpec moduleSpec;
     try {
       InputStream inputStream = jarFile.getInputStream(moduleXmlEntry);
       try {
         moduleSpec =
             ModuleXmlParser.parseModuleXml(
                 new ModuleXmlParser.ResourceRootFactory() {
                   public ResourceLoader createResourceLoader(
                       final String rootPath, final String loaderPath, final String loaderName)
                       throws IOException {
                     return new JarFileResourceLoader(loaderName, jarFile, loaderPath);
                   }
                 },
                 basePath,
                 inputStream,
                 moduleXmlEntry.getName(),
                 delegateLoader,
                 identifier);
       } finally {
         JarModuleLoader.safeClose(inputStream);
       }
     } catch (IOException e) {
       throw new ModuleLoadException("Failed to read module.xml file", e);
     }
     return moduleSpec;
   }
 }
 /**
  * Find a module specification for the given name. The default implementation delegates to the
  * legacy {@link #findModule(ModuleIdentifier, ModuleLoader)} method.
  *
  * @param name the module name
  * @param delegateLoader the module loader from which dependencies should be resolved
  * @return the module specification, or {@code null} if no specification is found for this
  *     identifier
  */
 default ModuleSpec findModule(String name, ModuleLoader delegateLoader)
     throws ModuleLoadException {
   return findModule(ModuleIdentifier.fromString(name), delegateLoader);
 }
 public static ModuleClassLoader forModuleName(String identifier) throws ModuleLoadException {
   return forModule(ModuleIdentifier.fromString(identifier));
 }