Example usage for org.apache.maven.project MavenProject getRemoteArtifactRepositories

List of usage examples for org.apache.maven.project MavenProject getRemoteArtifactRepositories

Introduction

In this page you can find the example usage for org.apache.maven.project MavenProject getRemoteArtifactRepositories.

Prototype

public List<ArtifactRepository> getRemoteArtifactRepositories() 

Source Link

Usage

From source file:org.jboss.tools.maven.jsf.configurators.JSFProjectConfigurator.java

License:Open Source License

private String inferJsfVersionFromDependencies(MavenProject mavenProject, String groupId, String artifactId,
        String defaultVersion) {/*w  w w . ja  v a 2s.  c  om*/
    boolean hasCandidates = false;
    String jsfVersion = null;
    List<ArtifactRepository> repos = mavenProject.getRemoteArtifactRepositories();
    for (Artifact artifact : mavenProject.getArtifacts()) {
        if (isKnownJsfBasedArtifact(artifact)) {
            hasCandidates = true;
            jsfVersion = Activator.getDefault().getDependencyVersion(artifact, repos, groupId, artifactId);
            if (jsfVersion != null) {
                //TODO should probably not break and take the highest version returned from all dependencies
                break;
            }
        }
    }
    //Fallback to default JSF version
    if (hasCandidates && jsfVersion == null) {
        return defaultVersion;
    }
    return jsfVersion;
}

From source file:org.jetbrains.idea.maven.server.Maven30ServerEmbedderImpl.java

License:Apache License

@Nonnull
public MavenExecutionResult doResolveProject(@Nonnull final File file,
        @Nonnull final List<String> activeProfiles, @Nonnull final List<String> inactiveProfiles,
        final List<ResolutionListener> listeners) throws RemoteException {
    final MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles,
            Collections.<String>emptyList());

    request.setUpdateSnapshots(myAlwaysUpdateSnapshots);

    final AtomicReference<MavenExecutionResult> ref = new AtomicReference<MavenExecutionResult>();

    executeWithMavenSession(request, new Runnable() {
        @Override//from ww  w  .  ja  v  a2 s  . c  o  m
        public void run() {
            try {
                // copied from DefaultMavenProjectBuilder.buildWithDependencies
                ProjectBuilder builder = getComponent(ProjectBuilder.class);

                CustomMaven3ModelInterpolator2 modelInterpolator = (CustomMaven3ModelInterpolator2) getComponent(
                        ModelInterpolator.class);

                String savedLocalRepository = modelInterpolator.getLocalRepository();
                modelInterpolator.setLocalRepository(request.getLocalRepositoryPath().getAbsolutePath());
                List<ProjectBuildingResult> results;

                try {
                    // Don't use build(File projectFile, ProjectBuildingRequest request) , because it don't use cache !!!!!!!! (see http://devnet.jetbrains.com/message/5500218)
                    results = builder.build(Collections.singletonList(new File(file.getPath())), false,
                            request.getProjectBuildingRequest());
                } finally {
                    modelInterpolator.setLocalRepository(savedLocalRepository);
                }

                ProjectBuildingResult buildingResult = results.get(0);

                MavenProject project = buildingResult.getProject();

                RepositorySystemSession repositorySession = getComponent(LegacySupport.class)
                        .getRepositorySession();
                if (repositorySession instanceof DefaultRepositorySystemSession) {
                    ((DefaultRepositorySystemSession) repositorySession)
                            .setTransferListener(new Maven30TransferListenerAdapter(myCurrentIndicator));

                    if (myWorkspaceMap != null) {
                        ((DefaultRepositorySystemSession) repositorySession)
                                .setWorkspaceReader(new Maven30WorkspaceReader(myWorkspaceMap));
                    }
                }

                List<Exception> exceptions = new ArrayList<Exception>();
                loadExtensions(project, exceptions);

                //Artifact projectArtifact = project.getArtifact();
                //Map managedVersions = project.getManagedVersionMap();
                //ArtifactMetadataSource metadataSource = getComponent(ArtifactMetadataSource.class);
                project.setDependencyArtifacts(
                        project.createArtifacts(getComponent(ArtifactFactory.class), null, null));
                //

                if (USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING) {
                    ArtifactResolutionRequest resolutionRequest = new ArtifactResolutionRequest();
                    resolutionRequest.setArtifactDependencies(project.getDependencyArtifacts());
                    resolutionRequest.setArtifact(project.getArtifact());
                    resolutionRequest.setManagedVersionMap(project.getManagedVersionMap());
                    resolutionRequest.setLocalRepository(myLocalRepository);
                    resolutionRequest.setRemoteRepositories(project.getRemoteArtifactRepositories());
                    resolutionRequest.setListeners(listeners);

                    resolutionRequest.setResolveRoot(false);
                    resolutionRequest.setResolveTransitively(true);

                    ArtifactResolver resolver = getComponent(ArtifactResolver.class);
                    ArtifactResolutionResult result = resolver.resolve(resolutionRequest);

                    project.setArtifacts(result.getArtifacts());
                    // end copied from DefaultMavenProjectBuilder.buildWithDependencies
                    ref.set(new MavenExecutionResult(project, exceptions));
                } else {
                    final DependencyResolutionResult dependencyResolutionResult = resolveDependencies(project,
                            repositorySession);
                    final List<Dependency> dependencies = dependencyResolutionResult.getDependencies();

                    Set<Artifact> artifacts = new LinkedHashSet<Artifact>(dependencies.size());
                    for (Dependency dependency : dependencies) {
                        final Artifact artifact = RepositoryUtils.toArtifact(dependency.getArtifact());
                        artifact.setScope(dependency.getScope());
                        artifact.setOptional(dependency.isOptional());
                        artifacts.add(artifact);
                        resolveAsModule(artifact);
                    }

                    project.setArtifacts(artifacts);
                    ref.set(new MavenExecutionResult(project, dependencyResolutionResult, exceptions));
                }
            } catch (Exception e) {
                ref.set(handleException(e));
            }
        }
    });

    return ref.get();
}

From source file:org.jetbrains.idea.maven.server.Maven32ServerEmbedderImpl.java

License:Apache License

@Nonnull
public MavenExecutionResult doResolveProject(@Nonnull final File file,
        @Nonnull final List<String> activeProfiles, @Nonnull final List<String> inactiveProfiles,
        final List<ResolutionListener> listeners) throws RemoteException {
    final MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles,
            Collections.<String>emptyList());

    request.setUpdateSnapshots(myAlwaysUpdateSnapshots);

    final AtomicReference<MavenExecutionResult> ref = new AtomicReference<MavenExecutionResult>();

    executeWithMavenSession(request, new Runnable() {
        @Override//  w ww  . j  a  v a  2 s.com
        public void run() {
            try {
                // copied from DefaultMavenProjectBuilder.buildWithDependencies
                ProjectBuilder builder = getComponent(ProjectBuilder.class);

                CustomMaven3ModelInterpolator2 modelInterpolator = (CustomMaven3ModelInterpolator2) getComponent(
                        ModelInterpolator.class);

                String savedLocalRepository = modelInterpolator.getLocalRepository();
                modelInterpolator.setLocalRepository(request.getLocalRepositoryPath().getAbsolutePath());
                List<ProjectBuildingResult> results;

                try {
                    // Don't use build(File projectFile, ProjectBuildingRequest request) , because it don't use cache !!!!!!!! (see http://devnet.jetbrains.com/message/5500218)
                    results = builder.build(Collections.singletonList(new File(file.getPath())), false,
                            request.getProjectBuildingRequest());
                } finally {
                    modelInterpolator.setLocalRepository(savedLocalRepository);
                }

                ProjectBuildingResult buildingResult = results.get(0);

                MavenProject project = buildingResult.getProject();

                RepositorySystemSession repositorySession = getComponent(LegacySupport.class)
                        .getRepositorySession();
                if (repositorySession instanceof DefaultRepositorySystemSession) {
                    ((DefaultRepositorySystemSession) repositorySession)
                            .setTransferListener(new TransferListenerAdapter(myCurrentIndicator));

                    if (myWorkspaceMap != null) {
                        ((DefaultRepositorySystemSession) repositorySession)
                                .setWorkspaceReader(new Maven32WorkspaceReader(myWorkspaceMap));
                    }
                }

                List<Exception> exceptions = new ArrayList<Exception>();
                loadExtensions(project, exceptions);

                //Artifact projectArtifact = project.getArtifact();
                //Map managedVersions = project.getManagedVersionMap();
                //ArtifactMetadataSource metadataSource = getComponent(ArtifactMetadataSource.class);
                project.setDependencyArtifacts(
                        project.createArtifacts(getComponent(ArtifactFactory.class), null, null));
                //

                if (USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING) {
                    ArtifactResolutionRequest resolutionRequest = new ArtifactResolutionRequest();
                    resolutionRequest.setArtifactDependencies(project.getDependencyArtifacts());
                    resolutionRequest.setArtifact(project.getArtifact());
                    resolutionRequest.setManagedVersionMap(project.getManagedVersionMap());
                    resolutionRequest.setLocalRepository(myLocalRepository);
                    resolutionRequest.setRemoteRepositories(project.getRemoteArtifactRepositories());
                    resolutionRequest.setListeners(listeners);

                    resolutionRequest.setResolveRoot(false);
                    resolutionRequest.setResolveTransitively(true);

                    ArtifactResolver resolver = getComponent(ArtifactResolver.class);
                    ArtifactResolutionResult result = resolver.resolve(resolutionRequest);

                    project.setArtifacts(result.getArtifacts());
                    // end copied from DefaultMavenProjectBuilder.buildWithDependencies
                    ref.set(new MavenExecutionResult(project, exceptions));
                } else {
                    final DependencyResolutionResult dependencyResolutionResult = resolveDependencies(project,
                            repositorySession);
                    final List<Dependency> dependencies = dependencyResolutionResult.getDependencies();

                    Set<Artifact> artifacts = new LinkedHashSet<Artifact>(dependencies.size());
                    for (Dependency dependency : dependencies) {
                        final Artifact artifact = RepositoryUtils.toArtifact(dependency.getArtifact());
                        artifact.setScope(dependency.getScope());
                        artifact.setOptional(dependency.isOptional());
                        artifacts.add(artifact);
                        resolveAsModule(artifact);
                    }

                    project.setArtifacts(artifacts);
                    ref.set(new MavenExecutionResult(project, dependencyResolutionResult, exceptions));
                }
            } catch (Exception e) {
                ref.set(handleException(e));
            }
        }
    });

    return ref.get();
}

From source file:org.jetbrains.maven.embedder.MavenEmbedder.java

License:Apache License

@Nonnull
public MavenExecutionResult resolveProject(@Nonnull final File file, @Nonnull final List<String> activeProfiles,
        @Nonnull final List<String> inactiveProfiles, List<ResolutionListener> listeners) {
    MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles,
            Collections.<String>emptyList());
    ProjectBuilderConfiguration config = request.getProjectBuilderConfiguration();

    request.getGlobalProfileManager().loadSettingsProfiles(mySettings);

    ProfileManager globalProfileManager = request.getGlobalProfileManager();
    globalProfileManager.loadSettingsProfiles(request.getSettings());

    List<Exception> exceptions = new ArrayList<Exception>();
    MavenProject project = null;
    try {//  w  w  w .j  a v  a  2s .  c o m
        // copied from DefaultMavenProjectBuilder.buildWithDependencies
        MavenProjectBuilder builder = getComponent(MavenProjectBuilder.class);
        project = builder.build(new File(file.getPath()), config);
        builder.calculateConcreteState(project, config, false);

        // copied from DefaultLifecycleExecutor.execute
        findExtensions(project);
        // end copied from DefaultLifecycleExecutor.execute

        Artifact projectArtifact = project.getArtifact();
        Map managedVersions = project.getManagedVersionMap();
        ArtifactMetadataSource metadataSource = getComponent(ArtifactMetadataSource.class);
        project.setDependencyArtifacts(
                project.createArtifacts(getComponent(ArtifactFactory.class), null, null));

        ArtifactResolver resolver = getComponent(ArtifactResolver.class);
        ArtifactResolutionResult result = resolver.resolveTransitively(project.getDependencyArtifacts(),
                projectArtifact, managedVersions, myLocalRepository, project.getRemoteArtifactRepositories(),
                metadataSource, null, listeners);
        project.setArtifacts(result.getArtifacts());
        // end copied from DefaultMavenProjectBuilder.buildWithDependencies
    } catch (Exception e) {
        return handleException(e);
    }

    return new MavenExecutionResult(project, exceptions);
}

From source file:org.jfrog.jade.plugins.idea.AbstractIdeaMojo.java

License:Apache License

protected void doDependencyResolution() throws InvalidDependencyVersionException, ProjectBuildingException,
        InvalidVersionSpecificationException {
    // If the execution root project is not a parent (meaning it is last one in reactor list)
    // Then the mojo will inherit manually its configuration
    if (reactorProjects != null) {
        int nbProjects = reactorProjects.size();
        // Get the last project it contains the specific ideaj configuration
        if (nbProjects > 1) {
            MavenProject lastproject = reactorProjects.get(nbProjects - 1);
            if (lastproject.isExecutionRoot()) {
                //noinspection unchecked
                List<Plugin> plugins = lastproject.getBuildPlugins();
                fillPluginSettings(plugins, "jade-idea-plugin", this, null);
            }//from w  w  w  .ja va2 s  . c  om
        }
    }

    MavenProject project = getExecutedProject();
    ArtifactRepository localRepo = getLocalRepository();
    Map managedVersions = createManagedVersionMap();

    try {
        ArtifactResolutionResult result = getArtifactResolver().resolveTransitively(getProjectArtifacts(),
                project.getArtifact(), managedVersions, localRepo, project.getRemoteArtifactRepositories(),
                artifactMetadataSource);

        project.setArtifacts(result.getArtifacts());
    } catch (ArtifactNotFoundException e) {
        getLog().debug(e.getMessage(), e);

        StringBuffer msg = new StringBuffer();
        msg.append("An error occurred during dependency resolution.\n\n");
        msg.append("    Failed to retrieve ").append(e.getDownloadUrl()).append("\n");
        msg.append("from the following repositories:");
        for (Iterator repositories = e.getRemoteRepositories().iterator(); repositories.hasNext();) {
            ArtifactRepository repository = (ArtifactRepository) repositories.next();
            msg.append("\n    ").append(repository.getId()).append("(").append(repository.getUrl()).append(")");
        }
        msg.append("\nCaused by: ").append(e.getMessage());

        getLog().warn(msg);
    } catch (ArtifactResolutionException e) {
        getLog().debug(e.getMessage(), e);

        StringBuffer msg = new StringBuffer();
        msg.append("An error occurred during dependency resolution of the following artifact:\n\n");
        msg.append("    ").append(e.getGroupId()).append(":").append(e.getArtifactId()).append(e.getVersion())
                .append("\n\n");
        msg.append("Caused by: ").append(e.getMessage());

        getLog().warn(msg);
    }
}

From source file:org.lilyproject.tools.mavenplugin.lilyruntimedepresolver.LilyRuntimeProjectClasspath.java

License:Apache License

public ModuleArtifacts getModuleArtifactsFromLilyRuntimeConfig(Set<Artifact> dependencies,
        String[] wiringPathPatterns, MavenProjectBuilder mavenProjectBuilder, List remoteRepos)
        throws MojoExecutionException {

    ModuleArtifacts result = new ModuleArtifacts();
    result.artifacts = new HashSet<Artifact>();
    result.remoteRepositories = new ArrayList();

    boolean foundAtLeastOneWiring = false;

    try {//from w ww . j a  v a2  s . c om
        // Search in the jars of all the direct dependencies of the project for the wiring file
        // (not sure if this won't be too slow? it's just to avoid the user having to specify the artifact)
        log.info("Searching " + dependencies.size() + " dependencies for " + wiringPathPatterns.length
                + " path patterns.");

        for (Artifact artifact : dependencies) {
            if ("jar".equals(artifact.getType())) {
                resolver.resolve(artifact, remoteRepos, localRepository);

                AntPathMatcher matcher = new AntPathMatcher();
                ZipFile zipFile;
                zipFile = new ZipFile(artifact.getFile());
                try {
                    Enumeration<? extends ZipEntry> entryEnum = zipFile.entries();
                    while (entryEnum.hasMoreElements()) {
                        ZipEntry zipEntry = entryEnum.nextElement();
                        for (String pattern : wiringPathPatterns) {
                            if (matcher.match(pattern, zipEntry.getName())) {
                                foundAtLeastOneWiring = true;
                                log.info("Reading " + zipEntry.getName() + " from " + artifact.getFile());
                                Set<Artifact> moduleArtifacts = getModuleArtifactsFromLilyRuntimeConfig(
                                        zipFile.getInputStream(zipEntry), zipEntry.getName(), remoteRepos);

                                MavenProject wiringSourceProject = mavenProjectBuilder
                                        .buildFromRepository(artifact, remoteRepos, localRepository);
                                List repositories = wiringSourceProject.getRemoteArtifactRepositories();

                                result.artifacts.addAll(moduleArtifacts);
                                result.remoteRepositories.addAll(repositories);
                            }
                        }
                    }
                } finally {
                    zipFile.close();
                }
            }
        }

    } catch (Exception e) {
        throw new MojoExecutionException("Error searching/reading wiring.xml file from dependency jars.", e);
    }

    if (!foundAtLeastOneWiring) {
        throw new MojoExecutionException("No wiring xml's were found.");
    }

    return result;
}

From source file:org.maven.ide.eclipse.checkstyle.AbstractMavenPluginProjectConfigurator.java

License:Apache License

/**
 * Create a classloader based on the plugin artifact and dependencies, if any
 * /*from   ww  w. ja va 2 s . c  om*/
 * @param mavenProject the maven project that declares the plugin
 * @param maven maven maven to resolve maven artifacts and dependencies
 * @param plugin the maven plugin
 */
protected ClassLoader getPluginClassLoader(Plugin mavenPlugin, MavenProject mavenProject,
        IProgressMonitor monitor) throws CoreException {
    // Let's default to the current context classloader
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    // list of jars that will make up classpath
    List<URL> jars = new LinkedList<URL>();

    // add the plugin artifact
    Artifact pluginArtifact = resolvePluginArtifact(mavenPlugin, mavenProject, monitor);

    if (!pluginArtifact.isResolved()) {
        console.logMessage("Failed to resolve maven plugin " + mavenPlugin.getKey());
        // May not be a blocker : in many case, the classloader is used to retrieve
        // additional resources, not the plugin artifact itself
    } else {
        try {
            jars.add(pluginArtifact.getFile().toURI().toURL());
        } catch (MalformedURLException e) {
            console.logError("Could not create URL for artifact: " + pluginArtifact.getFile());
        }
    }

    List<Dependency> dependencies = mavenPlugin.getDependencies();
    if (dependencies != null && dependencies.size() > 0) {
        for (Dependency dependency : dependencies) {
            // create artifact based on dependency
            Artifact artifact = maven.resolve(dependency.getGroupId(), dependency.getArtifactId(),
                    dependency.getVersion(), dependency.getScope(), dependency.getType(),
                    mavenProject.getRemoteArtifactRepositories(), monitor);

            // add artifact and its dependencies to list of jars
            if (artifact.isResolved()) {
                try {
                    // Use classpath ordering to mimic dependency overrides
                    jars.add(0, artifact.getFile().toURI().toURL());
                } catch (MalformedURLException e) {
                    console.logError("Could not create URL for artifact: " + artifact.getFile());
                }
            }
        }
    }

    classLoader = new URLClassLoader(jars.toArray(new URL[0]), classLoader);

    return classLoader;
}

From source file:org.maven.ide.eclipse.checkstyle.AbstractMavenPluginProjectConfigurator.java

License:Apache License

private Artifact resolvePluginArtifact(Plugin mavenPlugin, MavenProject mavenProject, IProgressMonitor monitor)
        throws CoreException {
    String groupId = mavenPlugin.getGroupId();
    String artifactId = mavenPlugin.getArtifactId();
    String version = mavenPlugin.getVersion();
    if (version == null) {
        version = Artifact.LATEST_VERSION;
    }//ww  w. j  ava2s .co m
    return maven.resolve(groupId, artifactId, version, "compile", "maven-plugin",
            mavenProject.getRemoteArtifactRepositories(), monitor);

}

From source file:org.mobicents.maven.plugin.eclipse.ClasspathWriter.java

License:Open Source License

/**
 * Writes the .classpath file for eclipse.
 * //from   w w w . j  a  v a 2 s  .  c om
 * @param projects
 *            the list of projects from which the .classpath will get its
 *            dependencies.
 * @param repositoryVariableName
 *            the name of the maven repository variable.
 * @param artifactFactory
 *            the factory for constructing artifacts.
 * @param artifactResolver
 *            the artifact resolver.
 * @param localRepository
 *            the local repository instance.
 * @param artifactMetadataSource
 * @param classpathArtifactTypes
 *            the artifacts types that are allowed in the classpath file.
 * @param remoteRepositories
 *            the list of remote repository instances.
 * @param resolveTransitiveDependencies
 *            whether or not dependencies shall be transitively resolved.
 * @param merge
 *            anything extra (not auto-generated), that should be "merged"
 *            into the generated .classpath
 * @param classpathExcludes
 * @param includeTestsDirectory
 * @param includeResourcesDirectory
 * @throws Exception
 */
public void write(final List projects, final String repositoryVariableName,
        final ArtifactFactory artifactFactory, final ArtifactResolver artifactResolver,
        final ArtifactRepository localRepository, final ArtifactMetadataSource artifactMetadataSource,
        final Set classpathArtifactTypes, final List remoteRepositories,
        final boolean resolveTransitiveDependencies, final String merge, Set classpathExcludes,
        boolean includeResourcesDirectory) throws Exception {
    final String rootDirectory = PathNormalizer.normalizePath(this.project.getBasedir().toString());
    final File classpathFile = new File(rootDirectory, ".classpath");
    final FileWriter fileWriter = new FileWriter(classpathFile);
    final XMLWriter writer = new PrettyPrintXMLWriter(fileWriter, "UTF-8", null);
    writer.startElement("classpath");

    final Set projectArtifactIds = new LinkedHashSet();
    for (final Iterator iterator = projects.iterator(); iterator.hasNext();) {
        final MavenProject project = (MavenProject) iterator.next();
        final Artifact projectArtifact = artifactFactory.createArtifact(project.getGroupId(),
                project.getArtifactId(), project.getVersion(), null, project.getPackaging());
        projectArtifactIds.add(projectArtifact.getId());
    }

    // - collect the source roots for the root project (if they are any)
    Set<String> sourceRoots = collectSourceRoots(this.project, rootDirectory, writer,
            includeResourcesDirectory);

    final Set allArtifacts = new LinkedHashSet(this.project.createArtifacts(artifactFactory, null, null));

    for (final Iterator iterator = projects.iterator(); iterator.hasNext();) {
        final MavenProject project = (MavenProject) iterator.next();
        sourceRoots.addAll(collectSourceRoots(project, rootDirectory, writer, includeResourcesDirectory));
        final Set artifacts = project.createArtifacts(artifactFactory, null, null);
        // - get the direct dependencies
        for (final Iterator artifactIterator = artifacts.iterator(); artifactIterator.hasNext();) {
            final Artifact artifact = (Artifact) artifactIterator.next();
            // - don't attempt to resolve the artifact if its part of the
            // project (we
            // infer this if it has the same id has one of the projects or
            // is in
            // the same groupId).
            if (!projectArtifactIds.contains(artifact.getId())
                    && !project.getGroupId().equals(artifact.getGroupId())) {
                artifactResolver.resolve(artifact, project.getRemoteArtifactRepositories(), localRepository);
                allArtifacts.add(artifact);
            } else {
                allArtifacts.add(artifact);
            }
        }
    }

    // we have all source roots now, sort and write
    for (String sourceRoot : sourceRoots) {
        logger.info("Adding src path " + sourceRoot);
        this.writeClasspathEntry(writer, "src", sourceRoot);
    }

    // - remove the project artifacts
    for (final Iterator iterator = projects.iterator(); iterator.hasNext();) {
        final MavenProject project = (MavenProject) iterator.next();
        final Artifact projectArtifact = project.getArtifact();
        if (projectArtifact != null) {
            for (final Iterator artifactIterator = allArtifacts.iterator(); artifactIterator.hasNext();) {
                final Artifact artifact = (Artifact) artifactIterator.next();
                final String projectId = projectArtifact.getArtifactId();
                final String projectGroupId = projectArtifact.getGroupId();
                final String artifactId = artifact.getArtifactId();
                final String groupId = artifact.getGroupId();
                if (artifactId.equals(projectId) && groupId.equals(projectGroupId)) {
                    artifactIterator.remove();
                }
            }
        }
    }

    // - now we resolve transitively, if we have the flag on
    if (resolveTransitiveDependencies) {
        final Artifact rootProjectArtifact = artifactFactory.createArtifact(this.project.getGroupId(),
                this.project.getArtifactId(), this.project.getVersion(), null, this.project.getPackaging());

        final OrArtifactFilter filter = new OrArtifactFilter();
        filter.add(new ScopeArtifactFilter(Artifact.SCOPE_COMPILE));
        filter.add(new ScopeArtifactFilter(Artifact.SCOPE_PROVIDED));
        filter.add(new ScopeArtifactFilter(Artifact.SCOPE_TEST));
        final ArtifactResolutionResult result = artifactResolver.resolveTransitively(allArtifacts,
                rootProjectArtifact, localRepository, remoteRepositories, artifactMetadataSource, filter);

        allArtifacts.clear();
        allArtifacts.addAll(result.getArtifacts());
    }

    // remove excluded ones
    for (Iterator i = allArtifacts.iterator(); i.hasNext();) {
        Artifact artifact = (Artifact) i.next();

        if (classpathExcludes != null) {
            if (classpathExcludes.contains(artifact.getGroupId())) {
                logger.info("Excluding " + artifact + " from .classpath, groupId is excluded");
                i.remove();
            } else if (classpathExcludes.contains(artifact.getGroupId() + ":" + artifact.getArtifactId())) {
                logger.info("Excluding " + artifact + " from .classpath, groupId:artifactId is excluded");
                i.remove();
            } else if (classpathExcludes.contains(
                    artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion())) {
                logger.info(
                        "Excluding " + artifact + " from .classpath, groupId:artifactId:version is excluded");
                i.remove();
            }
        }
    }

    final List allArtifactPaths = new ArrayList(allArtifacts);
    for (final ListIterator iterator = allArtifactPaths.listIterator(); iterator.hasNext();) {
        final Artifact artifact = (Artifact) iterator.next();
        if (classpathArtifactTypes.contains(artifact.getType())) {
            File artifactFile = artifact.getFile();
            if (artifactFile == null) {
                artifactResolver.resolve(artifact, project.getRemoteArtifactRepositories(), localRepository);
                artifactFile = artifact.getFile();
            }
            if (artifactFile != null) {
                final String path = StringUtils.replace(PathNormalizer.normalizePath(artifactFile.toString()),
                        PathNormalizer.normalizePath(localRepository.getBasedir()), repositoryVariableName);
                iterator.set(path);
            } else {
                iterator.remove();
            }
        } else {
            iterator.remove();
        }
    }

    // - sort the paths
    Collections.sort(allArtifactPaths);

    for (final Iterator iterator = allArtifactPaths.iterator(); iterator.hasNext();) {
        String path = (String) iterator.next();
        if (path.startsWith(repositoryVariableName)) {
            this.writeClasspathEntry(writer, "var", path);
        } else {
            if (path.startsWith(rootDirectory)) {
                path = StringUtils.replace(path, rootDirectory + '/', "");
            }
            this.writeClasspathEntry(writer, "lib", path);
        }
    }

    this.writeClasspathEntry(writer, "con", "org.eclipse.jdt.launching.JRE_CONTAINER");

    String outputPath = StringUtils.replace(
            PathNormalizer.normalizePath(this.project.getBuild().getOutputDirectory()), rootDirectory, "");
    if (outputPath.startsWith("/")) {
        outputPath = outputPath.substring(1, outputPath.length());
    }
    this.writeClasspathEntry(writer, "output", outputPath);

    if (StringUtils.isNotBlank(merge)) {
        writer.writeMarkup(merge);
    }
    writer.endElement();

    logger.info("Classpath file written --> '" + classpathFile + "'");
    IOUtil.close(fileWriter);
}

From source file:org.nbheaven.sqe.core.maven.utils.MavenUtilities.java

License:Open Source License

/**
 * try to collect the plugin's dependency artifacts
 * as defined in <dependencies> section within <plugin>. Will only
 * return files currently in local repository
 *
 * @return list of files in local repository
 */// www  .  j  av  a  2s  .c om
public static List<File> findDependencyArtifacts(Project project, String pluginGroupId, String pluginArtifactId,
        boolean includePluginArtifact) {
    List<File> cpFiles = new ArrayList<File>();
    final NbMavenProject p = project.getLookup().lookup(NbMavenProject.class);
    final MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
    MavenProject mp = p.getMavenProject();
    if (includePluginArtifact) {
        Set<Artifact> arts = new HashSet<Artifact>();
        arts.addAll(mp.getReportArtifacts());
        arts.addAll(mp.getPluginArtifacts());
        for (Artifact a : arts) {
            if (pluginArtifactId.equals(a.getArtifactId()) && pluginGroupId.equals(a.getGroupId())) {
                File f = a.getFile();
                if (f == null) {
                    //somehow the report plugins are not resolved, we need to workaround that..
                    f = FileUtil.normalizeFile(new File(new File(online.getLocalRepository().getBasedir()),
                            online.getLocalRepository().pathOf(a)));
                }
                if (!f.exists()) {
                    try {
                        online.resolve(a, mp.getRemoteArtifactRepositories(), online.getLocalRepository());
                    } catch (ArtifactResolutionException ex) {
                        Exceptions.printStackTrace(ex);
                    } catch (ArtifactNotFoundException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                }
                if (f.exists()) {
                    cpFiles.add(f);
                    try {
                        ProjectBuildingRequest req = new DefaultProjectBuildingRequest();
                        req.setRemoteRepositories(mp.getRemoteArtifactRepositories());
                        req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
                        req.setSystemProperties(online.getSystemProperties());
                        ProjectBuildingResult res = online.buildProject(a, req);
                        MavenProject mp2 = res.getProject();
                        if (mp2 != null) {
                            // XXX this is not really right, but mp.dependencyArtifacts = null for some reason
                            for (Dependency dep : mp2.getDependencies()) {
                                Artifact a2 = online.createArtifact(dep.getGroupId(), dep.getArtifactId(),
                                        dep.getVersion(), "jar");
                                online.resolve(a2, mp.getRemoteArtifactRepositories(),
                                        online.getLocalRepository());
                                File df = a2.getFile();
                                if (df.exists()) {
                                    cpFiles.add(df);
                                }
                            }
                        }
                    } catch (Exception x) {
                        Exceptions.printStackTrace(x);
                    }
                }
            }
        }

    }
    List<Plugin> plugins = mp.getBuildPlugins();
    for (Plugin plug : plugins) {
        if (pluginArtifactId.equals(plug.getArtifactId()) && pluginGroupId.equals(plug.getGroupId())) {
            try {
                List<Dependency> deps = plug.getDependencies();
                ArtifactFactory artifactFactory = online.getPlexus().lookup(ArtifactFactory.class);
                for (Dependency d : deps) {
                    final Artifact projectArtifact = artifactFactory.createArtifactWithClassifier(
                            d.getGroupId(), d.getArtifactId(), d.getVersion(), d.getType(), d.getClassifier());
                    String localPath = online.getLocalRepository().pathOf(projectArtifact);
                    File f = FileUtil
                            .normalizeFile(new File(online.getLocalRepository().getBasedir(), localPath));
                    if (!f.exists()) {
                        try {
                            online.resolve(projectArtifact, mp.getRemoteArtifactRepositories(),
                                    online.getLocalRepository());
                        } catch (ArtifactResolutionException ex) {
                            ex.printStackTrace();
                            //                                        Exceptions.printStackTrace(ex);
                        } catch (ArtifactNotFoundException ex) {
                            ex.printStackTrace();
                            //                            Exceptions.printStackTrace(ex);
                        }
                    }
                    if (f.exists()) {
                        cpFiles.add(f);
                    }
                }
            } catch (ComponentLookupException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    return cpFiles;
}