private static String toPathString(ModuleIdentifier moduleIdentifier) { final StringBuilder builder = new StringBuilder(); builder.append(moduleIdentifier.getName().replace('.', File.separatorChar)); builder.append(File.separatorChar).append(moduleIdentifier.getSlot()); builder.append(File.separatorChar); return builder.toString(); }
private void doDeployVerticle( boolean worker, boolean multiThreaded, final String main, final JsonObject config, final URL[] urls, int instances, File currentModDir, String includes, Handler<String> doneHandler) { checkWorkerContext(); // There is one module class loader per enclosing module + the name of the verticle. // If there is no enclosing module, there is one per top level verticle deployment // E.g. if a module A deploys "foo.js" as a verticle then all instances of foo.js deployed by // the enclosing // module will share a module class loader String depName = genDepName(); ModuleIdentifier enclosingModName = getEnclosingModID(); String moduleKey; if (enclosingModName == null) { // We are at the top level - just use the deployment name as the key moduleKey = createInternalModIDForVerticle(depName).toString(); } else { // Use the enclosing module name / or enclosing verticle PLUS the main moduleKey = enclosingModName.toString() + "#" + main; } ModuleReference mr = moduleRefs.get(moduleKey); if (mr == null) { mr = new ModuleReference( this, moduleKey, new ModuleClassLoader(platformClassLoader, urls), false); ModuleReference prev = moduleRefs.putIfAbsent(moduleKey, mr); if (prev != null) { mr = prev; } } if (includes != null) { loadIncludedModules(currentModDir, mr, includes); } doDeploy( depName, false, worker, multiThreaded, main, null, config, urls, instances, currentModDir, mr, doneHandler); }
public void deployModuleFromZip( String zipFileName, JsonObject config, int instances, Handler<String> doneHandler) { final String modName = zipFileName.substring(0, zipFileName.length() - 4); ModuleIdentifier modID = new ModuleIdentifier("__vertx_tmp#" + modName + "#__vertx_tmp"); if (unzipModule(modID, new ModuleZipInfo(false, zipFileName), false)) { deployModule(modID.toString(), config, instances, doneHandler); } else { doneHandler.handle(null); } }
public List<String> queryLoadedModuleNames() { ModuleLoader loader = getModuleLoader(); final Set<ModuleIdentifier> identifiers = loader.moduleMap.keySet(); final ArrayList<String> list = new ArrayList<String>(identifiers.size()); for (ModuleIdentifier identifier : identifiers) { list.add(identifier.toString()); } Collections.sort(list); return list; }
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(); }
/** * Creates a path name from the module identifier. The name always ends with the separator * character. A {@code null} identifier will result in no separator being used. * * @param identifier the module identifier. * @param separator the directory separator. * @return a path name of the module identifier. * @throws IllegalArgumentException if the module identifier is {@code null}. */ public static String baseDirectory(final ModuleIdentifier identifier, final String separator) { if (identifier == null) { throw new IllegalArgumentException("The module identifier cannot be null."); } final String namePath = identifier.getName().replace('.', File.separatorChar); final StringBuilder baseName = new StringBuilder(); baseName .append(namePath) .append((separator == null ? "" : separator)) .append(identifier.getSlot()) .append((separator == null ? "" : separator)); return baseName.toString(); }
/** {@inheritDoc} */ @Override protected Module preloadModule(final ModuleIdentifier identifier) throws ModuleLoadException { if (identifier.equals(ModuleIdentifier.SYSTEM)) { return preloadModule(ModuleIdentifier.SYSTEM, SystemModuleLoader.getInstance()); } return super.preloadModule(identifier); }
/** * Load a module based on an identifier. This method delegates to {@link * #preloadModule(ModuleIdentifier)} and then links the returned module if necessary. * * @param identifier The module identifier * @return The loaded Module * @throws ModuleLoadException if the Module can not be loaded */ public final Module loadModule(ModuleIdentifier identifier) throws ModuleLoadException { final Module module = preloadModule(identifier); if (module == null) { throw new ModuleNotFoundException(identifier.toString()); } module.relinkIfNecessary(); return module; }
/** * Defines a Module based on a specification. Use of this method is required by any ModuleLoader * implementations in order to fully define a Module. * * @param moduleSpec The module specification to create the Module from * @return The defined Module * @throws ModuleLoadException If any dependent modules can not be loaded */ protected final Module defineModule(ModuleSpec moduleSpec) throws ModuleLoadException { final ModuleIdentifier moduleIdentifier = moduleSpec.getIdentifier(); FutureModule futureModule = moduleMap.get(moduleIdentifier); if (futureModule == null) { FutureModule newFuture = new FutureModule(moduleIdentifier); futureModule = moduleMap.putIfAbsent(moduleIdentifier, newFuture); if (futureModule == null) futureModule = newFuture; } // early detect if (futureModule.module != null) { throw new ModuleAlreadyExistsException(moduleIdentifier.toString()); } try { final List<Dependency> dependencies = new ArrayList<Dependency>(moduleSpec.getDependencies().size()); for (DependencySpec dependencySpec : moduleSpec.getDependencies()) { final Module dependencyModule; try { dependencyModule = loadModule(dependencySpec.getModuleIdentifier()); } catch (ModuleLoadException e) { if (dependencySpec.isOptional()) { continue; } else { throw e; } } final Dependency dependency = new Dependency(dependencyModule, dependencySpec.isExport()); dependencies.add(dependency); } final Module module = new Module(moduleSpec, dependencies, moduleSpec.getModuleFlags(), this); synchronized (futureModule) { futureModule.setModule(module); } return module; } catch (ModuleLoadException e) { futureModule.setModule(null); throw e; } catch (RuntimeException e) { futureModule.setModule(null); throw e; } catch (Error e) { futureModule.setModule(null); throw e; } }
private File locateModule(File currentModDir, ModuleIdentifier modID) { if (currentModDir != null) { // Nested moduleRefs - look inside current module dir File modDir = new File(new File(currentModDir, LOCAL_MODS_DIR), modID.toString()); if (modDir.exists()) { return modDir; } } File modDir = new File(modRoot, modID.toString()); if (modDir.exists()) { return modDir; } else if (!systemModRoot.equals(modRoot)) { modDir = new File(systemModRoot, modID.toString()); if (modDir.exists()) { return modDir; } } return null; }
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; } }
private boolean unzipModule( final ModuleIdentifier modID, final ModuleZipInfo zipInfo, boolean deleteZip) { // We synchronize to prevent a race whereby it tries to unzip the same module at the // same time (e.g. deployModule for the same module name has been called in parallel) String modName = modID.toString(); synchronized (modName.intern()) { if (!checkModDirs()) { return false; } File fdest = new File(modRoot, modName); File sdest = new File(systemModRoot, modName); if (fdest.exists() || sdest.exists()) { // This can happen if the same module is requested to be installed // at around the same time // It's ok if this happens log.warn("Module " + modID + " is already installed"); return true; } // Unzip into temp dir first File tdest = unzipIntoTmpDir(zipInfo, deleteZip); if (tdest == null) { return false; } // Check if it's a system module JsonObject conf = loadModuleConfig(modID, tdest); ModuleFields fields = new ModuleFields(conf); boolean system = fields.isSystem(); // Now copy it to the proper directory String moveFrom = tdest.getAbsolutePath(); try { vertx .fileSystem() .moveSync(moveFrom, system ? sdest.getAbsolutePath() : fdest.getAbsolutePath()); } catch (Exception e) { log.error("Failed to move module", e); return false; } log.info("Module " + modID + " successfully installed"); return true; } }
private boolean doPullInDependencies(File modRoot, ModuleIdentifier modID) { File modDir = new File(modRoot, modID.toString()); if (!modDir.exists()) { log.error("Cannot find module to uninstall"); } JsonObject conf = loadModuleConfig(modID, modDir); if (conf == null) { log.error("Module " + modID + " does not contain a mod.json"); } ModuleFields fields = new ModuleFields(conf); List<String> mods = new ArrayList<>(); String includes = fields.getIncludes(); if (includes != null) { mods.addAll(Arrays.asList(parseIncludeString(includes))); } String deploys = fields.getDeploys(); if (deploys != null) { mods.addAll(Arrays.asList(parseIncludeString(deploys))); } if (!mods.isEmpty()) { File internalModsDir = new File(modDir, "mods"); if (!internalModsDir.exists()) { internalModsDir.mkdir(); } for (String modName : mods) { File internalModDir = new File(internalModsDir, modName); if (!internalModDir.exists()) { ModuleIdentifier theModID = new ModuleIdentifier(modName); ModuleZipInfo zipInfo = getModule(theModID); if (zipInfo.filename != null) { internalModDir.mkdir(); if (!unzipModuleData(internalModDir, zipInfo, true)) { return false; } else { log.info("Module " + modName + " successfully installed in mods dir of " + modName); // Now recurse so we bring in all of the deps doPullInDependencies(internalModsDir, theModID); } } } } } return true; }
Module getModule() throws ModuleNotFoundException { boolean intr = false; try { Object module = this.module; if (module == null) synchronized (this) { while ((module = this.module) == null) { try { wait(); } catch (InterruptedException e) { intr = true; } } } if (module == NOT_FOUND) throw new ModuleNotFoundException(identifier.toString()); return (Module) module; } finally { if (intr) Thread.currentThread().interrupt(); } }
/** * Load a module based on an identifier. * * @param identifier The module identifier * @return The loaded Module * @throws ModuleLoadException if the Module can not be loaded */ public Module loadModule(ModuleIdentifier identifier) throws ModuleLoadException { final Set<ModuleIdentifier> visited = VISITED.get(); if (visited.contains(identifier)) throw new ModuleLoadException( "Failed to load " + identifier + "; module cycle discovered: " + visited); FutureModule futureModule = moduleMap.get(identifier); if (futureModule == null) { FutureModule newFuture = new FutureModule(identifier); futureModule = moduleMap.putIfAbsent(identifier, newFuture); if (futureModule == null) { visited.add(identifier); try { final Module module = findModule(identifier); if (module == null) throw new ModuleNotFoundException(identifier.toString()); return module; } finally { visited.remove(identifier); } } } return futureModule.getModule(); }
/** * 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 static ModuleClassLoader forModuleName(String identifier) throws ModuleLoadException { return forModule(ModuleIdentifier.fromString(identifier)); }
/** * 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 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; } }
@Override public String toString() { return id.toString(); }
private void doDeployMod( final boolean redeploy, final String depName, final ModuleIdentifier modID, final JsonObject config, final int instances, final File currentModDir, final Handler<String> doneHandler) { checkWorkerContext(); File modDir = locateModule(currentModDir, modID); if (modDir != null) { JsonObject conf = loadModuleConfig(modID, modDir); ModuleFields fields = new ModuleFields(conf); String main = fields.getMain(); if (main == null) { log.error("Runnable module " + modID + " mod.json must contain a \"main\" field"); callDoneHandler(doneHandler, null); return; } boolean worker = fields.isWorker(); boolean multiThreaded = fields.isMultiThreaded(); if (multiThreaded && !worker) { throw new IllegalArgumentException("Multi-threaded modules must be workers"); } boolean preserveCwd = fields.isPreserveCurrentWorkingDirectory(); // If preserveCwd then use the current module directory instead, or the cwd if not in a module File modDirToUse = preserveCwd ? currentModDir : modDir; List<URL> urls = getModuleClasspath(modDir); if (urls == null) { callDoneHandler(doneHandler, null); return; } ModuleReference mr = moduleRefs.get(modID.toString()); if (mr == null) { boolean res = fields.isResident(); mr = new ModuleReference( this, modID.toString(), new ModuleClassLoader(platformClassLoader, urls.toArray(new URL[urls.size()])), res); ModuleReference prev = moduleRefs.putIfAbsent(modID.toString(), mr); if (prev != null) { mr = prev; } } ModuleIdentifier enclosingModID = getEnclosingModID(); if (enclosingModID != null) { // If enclosed in another module then the enclosing module classloader becomes a parent of // this one ModuleReference parentRef = moduleRefs.get(enclosingModID.toString()); mr.mcl.addParent(parentRef); parentRef.incRef(); } // Now load any included moduleRefs String includes = fields.getIncludes(); if (includes != null) { if (!loadIncludedModules(modDir, mr, includes)) { callDoneHandler(doneHandler, null); return; } } final boolean autoRedeploy = fields.isAutoRedeploy(); doDeploy( depName, autoRedeploy, worker, multiThreaded, main, modID, config, urls.toArray(new URL[urls.size()]), instances, modDirToUse, mr, new Handler<String>() { @Override public void handle(String deploymentID) { if (deploymentID != null && !redeploy && autoRedeploy) { redeployer.moduleDeployed(deployments.get(deploymentID)); } callDoneHandler(doneHandler, deploymentID); } }); } else { if (doInstallMod(modID)) { doDeployMod(redeploy, depName, modID, config, instances, currentModDir, doneHandler); } else { callDoneHandler(doneHandler, null); } } }
private static void parseModuleDependency( final XMLStreamReader reader, final ModuleSpec.Builder specBuilder) throws XMLStreamException { String name = null; String slot = null; boolean export = false; boolean optional = false; final Set<Attribute> required = EnumSet.of(Attribute.NAME); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { final Attribute attribute = Attribute.of(reader.getAttributeName(i)); required.remove(attribute); switch (attribute) { case NAME: name = reader.getAttributeValue(i); break; case SLOT: slot = reader.getAttributeValue(i); break; case EXPORT: export = Boolean.parseBoolean(reader.getAttributeValue(i)); break; case OPTIONAL: optional = Boolean.parseBoolean(reader.getAttributeValue(i)); break; default: throw unexpectedContent(reader); } } if (!required.isEmpty()) { throw missingAttributes(reader.getLocation(), required); } final MultiplePathFilterBuilder importBuilder = PathFilters.multiplePathFilterBuilder(true); final MultiplePathFilterBuilder exportBuilder = PathFilters.multiplePathFilterBuilder(true); while (reader.hasNext()) { switch (reader.nextTag()) { case XMLStreamConstants.END_ELEMENT: { final PathFilter exportFilter = export ? exportBuilder.create() : PathFilters.rejectAll(); final PathFilter importFilter = importBuilder.create(); specBuilder.addDependency( DependencySpec.createModuleDependencySpec( importFilter, exportFilter, null, ModuleIdentifier.create(name, slot), optional)); return; } case XMLStreamConstants.START_ELEMENT: { switch (Element.of(reader.getName())) { case EXPORTS: parseFilterList(reader, exportBuilder); break; case IMPORTS: parseFilterList(reader, importBuilder); break; default: throw unexpectedContent(reader); } break; } default: { throw unexpectedContent(reader); } } } }
private static void parseModuleContents( final File root, final XMLStreamReader reader, final ModuleSpec.Builder specBuilder) throws XMLStreamException { final int count = reader.getAttributeCount(); String name = null; String slot = null; final Set<Attribute> required = EnumSet.of(Attribute.NAME); for (int i = 0; i < count; i++) { final Attribute attribute = Attribute.of(reader.getAttributeName(i)); required.remove(attribute); switch (attribute) { case NAME: name = reader.getAttributeValue(i); break; case SLOT: slot = reader.getAttributeValue(i); break; default: throw unexpectedContent(reader); } } if (!required.isEmpty()) { throw missingAttributes(reader.getLocation(), required); } if (!specBuilder.getIdentifier().equals(ModuleIdentifier.create(name, slot))) { throw invalidModuleName(reader.getLocation(), specBuilder.getIdentifier()); } // xsd:all Set<Element> visited = EnumSet.noneOf(Element.class); while (reader.hasNext()) { switch (reader.nextTag()) { case XMLStreamConstants.END_ELEMENT: { specBuilder.addDependency(DependencySpec.createLocalDependencySpec()); return; } case XMLStreamConstants.START_ELEMENT: { final Element element = Element.of(reader.getName()); if (visited.contains(element)) { throw unexpectedContent(reader); } visited.add(element); switch (element) { case DEPENDENCIES: parseDependencies(reader, specBuilder); break; case MAIN_CLASS: parseMainClass(reader, specBuilder); break; case RESOURCES: parseResources(root, reader, specBuilder); break; default: throw unexpectedContent(reader); } break; } default: { throw unexpectedContent(reader); } } } throw endOfDocument(reader.getLocation()); }