final String[] resourceArr = (resourcePaths == null) ? new String[0] : resourcePaths.split(PATH_SEPARATOR);
File[] resourceFiles = new File[resourceArr.length];
for(int i = 0; i < resourceArr.length; ++i) {
final File f = new File(ctx.getCurrentDir(), resourceArr[i]);
if(!f.exists()) {
throw new CommandLineException("Failed to locate " + f.getAbsolutePath());
}
resourceFiles[i] = f;
}
final File moduleDir = getModulePath(getModulesDir(), moduleName, slot.getValue(parsedCmd));
if(moduleDir.exists()) {
throw new CommandLineException("Module " + moduleName + " already exists at " + moduleDir.getAbsolutePath());
}
if(!moduleDir.mkdirs()) {
throw new CommandLineException("Failed to create directory " + moduleDir.getAbsolutePath());
}
final ModuleConfigImpl config;
final String moduleXml = moduleArg.getValue(parsedCmd);
if(moduleXml != null) {
config = null;
final File source = new File(ctx.getCurrentDir(), moduleXml);
if(!source.exists()) {
throw new CommandLineException("Failed to locate the file on the filesystem: " + source.getAbsolutePath());
}
copy(source, new File(moduleDir, "module.xml"));
} else {
config = new ModuleConfigImpl(moduleName);
}
for(File f : resourceFiles) {
copy(f, new File(moduleDir, f.getName()));
if(config != null) {
config.addResource(new ResourceRoot(f.getName()));
}
}
if(config != null) {
final String dependenciesStr = dependencies.getValue(parsedCmd);
if(dependenciesStr != null) {
final String[] depsArr = dependenciesStr.split(",+");
for(String dep : depsArr) {
// TODO validate dependencies
config.addDependency(new ModuleDependency(dep));
}
}
final String propsStr = props.getValue(parsedCmd);
if(propsStr != null) {
final String[] pairs = propsStr.split(",");
for (String pair : pairs) {
int equals = pair.indexOf('=');
if (equals == -1) {
throw new CommandFormatException("Property '" + pair + "' in '" + propsStr + "' is missing the equals sign.");
}
final String propName = pair.substring(0, equals);
if (propName.isEmpty()) {
throw new CommandFormatException("Property name is missing for '" + pair + "' in '" + propsStr + "'");
}
config.setProperty(propName, pair.substring(equals + 1));
}
}
final String slotVal = slot.getValue(parsedCmd);
if (slotVal != null) {
config.setSlot(slotVal);
}
final String mainCls = mainClass.getValue(parsedCmd);
if(mainCls != null) {
config.setMainClass(mainCls);
}
FileWriter moduleWriter = null;
final File moduleFile = new File(moduleDir, "module.xml");
try {
moduleWriter = new FileWriter(moduleFile);
XMLExtendedStreamWriter xmlWriter = create(XMLOutputFactory.newInstance().createXMLStreamWriter(moduleWriter));
config.writeContent(xmlWriter, null);
xmlWriter.flush();
} catch (IOException e) {
throw new CommandLineException("Failed to create file " + moduleFile.getAbsolutePath(), e);
} catch (XMLStreamException e) {
throw new CommandLineException("Failed to write to " + moduleFile.getAbsolutePath(), e);
} finally {
if(moduleWriter != null) {
try {
moduleWriter.close();
} catch (IOException e) {}