List of usage examples for org.apache.maven.project MavenProject getArtifact
public Artifact getArtifact()
From source file:com.alibaba.citrus.maven.eclipse.base.ide.AbstractIdeSupportMojo.java
License:Apache License
/** * Resolve project dependencies. Manual resolution is needed in order to avoid resolution of multiproject artifacts * (if projects will be linked each other an installed jar is not needed) and to avoid a failure when a jar is * missing./*w ww . j ava 2s . c o m*/ * * @return resolved IDE dependencies, with attached jars for non-reactor dependencies * @throws MojoExecutionException if dependencies can't be resolved */ protected IdeDependency[] doDependencyResolution() throws MojoExecutionException { if (ideDeps == null) { if (resolveDependencies) { MavenProject project = getProject(); ArtifactRepository localRepo = getLocalRepository(); List deps = getProject().getDependencies(); // Collect the list of resolved IdeDependencies. List dependencies = new ArrayList(); if (deps != null) { Map managedVersions = createManagedVersionMap(getArtifactFactory(), project.getId(), project.getDependencyManagement()); ArtifactResolutionResult artifactResolutionResult = null; try { List listeners = new ArrayList(); if (logger.isDebugEnabled()) { listeners.add(new DebugResolutionListener(logger)); } listeners.add(new WarningResolutionListener(logger)); artifactResolutionResult = artifactCollector.collect(getProjectArtifacts(), project.getArtifact(), managedVersions, localRepo, project.getRemoteArtifactRepositories(), getArtifactMetadataSource(), null, listeners); } catch (ArtifactResolutionException e) { getLog().debug(e.getMessage(), e); getLog().error( Messages.getString("AbstractIdeSupportMojo.artifactresolution", new Object[] { //$NON-NLS-1$ e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); // if we are here artifactResolutionResult is null, create a project without dependencies but // don't fail // (this could be a reactor projects, we don't want to fail everything) // Causes MECLIPSE-185. Not sure if it should be handled this way?? return new IdeDependency[0]; } // keep track of added reactor projects in order to avoid duplicates Set emittedReactorProjectId = new HashSet(); for (Iterator i = artifactResolutionResult.getArtifactResolutionNodes().iterator(); i .hasNext();) { ResolutionNode node = (ResolutionNode) i.next(); int dependencyDepth = node.getDepth(); Artifact art = node.getArtifact(); // don't resolve jars for reactor projects if (hasToResolveJar(art)) { try { artifactResolver.resolve(art, node.getRemoteRepositories(), localRepository); } catch (ArtifactNotFoundException e) { getLog().debug(e.getMessage(), e); getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactdownload", //$NON-NLS-1$ new Object[] { e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); } catch (ArtifactResolutionException e) { getLog().debug(e.getMessage(), e); getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactresolution", new Object[] { //$NON-NLS-1$ e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); } } boolean includeArtifact = true; if (getExcludes() != null) { String artifactFullId = art.getGroupId() + ":" + art.getArtifactId(); if (getExcludes().contains(artifactFullId)) { getLog().info("excluded: " + artifactFullId); includeArtifact = false; } } if (includeArtifact && (!(getUseProjectReferences() && isAvailableAsAReactorProject(art)) || emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId()))) { // the following doesn't work: art.getArtifactHandler().getPackaging() always returns "jar" // also // if the packaging specified in pom.xml is different. // osgi-bundle packaging is provided by the felix osgi plugin // eclipse-plugin packaging is provided by this eclipse plugin // String packaging = art.getArtifactHandler().getPackaging(); // boolean isOsgiBundle = "osgi-bundle".equals( packaging ) || "eclipse-plugin".equals( // packaging ); // we need to check the manifest, if "Bundle-SymbolicName" is there the artifact can be // considered // an osgi bundle boolean isOsgiBundle = false; String osgiSymbolicName = null; if (art.getFile() != null) { JarFile jarFile = null; try { jarFile = new JarFile(art.getFile(), false, ZipFile.OPEN_READ); Manifest manifest = jarFile.getManifest(); if (manifest != null) { osgiSymbolicName = manifest.getMainAttributes() .getValue(new Attributes.Name("Bundle-SymbolicName")); } } catch (IOException e) { getLog().info("Unable to read jar manifest from " + art.getFile()); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { // ignore } } } } isOsgiBundle = osgiSymbolicName != null; IdeDependency dep = new IdeDependency(art.getGroupId(), art.getArtifactId(), art.getVersion(), art.getClassifier(), useProjectReference(art), Artifact.SCOPE_TEST.equals(art.getScope()), Artifact.SCOPE_SYSTEM.equals(art.getScope()), Artifact.SCOPE_PROVIDED.equals(art.getScope()), art.getArtifactHandler().isAddedToClasspath(), art.getFile(), art.getType(), isOsgiBundle, osgiSymbolicName, dependencyDepth, getProjectNameForArifact(art)); // no duplicate entries allowed. System paths can cause this problem. if (!dependencies.contains(dep)) { dependencies.add(dep); } } } // @todo a final report with the list of // missingArtifacts? } ideDeps = (IdeDependency[]) dependencies.toArray(new IdeDependency[dependencies.size()]); } else { ideDeps = new IdeDependency[0]; } } return ideDeps; }
From source file:com.baidu.jprotobuf.mojo.PreCompileMojo.java
License:Apache License
/** * Resolve the executable dependencies for the specified project * /* w ww .j a v a2 s . co m*/ * @param executablePomArtifact the project's POM * @return a set of Artifacts * @throws MojoExecutionException if a failure happens */ private Set<Artifact> resolveExecutableDependencies(Artifact executablePomArtifact) throws MojoExecutionException { Set<Artifact> executableDependencies; try { MavenProject executableProject = this.projectBuilder.buildFromRepository(executablePomArtifact, this.remoteRepositories, this.localRepository); // get all of the dependencies for the executable project List<Dependency> dependencies = executableProject.getDependencies(); // make Artifacts of all the dependencies Set<Artifact> dependencyArtifacts = MavenMetadataSource.createArtifacts(this.artifactFactory, dependencies, null, null, null); // not forgetting the Artifact of the project itself dependencyArtifacts.add(executableProject.getArtifact()); // resolve all dependencies transitively to obtain a comprehensive list of assemblies ArtifactResolutionResult result = artifactResolver.resolveTransitively(dependencyArtifacts, executablePomArtifact, Collections.emptyMap(), this.localRepository, this.remoteRepositories, metadataSource, null, Collections.emptyList()); executableDependencies = result.getArtifacts(); } catch (Exception ex) { throw new MojoExecutionException("Encountered problems resolving dependencies of the executable " + "in preparation for its execution.", ex); } return executableDependencies; }
From source file:com.basistech.bbhmp.RosapiBundleCollectorMojo.java
License:Open Source License
/** * Checks to see if the specified artifact is available from the reactor. * * @param artifact The artifact we are looking for. * @return The resolved artifact that is the same as the one we were looking for or <code>null</code> if one could * not be found./*w ww . j a va 2 s .c o m*/ */ private Artifact getArtifactFomReactor(Artifact artifact) { // check project dependencies first off for (Artifact a : project.getArtifacts()) { if (equals(artifact, a) && hasFile(a)) { return a; } } // check reactor projects for (MavenProject p : reactorProjects == null ? Collections.<MavenProject>emptyList() : reactorProjects) { // check the main artifact if (equals(artifact, p.getArtifact()) && hasFile(p.getArtifact())) { return p.getArtifact(); } // check any side artifacts for (Artifact a : (List<Artifact>) p.getAttachedArtifacts()) { if (equals(artifact, a) && hasFile(a)) { return a; } } } // not available return null; }
From source file:com.carrotgarden.maven.osgi.BaseMojo.java
License:BSD License
/** *//*ww w . j av a2 s . c om*/ protected void addProjectBundles(MavenProject project, String tab) { if (PomUtils.isBundleProject(// project, m_resolver, m_remoteRepos, m_localRepo, true)) { getLog().warn(tab + "found bundle : " + project.getId()); provisionBundle(project.getArtifact(), tab); } else { getLog().warn(tab + "check non-bundle: " + project.getId()); } addProjectDependencies(project, tab + TAB); }
From source file:com.cloudbees.eclipse.m2e.CBMavenUtils.java
License:Open Source License
public static IFile runMaven(IProject project, IProgressMonitor monitor, String[] goals) throws CloudBeesException { boolean pomExists = project.exists(new Path("/pom.xml")); if (!pomExists) { return null; }//w ww.j ava 2 s . co m IMaven maven = MavenPlugin.getMaven(); String version = MavenPlugin.getMavenRuntimeManager().getDefaultRuntime().getVersion(); MavenExecutionRequest request; IMavenProjectFacade mpr = MavenPlugin.getMavenProjectRegistry().getProject(project); try { if (mpr == null) { // maven not configured for the project. But as pom.xml existed, let's configure. NatureUtil.addNatures(project, new String[] { CloudBeesNature.NATURE_ID, JavaCore.NATURE_ID, "org.eclipse.m2e.core.maven2Nature" }, monitor); project.refreshLocal(IProject.DEPTH_INFINITE, monitor); mpr = MavenPlugin.getMavenProjectRegistry().getProject(project); } request = maven.createExecutionRequest(monitor); } catch (CoreException e) { throw new CloudBeesException("Failed to prepare maven war preparation request", e); } //IMavenProjectFacade facade = projectManager.create(pomFile, true, new SubProgressMonitor(monitor, 1)); //ResolverConfiguration config = mpr.getResolverConfiguration(); request.setPom(project.getFile(new Path("/pom.xml")).getRawLocation().toFile()); //request.setBaseDirectory(project.getRawLocation().toFile()); request.getSystemProperties().put("maven.test.skip", "true"); //MavenExecutionRequest request = projectManager.createExecutionRequest(pomFile, config, new SubProgressMonitor(monitor, 1)); //request.getUserProperties().setProperty("m2e.version", MavenPlugin.getVersion()); //goals.add("package"); //goals.add("eclipse:eclipse"); request.setGoals(Arrays.asList(goals)); //MavenPlugin.getConsole().showConsole(); MavenExecutionResult result = maven.execute(request, monitor); if (result.hasExceptions()) { // Throw CoreException //System.out.println("Got exceptions while running!"); Iterator<Throwable> it = result.getExceptions().iterator(); Throwable e = null; while (it.hasNext()) { Throwable throwable = (Throwable) it.next(); throwable.printStackTrace(); e = throwable; } throw new CloudBeesException("Maven build failed!", e); } BuildSummary summary = result.getBuildSummary(result.getProject()); MavenProject proj = summary.getProject(); Artifact artifact = proj.getArtifact(); File f = artifact.getFile(); //System.out.println("Artifact: " + f); //System.out.println("Artifact name: " + f.getName()); if (f == null) { return null; } if (BeesSDK.hasSupportedExtension(f.getName())) { String apath = f.getAbsolutePath().substring(project.getLocation().toFile().getAbsolutePath().length()); //System.out.println("APATH: " + apath); return project.getFile(apath); } return null; }
From source file:com.edugility.maven.Artifacts.java
License:Open Source License
/** * Returns an unmodifiable, non-{@code null} {@link Collection} of * {@link Artifact}s, each element of which is a non-{@code null} * {@link Artifact} that represents either the supplied {@link * MavenProject} itself or a {@linkplain MavenProject#getArtifacts() * dependency of it}./*from w w w . j a v a 2s . com*/ * * <p>The returned {@link Artifact} {@link Collection} will be * sorted in topological order, from an {@link Artifact} with no * dependencies as the first element, to the {@link Artifact} * representing the {@link MavenProject} itself as the last.</p> * * <p>All {@link Artifact}s that are not {@linkplain * Object#equals(Object) equal to} the return value of {@link * MavenProject#getArtifact() project.getArtifact()} will be * {@linkplain ArtifactResolver#resolve(ArtifactResolutionRequest) * resolved} if they are not already {@linkplain * Artifact#isResolved() resolved}. No guarantee of {@linkplain * Artifact#isResolved() resolution status} is made of the * {@linkplain MavenProject#getArtifact() project * <code>Artifact</code>}, which in normal—possibly * all?—cases will be unresolved.</p> * * @param project the {@link MavenProject} for which resolved {@link * Artifact}s should be returned; must not be {@code null} * * @param dependencyGraphBuilder the {@link DependencyGraphBuilder} * instance that will calculate the dependency graph whose postorder * traversal will yield the {@link Artifact}s to be resolved; must * not be {@code null} * * @param filter an {@link ArtifactFilter} used during {@linkplain * DependencyGraphBuilder#buildDependencyGraph(MavenProject, * ArtifactFilter) dependency graph assembly}; may be {@code null} * * @param resolver an {@link ArtifactResolver} that will use the <a * href="http://maven.apache.org/ref/3.0.5/maven-compat/apidocs/src-html/org/apache/maven/artifact/resolver/DefaultArtifactResolver.html#line.335">Maven * 3.0.5 <code>Artifact</code> resolution algorithm</a> to resolve * {@link Artifact}s returned by the {@link * DependencyGraphBuilder#buildDependencyGraph(MavenProject, * ArtifactFilter)} method; must not be {@code null} * * @param localRepository an {@link ArtifactRepository} representing * the local Maven repository in effect; may be {@code null} * * @return a non-{@code null}, {@linkplain * Collections#unmodifiableCollection(Collection) unmodifiable} * {@link Collection} of non-{@code null} {@link Artifact} instances * * @exception IllegalArgumentException if {@code project}, {@code * dependencyGraphBuilder} or {@code resolver} is {@code null} * * @exception ArtifactResolutionException if there were problems * {@linkplain ArtifactResolver#resolve(ArtifactResolutionRequest) * resolving} {@link Artifact} instances * * @exception DependencyGraphBuilderException if there were problems * {@linkplain * DependencyGraphBuilder#buildDependencyGraph(MavenProject, * ArtifactFilter) building the dependency graph} * * @see ArtifactResolver#resolve(ArtifactResolutionRequest) * * @see DependencyGraphBuilder#buildDependencyGraph(MavenProject, * ArtifactFilter) */ public Collection<? extends Artifact> getArtifactsInTopologicalOrder(final MavenProject project, final DependencyGraphBuilder dependencyGraphBuilder, final ArtifactFilter filter, final ArtifactResolver resolver, final ArtifactRepository localRepository) throws DependencyGraphBuilderException, ArtifactResolutionException { final Logger logger = this.getLogger(); if (logger != null && logger.isLoggable(Level.FINER)) { logger.entering(this.getClass().getName(), "getArtifactsInTopologicalOrder", new Object[] { project, dependencyGraphBuilder, filter, resolver, localRepository }); } if (project == null) { throw new IllegalArgumentException("project", new NullPointerException("project")); } if (dependencyGraphBuilder == null) { throw new IllegalArgumentException("dependencyGraphBuilder", new NullPointerException("dependencyGraphBuilder")); } if (resolver == null) { throw new IllegalArgumentException("resolver", new NullPointerException("resolver")); } List<Artifact> returnValue = null; final DependencyNode projectNode = dependencyGraphBuilder.buildDependencyGraph(project, filter); assert projectNode != null; final CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor(); projectNode.accept(visitor); final Collection<? extends DependencyNode> nodes = visitor.getNodes(); if (nodes == null || nodes.isEmpty()) { if (logger != null && logger.isLoggable(Level.FINE)) { logger.logp(Level.FINE, this.getClass().getName(), "getArtifactsInTopologicalOrder", "No dependency nodes encountered"); } } else { final Artifact projectArtifact = project.getArtifact(); returnValue = new ArrayList<Artifact>(); for (final DependencyNode node : nodes) { if (node != null) { Artifact artifact = node.getArtifact(); if (artifact != null) { if (!artifact.isResolved()) { if (logger != null && logger.isLoggable(Level.FINE)) { logger.logp(Level.FINE, this.getClass().getName(), "getArtifactsInTopologicalOrder", "Artifact {0} is unresolved", artifact); } if (artifact.equals(projectArtifact)) { // First see if the artifact is the project artifact. // If so, then it by definition won't be able to be // resolved, because it's being built. if (logger != null && logger.isLoggable(Level.FINE)) { logger.logp(Level.FINE, this.getClass().getName(), "getArtifactsInTopologicalOrder", "Artifact {0} resolved to project artifact: {1}", new Object[] { artifact, projectArtifact }); } artifact = projectArtifact; } else { // See if the project's associated artifact map // contains a resolved version of this artifact. The // artifact map contains all transitive dependency // artifacts of the project. Each artifact in the map // is guaranteed to be resolved. @SuppressWarnings("unchecked") final Map<String, Artifact> artifactMap = project.getArtifactMap(); if (artifactMap != null && !artifactMap.isEmpty()) { final Artifact mapArtifact = artifactMap .get(new StringBuilder(artifact.getGroupId()).append(":") .append(artifact.getArtifactId()).toString()); if (mapArtifact != null) { if (logger != null && logger.isLoggable(Level.FINE)) { logger.logp(Level.FINE, this.getClass().getName(), "getArtifactsInTopologicalOrder", "Artifact {0} resolved from project artifact map: {1}", new Object[] { artifact, mapArtifact }); } artifact = mapArtifact; } } if (!artifact.isResolved()) { // Finally, perform manual artifact resolution. final ArtifactResolutionRequest request = new ArtifactResolutionRequest(); request.setArtifact(artifact); request.setLocalRepository(localRepository); @SuppressWarnings("unchecked") final List<ArtifactRepository> remoteRepositories = project .getRemoteArtifactRepositories(); request.setRemoteRepositories(remoteRepositories); if (logger != null && logger.isLoggable(Level.FINE)) { logger.logp(Level.FINE, this.getClass().getName(), "getArtifactsInTopologicalOrder", "Resolving artifact {0} using ArtifactResolutionRequest {1}", new Object[] { artifact, request }); } final ArtifactResolutionResult result = resolver.resolve(request); if (result == null || !result.isSuccess()) { this.handleArtifactResolutionError(request, result); } else { @SuppressWarnings("unchecked") final Collection<? extends Artifact> resolvedArtifacts = (Set<? extends Artifact>) result .getArtifacts(); if (resolvedArtifacts == null || resolvedArtifacts.isEmpty()) { if (logger != null && logger.isLoggable(Level.WARNING)) { logger.logp(Level.WARNING, this.getClass().getName(), "getArtifactsInTopologicalOrder", "Artifact resolution failed silently for artifact {0}", artifact); } } else { final Artifact resolvedArtifact = resolvedArtifacts.iterator().next(); if (resolvedArtifact != null) { assert resolvedArtifact.isResolved(); artifact = resolvedArtifact; } else if (logger != null && logger.isLoggable(Level.WARNING)) { logger.logp(Level.WARNING, this.getClass().getName(), "getArtifactsInTopologicalOrder", "Artifact resolution failed silently for artifact {0}", artifact); } } } } } } if (artifact != null) { returnValue.add(artifact); } } } } if (!returnValue.isEmpty()) { Collections.reverse(returnValue); Collections.sort(returnValue, scopeComparator); } } if (returnValue == null) { returnValue = Collections.emptyList(); } else { returnValue = Collections.unmodifiableList(returnValue); } if (logger != null && logger.isLoggable(Level.FINER)) { logger.exiting(this.getClass().getName(), "getArtifactsInTopologicalOrder", returnValue); } return returnValue; }
From source file:com.edugility.maven.liquibase.LiquibaseChangeLogArtifactsProcessor.java
License:Open Source License
private final Collection<? extends URL> gatherArtifactUrls(final MavenProject project, final Collection<? extends Artifact> artifacts, final Log log) throws ArtifactsProcessingException { Collection<URL> returnValue = null; if (artifacts != null && !artifacts.isEmpty()) { final Collection<? extends String> names = this.getChangeLogResourceNames(); if (names != null && !names.isEmpty()) { for (final Artifact artifact : artifacts) { if (artifact != null && artifact.isResolved() && (project == null || !artifact.equals(project.getArtifact()))) { final File artifactFile = artifact.getFile(); if (artifactFile != null && artifactFile.canRead()) { for (final String name : names) { if (name != null) { URL url = null; try { url = artifactFile.toURI().toURL(); } catch (final MalformedURLException wrapMe) { throw new ArtifactsProcessingException(wrapMe); }// w w w .j av a 2 s . co m final URLClassLoader loader = new URLClassLoader(new URL[] { url }, Thread.currentThread().getContextClassLoader()); final URL jarUrlToChangeLog = loader.getResource(name); if (jarUrlToChangeLog != null) { if (returnValue == null) { returnValue = new ArrayList<URL>(artifacts.size() * names.size()); } returnValue.add(jarUrlToChangeLog); } } } } } } } } return returnValue; }
From source file:com.github.ferstl.depgraph.AggregatingGraphFactory.java
License:Apache License
private boolean isPartOfGraph(MavenProject project) { boolean result = this.artifactFilter.include(project.getArtifact()); // Project is not filtered and is a parent project if (result && project.getModules().size() > 0) { result = result && this.includeParentProjects; }/* ww w . ja va 2 s . co m*/ return result; }
From source file:com.github.ferstl.depgraph.AggregatingGraphFactory.java
License:Apache License
private Node filterProject(MavenProject project) { Artifact artifact = project.getArtifact(); if (this.artifactFilter.include(artifact)) { return new DependencyNodeAdapter(artifact); }/* w w w .j a va2 s.c o m*/ return null; }
From source file:com.github.ferstl.depgraph.dependency.AggregatingGraphFactory.java
License:Apache License
@Override public String createGraph(MavenProject parent) { this.graphBuilder.graphName(parent.getArtifactId()); if (this.includeParentProjects) { buildModuleTree(parent, this.graphBuilder); }/*from ww w . j a va2 s .c om*/ List<MavenProject> collectedProjects = parent.getCollectedProjects(); for (MavenProject collectedProject : collectedProjects) { // Process project only if its artifact is not filtered if (isPartOfGraph(collectedProject)) { this.mavenGraphAdapter.buildDependencyGraph(collectedProject, this.globalFilter, this.graphBuilder); } } // Add the project as single node if the graph is empty Artifact artifact = parent.getArtifact(); if (this.graphBuilder.isEmpty() && this.globalFilter.include(artifact)) { this.graphBuilder.addNode(new DependencyNode(artifact)); } return this.graphBuilder.toString(); }