List of usage examples for org.apache.maven.project MavenProject getDependencies
public List<Dependency> getDependencies()
From source file:org.sonatype.flexmojos.htmlwrapper.HtmlWrapperMojo.java
License:Apache License
@SuppressWarnings("unchecked") private Artifact findArtifact(MavenProject project, String groupId, String artifactId, String version, String type, String classifier) throws MojoExecutionException { // Dependencies must be traversed instead of artifacts here because of the execution phase of the mojo List<Dependency> dependencies = project.getDependencies(); for (Dependency dependency : dependencies) { String matchGroupId = dependency.getGroupId(); String matchArtifactId = dependency.getArtifactId(); String matchType = dependency.getType(); if (groupId.equals(matchGroupId) && artifactId.equals(matchArtifactId) && type.equals(matchType)) { if (version != null) { String matchVersion = dependency.getVersion(); if (version.equals(matchVersion)) { if (classifier != null) { String matchClassifier = dependency.getClassifier(); if (classifier.equals(matchClassifier)) { return convertToArtifact(dependency); } else { getLog().warn("Wrapper found matching artifact with classifier [" + matchClassifier + "], but did not match requested classifier [" + classifier + "] so it is being ignored"); }//from w w w.ja va 2 s .co m } else { return convertToArtifact(dependency); } } else { getLog().warn("Wrapper found matching artifact with version [" + matchVersion + "], but did not match requested version [" + version + "] so it is being ignored"); } } else { return convertToArtifact(dependency); } } } return null; }
From source file:org.sonatype.flexmojos.plugin.htmlwrapper.HtmlWrapperMojo.java
License:Open Source License
private Artifact findArtifact(MavenProject project, String groupId, String artifactId, String version, String type, String classifier) throws MojoExecutionException { // Dependencies must be traversed instead of artifacts here because of the execution phase of the mojo List<Dependency> dependencies = project.getDependencies(); for (Dependency dependency : dependencies) { String matchGroupId = dependency.getGroupId(); String matchArtifactId = dependency.getArtifactId(); String matchType = dependency.getType(); if (groupId.equals(matchGroupId) && artifactId.equals(matchArtifactId) && type.equals(matchType)) { if (version != null) { String matchVersion = dependency.getVersion(); if (version.equals(matchVersion)) { if (classifier != null) { String matchClassifier = dependency.getClassifier(); if (classifier.equals(matchClassifier)) { return convertToArtifact(dependency); } else { getLog().warn("Wrapper found matching artifact with classifier [" + matchClassifier + "], but did not match requested classifier [" + classifier + "] so it is being ignored"); }// ww w . j a va 2s .c om } else { return convertToArtifact(dependency); } } else { getLog().warn("Wrapper found matching artifact with version [" + matchVersion + "], but did not match requested version [" + version + "] so it is being ignored"); } } else { return convertToArtifact(dependency); } } } return null; }
From source file:org.sonatype.maven.plugins.provideddependencies.GenerateMojo.java
License:Open Source License
/** * Builds a multimap of dependency groupId:artifactId to exclusions {@link GroupArtifact}. *//* ww w . j ava2s . c o m*/ private Multimap<String, GroupArtifact> collectExclusions() { Multimap<String, GroupArtifact> mapping = LinkedHashMultimap.create(); for (Artifact artifact : project.getArtifacts()) { MavenProject p; try { p = projectBuilder.buildFromRepository(artifact, project.getRemoteArtifactRepositories(), localRepository); } catch (ProjectBuildingException e) { // ignore continue; } appendExclusions(mapping, p.getDependencies()); if (p.getDependencyManagement() != null) { appendExclusions(mapping, p.getDependencyManagement().getDependencies()); } } return mapping; }
From source file:org.sonatype.plugin.nexus.testenvironment.UnpackTestsMojo.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*from ww w .j av a 2s.c om*/ public void execute() throws MojoExecutionException, MojoFailureException { if (testSkip || pluginSkip) { return; } testOutputDirectory.mkdirs(); resourcesSourceLocation.mkdirs(); testResourcesDirectory.mkdirs(); Resource resource = new Resource(); resource.setDirectory(testResourcesDirectory.getAbsolutePath()); resource.addInclude("*"); resource.setTargetPath(testOutputDirectory.getAbsolutePath()); project.addResource(resource); Collection<Artifact> plugins = new LinkedHashSet<Artifact>(); plugins.addAll(getNexusPlugins()); plugins.addAll(getExtraTestSuites()); Set<Artifact> classpath = new LinkedHashSet<Artifact>(); if (project.getDependencyArtifacts() != null) { classpath.addAll(project.getDependencyArtifacts()); } ComponentsXmlResourceTransformer plxXml = new ComponentsXmlResourceTransformer(); ComponentsXmlResourceTransformer compXml = new ComponentsXmlResourceTransformer(); Properties baseProps = new Properties(); for (Artifact artifact : plugins) { Artifact jar = artifactFactory.createArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), "test", "jar"); try { classpath.add(resolve(jar)); } catch (MojoExecutionException e) { // ignore for now } Artifact testResources = artifactFactory.createArtifactWithClassifier(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), "zip", "test-resources"); try { resolve(testResources); } catch (MojoExecutionException e) { continue; } ZipFile zip = null; try { zip = new ZipFile(testResources.getFile()); copyAllTo(zip, "classes/", testOutputDirectory); copyAllTo(zip, "test-resources/", testResourcesDirectory); copyAllTo(zip, "resources/", resourcesSourceLocation); ZipEntry plexusXml = zip.getEntry("test-resources/META-INF/plexus/components.xml"); if (plexusXml != null) { InputStream is = zip.getInputStream(plexusXml); plxXml.processResource(is); IOUtil.close(is); } ZipEntry componentsXml = zip.getEntry("test-resources/components.xml"); if (componentsXml != null) { InputStream is = zip.getInputStream(componentsXml); compXml.processResource(is); IOUtil.close(is); } ZipEntry testProperties = zip.getEntry("test-resources/baseTest.properties"); if (testProperties != null) { InputStream is = zip.getInputStream(testProperties); baseProps.load(is); IOUtil.close(is); } } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } MavenProject model; try { model = mavenProjectBuilder.buildFromRepository(artifact, remoteRepositories, localRepository); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } List<Dependency> deps = model.getDependencies(); for (Dependency dependency : deps) { if (Artifact.SCOPE_TEST.equals(dependency.getScope())) { Artifact dep = artifactFactory.createArtifactWithClassifier(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getType(), dependency.getClassifier()); dep.setScope(Artifact.SCOPE_TEST); classpath.add(resolve(dep)); } } } try { plxXml.processResource(getClass().getResourceAsStream("/default-config/components.xml")); compXml.processResource(getClass().getResourceAsStream("/default-config/components.xml")); FileUtils.copyFile(plxXml.getTransformedResource(), new File(testResourcesDirectory, "META-INF/plexus/components.xml")); FileUtils.copyFile(compXml.getTransformedResource(), new File(testResourcesDirectory, "components.xml")); OutputStream out = new FileOutputStream(new File(testResourcesDirectory, "baseTest.properties")); baseProps.store(out, null); IOUtil.close(out); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } project.setDependencyArtifacts(classpath); }
From source file:org.sourcepit.b2.internal.generator.P2RepositoryDependencyConverter.java
License:Apache License
@Override protected void generate(Annotatable inputElement, boolean skipFacets, PropertiesSource properties, ITemplates templates, ModuleDirectory moduleDirectory) { final MavenSession session = legacySupport.getSession(); final MavenProject project = session.getCurrentProject(); final Collection<Dependency> p2RepoDeps = Collections2.filter(project.getDependencies(), P2_REPOSITORIES); if (!p2RepoDeps.isEmpty()) { final File pomFile = resolvePomFile(inputElement); final Model pom = readMavenModel(pomFile); for (Dependency p2RepoDep : p2RepoDeps) { final Artifact artifact = resolveArtifact(project, p2RepoDep.getGroupId(), p2RepoDep.getArtifactId(), "zip", p2RepoDep.getVersion(), p2RepoDep.getClassifier()); final ArtifactIdentifier ident = toArtifactIdentifier(artifact); final Repository repository = toRepository(ident, artifact.getFile()); LOGGER.info(/* w w w . j a v a 2s . c om*/ "Resolved dependency '" + ident + "' to local p2 repository '" + repository.getUrl() + "'"); pom.getRepositories().add(repository); } removeDependencies(pom, P2_REPOSITORIES); writeMavenModel(pomFile, pom); } }
From source file:org.sourcepit.b2.p2.MavenDependenciesSiteGenerator.java
License:Apache License
public void preInterpolation(AbstractModule module, final PropertiesSource moduleProperties) { final MavenSession session = legacySupport.getSession(); final MavenProject project = session.getCurrentProject(); final List<Dependency> dependencies = new ArrayList<Dependency>(filter(project.getDependencies(), JARS)); if (!dependencies.isEmpty()) { final IInterpolationLayout layout = layoutManager.getLayout(module.getLayoutId()); final File siteDir = new File(layout.pathOfMetaDataFile(module, "maven-dependencies")); final String repositoryName = "maven-dependencies@" + project.getArtifactId(); final List<ArtifactRepository> remoteRepositories = project.getRemoteArtifactRepositories(); final ArtifactRepository localRepository = session.getLocalRepository(); final Date startTime = session.getStartTime(); final String pattern = moduleProperties.get("osgifier.updateSiteBundles"); final PathMatcher bundleMatcher = pattern == null ? null : PathMatcher.parsePackagePatterns(pattern); BundleSelector bundleSelector = new AbstractBundleTreeSelector() { @Override/*from www .j a v a2s .com*/ public Collection<BundleCandidate> selectRootBundles(OsgifierContext bundleContext) { final DependencyModel dependencyModel = bundleContext.getExtension(DependencyModel.class); final Map<ArtifactKey, BundleCandidate> artifactKeyToBundle = new HashMap<ArtifactKey, BundleCandidate>(); for (BundleCandidate bundle : bundleContext.getBundles()) { artifactKeyToBundle.put(getArtifactKey(bundle), bundle); } final List<BundleCandidate> rootBundles = new ArrayList<BundleCandidate>(); for (MavenArtifact artifact : dependencyModel.getRootArtifacts()) { final BundleCandidate rootBundle = artifactKeyToBundle.get(artifact.getArtifactKey()); if (rootBundle != null && select(rootBundle)) { rootBundles.add(rootBundle); } } return rootBundles; } private ArtifactKey getArtifactKey(BundleCandidate bundle) { return bundle.getExtension(MavenArtifact.class).getArtifactKey(); } @Override public boolean select(Stack<BundleCandidate> path, BundleReference reference) { return !reference.isOptional() && super.select(path, reference); } @Override protected boolean select(BundleCandidate bundle) { return bundleMatcher == null || bundleMatcher.isMatch(bundle.getSymbolicName()); } }; final OsgifierContext bundleContext = updateSiteGenerator.generateUpdateSite(siteDir, dependencies, true, remoteRepositories, localRepository, repositoryName, moduleProperties, startTime, bundleSelector); try { module.setAnnotationData("b2.mavenDependencies", "repositoryURL", siteDir.toURI().toURL().toExternalForm()); } catch (MalformedURLException e) { throw pipe(e); } module.setAnnotationData("b2.mavenDependencies", "repositoryName", repositoryName); final Collection<BundleCandidate> selectedBundles = new LinkedHashSet<BundleCandidate>(); selectBundles(selectedBundles, bundleContext, bundleSelector); interpolatePlugins(module, moduleProperties, selectedBundles); } }
From source file:org.springframework.ide.eclipse.maven.legacy.internal.core.GoogleProjectConfigurator.java
License:Open Source License
/** * {@inheritDoc}// ww w . ja v a 2 s .com */ @Override protected void doConfigure(final MavenProject mavenProject, IProject project, ProjectConfigurationRequest request, final IProgressMonitor monitor) throws CoreException { final IMaven maven = MavenPlugin.getDefault().getMaven(); configureNature(project, mavenProject, GAE_NATURE_ID, true, new NatureCallbackAdapter() { @Override public void beforeAddingNature() { try { DefaultMavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest(); executionRequest.setBaseDirectory(mavenProject.getBasedir()); executionRequest.setLocalRepository(maven.getLocalRepository()); executionRequest.setRemoteRepositories(mavenProject.getRemoteArtifactRepositories()); executionRequest.setPluginArtifactRepositories(mavenProject.getPluginArtifactRepositories()); executionRequest.setPom(mavenProject.getFile()); executionRequest.setGoals(GAE_UNPACK_GOAL); MavenExecutionResult result = maven.execute(executionRequest, monitor); if (result.hasExceptions()) { MavenCorePlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, MavenCorePlugin.NON_LEGACY_PLUGIN_ID, "Error configuring project", result.getExceptions().get(0))); } } catch (CoreException e) { MavenCorePlugin.getDefault().getLog().log(new Status(IStatus.ERROR, MavenCorePlugin.NON_LEGACY_PLUGIN_ID, "Error configuring project", e)); } } }, monitor); if (configureNature(project, mavenProject, GWT_NATURE_ID, true, new NatureCallbackAdapter() { @Override public void beforeAddingNature() { // Get the GWT version from the project pom String gwtVersion = null; List<Dependency> dependencies = mavenProject.getDependencies(); for (Dependency dependency : dependencies) { if (GWT_GROUP_ID.equals(dependency.getGroupId()) && ("gwt-user".equals(dependency.getArtifactId()) || "gwt-servlet".equals(dependency.getArtifactId()))) { gwtVersion = dependency.getVersion(); break; } } // Check that the pom.xml has GWT dependencies if (StringUtils.hasLength(gwtVersion)) { try { // Download and install the gwt-dev.jar into the local repository maven.resolve(GWT_GROUP_ID, "gwt-dev", gwtVersion, "jar", null, mavenProject.getRemoteArtifactRepositories(), monitor); } catch (CoreException e) { MavenCorePlugin.getDefault().getLog().log(new Status(IStatus.ERROR, MavenCorePlugin.NON_LEGACY_PLUGIN_ID, "Error configuring project", e)); } } } }, monitor)) { try { // Add GWT Web Application configuration parameters IEclipsePreferences prefs = SpringCorePreferences .getProjectPreferences(project, "com.google.gdt.eclipse.core").getProjectPreferences(); prefs.put("warSrcDir", "src/main/webapp"); prefs.putBoolean("warSrcDirIsOutput", false); String artifactId = mavenProject.getArtifactId(); String version = mavenProject.getVersion(); IPath location = SpringCoreUtils.getProjectLocation(project); if (location != null && artifactId != null && version != null) { prefs.put("lastWarOutDir", location.append("target").append(artifactId + "-" + version).toFile() .getAbsolutePath()); } prefs.flush(); } catch (BackingStoreException e) { MavenCorePlugin.getDefault().getLog().log(new Status(IStatus.ERROR, MavenCorePlugin.NON_LEGACY_PLUGIN_ID, "Error configuring project", e)); } } }
From source file:org.springframework.ide.vscode.commons.maven.MavenCore.java
License:Open Source License
/** * Taken from M2E same named method from MavenModelManager * * @param repositorySystem/*from w w w .ja v a 2 s . com*/ * @param repositorySession * @param mavenProject * @param scope * @return */ private DependencyNode readDependencyTree(org.eclipse.aether.RepositorySystem repositorySystem, RepositorySystemSession repositorySession, MavenProject mavenProject, String scope) { DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(repositorySession); ConflictResolver transformer = new ConflictResolver(new NearestVersionSelector(), new JavaScopeSelector(), new SimpleOptionalitySelector(), new JavaScopeDeriver()); session.setDependencyGraphTransformer(transformer); session.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, Boolean.toString(true)); session.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, true); ArtifactTypeRegistry stereotypes = session.getArtifactTypeRegistry(); CollectRequest request = new CollectRequest(); request.setRequestContext("project"); //$NON-NLS-1$ request.setRepositories(mavenProject.getRemoteProjectRepositories()); for (org.apache.maven.model.Dependency dependency : mavenProject.getDependencies()) { request.addDependency(RepositoryUtils.toDependency(dependency, stereotypes)); } DependencyManagement depMngt = mavenProject.getDependencyManagement(); if (depMngt != null) { for (org.apache.maven.model.Dependency dependency : depMngt.getDependencies()) { request.addManagedDependency(RepositoryUtils.toDependency(dependency, stereotypes)); } } DependencyNode node; try { node = repositorySystem.collectDependencies(session, request).getRoot(); } catch (DependencyCollectionException ex) { node = ex.getResult().getRoot(); } Collection<String> scopes = new HashSet<String>(); Collections.addAll(scopes, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_COMPILE, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_RUNTIME, Artifact.SCOPE_TEST); if (Artifact.SCOPE_COMPILE.equals(scope)) { scopes.remove(Artifact.SCOPE_COMPILE); scopes.remove(Artifact.SCOPE_SYSTEM); scopes.remove(Artifact.SCOPE_PROVIDED); } else if (Artifact.SCOPE_RUNTIME.equals(scope)) { scopes.remove(Artifact.SCOPE_COMPILE); scopes.remove(Artifact.SCOPE_RUNTIME); } else if (Artifact.SCOPE_COMPILE_PLUS_RUNTIME.equals(scope)) { scopes.remove(Artifact.SCOPE_COMPILE); scopes.remove(Artifact.SCOPE_SYSTEM); scopes.remove(Artifact.SCOPE_PROVIDED); scopes.remove(Artifact.SCOPE_RUNTIME); } else { scopes.clear(); } CloningDependencyVisitor cloner = new CloningDependencyVisitor(); node.accept(new FilteringDependencyVisitor(cloner, new ScopeDependencyFilter(null, scopes))); node = cloner.getRootNode(); return node; }
From source file:org.srcdeps.mvn.enforcer.SrcdepsEnforcer.java
License:Apache License
@Override public void beforeProjectLifecycleExecution(ProjectExecutionEvent event) throws LifecycleExecutionException { final MavenProject project = event.getProject(); log.info("srcdeps enforcer checks for violations in {}:{}", project.getGroupId(), project.getArtifactId()); final Maven maven = configurationProducer.getConfiguration().getMaven(); final List<MojoExecution> mojoExecutions = event.getExecutionPlan(); final List<String> goals = new ArrayList<>(mojoExecutions.size()); for (MojoExecution mojoExecution : mojoExecutions) { MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); goals.add(mojoDescriptor.getFullGoalName()); goals.add(mojoDescriptor.getGoal()); }//from ww w . j av a 2s .c o m final List<String> profiles = new ArrayList<>(); final List<Profile> activeProfiles = project.getActiveProfiles(); for (Profile profile : activeProfiles) { final String id = profile.getId(); profiles.add(id); } final Properties props = new Properties(); props.putAll(project.getProperties()); props.putAll(System.getProperties()); String[] firstViolation = assertFailWithout(maven.getFailWithout(), goals, profiles, props); if (firstViolation == null) { firstViolation = assertFailWith(maven.getFailWith(), goals, profiles, props); } if (firstViolation != null) { /* check if there are srcdeps */ Artifact parent = project.getParentArtifact(); if (parent != null) { assertNotSrcdeps(parent.getGroupId(), parent.getArtifactId(), parent.getVersion(), firstViolation); } DependencyManagement dm; List<Dependency> deps; if ((dm = project.getDependencyManagement()) != null && (deps = dm.getDependencies()) != null) { assertNotSrcdeps(deps, firstViolation); } if ((deps = project.getDependencies()) != null) { assertNotSrcdeps(deps, firstViolation); } } }
From source file:org.srcdeps.mvn.plugin.SrcdepsInitMojo.java
License:Apache License
@Override public void execute() throws MojoExecutionException, MojoFailureException { super.execute(); org.srcdeps.core.GavSet.Builder gavSetBuilder = GavSet.builder() // .includes(includes) // .excludes(excludes);/*from w w w .java 2s. c o m*/ if (excludeSnapshots) { gavSetBuilder.excludeSnapshots(); } this.gavSet = gavSetBuilder.build(); log.info("Using includes and excludes [{}]", gavSet); log.info("Supported SCMs: {}", scms); if (skip || !multiModuleRootDir.equals(session.getCurrentProject().getBasedir())) { log.info(getClass().getSimpleName() + " skipped"); } else { Configuration.Builder config = Configuration.builder() // .configModelVersion(Configuration.getLatestConfigModelVersion()).commentBefore("") // .commentBefore("srcdeps.yaml - the srcdeps configuration file") // .commentBefore("") // .commentBefore( "The full srcdeps.yaml reference can be found under https://github.com/srcdeps/srcdeps-core/tree/master/doc/srcdeps.yaml") // .commentBefore("") // .commentBefore("This file was generated by the following command:") // .commentBefore("") // .commentBefore(" mvn org.srcdeps.mvn:srcdeps-maven-plugin:init") // .commentBefore("") // ; ScmRepositoryIndex index = new ScmRepositoryIndex(session, repoSession, repositorySystem, projectBuilder, scms); log.debug("Going over [{}] reactor projects", reactorProjects.size()); /* first add the reactor projects to seenGas so that they get ignored */ for (MavenProject project : reactorProjects) { index.ignoreGav(project.getGroupId(), project.getArtifactId(), project.getVersion()); } for (MavenProject project : reactorProjects) { final List<Dependency> dependencies = project.getDependencies(); log.info("Project [{}] has [{}] dependencies", project.getArtifactId(), dependencies == null ? 0 : dependencies.size()); if (dependencies != null) { for (Dependency dependency : dependencies) { final String g = dependency.getGroupId(); final String a = dependency.getArtifactId(); final String v = dependency.getVersion(); if (!"system".equals(dependency.getScope()) && gavSet.contains(g, a, v)) { /* Ignore system scope */ index.addGav(g, a, v, failOnUnresolvable); } } } final DependencyManagement dependencyManagement = project.getDependencyManagement(); if (dependencyManagement != null) { final List<Dependency> managedDeps = dependencyManagement.getDependencies(); if (managedDeps != null) { for (Dependency dependency : managedDeps) { final String g = dependency.getGroupId(); final String a = dependency.getArtifactId(); final String v = dependency.getVersion(); if (!"system".equals(dependency.getScope()) && gavSet.contains(g, a, v)) { /* Ignore system scope */ index.addGav(g, a, v, false); } } } } MavenProject parent = project.getParent(); if (parent != null) { final String g = parent.getGroupId(); final String a = parent.getArtifactId(); final String v = parent.getVersion(); if (gavSet.contains(g, a, v)) { index.addGav(g, a, v, failOnUnresolvable); } } } Map<String, Builder> repos = index.createSortedScmRepositoryMap(); if (repos.size() == 0) { /* add some dummy repo so that we do not write an empty srcdeps.yaml file */ ScmRepository.Builder dummyRepo = ScmRepository.builder() // .commentBefore( "FIXME: srcdeps-maven-plugin could not authomatically identify any SCM URLs for dependencies in this project") // .commentBefore( " and has added this dummy repository only as a starting point for you to proceed manually") // .id("org.my-group") // .selector("org.my-group") // .url("git:https://github.com/my-org/my-project.git") // ; repos.put(dummyRepo.getName(), dummyRepo); } config // .repositories(repos) // .accept(new OverrideVisitor(System.getProperties())) // .accept(new DefaultsAndInheritanceVisitor()) // ; final Path srcdepsYamlPath = multiModuleRootDir.toPath().resolve("srcdeps.yaml"); try { YamlWriterConfiguration yamlWriterConfiguration = YamlWriterConfiguration.builder().build(); try (Writer out = Files.newBufferedWriter(srcdepsYamlPath, Charset.forName(encoding))) { config.accept(new YamlWriterVisitor(out, yamlWriterConfiguration)); } } catch (IOException e) { throw new MojoExecutionException(String.format("Could not write [%s]", srcdepsYamlPath), e); } } }