use of org.commonjava.maven.atlas.ident.ref.ArtifactRef in project galley by Commonjava.
the class MavenModelProcessor method addDependencies.
private void addDependencies(final List<DependencyView> deps, final ProjectVersionRef projectRef, final Builder builder, final URI source, final boolean managed) {
if (deps != null) {
for (final DependencyView dep : deps) {
try {
final ProjectVersionRef ref = dep.asProjectVersionRef();
final String profileId = dep.getProfileId();
final URI location = RelationshipUtils.profileLocation(profileId);
final ArtifactRef artifactRef = new SimpleArtifactRef(ref, dep.getType(), dep.getClassifier());
// force the InvalidVersionSpecificationException.
artifactRef.getVersionSpec();
Set<ProjectRefView> exclusionsView = dep.getExclusions();
ProjectRef[] excludes;
if (exclusionsView != null && !exclusionsView.isEmpty()) {
excludes = new ProjectRef[exclusionsView.size()];
int i = 0;
for (ProjectRefView exclusionView : exclusionsView) {
excludes[i] = exclusionView.asProjectRef();
i++;
}
} else {
excludes = new ProjectRef[0];
}
builder.withDependencies(new SimpleDependencyRelationship(source, location, projectRef, artifactRef, dep.getScope(), builder.getNextDependencyIndex(managed), managed, dep.getOriginInfo().isInherited(), dep.isOptional(), excludes));
} catch (final InvalidRefException e) {
logger.error(String.format("%s: dependency is invalid! Reason: %s. Skipping:\n\n%s\n\n", projectRef, e.getMessage(), dep.toXML()), e);
} catch (final InvalidVersionSpecificationException e) {
logger.error(String.format("%s: dependency is invalid! Reason: %s. Skipping:\n\n%s\n\n", projectRef, e.getMessage(), dep.toXML()), e);
} catch (final GalleyMavenException e) {
logger.error(String.format("%s: dependency is invalid! Reason: %s. Skipping:\n\n%s\n\n", projectRef, e.getMessage(), dep.toXML()), e);
}
}
}
}
use of org.commonjava.maven.atlas.ident.ref.ArtifactRef in project pom-manipulation-ext by release-engineering.
the class Cli method run.
public int run(String[] args) {
Options options = new Options();
options.addOption("h", false, "Print this help message.");
options.addOption(Option.builder("d").longOpt("debug").desc("Enable debug").build());
options.addOption(Option.builder("t").longOpt("trace").desc("Enable trace").build());
options.addOption(Option.builder("h").longOpt("help").desc("Print help").build());
options.addOption(Option.builder("f").longOpt("file").hasArgs().numberOfArgs(1).desc("POM file").build());
options.addOption(Option.builder().longOpt("log-context").desc("Add log-context ID").numberOfArgs(1).build());
options.addOption(Option.builder("l").longOpt("log").desc("Log file to output logging to").numberOfArgs(1).build());
options.addOption(Option.builder("s").longOpt("settings").hasArgs().numberOfArgs(1).desc("Optional settings.xml file").build());
options.addOption(Option.builder("P").longOpt("activeProfiles").desc("Comma separated list of active profiles.").numberOfArgs(1).build());
options.addOption(Option.builder("o").longOpt("outputFile").desc("outputFile to output dependencies to. Only used with '-p' (Print all project dependencies)").numberOfArgs(1).build());
options.addOption(Option.builder("p").longOpt("printDeps").desc("Print all project dependencies").build());
options.addOption(Option.builder().longOpt("printGAVTC").desc("Print all project dependencies in group:artifact:version:type:classifier with scope information").build());
options.addOption(Option.builder("D").hasArgs().numberOfArgs(2).valueSeparator('=').desc("Java Properties").build());
options.addOption(Option.builder("x").hasArgs().numberOfArgs(2).desc("XPath tester ( file : xpath )").build());
CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
logger.debug("Caught problem parsing ", e);
System.err.println(e.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("...", options);
return 10;
}
if (cmd.hasOption('h')) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("...", options);
System.exit(0);
}
if (cmd.hasOption('D')) {
userProps = cmd.getOptionProperties("D");
}
if (cmd.hasOption('f')) {
target = new File(cmd.getOptionValue('f'));
}
if (cmd.hasOption('s')) {
settings = new File(cmd.getOptionValue('s'));
}
if (cmd.hasOption("log-context")) {
String mdc = cmd.getOptionValue("log-context");
if (isNotEmpty(mdc)) {
// Append a space to split up level and log-context markers.
MDC.put("LOG-CONTEXT", mdc + ' ');
}
}
createSession(target, settings);
final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
if (cmd.hasOption('l')) {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setPattern("%mdc{LOG-CONTEXT}%level %logger{36} %msg%n");
ple.setContext(loggerContext);
ple.start();
FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
fileAppender.setEncoder(ple);
fileAppender.setContext(loggerContext);
fileAppender.setName("fileLogging");
fileAppender.setAppend(false);
fileAppender.setFile(cmd.getOptionValue("l"));
fileAppender.start();
root.addAppender(fileAppender);
root.setLevel(Level.INFO);
}
// creation stuff.
if (cmd.hasOption('d')) {
root.setLevel(Level.DEBUG);
}
if (cmd.hasOption('t')) {
root.setLevel(Level.TRACE);
}
if (!session.isEnabled()) {
logger.info("Manipulation engine disabled via command-line option");
return 0;
}
if (!target.exists()) {
logger.info("Manipulation engine disabled. Project {} cannot be found.", target);
return 10;
} else // Don't bother skipping if we're just trying to analyse deps.
if (new File(target.getParentFile(), ManipulationManager.MARKER_FILE).exists() && !cmd.hasOption('p')) {
logger.info("Skipping manipulation as previous execution found.");
return 0;
}
try {
Properties config = new ConfigIO().parse(target.getParentFile());
String value = session.getUserProperties().getProperty("allowConfigFilePrecedence");
if (isNotEmpty(value) && "true".equalsIgnoreCase(value)) {
session.getUserProperties().putAll(config);
} else {
for (String key : config.stringPropertyNames()) {
if (!session.getUserProperties().containsKey(key)) {
session.getUserProperties().setProperty(key, config.getProperty(key));
}
}
}
} catch (ManipulationException e) {
logger.error("POM Manipulation failed: Unable to read config file ", e);
return 10;
}
try {
// Note : don't print out settings information earlier (like when we actually read it) as the logging
// isn't setup then.
logger.debug("Using local repository \n{} and found global settings file in {} with contents \n{} and user settings file in {} with contents \n{}", session.getLocalRepository(), DEFAULT_GLOBAL_SETTINGS_FILE, DEFAULT_GLOBAL_SETTINGS_FILE.exists() ? FileUtils.readFileToString(DEFAULT_GLOBAL_SETTINGS_FILE) : "** File does not exist **", settings, (settings != null && settings.exists()) ? FileUtils.readFileToString(settings) : "** File does not exist **");
manipulationManager.init(session);
Set<String> activeProfiles = null;
if (cmd.hasOption('P')) {
activeProfiles = new HashSet<>();
Collections.addAll(activeProfiles, cmd.getOptionValue('P').trim().split(","));
session.getUserProperties().setProperty(PROFILE_SCANNING, "true");
session.getActiveProfiles().addAll(activeProfiles);
}
if (cmd.hasOption('x')) {
String[] params = cmd.getOptionValues('x');
if (params.length != 2) {
throw new ManipulationException("Invalid number of parameters (" + params.length + "); should be <file> <xpath>");
}
XMLIO xmlIO = new XMLIO();
Document doc = xmlIO.parseXML(new File(params[0]));
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.evaluate(params[1], doc, XPathConstants.NODESET);
logger.info("Found {} node", nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
logger.info("Found node {} and value {} ", node.getNodeName(), node.getTextContent());
}
} else if (cmd.hasOption('p') || cmd.hasOption("printGAVTC")) {
Set<ArtifactRef> ts = RESTCollector.establishAllDependencies(session, pomIO.parseProject(session.getPom()), activeProfiles);
logger.info("Found {} dependencies. {}", ts.size(), ts);
File output = null;
if (cmd.hasOption('o')) {
output = new File(cmd.getOptionValue('o'));
output.delete();
}
for (ArtifactRef a : ts) {
String scope = null;
if (a instanceof SimpleScopedArtifactRef) {
scope = ((SimpleScopedArtifactRef) a).getScope();
}
if (cmd.hasOption('o')) {
if (cmd.hasOption("printGAVTC")) {
FileUtils.writeStringToFile(output, String.format("%-80s%10s\n", a, scope), true);
} else {
FileUtils.writeStringToFile(output, a.asProjectVersionRef().toString() + '\n', true);
}
} else {
if (cmd.hasOption("printGAVTC")) {
System.out.format("%-80s%10s\n", a, scope);
} else {
System.out.println(a.asProjectVersionRef());
}
}
}
} else {
manipulationManager.scanAndApply(session);
}
} catch (ManipulationException e) {
logger.error("POM Manipulation failed; original error is {}", e.getMessage());
logger.debug("POM Manipulation error trace is", e);
return 10;
} catch (RestException e) {
logger.error("REST communication with {} failed. {}", userProps.getProperty("restURL"), e.getMessage());
logger.trace("Exception trace is", e);
return 100;
} catch (Exception e) {
logger.error("POM Manipulation failed.", e);
return 100;
}
return 0;
}
use of org.commonjava.maven.atlas.ident.ref.ArtifactRef in project pom-manipulation-ext by release-engineering.
the class Project method getAllResolvedProfileDependencies.
/**
* This method will scan the dependencies in the potentially active Profiles in this project and
* return a fully resolved list. Note that this will return all dependencies including managed
* i.e. those with a group, artifact and potentially empty version.
*
* Note that while updating the {@link Dependency} reference returned will be reflected in the
* Model as it is the same object, if you wish to remove or add items to the Model then you
* must use {@link #getModel()}
*
* @param session MavenSessionHandler, used by {@link PropertyResolver}
* @return a list of fully resolved {@link ArtifactRef} to the original {@link Dependency}
* @throws ManipulationException if an error occurs
*/
public HashMap<Profile, HashMap<ArtifactRef, Dependency>> getAllResolvedProfileDependencies(MavenSessionHandler session) throws ManipulationException {
if (allResolvedProfileDependencies == null) {
allResolvedProfileDependencies = new HashMap<>();
for (final Profile profile : ProfileUtils.getProfiles(session, model)) {
HashMap<ArtifactRef, Dependency> profileDeps = new HashMap<>();
resolveDeps(session, profile.getDependencies(), true, profileDeps);
allResolvedProfileDependencies.put(profile, profileDeps);
}
}
return allResolvedProfileDependencies;
}
use of org.commonjava.maven.atlas.ident.ref.ArtifactRef in project pom-manipulation-ext by release-engineering.
the class Project method getResolvedProfileDependencies.
/**
* This method will scan the dependencies in the potentially active Profiles in this project and
* return a fully resolved list. Note that this will only return full dependencies not managed
* i.e. those with a group, artifact and version.
*
* Note that while updating the {@link Dependency} reference returned will be reflected in the
* Model as it is the same object, if you wish to remove or add items to the Model then you
* must use {@link #getModel()}
*
* @param session MavenSessionHandler, used by {@link PropertyResolver}
* @return a list of fully resolved {@link ArtifactRef} to the original {@link Dependency}
* @throws ManipulationException if an error occurs
*/
public HashMap<Profile, HashMap<ArtifactRef, Dependency>> getResolvedProfileDependencies(MavenSessionHandler session) throws ManipulationException {
if (resolvedProfileDependencies == null) {
resolvedProfileDependencies = new HashMap<>();
for (final Profile profile : ProfileUtils.getProfiles(session, model)) {
HashMap<ArtifactRef, Dependency> profileDeps = new HashMap<>();
resolveDeps(session, profile.getDependencies(), false, profileDeps);
resolvedProfileDependencies.put(profile, profileDeps);
}
}
return resolvedProfileDependencies;
}
use of org.commonjava.maven.atlas.ident.ref.ArtifactRef in project pom-manipulation-ext by release-engineering.
the class DependencyManipulator method apply.
/**
* Applies dependency overrides to the project.
*/
private void apply(final Project project, final Model model, final Map<ArtifactRef, String> overrides) throws ManipulationException {
// Map of Group : Map of artifactId [ may be wildcard ] : value
final WildcardMap<String> explicitOverrides = new WildcardMap<>();
final String projectGA = ga(project);
final DependencyState dependencyState = session.getState(DependencyState.class);
final CommonState commonState = session.getState(CommonState.class);
logger.info("Processing project {} ", projectGA);
Map<ArtifactRef, String> moduleOverrides = new LinkedHashMap<>(overrides);
moduleOverrides = removeReactorGAs(moduleOverrides);
try {
moduleOverrides = applyModuleVersionOverrides(projectGA, dependencyState.getDependencyExclusions(), moduleOverrides, explicitOverrides);
logger.debug("Module overrides are:\n{}", moduleOverrides);
logger.debug("Explicit overrides are:\n{}", explicitOverrides);
} catch (InvalidRefException e) {
logger.error("Invalid module exclusion override {} : {} ", moduleOverrides, explicitOverrides);
throw e;
}
if (project.isInheritanceRoot()) {
// Handle the situation where the top level parent refers to a prior build that is in the BOM.
if (project.getModelParent() != null) {
for (Map.Entry<ArtifactRef, String> entry : moduleOverrides.entrySet()) {
String oldValue = project.getModelParent().getVersion();
String newValue = entry.getValue();
if (entry.getKey().asProjectRef().equals(SimpleProjectRef.parse(ga(project.getModelParent())))) {
if (commonState.getStrict()) {
if (!PropertiesUtils.checkStrictValue(session, oldValue, newValue)) {
if (commonState.getFailOnStrictViolation()) {
throw new ManipulationException("Parent reference {} replacement: {} of original version: {} violates the strict version-alignment rule!", ga(project.getModelParent()), newValue, oldValue);
} else {
logger.warn("Parent reference {} replacement: {} of original version: {} violates the strict version-alignment rule!", ga(project.getModelParent()), newValue, oldValue);
// a new property either.
continue;
}
}
}
logger.debug(" Modifying parent reference from {} to {} for {} ", model.getParent().getVersion(), newValue, ga(project.getModelParent()));
model.getParent().setVersion(newValue);
break;
}
}
// Apply any explicit overrides to the top level parent. Convert it to a simulated
// dependency so we can reuse applyExplicitOverrides.
HashMap<ArtifactRef, Dependency> pDepMap = new HashMap<>();
Dependency d = new Dependency();
d.setGroupId(project.getModelParent().getGroupId());
d.setArtifactId(project.getModelParent().getArtifactId());
d.setVersion(project.getModelParent().getVersion());
pDepMap.put(SimpleArtifactRef.parse(d.getManagementKey()), d);
applyExplicitOverrides(project, pDepMap, explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
project.getModelParent().setVersion(d.getVersion());
}
if (session.getState(DependencyState.class).getOverrideDependencies()) {
// Apply overrides to project dependency management
logger.debug("Applying overrides to managed dependencies for: {}", projectGA);
final Map<ArtifactRef, String> nonMatchingVersionOverrides = applyOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, moduleOverrides);
final Map<ArtifactRef, String> matchedOverrides = new LinkedHashMap<>(moduleOverrides);
matchedOverrides.keySet().removeAll(nonMatchingVersionOverrides.keySet());
applyExplicitOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
if (commonState.getOverrideTransitive()) {
final List<Dependency> extraDeps = new ArrayList<>();
// Add dependencies to Dependency Management which did not match any existing dependency
for (final ArtifactRef var : overrides.keySet()) {
if (!nonMatchingVersionOverrides.containsKey(var)) {
// This one in the remote pom was already dealt with ; continue.
continue;
}
final Dependency newDependency = new Dependency();
newDependency.setGroupId(var.getGroupId());
newDependency.setArtifactId(var.getArtifactId());
newDependency.setType(var.getType());
newDependency.setClassifier(var.getClassifier());
final String artifactVersion = moduleOverrides.get(var);
newDependency.setVersion(artifactVersion);
extraDeps.add(newDependency);
logger.debug("New entry added to <DependencyManagement/> - {} : {} ", var, artifactVersion);
}
// If the model doesn't have any Dependency Management set by default, create one for it
DependencyManagement dependencyManagement = model.getDependencyManagement();
if (extraDeps.size() > 0) {
if (dependencyManagement == null) {
dependencyManagement = new DependencyManagement();
model.setDependencyManagement(dependencyManagement);
logger.debug("Added <DependencyManagement/> for current project");
}
dependencyManagement.getDependencies().addAll(0, extraDeps);
}
} else {
logger.debug("Non-matching dependencies ignored.");
}
} else {
logger.debug("NOT applying overrides to managed dependencies for top-pom: {}", projectGA);
}
} else {
// If a child module has a depMgmt section we'll change that as well.
if (session.getState(DependencyState.class).getOverrideDependencies()) {
logger.debug("Applying overrides to managed dependencies for: {}", projectGA);
applyOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, moduleOverrides);
applyExplicitOverrides(project, project.getResolvedManagedDependencies(session), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
} else {
logger.debug("NOT applying overrides to managed dependencies for: {}", projectGA);
}
}
if (session.getState(DependencyState.class).getOverrideDependencies()) {
logger.debug("Applying overrides to concrete dependencies for: {}", projectGA);
// Apply overrides to project direct dependencies
applyOverrides(project, project.getResolvedDependencies(session), explicitOverrides, moduleOverrides);
applyExplicitOverrides(project, project.getResolvedDependencies(session), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
final HashMap<Profile, HashMap<ArtifactRef, Dependency>> pd = project.getResolvedProfileDependencies(session);
final HashMap<Profile, HashMap<ArtifactRef, Dependency>> pmd = project.getResolvedProfileManagedDependencies(session);
for (Profile p : pd.keySet()) {
applyOverrides(project, pd.get(p), explicitOverrides, moduleOverrides);
applyExplicitOverrides(project, pd.get(p), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
}
for (Profile p : pmd.keySet()) {
applyOverrides(project, pmd.get(p), explicitOverrides, moduleOverrides);
applyExplicitOverrides(project, pmd.get(p), explicitOverrides, commonState, explicitVersionPropertyUpdateMap);
}
} else {
logger.debug("NOT applying overrides to concrete dependencies for: {}", projectGA);
}
}
Aggregations