org.apache.maven.artifact.Artifact Java Examples

The following examples show how to use org.apache.maven.artifact.Artifact. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProGuardMojo.java    From code-hidding-plugin with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static File getClasspathElement(Artifact artifact, MavenProject mavenProject)
                                                                                     throws MojoExecutionException {
    if (artifact.getClassifier() != null) {
        return artifact.getFile();
    }
    String refId = artifact.getGroupId() + ":" + artifact.getArtifactId();
    MavenProject project = (MavenProject) mavenProject.getProjectReferences().get(refId);
    if (project != null) {
        return new File(project.getBuild().getOutputDirectory());
    } else {
        File file = artifact.getFile();
        if ((file == null) || (!file.exists())) {
            throw new MojoExecutionException("Dependency Resolution Required " + artifact);
        }
        return file;
    }
}
 
Example #2
Source File: JavaFXRunMojoTestCase.java    From javafx-maven-plugin with Apache License 2.0 6 votes vote down vote up
protected JavaFXRunMojo getJavaFXRunMojo(String parent) throws Exception {
    File testPom = new File(getBasedir(), parent + "/pom.xml");
    JavaFXRunMojo mojo = (JavaFXRunMojo) lookupMojo("run", testPom);
    assertNotNull(mojo);

    setUpProject(testPom, mojo);
    MavenProject project = (MavenProject) getVariableValueFromObject( mojo, "project" );
    assertNotNull(project);

    if (! project.getDependencies().isEmpty()) {
        final MavenArtifactResolver resolver = new MavenArtifactResolver(project.getRepositories());
        Set<Artifact> artifacts = project.getDependencies().stream()
                .map(d -> new DefaultArtifact(d.getGroupId(), d.getArtifactId(), d.getClassifier(), d.getType(), d.getVersion()))
                .flatMap(a -> resolver.resolve(a).stream())
                .collect(Collectors.toSet());
        if (artifacts != null) {
            project.setArtifacts(artifacts);
        }
    }
    setVariableValueToObject(mojo, "compilePath", project.getCompileClasspathElements());
    setVariableValueToObject(mojo, "session", session);
    setVariableValueToObject(mojo, "executable", "java");
    setVariableValueToObject(mojo, "basedir", new File(getBasedir(), parent));

    return mojo;
}
 
Example #3
Source File: DefaultJnlpDependencyRequestBuilder.java    From webstart with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public JnlpDependencyRequest createRequest( Artifact artifact, boolean outputJarVersion, boolean useUniqueVersions )
{

    if ( globalConfig == null )
    {
        throw new IllegalStateException( "No config found, use init method before creating a request" );
    }

    JnlpDependencyConfig config = createConfig( artifact, outputJarVersion, useUniqueVersions );

    JnlpDependencyTask[] tasks = createTasks( config );

    JnlpDependencyRequest request = new JnlpDependencyRequest( config, tasks );
    return request;
}
 
Example #4
Source File: AbstractVertxMojo.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * this method helps in resolving the {@link Artifact} as maven coordinates
 * coordinates ::= group:artifact[:packaging[:classifier]]:version
 *
 * @param artifact - the artifact which need to be represented as maven coordinate
 * @return string representing the maven coordinate
 */
protected String asMavenCoordinates(Artifact artifact) {
    // TODO-ROL: Shouldn't there be also the classified included after the groupId (if given ?)
    // Maybe we we should simply reuse DefaultArtifact.toString() (but could be too fragile as it might change
    // although I don't think it will change any time soon since probably many people already
    // rely on it)
    StringBuilder artifactCords = new StringBuilder().
        append(artifact.getGroupId())
        .append(":")
        .append(artifact.getArtifactId());
    if (!"jar".equals(artifact.getType()) || artifact.hasClassifier()) {
        artifactCords.append(":").append(artifact.getType());
    }
    if (artifact.hasClassifier()) {
        artifactCords.append(":").append(artifact.getClassifier());
    }
    artifactCords.append(":").append(artifact.getVersion());
    return artifactCords.toString();
}
 
Example #5
Source File: Util.java    From jax-maven-plugin with Apache License 2.0 6 votes vote down vote up
static Stream<String> getPluginRuntimeDependencyEntries(AbstractMojo mojo, MavenProject project, Log log,
        RepositorySystem repositorySystem, ArtifactRepository localRepository,
        List<ArtifactRepository> remoteRepositories) {
    PluginDescriptor pluginDescriptor = (PluginDescriptor) mojo.getPluginContext().get(PLUGIN_DESCRIPTOR);
    Plugin plugin = project.getBuild().getPluginsAsMap().get(pluginDescriptor.getPluginLookupKey());

    List<ArtifactResolutionResult> artifactResolutionResults = plugin //
            .getDependencies() //
            .stream() //
            .map(repositorySystem::createDependencyArtifact) //
            .map(a -> Util.resolve(log, a, repositorySystem, localRepository, remoteRepositories)) //
            .collect(Collectors.toList());

    Stream<Artifact> originalArtifacts = artifactResolutionResults.stream()
            .map(ArtifactResolutionResult::getOriginatingArtifact);

    Stream<Artifact> childArtifacts = artifactResolutionResults.stream()
            .flatMap(resolutionResult -> resolutionResult.getArtifactResolutionNodes().stream())
            .map(ResolutionNode::getArtifact);

    return Stream.concat(originalArtifacts, childArtifacts).map(Artifact::getFile).map(File::getAbsolutePath);
}
 
Example #6
Source File: MutableMojo.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
static void resolveDependencies(final MavenSession session, final MojoExecution execution, final MojoExecutor executor, final ProjectDependenciesResolver projectDependenciesResolver) throws DependencyResolutionException, LifecycleExecutionException {
//    flushProjectArtifactsCache(executor);

    final MavenProject project = session.getCurrentProject();
    final Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();
    final Map<String,List<MojoExecution>> executions = new LinkedHashMap<>(execution.getForkedExecutions());
    final ExecutionListener executionListener = session.getRequest().getExecutionListener();
    try {
      project.setDependencyArtifacts(null);
      execution.getForkedExecutions().clear();
      session.getRequest().setExecutionListener(null);
      executor.execute(session, Collections.singletonList(execution), new ProjectIndex(session.getProjects()));
    }
    finally {
      execution.getForkedExecutions().putAll(executions);
      session.getRequest().setExecutionListener(executionListener);
      project.setDependencyArtifacts(dependencyArtifacts);
    }

    projectDependenciesResolver.resolve(newDefaultDependencyResolutionRequest(session));
  }
 
Example #7
Source File: AbstractJnlpMojo.java    From webstart with MIT License 6 votes vote down vote up
/**
 * @param pattern   pattern to test over artifacts
 * @param artifacts collection of artifacts to check
 * @return true if filter matches no artifact, false otherwise *
 */
private boolean ensurePatternMatchesAtLeastOneArtifact( String pattern, Collection<Artifact> artifacts )
{
    List<String> onePatternList = new ArrayList<>();
    onePatternList.add( pattern );
    ArtifactFilter filter = new IncludesArtifactFilter( onePatternList );

    boolean noMatch = true;
    for ( Artifact artifact : artifacts )
    {
        getLog().debug( "checking pattern: " + pattern + " against " + artifact );

        if ( filter.include( artifact ) )
        {
            noMatch = false;
            break;
        }
    }
    if ( noMatch )
    {
        getLog().error( "pattern: " + pattern + " doesn't match any artifact." );
    }
    return noMatch;
}
 
Example #8
Source File: BotsingMojo.java    From botsing with Apache License 2.0 6 votes vote down vote up
public List<Artifact> getDependencyTree(DependencyInputType dependencyType) throws MojoExecutionException {
	try {
		ProjectBuildingRequest buildingRequest = getProjectbuildingRequest(dependencyType);

		// TODO check if it is necessary to specify an artifact filter
		DependencyNode rootNode = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, null,
				reactorProjects);

		List<Artifact> artifactList = new ArrayList<Artifact>();
		addChildDependencies(rootNode, artifactList);

		return artifactList;

	} catch (DependencyGraphBuilderException e) {
		throw new MojoExecutionException("Couldn't download artifact: " + e.getMessage(), e);
	}
}
 
Example #9
Source File: AbstractKieMojo.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected boolean hasClassOnClasspath(MavenProject project, String className) {
    try {
        Set<Artifact> elements = project.getArtifacts();
        URL[] urls = new URL[elements.size()];

        int i = 0;
        Iterator<Artifact> it = elements.iterator();
        while (it.hasNext()) {
            Artifact artifact = it.next();

            urls[i] = artifact.getFile().toURI().toURL();
            i++;
        }
        try (URLClassLoader cl = new URLClassLoader(urls)) {
            cl.loadClass(className);
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example #10
Source File: SpringBootStarterMojo.java    From camel-spring-boot with Apache License 2.0 6 votes vote down vote up
private Set<String> filterIncludedArtifacts(Set<String> artifacts) {

        Set<Artifact> dependencies;
        try {
            Artifact artifact = project.getArtifactMap().get(getMainDepGroupId() + ":" + getMainDepArtifactId());
            ProjectBuildingResult result = projectBuilder.build(artifact, project.getProjectBuildingRequest());
            MavenProject prj = result.getProject();
            prj.setRemoteArtifactRepositories(project.getRemoteArtifactRepositories());
            dependencies = projectDependenciesResolver.resolve(prj, Collections.singleton(Artifact.SCOPE_COMPILE), session);
        } catch (Exception e) {
            throw new RuntimeException("Unable to build project dependency tree", e);
        }

        Set<String> included = new TreeSet<>();
        dependencies.stream()
                .filter(a -> !Artifact.SCOPE_TEST.equals(a.getScope()))
                .map(a -> a.getGroupId() + ":" + a.getArtifactId())
                .forEach(included::add);
        included.retainAll(artifacts);

        return included;
    }
 
Example #11
Source File: EarImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private EarImpl.MavenModule findMavenModule(Artifact art, EarImpl.MavenModule[] mm) {
    EarImpl.MavenModule toRet = null;
    for (EarImpl.MavenModule m : mm) {
        if (art.getGroupId().equals(m.groupId) && art.getArtifactId().equals(m.artifactId)) {
            m.artifact = art;
            toRet = m;
            break;
        }
    }
    if (toRet == null) {
        toRet = new EarImpl.MavenModule();
        toRet.artifact = art;
        toRet.groupId = art.getGroupId();
        toRet.artifactId = art.getArtifactId();
        toRet.classifier = art.getClassifier();
        //add type as well?
    }
    return toRet;
}
 
Example #12
Source File: SCoveragePreCompileMojo.java    From scoverage-maven-plugin with Apache License 2.0 6 votes vote down vote up
private Artifact getScalaScoverageRuntimeArtifact( String scalaMainVersion )
    throws ArtifactNotFoundException, ArtifactResolutionException
{
    Artifact result = null;

    String resolvedScalacRuntimeVersion = scalacPluginVersion;
    if ( resolvedScalacRuntimeVersion == null || "".equals( resolvedScalacRuntimeVersion ) )
    {
        for ( Artifact artifact : pluginArtifacts )
        {
            if ( "org.scoverage".equals( artifact.getGroupId() )
                && "scalac-scoverage-plugin_2.12".equals( artifact.getArtifactId() ) )
            {
                resolvedScalacRuntimeVersion = artifact.getVersion();
                break;
            }
        }
    }

    result =
        getResolvedArtifact( "org.scoverage", "scalac-scoverage-runtime_" + scalaMainVersion,
                             resolvedScalacRuntimeVersion );
    return result;
}
 
Example #13
Source File: AbstractScriptGeneratorMojo.java    From appassembler with MIT License 6 votes vote down vote up
protected void installDependencies( final String outputDirectory, final String repositoryName )
    throws MojoExecutionException, MojoFailureException
{
    if ( generateRepository )
    {
        // The repo where the jar files will be installed
        ArtifactRepository artifactRepository =
            artifactRepositoryFactory.createDeploymentArtifactRepository( "appassembler", "file://"
                + outputDirectory + "/" + repositoryName, getArtifactRepositoryLayout(), false );

        for ( Artifact artifact : artifacts )
        {
            installArtifact( artifact, artifactRepository, this.useTimestampInSnapshotFileName );
        }

        // install the project's artifact in the new repository
        installArtifact( projectArtifact, artifactRepository );
    }
}
 
Example #14
Source File: MavenHelper.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Resolve the artifacts with the given key.
 *
 * @param groupId the group identifier.
 * @param artifactId the artifact identifier.
 * @return the discovered artifacts.
 * @throws MojoExecutionException if resolution cannot be done.
 * @since 0.8
 */
public Set<Artifact> resolve(String groupId, String artifactId) throws MojoExecutionException {
	final ArtifactResolutionRequest request = new ArtifactResolutionRequest();
	request.setResolveRoot(true);
	request.setResolveTransitively(true);
	request.setLocalRepository(getSession().getLocalRepository());
	request.setRemoteRepositories(getSession().getCurrentProject().getRemoteArtifactRepositories());
	request.setOffline(getSession().isOffline());
	request.setForceUpdate(getSession().getRequest().isUpdateSnapshots());
	request.setServers(getSession().getRequest().getServers());
	request.setMirrors(getSession().getRequest().getMirrors());
	request.setProxies(getSession().getRequest().getProxies());
	request.setArtifact(createArtifact(groupId, artifactId));

	final ArtifactResolutionResult result = resolve(request);

	return result.getArtifacts();
}
 
Example #15
Source File: DependenciesRenderer.java    From maven-confluence-plugin with Apache License 2.0 5 votes vote down vote up
private String[] getArtifactRow( Artifact artifact )
{
    return new String[] {
      		artifact.getGroupId(), 
      		artifact.getArtifactId(), 
      		artifact.getVersion(),
      		artifact.getClassifier(), 
      		artifact.getType(), 
      		artifact.isOptional() ? "(optional)" : " "
    			};
}
 
Example #16
Source File: MavenEmbedder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static void normalizePath(Artifact a) {
    if (a != null) {
        File f = a.getFile();
        if (f != null) {
            a.setFile(FileUtil.normalizeFile(f));
        }
    }
}
 
Example #17
Source File: ClassesWithSameNameTest.java    From extra-enforcer-rules with Apache License 2.0 5 votes vote down vote up
@Test
public void getAllArtifactsThisClassWasFoundInShouldReturnAllArtifacts() throws Exception
{
    ClassFile classFile1 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" );
    ClassFile classFile2 = classFileHelper.createWithContent( PATH_TO_CLASS_FILE, "" );
    ClassesWithSameName classesWithSameName = new ClassesWithSameName( log, classFile1, classFile2 );
    Artifact artifact1 = classFile1.getArtifactThisClassWasFoundIn();
    Artifact artifact2 = classFile2.getArtifactThisClassWasFoundIn();

    Set<Artifact> result = classesWithSameName.getAllArtifactsThisClassWasFoundIn();

    assertEquals( 2, result.size() );
    assertTrue( result.contains( artifact1 ) );
    assertTrue( result.contains( artifact2 ) );
}
 
Example #18
Source File: AbstractJnlpMojo.java    From webstart with MIT License 5 votes vote down vote up
/**
 * @param patterns  list of patterns to test over artifacts
 * @param artifacts collection of artifacts to check
 * @return true if at least one of the pattern in the list matches no artifact, false otherwise
 */
private boolean checkDependencies( List<String> patterns, Collection<Artifact> artifacts )
{
    if ( dependencies == null )
    {
        return false;
    }

    boolean failed = false;
    for ( String pattern : patterns )
    {
        failed = ensurePatternMatchesAtLeastOneArtifact( pattern, artifacts ) || failed;
    }
    return failed;
}
 
Example #19
Source File: CompareDependenciesMojo.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a key that is similar to what {@link Dependency#getManagementKey()} generates for a dependency.
 */
private static String generateId( Artifact artifact )
{
    StringBuilder sb = new StringBuilder();
    sb.append( artifact.getGroupId() ).append( ":" ).append( artifact.getArtifactId() ).append( ":" ).append( artifact.getType() );
    if ( artifact.getClassifier() != null )
    {
        sb.append( ":" ).append( artifact.getClassifier() );
    }
    return sb.toString();
}
 
Example #20
Source File: ReportingResolutionListener.java    From maven-confluence-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void startProcessChildren( Artifact artifact )
{
    Node node = artifacts.get( artifact.getDependencyConflictId() );
    if ( parents.isEmpty() )
    {
        rootNode = node;
    }

    parents.push( node );
}
 
Example #21
Source File: ClassesWithSameName.java    From extra-enforcer-rules with Apache License 2.0 5 votes vote down vote up
/**
 * @return Return a Set rather than a List so we can use this as the key in another Map.
 *         List.of(3,2,1) doesn't equal List.of(1,2,3) but Set.of(3,2,1) equals Set.of(1,2,3)
 */
public Set<Artifact> getAllArtifactsThisClassWasFoundIn()
{
    Set<Artifact> result = new HashSet<Artifact>();

    for ( ClassFile classFile : list )
    {
        result.add( classFile.getArtifactThisClassWasFoundIn() );
    }

    return result;
}
 
Example #22
Source File: AbstractGoDependencyAwareMojo.java    From mvn-golang with Apache License 2.0 5 votes vote down vote up
@Nonnull
@MustNotContainNull
private List<Tuple<GoMod, File>> listRightPart(@Nonnull @MustNotContainNull final List<Tuple<Artifact, Tuple<GoMod, File>>> list) {
  final List<Tuple<GoMod, File>> parsed = new ArrayList<>();
  for (final Tuple<Artifact, Tuple<GoMod, File>> i : list) {
    parsed.add(i.right());
  }
  return parsed;
}
 
Example #23
Source File: MavenBatchCompiler.java    From sarl with Apache License 2.0 5 votes vote down vote up
private String findVersion(Logger logger) throws MojoExecutionException {
	final Set<Artifact> artifacts = this.helper.resolve(
			MAVEN_COMPILER_PLUGIN_GROUPID,
			MAVEN_COMPILER_PLUGIN_ARTIFACTID);
	final Artifact pluginArtifact = Iterables.find(artifacts, it -> MAVEN_COMPILER_PLUGIN_ARTIFACTID.equals(it.getArtifactId())
			&& MAVEN_COMPILER_PLUGIN_GROUPID.equals(it.getGroupId()));
	if (pluginArtifact != null) {
		return pluginArtifact.getVersion();
	}
	logger.warning(MessageFormat.format(Messages.MavenBatchCompiler_0, DEFAULT_COMPILER_VERSION));
	return DEFAULT_COMPILER_VERSION;
}
 
Example #24
Source File: VersionNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Messages("DownloadAction_label=Download")
DownloadAction(Artifact art) {
    super(DownloadAction_label());
    this.art = art;
    primary = true;
    setEnabled(localArtifact == null && info.isRemoteDownloadable());
}
 
Example #25
Source File: CreateLibraryPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static int getScopeOrder(String scope) {
    if (scope == null) {
        return 10;
    }
    if (scope.equals(Artifact.SCOPE_COMPILE)) {
        return 5;
    }
    if (scope.equals(Artifact.SCOPE_RUNTIME)) {
        return 4;
    }
    if (scope.equals(Artifact.SCOPE_TEST)) {
        return 3;
    }
    return 0;
}
 
Example #26
Source File: GenerateBomMojo.java    From sundrio with Apache License 2.0 5 votes vote down vote up
private Set<Artifact> getReactorArtifacts() {
    Set<Artifact> reactorArtifacts = new LinkedHashSet<Artifact>();
    for (MavenProject project : reactorProjects) {
        reactorArtifacts.add(project.getArtifact());
    }
    return reactorArtifacts;
}
 
Example #27
Source File: BaratineMojo.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
private void addJar(Artifact artifact)
{
  if ("io.baratine".equals(artifact.getGroupId()))
    return;

  File file = artifact.getFile();
  String name = file.getName();

  int lastSlash = name.lastIndexOf(File.separator);

  if (lastSlash > -1)
    name = name.substring(lastSlash + 1);

  this.archiver.addFile(file, "lib/" + name);
}
 
Example #28
Source File: DependencyFactory.java    From appassembler with MIT License 5 votes vote down vote up
/**
 * Used by AbstractBooterDaemonGenerator.
 * @param project {@link MavenProject}
 * @param id The id.
 * @param layout {@link ArtifactRepositoryLayout}
 * @param outputFileNameMapping The name mapping.
 * @return the dependency.
 */
public static Dependency create( MavenProject project, String id, ArtifactRepositoryLayout layout,
                                 String outputFileNameMapping )
    throws DaemonGeneratorException
{
    Artifact artifact = (Artifact) project.getArtifactMap().get( id );

    if ( artifact == null )
    {
        throw new DaemonGeneratorException( "The project has to have a dependency on '" + id + "'." );
    }

    return create( artifact, layout, outputFileNameMapping );
}
 
Example #29
Source File: ModuleGenerator.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
private Predicate<Artifact> artifactsWithCompileScope() {
    return new Predicate<Artifact>() {
        private ScopeArtifactFilter artifactFilter = new ScopeArtifactFilter(Artifact.SCOPE_COMPILE);

        @Override
        public boolean apply(@Nullable Artifact input) {
            return input != null && artifactFilter.include(input);
        }
    };
}
 
Example #30
Source File: OptionLoader.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static List<WadlOption> loadWsdlOptionsFromDependencies(MavenProject project,
                                                               Option defaultOptions, File outputDir) {
    List<WadlOption> options = new ArrayList<>();
    Set<Artifact> dependencies = project.getDependencyArtifacts();
    for (Artifact artifact : dependencies) {
        WadlOption option = generateWsdlOptionFromArtifact(artifact, outputDir);
        if (option != null) {
            if (defaultOptions != null) {
                option.merge(defaultOptions);
            }
            options.add(option);
        }
    }
    return options;
}