public void addDependencies(final String moduleName,
final Collection<? extends Dependency> newDependencies) {
Validate.isTrue(isProjectAvailable(moduleName),
"Dependency modification prohibited; no such module '%s'",
moduleName);
final Pom pom = getPomFromModuleName(moduleName);
Validate.notNull(pom,
"The pom is not available, so dependencies cannot be added");
final Document document = XmlUtils.readXml(fileManager
.getInputStream(pom.getPath()));
final Element dependenciesElement = DomUtils.createChildIfNotExists(
"dependencies", document.getDocumentElement(), document);
final List<Element> existingDependencyElements = XmlUtils.findElements(
"dependency", dependenciesElement);
final List<String> addedDependencies = new ArrayList<String>();
final List<String> removedDependencies = new ArrayList<String>();
final List<String> skippedDependencies = new ArrayList<String>();
for (final Dependency newDependency : newDependencies) {
if (pom.canAddDependency(newDependency)) {
// Look for any existing instances of this dependency
boolean inserted = false;
for (final Element existingDependencyElement : existingDependencyElements) {
final Dependency existingDependency = new Dependency(
existingDependencyElement);
if (existingDependency.hasSameCoordinates(newDependency)) {
// It's the same artifact, but might have a different
// version, exclusions, etc.
if (!inserted) {
// We haven't added the new one yet; do so now
dependenciesElement.insertBefore(
newDependency.getElement(document),
existingDependencyElement);
inserted = true;
if (!newDependency.getVersion().equals(
existingDependency.getVersion())) {
// It's a genuine version change => mention the
// old and new versions in the message
addedDependencies.add(newDependency
.getSimpleDescription());
removedDependencies.add(existingDependency
.getSimpleDescription());
}
}
// Either way, we remove the previous one in case it was
// different in any way
dependenciesElement
.removeChild(existingDependencyElement);
}
// Keep looping in case it's present more than once
}
if (!inserted) {
// We didn't encounter any existing dependencies with the
// same coordinates; add it now
dependenciesElement.appendChild(newDependency
.getElement(document));
addedDependencies.add(newDependency.getSimpleDescription());
}
}
else {
skippedDependencies.add(newDependency.getSimpleDescription());
}
}
if (!newDependencies.isEmpty() || !skippedDependencies.isEmpty()) {
final String message = getPomDependenciesUpdateMessage(
addedDependencies, removedDependencies, skippedDependencies);
fileManager.createOrUpdateTextFileIfRequired(pom.getPath(),
XmlUtils.nodeToString(document), message, false);
}
}