Java Code Examples for org.apache.maven.model.Dependency#getScope()

The following examples show how to use org.apache.maven.model.Dependency#getScope() . 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: AddDependencyPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * @return 0 -> no conflicts, 1 -> conflict in version, 2 -> conflict in scope
 */
private static int findConflict (List<Dependency> deps, String groupId, String artifactId, String version, String scope) {
    if (deps == null) {
        return 0;
    }
    for (Dependency dep : deps) {
        if (artifactId != null && artifactId.equals(dep.getArtifactId()) &&
                groupId != null && groupId.equals(dep.getGroupId())) {
            if (version != null && !version.equals(dep.getVersion())) {
                return 1;
            }
            if (scope != null) {
                if (!scope.equals(dep.getScope())) {
                    return 2;
                }
            } else if (dep.getScope() != null) {
                return 2;
            }

        }
    }

    return 0;
}
 
Example 2
Source File: ArtifactUtils.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void mergeDependencyWithDefaults(Dependency dep, Dependency def) {
	if (dep.getScope() == null && def.getScope() != null) {
		dep.setScope(def.getScope());
		dep.setSystemPath(def.getSystemPath());
	}

	if (dep.getVersion() == null && def.getVersion() != null) {
		dep.setVersion(def.getVersion());
	}

	if (dep.getClassifier() == null && def.getClassifier() != null) {
		dep.setClassifier(def.getClassifier());
	}

	if (dep.getType() == null && def.getType() != null) {
		dep.setType(def.getType());
	}

	@SuppressWarnings("rawtypes")
	List exclusions = dep.getExclusions();
	if (exclusions == null || exclusions.isEmpty()) {
		dep.setExclusions(def.getExclusions());
	}
}
 
Example 3
Source File: RawXJC2Mojo.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void injectDependencyDefaults(Dependency[] dependencies) {
	if (dependencies != null) {
		final Map<String, Dependency> dependencyMap = new TreeMap<String, Dependency>();
		for (final Dependency dependency : dependencies) {
			if (dependency.getScope() == null) {
				dependency.setScope(Artifact.SCOPE_RUNTIME);
			}
			dependencyMap.put(dependency.getManagementKey(), dependency);
		}

		final DependencyManagement dependencyManagement = getProject().getDependencyManagement();

		if (dependencyManagement != null) {
			merge(dependencyMap, dependencyManagement.getDependencies());
		}
		merge(dependencyMap, getProjectDependencies());
	}
}
 
Example 4
Source File: MavenNbModuleImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    FileObject fo = project.getProjectDirectory().getFileObject("pom.xml"); //NOI18N
    final DependencyAdder monitor = this;
    ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {
        @Override
        public void performOperation(POMModel model) {
            synchronized (monitor) {
                for (Dependency dep : toAdd) {
                    org.netbeans.modules.maven.model.pom.Dependency mdlDep =
                            ModelUtils.checkModelDependency(model, dep.getGroupId(), dep.getArtifactId(), true);
                    mdlDep.setVersion(dep.getVersion());
                    if (dep.getScope() != null) {
                        mdlDep.setScope(dep.getScope());
                    }
                }
                toAdd.clear();
            }
        }
    };
    Utilities.performPOMModelOperations(fo, Collections.singletonList(operation));
    project.getLookup().lookup(NbMavenProject.class).synchronousDependencyDownload();
}
 
Example 5
Source File: SearchClassDependencyInRepo.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Collection<NBVersionInfo> filter(NbMavenProject mavProj, List<NBVersionInfo> nbvis, boolean test) {


        Map<String, NBVersionInfo> items = new HashMap<String, NBVersionInfo>();
        //check dependency already added
        List<Dependency> dependencies = new ArrayList<Dependency>();
        MavenProject prj = mavProj.getMavenProject();
        if (test) {
            dependencies.addAll(prj.getTestDependencies());
        } else {
            dependencies.addAll(prj.getDependencies());
        }

        for (NBVersionInfo info : nbvis) {
            String key = info.getGroupId() + ":" + info.getArtifactId();

            boolean b = items.containsKey(key);
            if (!b) {
                items.put(key, info);
            }
            for (Dependency dependency : dependencies) {
                //check group id and ArtifactId and Scope even
                if (dependency.getGroupId() != null && dependency.getGroupId().equals(info.getGroupId())) {
                    if (dependency.getArtifactId() != null && dependency.getArtifactId().equals(info.getArtifactId())) {
                        if (!test && dependency.getScope() != null && ("compile".equals(dependency.getScope()))) {//NOI18N

                            return Collections.emptyList();
                        }
                    }
                }
            }

        }
        List<NBVersionInfo> filterd = new ArrayList<NBVersionInfo>(items.values());

        return filterd;

    }
 
Example 6
Source File: DependencyUpdatesReport.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a set of dependencies where the dependencies which are defined in the dependency management section have
 * been filtered out.
 *
 * @param dependencies The set of dependencies.
 * @param dependencyManagement The set of dependencies from the dependency management section.
 * @return A new set of dependencies which are from the set of dependencies but not from the set of dependency
 *         management dependencies.
 * @since 1.0-beta-1
 */
private static Set<Dependency> removeDependencyManagment( Set<Dependency> dependencies, Set<Dependency> dependencyManagement )
{
    Set<Dependency> result = new TreeSet<>( new DependencyComparator() );
    for ( Dependency c : dependencies )
    {
        boolean matched = false;
        Iterator<Dependency> j = dependencyManagement.iterator();
        while ( !matched && j.hasNext() )
        {
            Dependency t = j.next();
            if ( StringUtils.equals( t.getGroupId(), c.getGroupId() )
                && StringUtils.equals( t.getArtifactId(), c.getArtifactId() )
                && ( t.getScope() == null || StringUtils.equals( t.getScope(), c.getScope() ) )
                && ( t.getClassifier() == null || StringUtils.equals( t.getClassifier(), c.getClassifier() ) )
                && ( c.getVersion() == null || t.getVersion() == null
                    || StringUtils.equals( t.getVersion(), c.getVersion() ) ) )
            {
                matched = true;
                break;
            }
        }
        if ( !matched )
        {
            result.add( c );
        }
    }
    return result;
}
 
Example 7
Source File: DisplayDependencyUpdatesMojo.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a set of dependencies where the dependencies which are defined in the dependency management section have
 * been filtered out.
 *
 * @param dependencies The set of dependencies.
 * @param dependencyManagement The set of dependencies from the dependency management section.
 * @return A new set of dependencies which are from the set of dependencies but not from the set of dependency
 *         management dependencies.
 * @since 1.0-beta-1
 */
private static Set<Dependency> removeDependencyManagment( Set<Dependency> dependencies, Set<Dependency> dependencyManagement )
{
    Set<Dependency> result = new TreeSet<>( new DependencyComparator() );
    for ( Iterator<Dependency> i = dependencies.iterator(); i.hasNext(); )
    {
        Dependency c = i.next();
        boolean matched = false;
        Iterator<Dependency> j = dependencyManagement.iterator();
        while ( !matched && j.hasNext() )
        {
            Dependency t =j.next();
            if ( StringUtils.equals( t.getGroupId(), c.getGroupId() )
                && StringUtils.equals( t.getArtifactId(), c.getArtifactId() )
                && ( t.getScope() == null || StringUtils.equals( t.getScope(), c.getScope() ) )
                && ( t.getClassifier() == null || StringUtils.equals( t.getClassifier(), c.getClassifier() ) )
                && ( c.getVersion() == null || t.getVersion() == null
                    || StringUtils.equals( t.getVersion(), c.getVersion() ) ) )
            {
                matched = true;
                break;
            }
        }
        if ( !matched )
        {
            result.add( c );
        }
    }
    return result;
}
 
Example 8
Source File: CapsuleMojo.java    From capsule-maven-plugin with MIT License 5 votes vote down vote up
private String artifactString() throws IOException {
	final StringBuilder artifactList = new StringBuilder();

	if (includeApp) artifactList.append(coords(project.getArtifact())).append(" ");

	// go through artifacts
	final Set<Dependency> dependencies = includeTransitiveDep ? includedDependencies() : includedDirectDependencies();

	for (final Dependency dependency : dependencies) {

		final String scope = dependency.getScope() == null || dependency.getScope().isEmpty() ? "compile" : dependency.getScope();

		boolean optionalMatch = true;
		if (dependency.isOptional()) optionalMatch = includeOptionalDep;

		// ignore capsule jar
		if (dependency.getGroupId().equalsIgnoreCase(CAPSULE_GROUP) && dependency.getArtifactId().equalsIgnoreCase(DEFAULT_CAPSULE_NAME))
			continue;

		// check against requested scopes
		if (
				(includeCompileDep && scope.equals("compile") && optionalMatch) ||
						(includeRuntimeDep && scope.equals("runtime") && optionalMatch) ||
						(includeProvidedDep && scope.equals("provided") && optionalMatch) ||
						(includeSystemDep && scope.equals("system") && optionalMatch) ||
						(includeTestDep && scope.equals("test") && optionalMatch)
				)
			artifactList.append(coordsWithExclusions(dependency)).append(" ");
	}

	return artifactList.toString();
}
 
Example 9
Source File: CapsuleMojo.java    From capsule-maven-plugin with MIT License 5 votes vote down vote up
private String dependencyString() throws IOException {
	final StringBuilder dependenciesList = new StringBuilder();

	// add app to be resolved
	if (resolveApp)
		dependenciesList.append(coords(this.project.getArtifact())).append(" ");

	// go through dependencies
	final Set<Dependency> dependencies = resolveTransitiveDep ? resolvedDependencies() : resolvedDirectDependencies();

	for (final Dependency dependency : dependencies) {

		final String scope = dependency.getScope() == null || dependency.getScope().isEmpty() ? "compile" : dependency.getScope();

		boolean optionalMatch = true;
		if (dependency.isOptional()) optionalMatch = resolveOptionalDep;

		// ignore capsule jar
		if (dependency.getGroupId().equalsIgnoreCase(CAPSULE_GROUP) && dependency.getArtifactId().equalsIgnoreCase(DEFAULT_CAPSULE_NAME))
			continue;

		// check against requested scopes
		if (
				(resolveCompileDep && scope.equals("compile") && optionalMatch) ||
						(resolveRuntimeDep && scope.equals("runtime") && optionalMatch) ||
						(resolveProvidedDep && scope.equals("provided") && optionalMatch) ||
						(resolveSystemDep && scope.equals("system") && optionalMatch) ||
						(resolveTestDep && scope.equals("test") && optionalMatch)
				)
			dependenciesList.append(coordsWithExclusions(dependency)).append(" ");
	}

	return dependenciesList.toString();
}
 
Example 10
Source File: Mojo.java    From capsule-maven-plugin with MIT License 5 votes vote down vote up
private Dependency toDependency(final Artifact artifact) {
	if (artifact == null) return null;
	final Dependency dependency = new Dependency();
	dependency.setGroupId(artifact.getGroupId());
	dependency.setArtifactId(artifact.getArtifactId());
	dependency.setVersion(artifact.getVersion());
	dependency.setScope(artifact.getScope());
	dependency.setClassifier(artifact.getClassifier());
	dependency.setOptional(artifact.isOptional());
	if (dependency.getScope() == null || dependency.getScope().isEmpty()) dependency.setScope("compile");
	return dependency;
}
 
Example 11
Source File: SimpleScopedArtifactRef.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
public SimpleScopedArtifactRef( final Dependency dependency )
{
    super( dependency.getGroupId(), dependency.getArtifactId(),
           isEmpty( dependency.getVersion() ) ? "*" : dependency.getVersion(),
           dependency.getType(), dependency.getClassifier());
    this.scope = dependency.getScope();
}
 
Example 12
Source File: RESTCollector.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
/**
 * Translate a given set of pvr:dependencies into ArtifactRefs.
 * @param session the ManipulationSession
 * @param deps Set of ArtifactRef to store the results in.
 * @param dependencies dependencies to examine
 */
private static void recordDependencies( ManipulationSession session, Set<ArtifactRef> deps,
                                        Map<ArtifactRef, Dependency> dependencies )
{
    final VersioningState vs = session.getState( VersioningState.class );
    final RESTState state = session.getState( RESTState.class );

    for ( ArtifactRef pvr : dependencies.keySet() )
    {
        Dependency d = dependencies.get( pvr );

        SimpleScopedArtifactRef sa = new SimpleScopedArtifactRef(
                        new SimpleProjectVersionRef( pvr.asProjectRef(), handlePotentialSnapshotVersion( vs, pvr.getVersionString() ) ),
                        new SimpleTypeAndClassifier( d.getType(), d.getClassifier() ),
                        d.getScope() );

        boolean validate = true;

        // Don't bother adding an artifact with a property that couldn't be resolved.
        if (sa.getVersionString().contains( "$" ))
        {
            validate = false;
        }
        // If we are not (re)aligning suffixed dependencies then ignore them.
        // Null check to avoid problems with some tests where state is not instantiated.
        if ( state != null && !state.isRestSuffixAlign() &&
                        ( sa.getVersionString().contains( vs.getRebuildSuffix() ) ||
                                        vs.getSuffixAlternatives().stream().anyMatch( s -> sa.getVersionString().contains( s ) ) ) )
        {
            validate = false;
        }
        if (validate)
        {
            deps.add( sa );
        }
    }
}
 
Example 13
Source File: StoreGraphDependencyMojo.java    From maven-dependency-mapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void registerDependency(Node projectNode, final Dependency dependency) {
    Node artifactNode;
    String scope = dependency.getScope();

    if (scope == null) {
        scope = "compile"; // default scope
    }
    try {
        artifactNode = makeNode(dependency);
        projectNode.createRelationshipTo(artifactNode, MavenRelationships.getByName(scope));
        getLog().info("Registered dependency to " + ArtifactHelper.getId(dependency) + ", scope: " + scope);
    } catch (Throwable e) {
        getLog().error(e.getMessage(), e);
    }
}
 
Example 14
Source File: GenerateBomMojo.java    From sundrio with Apache License 2.0 4 votes vote down vote up
private Artifact toArtifact(Dependency dependency) {
    return new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getScope(), dependency.getType(), dependency.getClassifier(),
            getArtifactHandler());
}
 
Example 15
Source File: LocationAwareMavenXpp3Writer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void writeDependency(Dependency dependency, String tagName, XmlSerializer serializer)
        throws java.io.IOException {
    serializer.startTag(NAMESPACE, tagName);
    flush(serializer);
    StringBuffer b = b(serializer);
    int start = b.length();
    if (dependency.getGroupId() != null) {
        writeValue(serializer, "groupId", dependency.getGroupId(), dependency);
    }
    if (dependency.getArtifactId() != null) {
        writeValue(serializer, "artifactId", dependency.getArtifactId(), dependency);
    }
    if (dependency.getVersion() != null) {
        writeValue(serializer, "version", dependency.getVersion(), dependency);
    }
    if ((dependency.getType() != null) && !dependency.getType().equals("jar")) {
        writeValue(serializer, "type", dependency.getType(), dependency);
    }
    if (dependency.getClassifier() != null) {
        writeValue(serializer, "classifier", dependency.getClassifier(), dependency);
    }
    if (dependency.getScope() != null) {
        writeValue(serializer, "scope", dependency.getScope(), dependency);
    }
    if (dependency.getSystemPath() != null) {
        writeValue(serializer, "systemPath", dependency.getSystemPath(), dependency);
    }
    if ((dependency.getExclusions() != null) && (dependency.getExclusions().size() > 0)) {
        serializer.startTag(NAMESPACE, "exclusions");
        for (Iterator<Exclusion> iter = dependency.getExclusions().iterator(); iter.hasNext();) {
            Exclusion o = iter.next();
            writeExclusion(o, "exclusion", serializer);
        }
        serializer.endTag(NAMESPACE, "exclusions");
    }
    if (dependency.getOptional() != null) {
        writeValue(serializer, "optional", dependency.getOptional(), dependency);
    }
    serializer.endTag(NAMESPACE, tagName).flush();
    logLocation(dependency, "", start, b.length());
}
 
Example 16
Source File: BomGeneratorMojo.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
private void overwriteDependencyManagement(Document pom, List<Dependency> dependencies) throws Exception {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("/project/dependencyManagement/dependencies");

    NodeList nodes = (NodeList) expr.evaluate(pom, XPathConstants.NODESET);
    if (nodes.getLength() == 0) {
        throw new IllegalStateException("No dependencies found in the dependencyManagement section of the current pom");
    }

    Node dependenciesSection = nodes.item(0);
    // cleanup the dependency management section
    while (dependenciesSection.hasChildNodes()) {
        Node child = dependenciesSection.getFirstChild();
        dependenciesSection.removeChild(child);
    }

    for (Dependency dep : dependencies) {

        if ("target".equals(dep.getArtifactId())) {
            // skip invalid artifact that somehow gets included
            continue;
        }

        Element dependencyEl = pom.createElement("dependency");

        Element groupIdEl = pom.createElement("groupId");
        groupIdEl.setTextContent(dep.getGroupId());
        dependencyEl.appendChild(groupIdEl);

        Element artifactIdEl = pom.createElement("artifactId");
        artifactIdEl.setTextContent(dep.getArtifactId());
        dependencyEl.appendChild(artifactIdEl);

        Element versionEl = pom.createElement("version");
        versionEl.setTextContent(dep.getVersion());
        dependencyEl.appendChild(versionEl);

        if (!"jar".equals(dep.getType())) {
            Element typeEl = pom.createElement("type");
            typeEl.setTextContent(dep.getType());
            dependencyEl.appendChild(typeEl);
        }

        if (dep.getClassifier() != null) {
            Element classifierEl = pom.createElement("classifier");
            classifierEl.setTextContent(dep.getClassifier());
            dependencyEl.appendChild(classifierEl);
        }

        if (dep.getScope() != null && !"compile".equals(dep.getScope())) {
            Element scopeEl = pom.createElement("scope");
            scopeEl.setTextContent(dep.getScope());
            dependencyEl.appendChild(scopeEl);
        }

        if (dep.getExclusions() != null && !dep.getExclusions().isEmpty()) {

            Element exclsEl = pom.createElement("exclusions");

            for (Exclusion e : dep.getExclusions()) {
                Element exclEl = pom.createElement("exclusion");

                Element groupIdExEl = pom.createElement("groupId");
                groupIdExEl.setTextContent(e.getGroupId());
                exclEl.appendChild(groupIdExEl);

                Element artifactIdExEl = pom.createElement("artifactId");
                artifactIdExEl.setTextContent(e.getArtifactId());
                exclEl.appendChild(artifactIdExEl);

                exclsEl.appendChild(exclEl);
            }

            dependencyEl.appendChild(exclsEl);
        }


        dependenciesSection.appendChild(dependencyEl);
    }


}
 
Example 17
Source File: Project.java    From pom-manipulation-ext with Apache License 2.0 4 votes vote down vote up
private void resolveDeps( MavenSessionHandler session, List<Dependency> deps, boolean includeManagedDependencies,
                          Map<ArtifactRef, Dependency> resolvedDependencies )
                throws ManipulationException
{
    ListIterator<Dependency> iterator = deps.listIterator( deps.size() );

    // Iterate in reverse order so later deps take precedence
    while ( iterator.hasPrevious() )
    {
        Dependency d = iterator.previous();

        if ( session.getExcludedScopes().contains( d.getScope() ) )
        {
            logger.debug( "Ignoring dependency {} as scope matched {}", d, session.getExcludedScopes());
            continue;
        }

        String g = PropertyResolver.resolveInheritedProperties( session, this, "${project.groupId}".equals( d.getGroupId() ) ?
                        getGroupId() :
                        d.getGroupId() );
        String a = PropertyResolver.resolveInheritedProperties( session, this, "${project.artifactId}".equals( d.getArtifactId() ) ?
                        getArtifactId() :
                        d.getArtifactId() );
        String v = PropertyResolver.resolveInheritedProperties( session, this, d.getVersion() );

        if ( includeManagedDependencies && isEmpty( v ) )
        {
            v = "*";
        }
        if ( isNotEmpty( g ) && isNotEmpty( a ) && isNotEmpty( v ) )
        {
            SimpleScopedArtifactRef sar = new SimpleScopedArtifactRef( g, a, v, d.getType(), d.getClassifier(), d.getScope() );

            // If the GAVTC already exists within the map it means we have a duplicate entry. While Maven
            // technically allows this it does warn that this leads to unstable models. In PME case this breaks
            // the indexing as we don't have duplicate entries. Given they are exact matches, remove older duplicate.
            if ( resolvedDependencies.containsKey( sar ) )
            {
                logger.error( "Found duplicate entry within dependency list. Key of {} and dependency {}", sar, d );
                iterator.remove();
            }
            else
            {
                Dependency old = resolvedDependencies.put( sar, d );

                if ( old != null )
                {
                    logger.error( "Internal project dependency resolution failure ; replaced {} in store by {}:{}:{}.",
                                  old, g, a, v );
                    throw new ManipulationException(
                                    "Internal project dependency resolution failure ; replaced {} by {}", old, d );
                }
            }
        }
    }
}