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.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
            }/* ww w .  java  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);
    }
}

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

License:Open Source License

private void addToP2ViewOfLocalRepository(MavenSession session, Collection<Artifact> artifacts,
        MavenProject project) {
    LocalTychoRepositoryIndex artifactsIndex = new LocalTychoRepositoryIndex(
            new File(session.getLocalRepository().getBasedir()),
            LocalTychoRepositoryIndex.ARTIFACTS_INDEX_RELPATH);

    for (Artifact artifact : artifacts) {

        ArtifactResolutionRequest request = new ArtifactResolutionRequest();
        Artifact p2ArtifactData = repositorySystem.createArtifactWithClassifier(artifact.getGroupId(),
                artifact.getArtifactId(), artifact.getVersion(), RepositoryLayoutHelper.EXTENSION_P2_ARTIFACTS,
                RepositoryLayoutHelper.CLASSIFIER_P2_ARTIFACTS);
        request.setArtifact(p2ArtifactData);
        request.setRemoteRepositories(project.getRemoteArtifactRepositories());
        ArtifactResolutionResult result = repositorySystem.resolve(request);
        if (result.isSuccess()) {
            // add to .meta/localArtifacts.properties
            artifactsIndex.addProject(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion());
        } else {/*  w  w  w. ja va2  s .co m*/
            // TODO as part of TYCHO-570: generate p2 artifact entry
        }
    }

    try {
        artifactsIndex.save();
    } catch (IOException e) {
        throw new RuntimeException("I/O error while updating p2 view on local Maven repository", e);
    }
}

From source file:org.eclipse.tycho.p2.resolver.P2DependencyResolver.java

License:Open Source License

@Override
public TargetPlatform computePreliminaryTargetPlatform(MavenSession session, MavenProject project,
        List<ReactorProject> reactorProjects) {
    TargetPlatformConfiguration configuration = TychoProjectUtils.getTargetPlatformConfiguration(project);
    ExecutionEnvironmentConfiguration ee = TychoProjectUtils.getExecutionEnvironmentConfiguration(project);

    TargetPlatformConfigurationStub tpConfiguration = new TargetPlatformConfigurationStub();
    tpConfiguration.setIncludePackedArtifacts(configuration.isIncludePackedArtifacts());

    PomDependencyCollector pomDependencies = null;
    if (TargetPlatformConfiguration.POM_DEPENDENCIES_CONSIDER.equals(configuration.getPomDependencies())) {
        pomDependencies = collectPomDependencies(project, reactorProjects, session);
    } else {//from w w w . ja  v  a  2 s . c o  m
        // TODO 412416 remove this when the setProjectLocation is no longer needed
        pomDependencies = resolverFactory.newPomDependencyCollector();
        pomDependencies.setProjectLocation(project.getBasedir());
    }

    for (ArtifactRepository repository : project.getRemoteArtifactRepositories()) {
        addEntireP2RepositoryToTargetPlatform(repository, tpConfiguration);
    }

    tpConfiguration.setEnvironments(configuration.getEnvironments());
    for (File file : configuration.getTargets()) {
        addTargetFileContentToTargetPlatform(file, configuration.getTargetDefinitionIncludeSourceMode(),
                tpConfiguration);
    }

    tpConfiguration.addFilters(configuration.getFilters());

    return reactorRepositoryManager.computePreliminaryTargetPlatform(DefaultReactorProject.adapt(project),
            tpConfiguration, ee, reactorProjects, pomDependencies);
}

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

License:Open Source License

public TargetPlatform computeTargetPlatform(MavenSession session, MavenProject project,
        List<ReactorProject> reactorProjects) {
    TargetPlatformConfiguration configuration = TychoProjectUtils.getTargetPlatformConfiguration(project);

    ExecutionEnvironment ee = projectTypes.get(project.getPackaging()).getExecutionEnvironment(project);

    TargetPlatformBuilder tpBuilder = resolverFactory.createTargetPlatformBuilder(//
            ee != null ? ee.getProfileName() : null, configuration.isDisableP2Mirrors());
    tpBuilder.setProjectLocation(project.getBasedir());

    addThisReactorProjectToTargetPlatform(session, project, configuration, tpBuilder);

    addOtherReactorProjectsToTargetPlatform(project, reactorProjects, tpBuilder);

    if (TargetPlatformConfiguration.POM_DEPENDENCIES_CONSIDER.equals(configuration.getPomDependencies())) {
        addPomDependenciesToTargetPlatform(project, tpBuilder, reactorProjects, session);
    }/*w ww  . ja v a 2s . c  o m*/

    for (ArtifactRepository repository : project.getRemoteArtifactRepositories()) {
        addEntireP2RepositoryToTargetPlatform(repository, tpBuilder, session);
    }

    if (configuration.getTarget() != null) {
        addTargetFileContentToTargetPlatform(configuration, tpBuilder, session);
    }

    tpBuilder.addFilters(configuration.getFilters());

    return tpBuilder.buildTargetPlatform();
}

From source file:org.eclipse.tycho.p2.resolver.PomDependencyProcessor.java

License:Open Source License

void addPomDependenciesToResolutionContext(MavenProject project, Collection<Artifact> transitivePomDependencies,
        TargetPlatformBuilder resolutionContext) {
    final TychoRepositoryIndex p2ArtifactsInLocalRepo = localRepoIndices.getArtifactsIndex();

    for (Artifact artifact : transitivePomDependencies) {
        P2DataArtifacts p2Data = new P2DataArtifacts(artifact);
        p2Data.resolve(session, project.getRemoteArtifactRepositories());

        if (p2Data.p2MetadataXml.isAvailable() && p2Data.p2ArtifactsXml.isAvailable()) {
            /*//from   w  ww .  jav a  2 s.c om
             * The POM dependency has (probably) been built by Tycho, so we can re-use the
             * existing p2 data in the target platform. The data is stored in the attached
             * artifacts p2metadata.xml and p2artifacts.xml, which are now present in the local
             * Maven repository.
             */
            if (logger.isDebugEnabled()) {
                logger.debug("P2TargetPlatformResolver: Using existing metadata of " + artifact.toString());
            }

            resolutionContext.addArtifactWithExistingMetadata(new ArtifactFacade(artifact),
                    new ArtifactFacade(p2Data.p2MetadataXml.artifact));

            /*
             * Since the p2artifacts.xml exists on disk, we can add the artifact to the (global)
             * p2 artifact repository view of local Maven repository. Then, the artifact is
             * available in the build.
             */
            // TODO this should happen in resolution context
            p2ArtifactsInLocalRepo
                    .addGav(new GAV(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()));

        } else if (!p2Data.p2MetadataXml.isAvailable() && !p2Data.p2ArtifactsXml.isAvailable()) {
            /*
             * The POM dependency has not been built by Tycho. If the dependency is a bundle,
             * run the p2 bundle publisher on it and add the result to the resolution context.
             */
            if (logger.isDebugEnabled()) {
                logger.debug("P2resolver.addMavenArtifact " + artifact.toString());
            }

            resolutionContext.publishAndAddArtifactIfBundleArtifact(new ArtifactFacade(artifact));

        } else {
            failDueToPartialP2Data(artifact, p2Data);
        }
    }
}

From source file:org.efaps.maven_java5.EfapsAnnotationDescriptorExtractor.java

License:Open Source License

/**
 *
 * @param _project  maven project/*  w  ww  .  j a  va2 s.  c  o  m*/
 * @return
 * @throws InvalidPluginDescriptorException
 */
protected ClassLoader getClassLoader(final MavenProject _project) throws InvalidPluginDescriptorException {
    final List<URL> urls = new ArrayList<URL>();

    // append all compile dependencies to the urls
    final Set<Artifact> toResolve = new HashSet<Artifact>();
    for (final Object obj : _project.getDependencies()) {
        final Dependency dependency = (Dependency) obj;
        final String scope = dependency.getScope();
        if (isCompileScope(scope)) {
            final Artifact artifact = this.artifactFactory.createArtifact(dependency.getGroupId(),
                    dependency.getArtifactId(), dependency.getVersion(), scope, dependency.getType());
            toResolve.add(artifact);
        }
    }
    try {
        final ArtifactResolutionResult result = this.artifactResolver.resolveTransitively(toResolve,
                _project.getArtifact(), getManagedVersionMap(_project), getLocalRepository(),
                _project.getRemoteArtifactRepositories(), this.artifactMetadataSource, this.filter);
        for (final Object obj : result.getArtifacts()) {
            final Artifact artifact = (Artifact) obj;
            urls.add(artifact.getFile().toURL());
        }
    } catch (final Exception e) {
        throw new InvalidPluginDescriptorException(
                "Failed to resolve transitively artifacts: " + e.getMessage(), e);
    }

    // append compile class path elements
    for (final Object obj : _project.getArtifacts()) {
        final Artifact cpe = (Artifact) obj;
        try {
            urls.add(cpe.getFile().toURL()); // URI().toURL() );
        } catch (final MalformedURLException e) {
            getLogger().warn("Cannot convert '" + cpe + "' to URL", e);
        }
    }

    // append target output directory (where the compiled files are)
    try {
        urls.add(new File(_project.getBuild().getOutputDirectory()).toURL());
    } catch (final MalformedURLException e) {
        getLogger().warn("Cannot convert '" + _project.getBuild().getOutputDirectory() + "' to URL", e);
    }

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("URLS: \n" + urls.toString().replaceAll(",", "\n  "));
    } else if (getLogger().isInfoEnabled()) {
        getLogger().info("URLS: \n" + urls.toString().replaceAll(",", "\n  "));
    }

    return new URLClassLoader(urls.toArray(new URL[urls.size()]), getClass().getClassLoader());
}

From source file:org.fabric3.runtime.maven.itest.ArtifactHelper.java

License:Open Source License

/**
 * Sets the Maven project./*from  w w  w . j  av  a2s  .  c  o m*/
 *
 * @param project the Maven project.
 */
public void setProject(MavenProject project) {
    this.project = project;
    this.remoteRepositories = project.getRemoteArtifactRepositories();
}

From source file:org.jboss.maven.plugins.qstools.checkers.DependencyChecker.java

License:Apache License

/**
 * Resolve Each Maven Artifact from BOM Information
 * //from  ww w .ja v a 2  s .  co  m
 * @param mavenProject the project used to retrieve the remote artifact repositories
 * @param bom the bom model that is being parsed
 * @param groupId
 * @param artifactId
 * @param version
 * @throws Exception
 */
private void readBOMArtifact(MavenProject mavenProject, Bom bom, String groupId, String artifactId,
        String version) throws Exception {
    Artifact pomArtifact = repositorySystem.createArtifact(groupId, artifactId, version, "", "pom");
    ArtifactResolutionRequest arr = new ArtifactResolutionRequest();

    arr.setArtifact(pomArtifact).setRemoteRepositories(mavenProject.getRemoteArtifactRepositories())
            .setLocalRepository(getMavenSession().getLocalRepository());
    repositorySystem.resolve(arr);
    // Given the resolved maven artifact for BOM, parse it.
    readBOM(mavenProject, bom, pomArtifact);

}

From source file:org.jboss.maven.shared.release.phase.MapVersionRangesPhase.java

License:Open Source License

private Artifact resolveVersionRange(final Artifact artifact, final MavenProject project)
        throws ReleaseExecutionException {
    final Set<Artifact> artifacts = asSet(artifact);
    final ArtifactResolutionResult result;
    try {/*w w  w  .  j  a v a 2  s .c  o  m*/
        result = artifactResolver.resolveTransitively(artifacts, project.getArtifact(),
                project.getRemoteArtifactRepositories(), localRepository, artifactMetadataSource);
        return (Artifact) result.getArtifacts().iterator().next();
    } catch (AbstractArtifactResolutionException e) {
        throw new ReleaseExecutionException("Failed to resolve artifact " + artifact, e);
    }
}

From source file:org.jboss.tools.maven.cdi.configurators.CDIProjectConfigurator.java

License:Open Source License

private String inferCdiVersionFromDependencies(MavenProject mavenProject) {
    boolean hasCandidates = false;
    String cdiVersion = null;/*from www  .  ja  v  a 2s  . co m*/
    List<ArtifactRepository> repos = mavenProject.getRemoteArtifactRepositories();
    for (Artifact artifact : mavenProject.getArtifacts()) {
        if (isKnownCdiExtension(artifact)) {
            hasCandidates = true;
            cdiVersion = Activator.getDefault().getDependencyVersion(artifact, repos, CDI_API_GROUP_ID,
                    CDI_API_ARTIFACT_ID);
            if (cdiVersion != null) {
                //TODO should probably not break and take the highest version returned from all dependencies
                break;
            }
        }
    }
    //Fallback to default CDI version
    if (hasCandidates && cdiVersion == null) {
        return DEFAULT_CDI_VERSION;
    }
    return cdiVersion;
}