Example usage for org.apache.maven.artifact ArtifactUtils key

List of usage examples for org.apache.maven.artifact ArtifactUtils key

Introduction

In this page you can find the example usage for org.apache.maven.artifact ArtifactUtils key.

Prototype

public static String key(String groupId, String artifactId, String version) 

Source Link

Usage

From source file:io.takari.maven.workspace.GenerationsWorkspaceReader.java

License:Apache License

public File findArtifact(Artifact artifact) {

    File file = null;/*from  w w w .  j  a  v a2 s  . co  m*/

    String projectKey = ArtifactUtils.key(artifact.getGroupId(), artifact.getArtifactId(),
            artifact.getVersion());

    //
    // Try to resolve the project from the buildspace, which are the projects that have been requested to build
    //
    MavenProject project = buildProjects.get(projectKey);

    if (project != null) {
        file = find(project, artifact);
    }

    //
    // If workspace resolution is enabled and the project cannot be found in the buildspace then attempt to
    // find the project in the workspace.
    //
    if (file == null && workspaceResolutionEnabled) {
        project = workspaceProjects.get(projectKey);
        if (project != null) {
            file = findWorkspaceArtifact(project, artifact);
        }
    }

    return file;
}

From source file:io.takari.maven.workspace.GenerationsWorkspaceReader.java

License:Apache License

private Map<String, MavenProject> getProjectMap(Collection<MavenProject> projects) {
    Map<String, MavenProject> index = new LinkedHashMap<String, MavenProject>();
    Map<String, List<File>> collisions = new LinkedHashMap<String, List<File>>();

    for (MavenProject project : projects) {
        String projectId = ArtifactUtils.key(project.getGroupId(), project.getArtifactId(),
                project.getVersion());//from  w  ww.j  a  va 2  s .co  m

        MavenProject collision = index.get(projectId);

        if (collision == null) {
            index.put(projectId, project);
        } else {
            List<File> pomFiles = collisions.get(projectId);

            if (pomFiles == null) {
                pomFiles = new ArrayList<File>(Arrays.asList(collision.getFile(), project.getFile()));
                collisions.put(projectId, pomFiles);
            } else {
                pomFiles.add(project.getFile());
            }
        }
    }

    /*
     * 
     * We'll assume there is no collisions
     * 
     * if (!collisions.isEmpty()) { throw new DuplicateProjectException("Two or more projects in the reactor" + " have the same identifier, please make sure that <groupId>:<artifactId>:<version>" +
     * " is unique for each project: " + collisions, collisions); }
     */

    return index;
}

From source file:org.arakhne.maven.AbstractArakhneMojo.java

License:Open Source License

/**
 * Replies the maven artifact which is described by the given <code>pom.xml</code>.
 * /*w w  w .j a va 2s  .  c  o  m*/
 * @param pomFile
 *            is the <code>pom.xml</code> file.
 * @return the artifact or <code>null</code>.
 */
public synchronized final ExtendedArtifact readPomFile(File pomFile) {
    String groupId = null;
    String artifactId = null;
    String name = null;
    String version = null;
    String url = null;
    Organization organization = null;
    Scm scm = null;
    List<Developer> developers;
    List<Contributor> contributors;
    List<License> licenses;
    Parent parent = null;

    getLog().debug("Read pom file: " + pomFile.toString()); //$NON-NLS-1$

    if (!pomFile.canRead())
        return null;

    MavenXpp3Reader pomReader = new MavenXpp3Reader();
    try {
        FileReader fr = new FileReader(pomFile);
        try {
            Model model = pomReader.read(fr);
            groupId = model.getGroupId();
            artifactId = model.getArtifactId();
            name = model.getName();
            version = model.getVersion();
            url = model.getUrl();
            organization = model.getOrganization();
            scm = model.getScm();

            developers = model.getDevelopers();
            contributors = model.getContributors();
            licenses = model.getLicenses();

            parent = model.getParent();
        } catch (IOException e) {
            return null;
        } catch (XmlPullParserException e) {
            return null;
        } finally {
            fr.close();
        }
    } catch (IOException e) {
        return null;
    }

    if (developers == null) {
        developers = new ArrayList<Developer>();
    } else {
        List<Developer> list = new ArrayList<Developer>();
        list.addAll(developers);
        developers = list;
    }
    if (contributors == null) {
        contributors = new ArrayList<Contributor>();
    } else {
        List<Contributor> list = new ArrayList<Contributor>();
        list.addAll(contributors);
        contributors = list;
    }
    if (licenses == null) {
        licenses = new ArrayList<License>();
    } else {
        List<License> list = new ArrayList<License>();
        list.addAll(licenses);
        licenses = list;
    }

    if (parent != null) {
        String relPath = parent.getRelativePath();
        File parentPomDirectory = new File(pomFile.getParentFile(), relPath);
        try {
            parentPomDirectory = parentPomDirectory.getCanonicalFile();
            if (!parentPomDirectory.isDirectory()) {
                parentPomDirectory = parentPomDirectory.getParentFile();
            }
            ExtendedArtifact parentArtifact = this.localArtifactDescriptions.get(parentPomDirectory);
            if (parentArtifact == null) {
                parentArtifact = readPom(parentPomDirectory);
                if (parentArtifact != null) {
                    this.localArtifactDescriptions.put(parentPomDirectory, parentArtifact);
                    getLog().debug("Add local module description for " //$NON-NLS-1$
                            + parentArtifact.toString());
                } else {
                    String key = ArtifactUtils.key(parent.getGroupId(), parent.getArtifactId(),
                            parent.getVersion());
                    Artifact artifact = createArtifact(parent.getGroupId(), parent.getArtifactId(),
                            parent.getVersion());
                    ArtifactRepository repo = getMavenSession().getLocalRepository();
                    String artifactPath = repo.pathOf(artifact);
                    artifactPath = artifactPath.replaceFirst("\\.jar$", ".pom"); //$NON-NLS-1$ //$NON-NLS-2$
                    File artifactFile = new File(repo.getBasedir(), artifactPath);
                    getLog().debug("Getting pom file in local repository for " //$NON-NLS-1$
                            + key + ": " + artifactFile.getAbsolutePath()); //$NON-NLS-1$
                    BuildContext buildContext = getBuildContext();
                    buildContext.removeMessages(pomFile);
                    if (artifactFile.canRead()) {
                        parentArtifact = readPomFile(artifactFile);
                        if (parentArtifact != null) {
                            this.remoteArtifactDescriptions.put(key, parentArtifact);
                            getLog().debug("Add remote module description for " //$NON-NLS-1$
                                    + parentArtifact.toString());
                        } else {
                            buildContext.addMessage(pomFile, 1, 1, "Unable to retreive the pom file of " + key, //$NON-NLS-1$
                                    BuildContext.SEVERITY_WARNING, null);
                        }
                    } else {
                        buildContext.addMessage(pomFile, 1, 1,
                                "Cannot read the file for '" + key + "': " + artifactFile.getAbsolutePath(), //$NON-NLS-1$ //$NON-NLS-2$
                                BuildContext.SEVERITY_WARNING, null);
                    }
                }
            }
            if (parentArtifact != null) {
                developers.addAll(parentArtifact.getDevelopers());
                contributors.addAll(parentArtifact.getContributors());
            }
        } catch (IOException e) {
            getLog().warn(e);
        }

        // Be sure that the optional fields version and groupId are correctly set.
        if (version == null || version.isEmpty()) {
            version = parent.getVersion();
        }

        if (groupId == null || groupId.isEmpty()) {
            groupId = parent.getGroupId();
        }
    }

    String scmRevision = null;

    try {
        SVNClientManager svnManager = getSVNClientManager();
        SVNInfo svnInfo = svnManager.getWCClient().doInfo(pomFile.getParentFile(), SVNRevision.UNDEFINED);
        if (svnInfo != null) {
            SVNRevision revision = svnInfo.getRevision();
            if (revision != null) {
                scmRevision = Long.toString(revision.getNumber());
            }
        }
    } catch (SVNException _) {
        //
    }

    Artifact a = createArtifact(groupId, artifactId, version);
    return new ExtendedArtifact(a, name, url, organization, scmRevision, scm, developers, contributors,
            licenses);
}

From source file:org.arakhne.maven.plugins.licenseinstaller.InstallLicenseMojo.java

License:Open Source License

/**
 * {@inheritDoc}/*from  ww w .  j  a  va  2  s . c o  m*/
 */
@Override
public synchronized void executeMojo() throws MojoExecutionException {
    if ("pom".equalsIgnoreCase(this.mavenProject.getPackaging())) { //$NON-NLS-1$
        String key = ArtifactUtils.key(this.mavenProject.getGroupId(), this.mavenProject.getArtifactId(),
                this.mavenProject.getVersion());
        getLog().info("Ignoring project " + //$NON-NLS-1$
                key + " because it is a source-less project."); //$NON-NLS-1$
        return;
    }

    File classesDirectory = new File(getOutputDirectory(), CLASSES_DIR);
    File metainfDirectory = new File(classesDirectory, METAINF_DIR);
    File licenseDirectory = new File(metainfDirectory, LICENSE_DIR);

    licenseDirectory.mkdirs();

    Set<License> coreInstalled = new HashSet<License>();
    License lic;
    URL resource;
    String filename;
    File licFile;

    Map<String, License> includedLicenses = new HashMap<String, License>();
    Pattern re1 = Pattern.compile("^([^:]+):(.+):(.+)$"); //$NON-NLS-1$
    Pattern re2 = Pattern.compile("^([^:]+):(.+)$"); //$NON-NLS-1$
    if (this.thirdPartyLicenses != null) {
        for (String tpl : this.thirdPartyLicenses) {
            Matcher matcher = re1.matcher(tpl);
            if (matcher.matches()) {
                String l = matcher.group(1);
                String g = matcher.group(2);
                String a = matcher.group(3);
                lic = License.parse(l, null);
                if (lic != null) {
                    String depName = "mvndep_" + g + "_" + a; //$NON-NLS-1$ //$NON-NLS-2$
                    includedLicenses.put(depName, lic);
                }
            } else {
                matcher = re2.matcher(tpl);
                if (matcher.matches()) {
                    String l = matcher.group(1);
                    String f = matcher.group(2);
                    lic = License.parse(l, null);
                    if (lic != null) {
                        StringBuilder sb = new StringBuilder();
                        sb.append(this.name);
                        sb.append("_"); //$NON-NLS-1$
                        String b = f.replaceAll("[/\\:]", "."); //$NON-NLS-1$ //$NON-NLS-2$
                        b = b.replaceAll("^\\.", ""); //$NON-NLS-1$ //$NON-NLS-2$
                        sb.append(b);
                        includedLicenses.put(sb.toString(), lic);
                    }
                }
            }
        }
    }

    try {

        // ----------------------------------------------------
        // SOFTWARE LICENCES
        // ----------------------------------------------------

        for (String license : this.licenses) {
            lic = License.parse(license, License.GPLv3);
            if (!coreInstalled.contains(lic)) {
                resource = lic.getFullTextResource();
                if (resource != null) {

                    filename = LICENSE_FILENAME_PATTERN.replaceAll("%s", this.name); //$NON-NLS-1$
                    filename = filename.replaceAll("%l", lic.name()); //$NON-NLS-1$

                    getLog().info("Installing license: " + //$NON-NLS-1$
                            lic.getLicenseName() + ", into " + //$NON-NLS-1$
                            filename);

                    licFile = new File(licenseDirectory, filename);
                    fileCopy(resource, licFile);

                    coreInstalled.add(lic);
                } else {
                    throw new MojoExecutionException(
                            "Unable to find the full text of the license: " + lic.getLicenseName()); //$NON-NLS-1$
                }
            }
        }

        // ----------------------------------------------------
        // THIRD-PARTY LICENCES
        // ----------------------------------------------------

        for (Entry<String, License> licenseMap : includedLicenses.entrySet()) {
            lic = licenseMap.getValue();
            resource = lic.getFullTextResource();
            if (resource != null) {
                filename = LICENSE_FILENAME_PATTERN.replaceAll("%s", licenseMap.getKey()); //$NON-NLS-1$ 
                filename = filename.replaceAll("%l", lic.name()); //$NON-NLS-1$

                getLog().info("Installing included source code license: " + //$NON-NLS-1$
                        lic.getLicenseName() + ", into " + //$NON-NLS-1$
                        filename);

                licFile = new File(licenseDirectory, filename);
                fileCopy(resource, licFile);
            } else {
                throw new MojoExecutionException(
                        "Unable to find the full text of the license: " + lic.getLicenseName()); //$NON-NLS-1$
            }
        }

        // ----------------------------------------------------
        // NOTICES
        // ----------------------------------------------------

        filename = NOTICE_FILENAME_PATTERN.replaceAll("%s", this.name); //$NON-NLS-1$ 

        getLog().info("Installing license notice: " + //$NON-NLS-1$
                filename);

        StringBuilder addParts = new StringBuilder();
        for (Entry<String, License> licenseMap : includedLicenses.entrySet()) {
            lic = licenseMap.getValue();
            if (lic != null) {
                String s = getLString(InstallLicenseMojo.class, "NOTICE_SENTENCE", //$NON-NLS-1$
                        lic.getLicenseName(), licenseMap.getKey());
                addParts.append(s);
            }
        }

        StringBuilder fullLicenseText = new StringBuilder();
        int n = 0;
        for (License l : coreInstalled) {
            if (n > 0) {
                if (n == coreInstalled.size() - 1) {
                    fullLicenseText.append(getLString(InstallLicenseMojo.class, "AND")); //$NON-NLS-1$
                } else {
                    fullLicenseText.append(getLString(InstallLicenseMojo.class, "COMMA")); //$NON-NLS-1$
                }
            }
            fullLicenseText.append(l.getLicenseName());
            ++n;
        }

        String noticeText = getLString(InstallLicenseMojo.class, "NOTICE_TEXT", //$NON-NLS-1$
                this.name, this.copyrightDates, this.copyrighters, fullLicenseText.toString(),
                addParts.toString());

        File noticeFile = new File(metainfDirectory, filename);
        FileWriter fileWriter = new FileWriter(noticeFile);
        try {
            fileWriter.write(noticeText);
        } finally {
            fileWriter.close();
        }

        // ----------------------------------------------------
        // AUTHORS
        // ----------------------------------------------------

        filename = AUTHOR_FILENAME_PATTERN.replaceAll("%s", this.name); //$NON-NLS-1$ 

        getLog().info("Installing authors: " + //$NON-NLS-1$
                filename);

        StringBuilder authorsText = new StringBuilder();
        if (this.projectURL != null) {
            authorsText.append(
                    getLString(InstallLicenseMojo.class, "AUTHOR_INTRO", this.projectURL.toExternalForm())); //$NON-NLS-1$
        } else {
            authorsText.append(getLString(InstallLicenseMojo.class, "AUTHOR_INTRO", "")); //$NON-NLS-1$ //$NON-NLS-2$
        }
        authorsText.append("\n\n"); //$NON-NLS-1$
        authorsText.append(getLString(InstallLicenseMojo.class, "DEVELOPER_TITLE", this.name)); //$NON-NLS-1$
        authorsText.append("\n\n"); //$NON-NLS-1$
        for (Developer developer : this.mavenProject.getDevelopers()) {
            authorsText.append(getLString(InstallLicenseMojo.class, "DEVELOPER", //$NON-NLS-1$
                    developer.getName(), developer.getEmail()));
            authorsText.append("\n"); //$NON-NLS-1$
        }

        authorsText.append("\n\n\n"); //$NON-NLS-1$
        authorsText.append(getLString(InstallLicenseMojo.class, "CONTRIBUTOR_TITLE", this.name)); //$NON-NLS-1$
        authorsText.append("\n\n"); //$NON-NLS-1$
        for (Contributor contributor : this.mavenProject.getContributors()) {
            authorsText.append(getLString(InstallLicenseMojo.class, "DEVELOPER", //$NON-NLS-1$
                    contributor.getName(), contributor.getEmail()));
            authorsText.append("\n"); //$NON-NLS-1$
        }

        File authorFile = new File(metainfDirectory, filename);
        fileWriter = new FileWriter(authorFile);
        try {
            fileWriter.write(authorsText.toString());
        } finally {
            fileWriter.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.commonjava.emb.project.graph.DepGraphNode.java

License:Apache License

static String key(final Artifact a) {
    return ArtifactUtils.key(a.getGroupId(), a.getArtifactId(), a.getBaseVersion());
}

From source file:org.commonjava.emb.project.graph.DepGraphRootNode.java

License:Open Source License

public DepGraphRootNode(final DependencyNode node, final MavenProject project) {
    super(node, ArtifactUtils.key(project.getGroupId(), project.getArtifactId(), project.getVersion()), true);
    this.project = project;
}

From source file:org.commonjava.emb.project.ProjectLoader.java

License:Apache License

public Set<String> retrieveReactorProjectIds(final File rootPom) throws ProjectToolsException {
    if (LOGGER.isInfoEnabled()) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Finding projectIds contained within reactor for: " + rootPom);
        }// w  ww .  ja  va2  s.  com
    }

    final Map<File, Model> models = new LinkedHashMap<File, Model>();
    readReactorModels(rootPom, rootPom, models);

    final Set<String> projectIds = new HashSet<String>(models.size());
    for (final Model model : models.values()) {
        String groupId = model.getGroupId();
        final String artifactId = model.getArtifactId();
        String version = model.getVersion();
        String packaging = model.getPackaging();

        if (packaging == null) {
            packaging = "jar";
        }

        if (groupId == null || version == null) {
            final Parent parent = model.getParent();
            if (parent != null) {
                if (groupId == null) {
                    groupId = parent.getGroupId();
                }
                if (version == null) {
                    version = parent.getVersion();
                }
            } else {
                LOGGER.warn(String.format("Invalid POM: %s", model.getId()));
                continue;
            }
        }

        final String key = ArtifactUtils.key(groupId, artifactId, version);
        if (LOGGER.isInfoEnabled()) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Found: " + key);
            }
        }

        projectIds.add(key);
    }

    return projectIds;
}

From source file:org.eclipse.tycho.core.osgitools.targetplatform.LocalDependencyResolver.java

License:Open Source License

private void addDependencies(MavenSession session, MavenProject project, DefaultDependencyArtifacts platform) {
    TargetPlatformConfiguration configuration = (TargetPlatformConfiguration) project
            .getContextValue(TychoConstants.CTX_TARGET_PLATFORM_CONFIGURATION);

    if (configuration != null && TargetPlatformConfiguration.POM_DEPENDENCIES_CONSIDER
            .equals(configuration.getPomDependencies())) {
        Map<String, MavenProject> projectIds = new HashMap<String, MavenProject>(
                session.getProjects().size() * 2);
        // make a list of reactor projects
        for (MavenProject p : session.getProjects()) {
            String key = ArtifactUtils.key(p.getGroupId(), p.getArtifactId(), p.getVersion());
            projectIds.put(key, p);//  w  w w  .  ja v  a2s. co m
        }
        // handle dependencies that are in reactor
        for (Dependency dependency : project.getDependencies()) {
            if (Artifact.SCOPE_COMPILE.equals(dependency.getScope())) {
                String key = ArtifactUtils.key(dependency.getGroupId(), dependency.getArtifactId(),
                        dependency.getVersion());
                if (projectIds.containsKey(key)) {
                    MavenProject dependent = projectIds.get(key);
                    ArtifactKey artifactKey = getArtifactKey(session, dependent);
                    if (artifactKey != null) {
                        platform.removeAll(artifactKey.getType(), artifactKey.getId());
                        ReactorProject projectProxy = DefaultReactorProject.adapt(dependent);
                        platform.addReactorArtifact(artifactKey, projectProxy, null, null);
                        if (getLogger().isDebugEnabled()) {
                            getLogger().debug("Add Maven project " + artifactKey);
                        }
                    }
                }
            }
        }
        // handle rest of dependencies
        ArrayList<String> scopes = new ArrayList<String>();
        scopes.add(Artifact.SCOPE_COMPILE);
        Collection<Artifact> artifacts;
        try {
            artifacts = projectDependenciesResolver.resolve(project, scopes, session);
        } catch (MultipleArtifactsNotFoundException e) {
            Collection<Artifact> missing = new HashSet<Artifact>(e.getMissingArtifacts());

            for (Iterator<Artifact> it = missing.iterator(); it.hasNext();) {
                Artifact a = it.next();
                String key = ArtifactUtils.key(a.getGroupId(), a.getArtifactId(), a.getBaseVersion());
                if (projectIds.containsKey(key)) {
                    it.remove();
                }
            }

            if (!missing.isEmpty()) {
                throw new RuntimeException("Could not resolve project dependencies", e);
            }

            artifacts = e.getResolvedArtifacts();
            artifacts.removeAll(e.getMissingArtifacts());
        } catch (AbstractArtifactResolutionException e) {
            throw new RuntimeException("Could not resolve project dependencies", e);
        }
        for (Artifact artifact : artifacts) {
            String key = ArtifactUtils.key(artifact.getGroupId(), artifact.getArtifactId(),
                    artifact.getBaseVersion());
            if (!projectIds.containsKey(key)) {
                File plugin = artifact.getFile();
                ArtifactKey artifactKey = getArtifactKey(session, plugin);

                if (artifactKey != null) {
                    platform.addArtifactFile(artifactKey, plugin, null);
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("Add Maven artifact " + artifactKey);
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.tycho.core.osgitools.targetplatform.LocalTargetPlatformResolver.java

License:Open Source License

private void addDependencies(MavenSession session, MavenProject project, DefaultTargetPlatform platform) {
    TargetPlatformConfiguration configuration = (TargetPlatformConfiguration) project
            .getContextValue(TychoConstants.CTX_TARGET_PLATFORM_CONFIGURATION);

    if (configuration != null && TargetPlatformConfiguration.POM_DEPENDENCIES_CONSIDER
            .equals(configuration.getPomDependencies())) {
        Map<String, MavenProject> projectIds = new HashMap<String, MavenProject>(
                session.getProjects().size() * 2);
        // make a list of reactor projects
        for (MavenProject p : session.getProjects()) {
            String key = ArtifactUtils.key(p.getGroupId(), p.getArtifactId(), p.getVersion());
            projectIds.put(key, p);/*from  www.j av a 2  s  .co m*/
        }
        // handle dependencies that are in reactor
        for (Dependency dependency : project.getDependencies()) {
            if (Artifact.SCOPE_COMPILE.equals(dependency.getScope())) {
                String key = ArtifactUtils.key(dependency.getGroupId(), dependency.getArtifactId(),
                        dependency.getVersion());
                if (projectIds.containsKey(key)) {
                    MavenProject dependent = projectIds.get(key);
                    ArtifactKey artifactKey = getArtifactKey(session, dependent);
                    if (artifactKey != null) {
                        platform.removeAll(artifactKey.getType(), artifactKey.getId());
                        ReactorProject projectProxy = DefaultReactorProject.adapt(dependent);
                        platform.addReactorArtifact(artifactKey, projectProxy, null, null);
                        if (getLogger().isDebugEnabled()) {
                            getLogger().debug("Add Maven project " + artifactKey);
                        }
                    }
                }
            }
        }
        // handle rest of dependencies
        ArrayList<String> scopes = new ArrayList<String>();
        scopes.add(Artifact.SCOPE_COMPILE);
        Collection<Artifact> artifacts;
        try {
            artifacts = projectDependenciesResolver.resolve(project, scopes, session);
        } catch (MultipleArtifactsNotFoundException e) {
            Collection<Artifact> missing = new HashSet<Artifact>(e.getMissingArtifacts());

            for (Iterator<Artifact> it = missing.iterator(); it.hasNext();) {
                Artifact a = it.next();
                String key = ArtifactUtils.key(a.getGroupId(), a.getArtifactId(), a.getBaseVersion());
                if (projectIds.containsKey(key)) {
                    it.remove();
                }
            }

            if (!missing.isEmpty()) {
                throw new RuntimeException("Could not resolve project dependencies", e);
            }

            artifacts = e.getResolvedArtifacts();
            artifacts.removeAll(e.getMissingArtifacts());
        } catch (AbstractArtifactResolutionException e) {
            throw new RuntimeException("Could not resolve project dependencies", e);
        }
        for (Artifact artifact : artifacts) {
            String key = ArtifactUtils.key(artifact.getGroupId(), artifact.getArtifactId(),
                    artifact.getBaseVersion());
            if (!projectIds.containsKey(key)) {
                File plugin = artifact.getFile();
                ArtifactKey artifactKey = getArtifactKey(session, plugin);

                if (artifactKey != null) {
                    platform.addArtifactFile(artifactKey, plugin, null);
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("Add Maven artifact " + artifactKey);
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.tycho.p2.facade.P2TargetPlatformResolver.java

License:Open Source License

protected TargetPlatform doResolvePlatform(final MavenSession session, final MavenProject project,
        List<ReactorProject> reactorProjects, List<Dependency> dependencies, P2Resolver resolver) {
    TargetPlatformConfiguration configuration = (TargetPlatformConfiguration) project
            .getContextValue(TychoConstants.CTX_TARGET_PLATFORM_CONFIGURATION);

    resolver.setRepositoryCache(repositoryCache);

    resolver.setOffline(session.isOffline());

    resolver.setLogger(new P2Logger() {
        public void debug(String message) {
            if (message != null && message.length() > 0) {
                getLogger().info(message); // TODO
            }//  w w  w . j a va 2 s  . c  om
        }

        public void info(String message) {
            if (message != null && message.length() > 0) {
                getLogger().info(message);
            }
        }

        public boolean isDebugEnabled() {
            return getLogger().isDebugEnabled() && DebugUtils.isDebugEnabled(session, project);
        }
    });

    Map<File, ReactorProject> projects = new HashMap<File, ReactorProject>();

    resolver.setLocalRepositoryLocation(new File(session.getLocalRepository().getBasedir()));

    resolver.setEnvironments(getEnvironments(configuration));

    for (ReactorProject otherProject : reactorProjects) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("P2resolver.addMavenProject " + otherProject.getId());
        }
        projects.put(otherProject.getBasedir(), otherProject);
        resolver.addReactorArtifact(new ReactorArtifactFacade(otherProject, null));

        Map<String, Set<Object>> dependencyMetadata = otherProject.getDependencyMetadata();
        if (dependencyMetadata != null) {
            for (String classifier : dependencyMetadata.keySet()) {
                resolver.addReactorArtifact(new ReactorArtifactFacade(otherProject, classifier));
            }
        }
    }

    if (dependencies != null) {
        for (Dependency dependency : dependencies) {
            resolver.addDependency(dependency.getType(), dependency.getArtifactId(), dependency.getVersion());
        }
    }

    if (TargetPlatformConfiguration.POM_DEPENDENCIES_CONSIDER.equals(configuration.getPomDependencies())) {
        Set<String> projectIds = new HashSet<String>();
        for (ReactorProject p : reactorProjects) {
            String key = ArtifactUtils.key(p.getGroupId(), p.getArtifactId(), p.getVersion());
            projectIds.add(key);
        }

        ArrayList<String> scopes = new ArrayList<String>();
        scopes.add(Artifact.SCOPE_COMPILE);
        Collection<Artifact> artifacts;
        try {
            artifacts = projectDependenciesResolver.resolve(project, scopes, session);
        } catch (MultipleArtifactsNotFoundException e) {
            Collection<Artifact> missing = new HashSet<Artifact>(e.getMissingArtifacts());

            for (Iterator<Artifact> it = missing.iterator(); it.hasNext();) {
                Artifact a = it.next();
                String key = ArtifactUtils.key(a.getGroupId(), a.getArtifactId(), a.getBaseVersion());
                if (projectIds.contains(key)) {
                    it.remove();
                }
            }

            if (!missing.isEmpty()) {
                throw new RuntimeException("Could not resolve project dependencies", e);
            }

            artifacts = e.getResolvedArtifacts();
            artifacts.removeAll(e.getMissingArtifacts());
        } catch (AbstractArtifactResolutionException e) {
            throw new RuntimeException("Could not resolve project dependencies", e);
        }
        List<Artifact> externalArtifacts = new ArrayList<Artifact>(artifacts.size());
        for (Artifact artifact : artifacts) {
            String key = ArtifactUtils.key(artifact.getGroupId(), artifact.getArtifactId(),
                    artifact.getBaseVersion());
            if (projectIds.contains(key)) {
                // resolved to an older snapshot from the repo, we only want the current project in the reactor
                continue;
            }
            externalArtifacts.add(artifact);
        }
        addToP2ViewOfLocalRepository(session, externalArtifacts, project);
        for (Artifact artifact : externalArtifacts) {
            /*
             * TODO This call generates p2 metadata for the POM dependencies. If the artifact
             * has an attached p2metadata.xml, we should reuse that metadata.
             */
            /*
             * TODO The generated metadata is "depencency only" metadata. (Just by coincidence
             * this is currently full metadata.) Since this POM depencency metadata may be
             * copied into an eclipse-repository or p2-enabled RCP installation, it shall be
             * documented that the generated metadata must be full metadata.
             */
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("P2resolver.addMavenArtifact " + artifact.toString());
            }
            resolver.addMavenArtifact(new ArtifactFacade(artifact));
        }
    }

    for (ArtifactRepository repository : project.getRemoteArtifactRepositories()) {
        try {
            URI uri = new URL(repository.getUrl()).toURI();

            if (repository.getLayout() instanceof P2ArtifactRepositoryLayout) {
                if (session.isOffline()) {
                    getLogger().debug("Offline mode, using local cache only for repository "
                            + repository.getId() + " (" + repository.getUrl() + ")");
                }

                try {
                    Authentication auth = repository.getAuthentication();
                    if (auth != null) {
                        resolver.setCredentials(uri, auth.getUsername(), auth.getPassword());
                    }

                    resolver.addP2Repository(uri);

                    getLogger().debug(
                            "Added p2 repository " + repository.getId() + " (" + repository.getUrl() + ")");
                } catch (Exception e) {
                    String msg = "Failed to access p2 repository " + repository.getId() + " ("
                            + repository.getUrl() + "), will try to use local cache. Reason: " + e.getMessage();
                    if (getLogger().isDebugEnabled()) {
                        getLogger().warn(msg, e);
                    } else {
                        getLogger().warn(msg);
                    }
                }
            } else {
                if (!configuration.isIgnoreTychoRepositories() && !session.isOffline()) {
                    try {
                        MavenRepositoryReader reader = plexus.lookup(MavenRepositoryReader.class);
                        reader.setArtifactRepository(repository);
                        reader.setLocalRepository(session.getLocalRepository());

                        String repositoryKey = getRepositoryKey(repository);
                        TychoRepositoryIndex index = repositoryCache.getRepositoryIndex(repositoryKey);
                        if (index == null) {
                            index = new DefaultTychoRepositoryIndex(reader);

                            repositoryCache.putRepositoryIndex(repositoryKey, index);
                        }

                        resolver.addMavenRepository(uri, index, reader);
                        getLogger().debug("Added Maven repository " + repository.getId() + " ("
                                + repository.getUrl() + ")");
                    } catch (FileNotFoundException e) {
                        // it happens
                    } catch (Exception e) {
                        getLogger().debug("Unable to initialize remote Tycho repository", e);
                    }
                } else {
                    String msg = "Ignoring Maven repository " + repository.getId() + " (" + repository.getUrl()
                            + ")";
                    if (session.isOffline()) {
                        msg += " while in offline mode";
                    }
                    getLogger().debug(msg);
                }
            }
        } catch (MalformedURLException e) {
            getLogger().warn("Could not parse repository URL", e);
        } catch (URISyntaxException e) {
            getLogger().warn("Could not parse repository URL", e);
        }
    }

    Target target = configuration.getTarget();

    if (target != null) {
        Set<URI> uris = new HashSet<URI>();

        for (Target.Location location : target.getLocations()) {
            String type = location.getType();
            if (!"InstallableUnit".equalsIgnoreCase(type)) {
                getLogger().warn("Target location type: " + type + " is not supported");
                continue;
            }
            for (Target.Repository repository : location.getRepositories()) {

                try {
                    URI uri = new URI(getMirror(repository, session.getRequest().getMirrors()));
                    if (uris.add(uri)) {
                        if (session.isOffline()) {
                            getLogger().debug("Ignored repository " + uri + " while in offline mode");
                        } else {
                            String id = repository.getId();
                            if (id != null) {
                                Server server = session.getSettings().getServer(id);

                                if (server != null) {
                                    resolver.setCredentials(uri, server.getUsername(), server.getPassword());
                                } else {
                                    getLogger().info("Unknown server id=" + id + " for repository location="
                                            + repository.getLocation());
                                }
                            }

                            try {
                                resolver.addP2Repository(uri);
                            } catch (Exception e) {
                                String msg = "Failed to access p2 repository " + uri
                                        + ", will try to use local cache. Reason: " + e.getMessage();
                                if (getLogger().isDebugEnabled()) {
                                    getLogger().warn(msg, e);
                                } else {
                                    getLogger().warn(msg);
                                }
                            }
                        }
                    }
                } catch (URISyntaxException e) {
                    getLogger().debug("Could not parse repository URL", e);
                }
            }

            for (Target.Unit unit : location.getUnits()) {
                String versionRange;
                if ("0.0.0".equals(unit.getVersion())) {
                    versionRange = unit.getVersion();
                } else {
                    // perfect version match
                    versionRange = "[" + unit.getVersion() + "," + unit.getVersion() + "]";
                }
                resolver.addDependency(P2Resolver.TYPE_INSTALLABLE_UNIT, unit.getId(), versionRange);
            }
        }
    }

    if (!isAllowConflictingDependencies(project, configuration)) {
        List<P2ResolutionResult> results = resolver.resolveProject(project.getBasedir());

        MultiEnvironmentTargetPlatform multiPlatform = new MultiEnvironmentTargetPlatform();

        // FIXME this is just wrong
        for (int i = 0; i < configuration.getEnvironments().size(); i++) {
            TargetEnvironment environment = configuration.getEnvironments().get(i);
            P2ResolutionResult result = results.get(i);

            DefaultTargetPlatform platform = newDefaultTargetPlatform(session, projects, result);

            // addProjects( session, platform );

            multiPlatform.addPlatform(environment, platform);
        }

        return multiPlatform;
    } else {
        P2ResolutionResult result = resolver.collectProjectDependencies(project.getBasedir());

        return newDefaultTargetPlatform(session, projects, result);
    }
}