org.apache.maven.repository.RepositorySystem Java Examples

The following examples show how to use org.apache.maven.repository.RepositorySystem. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Util.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Read current project dependencies and check if it don't grab incorrect
 * artifacts versions which could be in conflict with plugin dependencies.
 *
 * @param project
 *            current project
 * @param repoSystem
 *            repository system
 * @param localRepo
 *            local repository
 * @param remoteRepos
 *            remote repositories
 */
static void checkClasspath(final MavenProject project, final RepositorySystem repoSystem,
        final ArtifactRepository localRepo, final List<ArtifactRepository> remoteRepos) {
    Plugin plugin = project.getPlugin(YangToSourcesMojo.PLUGIN_NAME);
    if (plugin == null) {
        LOG.warn("{} {} not found, dependencies version check skipped", LOG_PREFIX, YangToSourcesMojo.PLUGIN_NAME);
    } else {
        Map<Artifact, Collection<Artifact>> pluginDependencies = new HashMap<>();
        getPluginTransitiveDependencies(plugin, pluginDependencies, repoSystem, localRepo, remoteRepos);

        Set<Artifact> projectDependencies = project.getDependencyArtifacts();
        for (Map.Entry<Artifact, Collection<Artifact>> entry : pluginDependencies.entrySet()) {
            checkArtifact(entry.getKey(), projectDependencies);
            for (Artifact dependency : entry.getValue()) {
                checkArtifact(dependency, projectDependencies);
            }
        }
    }
}
 
Example #2
Source File: Util.java    From jax-maven-plugin with Apache License 2.0 6 votes vote down vote up
static Stream<String> getPluginRuntimeDependencyEntries(AbstractMojo mojo, MavenProject project, Log log,
        RepositorySystem repositorySystem, ArtifactRepository localRepository,
        List<ArtifactRepository> remoteRepositories) {
    PluginDescriptor pluginDescriptor = (PluginDescriptor) mojo.getPluginContext().get(PLUGIN_DESCRIPTOR);
    Plugin plugin = project.getBuild().getPluginsAsMap().get(pluginDescriptor.getPluginLookupKey());

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

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

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

    return Stream.concat(originalArtifacts, childArtifacts).map(Artifact::getFile).map(File::getAbsolutePath);
}
 
Example #3
Source File: Util.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Read transitive dependencies of given plugin and store them in map.
 *
 * @param plugin
 *            plugin to read
 * @param map
 *            map, where founded transitive dependencies will be stored
 * @param repoSystem
 *            repository system
 * @param localRepository
 *            local repository
 * @param remoteRepos
 *            list of remote repositories
 */
private static void getPluginTransitiveDependencies(final Plugin plugin,
        final Map<Artifact, Collection<Artifact>> map, final RepositorySystem repoSystem,
        final ArtifactRepository localRepository, final List<ArtifactRepository> remoteRepos) {

    List<Dependency> pluginDependencies = plugin.getDependencies();
    for (Dependency dep : pluginDependencies) {
        Artifact artifact = repoSystem.createDependencyArtifact(dep);

        ArtifactResolutionRequest request = new ArtifactResolutionRequest();
        request.setArtifact(artifact);
        request.setResolveTransitively(true);
        request.setLocalRepository(localRepository);
        request.setRemoteRepositories(remoteRepos);

        ArtifactResolutionResult result = repoSystem.resolve(request);
        Set<Artifact> pluginDependencyDependencies = result.getArtifacts();
        map.put(artifact, pluginDependencyDependencies);
    }
}
 
Example #4
Source File: JavaFXRunMojoTestCase.java    From javafx-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void setUpProject(File pomFile, AbstractMojo mojo) throws Exception {
    super.setUp();

    MockitoAnnotations.initMocks(this);

    ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class);
    buildingRequest.setResolveDependencies(true);
    when(session.getProjectBuildingRequest()).thenReturn(buildingRequest);
    DefaultRepositorySystemSession repositorySession = MavenRepositorySystemUtils.newSession();
    repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory()
            .newInstance(repositorySession, new LocalRepository(RepositorySystem.defaultUserLocalRepository)));
    when(buildingRequest.getRepositorySession()).thenReturn(repositorySession);

    ProjectBuilder builder = lookup(ProjectBuilder.class);
    ProjectBuildingResult build = builder.build(pomFile, buildingRequest);
    MavenProject project = build.getProject();

    project.getBuild().setOutputDirectory(new File( "target/test-classes").getAbsolutePath());
    setVariableValueToObject(mojo, "project", project);
}
 
Example #5
Source File: ArtifactResolverTest.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveProjectArtifactsEmpty() throws MojoExecutionException {
    final RepositorySystem repositorySystem = mock(RepositorySystem.class);
    final MavenSession session = mock(MavenSession.class);
    final ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
    when(session.getProjectBuildingRequest()).thenReturn(projectBuildingRequest);
    final ArtifactRepository localRepository = mock(ArtifactRepository.class);
    when(projectBuildingRequest.getLocalRepository()).thenReturn(localRepository);
    final List<ArtifactRepository> remoteRepositories = emptyList();
    when(projectBuildingRequest.getRemoteRepositories()).thenReturn(remoteRepositories);

    final ArtifactResolver resolver = new ArtifactResolver(repositorySystem, localRepository, remoteRepositories);
    final MavenProject project = mock(MavenProject.class);

    final Configuration config = new Configuration(new CompositeSkipper(emptyList()),
            new CompositeSkipper(emptyList()), false, false, false, false);
    final Set<Artifact> resolved = resolver.resolveProjectArtifacts(project, config);
    assertEquals(emptySet(), resolved);
}
 
Example #6
Source File: MavenCompilerUtilsTest.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtractAnnotationProcessors() {
    final RepositorySystem repository = mock(RepositorySystem.class);
    final Plugin plugin = mock(Plugin.class);
    when(plugin.getGroupId()).thenReturn("org.apache.maven.plugins");
    when(plugin.getArtifactId()).thenReturn("maven-compiler-plugin");
    when(plugin.getVersion()).thenReturn("3.8.1");
    when(plugin.getConfiguration()).thenReturn(createConfiguration());
    when(repository.createArtifact(anyString(), anyString(), anyString(), anyString())).thenAnswer(invocation -> {
        final Artifact artifact = mock(Artifact.class);
        when(artifact.getGroupId()).thenReturn(invocation.getArgument(0));
        when(artifact.getArtifactId()).thenReturn(invocation.getArgument(1));
        when(artifact.getVersion()).thenReturn(invocation.getArgument(2));
        return artifact;
    });
    final Set<Artifact> result = extractAnnotationProcessors(repository, plugin);
    assertEquals(result.size(), 1);
    final Artifact resultElement = result.iterator().next();
    assertEquals(resultElement.getGroupId(), "myGroupId");
    assertEquals(resultElement.getArtifactId(), "myArtifactId");
    assertEquals(resultElement.getVersion(), "1.2.3");
}
 
Example #7
Source File: LocalRepoProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public @Override List<Archetype> getArchetypes() {
    List<Archetype> lst = new ArrayList<Archetype>();
        List<NBVersionInfo> archs = RepositoryQueries.findArchetypesResult(Collections.singletonList(RepositoryPreferences.getInstance().getLocalRepository())).getResults();
        if (archs == null) {
            return lst;
        }
        for (NBVersionInfo art : archs) {
            Archetype arch = new Archetype(!"maven-archetype".equalsIgnoreCase(art.getPackaging())); //NOI18N
            arch.setArtifactId(art.getArtifactId());
            arch.setGroupId(art.getGroupId());
            arch.setVersion(art.getVersion());
            arch.setName(art.getProjectName());
            arch.setDescription(art.getProjectDescription());
            arch.setRepository(RepositorySystem.DEFAULT_LOCAL_REPO_ID);
            lst.add(arch);
        }
   
    return lst;
}
 
Example #8
Source File: NewMirrorPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void checkCentral() {
    String sel = (String)comMirrorOf.getSelectedItem();
    urlmodel.removeAllElements();
    if (RepositorySystem.DEFAULT_REMOTE_REPO_ID.equals(sel)) {
        //see http://docs.codehaus.org/display/MAVENUSER/Mirrors+Repositories
        // for a list of central mirrors.
        //TODO might be worth to externalize somehow.
        urlmodel.addElement("http://mirrors.ibiblio.org/pub/mirrors/maven2"); //NOI18N
        urlmodel.addElement("http://www.ibiblio.net/pub/packages/maven2");//NOI18N
        urlmodel.addElement("http://ftp.cica.es/mirrors/maven2");//NOI18N
        urlmodel.addElement("http://repo1.sonatype.net/maven2");//NOI18N
        urlmodel.addElement("http://repo.exist.com/maven2");//NOI18N
        urlmodel.addElement("http://mirrors.redv.com/maven2");//NOI18N
        urlmodel.addElement("http://mirrors.dotsrc.org/maven2");//NOI18N
    }
}
 
Example #9
Source File: MavenCompilerUtilsTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractAnnotationProcessorsNoConfiguration() {
    final RepositorySystem repository = mock(RepositorySystem.class);
    final Plugin plugin = mock(Plugin.class);
    when(plugin.getGroupId()).thenReturn("org.apache.maven.plugins");
    when(plugin.getArtifactId()).thenReturn("maven-compiler-plugin");
    when(plugin.getVersion()).thenReturn("3.8.1");
    assertEquals(extractAnnotationProcessors(repository, plugin), emptySet());
}
 
Example #10
Source File: UtilTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void checkClasspathTest() throws Exception {
    final MavenProject project = mock(MavenProject.class);
    final Plugin plugin = mock(Plugin.class);
    final RepositorySystem repoSystem = mock(RepositorySystem.class);
    final ArtifactRepository localRepo = mock(ArtifactRepository.class);
    final ArtifactResolutionResult artifactResolResult = mock(ArtifactResolutionResult.class);
    final Artifact artifact = mock(Artifact.class);
    final Dependency dep = mock(Dependency.class);

    final List<ArtifactRepository> remoteRepos = new ArrayList<>();
    remoteRepos.add(localRepo);

    final Set<Artifact> artifacts = new HashSet<>();
    artifacts.add(artifact);

    final List<Dependency> listDepcy = new ArrayList<>();
    listDepcy.add(dep);

    when(project.getPlugin(anyString())).thenReturn(plugin);
    when(plugin.getDependencies()).thenReturn(listDepcy);
    when(artifact.getArtifactId()).thenReturn("artifactId");
    when(artifact.getGroupId()).thenReturn("groupId");
    when(artifact.getVersion()).thenReturn("SNAPSHOT");
    when(repoSystem.createDependencyArtifact(dep)).thenReturn(artifact);
    when(repoSystem.resolve(any(ArtifactResolutionRequest.class))).thenReturn(artifactResolResult);
    when(artifactResolResult.getArtifacts()).thenReturn(artifacts);
    when(project.getDependencyArtifacts()).thenReturn(artifacts);

    Util.checkClasspath(project, repoSystem, localRepo, remoteRepos);
    assertEquals(1, artifacts.size());
    assertEquals(1, remoteRepos.size());
    assertEquals(1, listDepcy.size());
}
 
Example #11
Source File: MavenCompilerUtils.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Extract annotation processors for maven-compiler-plugin configuration.
 *
 * @param system maven repository system
 * @param plugin maven-compiler-plugin plugin
 * @return Returns set of maven artifacts configured as annotation processors.
 */
public static Set<Artifact> extractAnnotationProcessors(RepositorySystem system, Plugin plugin) {
    requireNonNull(system);
    if (!checkCompilerPlugin(plugin)) {
        throw new IllegalArgumentException("Plugin is not '" + GROUPID + ":" + ARTIFACTID + "'.");
    }
    final Object config = plugin.getConfiguration();
    if (config == null) {
        return emptySet();
    }
    if (config instanceof Xpp3Dom) {
        return stream(((Xpp3Dom) config).getChildren("annotationProcessorPaths"))
                .flatMap(aggregate -> stream(aggregate.getChildren("path")))
                .map(processor -> system.createArtifact(
                        extractChildValue(processor, "groupId"),
                        extractChildValue(processor, "artifactId"),
                        extractChildValue(processor, "version"),
                        PACKAGING))
                // A path specification is automatically ignored in maven-compiler-plugin if version is absent,
                // therefore there is little use in logging incomplete paths that are filtered out.
                .filter(a -> !a.getGroupId().isEmpty())
                .filter(a -> !a.getArtifactId().isEmpty())
                .filter(a -> !a.getVersion().isEmpty())
                .collect(Collectors.toSet());
    }
    // It is expected that this will never occur due to all Configuration instances of all plugins being provided as
    // XML document. If this happens to occur on very old plugin versions, we can safely add the type support and
    // simply return an empty set.
    throw new UnsupportedOperationException("Please report that an unsupported type of configuration container" +
            " was encountered: " + config.getClass());
}
 
Example #12
Source File: ArtifactResolver.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
ArtifactResolver(RepositorySystem repositorySystem, ArtifactRepository localRepository,
        List<ArtifactRepository> remoteRepositories) {
    this.repositorySystem = requireNonNull(repositorySystem);
    this.localRepository = requireNonNull(localRepository);
    this.remoteRepositories = requireNonNull(remoteRepositories);
    this.remoteRepositoriesIgnoreCheckSum = repositoriesIgnoreCheckSum(remoteRepositories);
}
 
Example #13
Source File: MavenCompilerUtilsTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractAnnotationProcessorsIllegalInputs() {
    assertThrows(NullPointerException.class, () -> extractAnnotationProcessors(null, null));
    final Plugin badPlugin = mock(Plugin.class);
    when(badPlugin.getGroupId()).thenReturn("org.my-bad-plugin");
    when(badPlugin.getArtifactId()).thenReturn("bad-plugin");
    when(badPlugin.getVersion()).thenReturn("1.1.1");
    assertThrows(NullPointerException.class, () -> extractAnnotationProcessors(null, badPlugin));
    final RepositorySystem repository = mock(RepositorySystem.class);
    assertThrows(NullPointerException.class, () -> extractAnnotationProcessors(repository, null));
    assertThrows(IllegalArgumentException.class, () -> extractAnnotationProcessors(repository, badPlugin));
}
 
Example #14
Source File: RepositoryUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to download an artifact.
 * @param info a version of an artifact
 * @return the file in the local repository (might not exist if download failed)
 * @throws AbstractArtifactResolutionException currently never?
 * @since 1.17
 */
public static File downloadArtifact(NBVersionInfo info) throws Exception {
    Artifact a = createArtifact(info);
    MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
    List<ArtifactRepository> remotes;
    RepositoryInfo repo = RepositoryPreferences.getInstance().getRepositoryInfoById(info.getRepoId());
    if (repo != null && repo.isRemoteDownloadable()) {
        remotes = Collections.singletonList(online.createRemoteRepository(repo.getRepositoryUrl(), repo.getId()));
    } else {
        remotes = Collections.singletonList(online.createRemoteRepository(RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID));
    }
    online.resolve(a, remotes, online.getLocalRepository());
    return a.getFile();
}
 
Example #15
Source File: MavenCompilerUtilsTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractAnnotationProcessorsUnsupportedConfigurationType() {
    final RepositorySystem repository = mock(RepositorySystem.class);
    final Plugin plugin = mock(Plugin.class);
    when(plugin.getGroupId()).thenReturn("org.apache.maven.plugins");
    when(plugin.getArtifactId()).thenReturn("maven-compiler-plugin");
    when(plugin.getVersion()).thenReturn("3.8.1");
    when(plugin.getConfiguration()).thenReturn("Massive configuration encoded in magic \"Hello World!\" string.");
    assertThrows(UnsupportedOperationException.class, () -> extractAnnotationProcessors(repository, plugin));
}
 
Example #16
Source File: ArtifactResolverTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructArtifactResolverWithNull() {
    final RepositorySystem repositorySystem = mock(RepositorySystem.class);
    final ArtifactRepository localRepository = mock(ArtifactRepository.class);
    assertThrows(NullPointerException.class,
            () -> new ArtifactResolver(null, null, null));
    assertThrows(NullPointerException.class,
            () -> new ArtifactResolver(null, localRepository, emptyList()));
    assertThrows(NullPointerException.class,
            () -> new ArtifactResolver(repositorySystem, null, emptyList()));
    assertThrows(NullPointerException.class,
            () -> new ArtifactResolver(repositorySystem, localRepository, null));
}
 
Example #17
Source File: ArtifactResolverTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolveSignaturesEmpty() throws MojoExecutionException {
    final RepositorySystem repositorySystem = mock(RepositorySystem.class);
    final MavenSession session = mock(MavenSession.class);
    final ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
    when(session.getProjectBuildingRequest()).thenReturn(projectBuildingRequest);
    final ArtifactRepository localRepository = mock(ArtifactRepository.class);
    when(projectBuildingRequest.getLocalRepository()).thenReturn(localRepository);
    final List<ArtifactRepository> remoteRepositories = emptyList();
    when(projectBuildingRequest.getRemoteRepositories()).thenReturn(remoteRepositories);
    final ArtifactResolver resolver = new ArtifactResolver(repositorySystem, localRepository, remoteRepositories);
    final Map<Artifact, Artifact> resolvedSignatures = resolver.resolveSignatures(
            emptyList(), SignatureRequirement.NONE);
    assertEquals(resolvedSignatures.size(), 0);
}
 
Example #18
Source File: ModuleGenerator.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new <code>ModuleGenerator</code>.
 *
 * @param repositorySystem the given <code>RepositorySystem</code> is required to resolve the class path of the
 *                         examined maven projects
 * @since 2.0.0
 */
public ModuleGenerator(@Nonnull final RepositorySystem repositorySystem) {
    packagingHandlers.put("pom", new PomPackagingHandler());
    packagingHandlers.put("war", new WarPackagingHandler());
    artifactResolverCache = new SequentialLoadingCache<Artifact, File>(NonNullFunctions.toFunction(new NonNullFunction<Artifact, Optional<File>>() {
        @Nonnull
        @Override
        public Optional<File> apply(@Nonnull Artifact input) {
            if (!input.isResolved()) {
                ArtifactResolutionRequest request = new ArtifactResolutionRequest();
                request.setResolveRoot(true);
                request.setResolveTransitively(false);
                request.setArtifact(input);
                ArtifactResolutionResult artifactResolutionResult = repositorySystem.resolve(request);
                if (!artifactResolutionResult.isSuccess()) {
                    logger.warn("  Failed to resolve [{}]; some analyzers may not work properly.", getVersionedKeyFor(input));
                    return absent();
                }
            }
            File classPathElement = input.getFile();
            if (classPathElement == null) {
                logger.warn("  No valid path to [{}] found; some analyzers may not work properly.", getVersionedKeyFor(input));
                return absent();
            }
            return of(classPathElement);
        }
    }));
}
 
Example #19
Source File: A_ModuleGenerator.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    mavenProject = givenMavenProject("project");
    repositorySystem = mock(RepositorySystem.class);
    disableArtifactResolving();

    objectUnderTest = new ModuleGenerator(repositorySystem);
}
 
Example #20
Source File: RepositoryPreferences.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** @since 2.2 */
@Messages("local=Local")
public @NonNull synchronized RepositoryInfo getLocalRepository() {
    if (local == null) {
        try {
            //TODO do we care about changing the instance when localrepo location changes?
            local = new RepositoryInfo(RepositorySystem.DEFAULT_LOCAL_REPO_ID, Bundle.local(), EmbedderFactory.getProjectEmbedder().getLocalRepositoryFile().getAbsolutePath(), null);
            local.setMirrorStrategy(RepositoryInfo.MirrorStrategy.NONE);
        } catch (URISyntaxException x) {
            throw new AssertionError(x);
        }
    }
    return local;
}
 
Example #21
Source File: RepositoryPreferences.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private RepositoryPreferences() {
    try {
        central = new RepositoryInfo(RepositorySystem.DEFAULT_REMOTE_REPO_ID, /* XXX pull display name from superpom? */RepositorySystem.DEFAULT_REMOTE_REPO_ID, null, RepositorySystem.DEFAULT_REMOTE_REPO_URL);
        //this repository can be mirrored
        central.setMirrorStrategy(RepositoryInfo.MirrorStrategy.ALL);

    } catch (URISyntaxException x) {
        throw new AssertionError(x);
    }
}
 
Example #22
Source File: NBRepositoryModelResolver.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void addRepository(Repository repository, boolean replace) throws InvalidRepositoryException {
    RepositorySystem repositorySystem = embedder.lookupComponent(RepositorySystem.class);
    try {
        ArtifactRepository repo = repositorySystem.buildArtifactRepository(repository);
        if(replace) { 
            remoteRepositories.remove(repo);
        }
        remoteRepositories.add(repo);
        remoteRepositories = repositorySystem.getEffectiveRepositories( remoteRepositories );
    } catch (org.apache.maven.artifact.InvalidRepositoryException ex) {
        throw new InvalidRepositoryException(ex.toString(), repository, ex);
    }
}
 
Example #23
Source File: MavenProtocolHandler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected @Override URLConnection openConnection(URL u) throws IOException {
    String path = u.getPath();
    if (!path.startsWith("/")) {
        throw new IOException(path);
    }
    String stuff = path.substring(1);
    MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
    Artifact a;
    String[] pieces = stuff.split(":");
    if (pieces.length == 4) {
        a = online.createArtifact(pieces[0], pieces[1], pieces[2], pieces[3]);
    } else if (pieces.length == 5) {
        a = online.createArtifactWithClassifier(pieces[0], pieces[1], pieces[2], pieces[3], pieces[4]);
    } else {
        throw new IOException(stuff);
    }
    try {
        online.resolve(a, Collections.<ArtifactRepository>singletonList(online.createRemoteRepository(RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID)), online.getLocalRepository());
    } catch (Exception x) {
        throw new IOException(stuff + ": " + x, x);
    }
    File f = a.getFile();
    if (!f.isFile()) {
        throw new IOException("failed to download " + stuff);
    }
    Logger.getLogger(MavenProtocolHandler.class.getName()).log(Level.FINE, "resolved {0} -> {1}", new Object[] {stuff, f});
    return BaseUtilities.toURI(f).toURL().openConnection();
}
 
Example #24
Source File: MavenEmbedder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
MavenEmbedder(EmbedderConfiguration configuration) throws ComponentLookupException {
    embedderConfiguration = configuration;
    plexus = configuration.getContainer();
    this.maven = (DefaultMaven) plexus.lookup(Maven.class);
    this.projectBuilder = plexus.lookup(ProjectBuilder.class);
    this.repositorySystem = plexus.lookup(RepositorySystem.class);
    this.settingsBuilder = plexus.lookup(SettingsBuilder.class);
    this.populator = plexus.lookup(MavenExecutionRequestPopulator.class);
    settingsDecrypter = plexus.lookup(SettingsDecrypter.class);
}
 
Example #25
Source File: RemoteRepoProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override public List<Archetype> getArchetypes() {
    List<Archetype> lst = new ArrayList<Archetype>();
    List<RepositoryInfo> infos = RepositoryPreferences.getInstance().getRepositoryInfos();
    for (RepositoryInfo info : infos) {
        if (RepositorySystem.DEFAULT_LOCAL_REPO_ID.equals(info.getId())) {
            continue;
        }
        search(info, lst);
    }
    return lst;
}
 
Example #26
Source File: Archetype.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
     * resolve the artifacts associated with the archetype (ideally downloads them to the local repository)
     * @param hndl
     * @throws ArtifactResolutionException
     * @throws ArtifactNotFoundException 
     */
    public void resolveArtifacts(AggregateProgressHandle hndl) throws ArtifactResolutionException, ArtifactNotFoundException {
        MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
        
        List<ArtifactRepository> repos;
        if (getRepository() == null) {
            repos = Collections.<ArtifactRepository>singletonList(online.createRemoteRepository(RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID));
        } else {
           repos = Collections.<ArtifactRepository>singletonList(online.createRemoteRepository(getRepository(), "custom-repo"));//NOI18N
           for (RepositoryInfo info : RepositoryPreferences.getInstance().getRepositoryInfos()) {
                if (getRepository().equals(info.getRepositoryUrl())) {
                    repos = Collections.<ArtifactRepository>singletonList(online.createRemoteRepository(getRepository(), info.getId()));//NOI18N
                    break;
                }
            }
        }
        try {
            ProgressTransferListener.setAggregateHandle(hndl);
            
            hndl.start();

//TODO how to rewrite to track progress?
//            try {
//                WagonManager wagon = online.getPlexusContainer().lookup(WagonManager.class);
//                wagon.setDownloadMonitor(new ProgressTransferListener());
//            } catch (ComponentLookupException ex) {
//                Exceptions.printStackTrace(ex);
//            }
            online.resolve(getPomArtifact(), repos, online.getLocalRepository());
            online.resolve(getArtifact(), repos, online.getLocalRepository());
        } catch (ThreadDeath d) { // download interrupted
        } catch (IllegalStateException ise) { //download interrupted in dependent thread. #213812
            if (!(ise.getCause() instanceof ThreadDeath)) {
                throw ise;
            }
        } finally {
            ProgressTransferListener.clearAggregateHandle();
            hndl.finish();
        }
    }
 
Example #27
Source File: ModelUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param mdl
 * @param url of the repository
 * @param add true == add to model, will not add if the repo is in project but not in model (eg. central repo)
 * @return null if repository with given url exists, otherwise a returned newly created item.
 */
public static Repository addModelRepository(MavenProject project, POMModel mdl, String url) {
    if (url.contains(RepositorySystem.DEFAULT_REMOTE_REPO_URL) || /* #212336 */url.contains("http://repo1.maven.org/maven2")) {
        return null;
    }
    List<Repository> repos = mdl.getProject().getRepositories();
    if (repos != null) {
        for (Repository r : repos) {
            if (url.equals(r.getUrl())) {
                //already in model..either in pom.xml or added in this session.
                return null;
            }
        }
    }
    
    List<org.apache.maven.model.Repository> reps = project.getRepositories();
    org.apache.maven.model.Repository prjret = null;
    Repository ret = null;
    if (reps != null) {
        for (org.apache.maven.model.Repository re : reps) {
            if (url.equals(re.getUrl())) {
                prjret = re;
                break;
            }
        }
    }
    if (prjret == null) {
        ret = mdl.getFactory().createRepository();
        ret.setUrl(url);
        ret.setId(url);
        mdl.getProject().addRepository(ret);
    }
    return ret;
}
 
Example #28
Source File: Util.java    From jax-maven-plugin with Apache License 2.0 5 votes vote down vote up
static ArtifactResolutionResult resolve(Log log, Artifact artifact, RepositorySystem repositorySystem,
        ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories) {
    ArtifactResolutionRequest request = new ArtifactResolutionRequest() //
            .setArtifact(artifact) //
            .setLocalRepository(localRepository) //
            .setRemoteRepositories(remoteRepositories) //
            .setResolveTransitively(true) //
            .addListener(Util.createLoggingResolutionListener(log));
    return repositorySystem.resolve(request);
}
 
Example #29
Source File: PluginIndexManager.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Gets available goals from known plugins.
 * @param groups e.g. {@code Collections.singleton("org.apache.maven.plugins")}
 * @return e.g. {@code [..., dependency:copy, ..., release:perform, ...]}
 */
public static Set<String> getPluginGoalNames(Set<String> groups) throws Exception {
    Set<String> result = new TreeSet<String>();
    // XXX rather use ArtifactInfo.PLUGIN_GOALS
    for (String groupId : groups) {
        for (String artifactId : RepositoryQueries.filterPluginArtifactIdsResult(groupId, "", null).getResults()) {
            for (NBVersionInfo v : RepositoryQueries.getVersionsResult(groupId, artifactId, null).getResults()) {
                if (v.getVersion().endsWith("-SNAPSHOT") && !v.getRepoId().equals(RepositorySystem.DEFAULT_LOCAL_REPO_ID)) {
                    continue;
                }
                //XXX mkleint: oh man this takes forever.. it's inpractical for any usecase unless one has already downloaded the internet.
                // now that I think of it, the only scalable solution is make the info part of the index.
                File jar = RepositoryUtil.downloadArtifact(v);
                Document pluginXml = loadPluginXml(jar);
                if (pluginXml == null) {
                    continue;
                }
                Element root = pluginXml.getDocumentElement();
                Element goalPrefix = XMLUtil.findElement(root, "goalPrefix", null);
                if (goalPrefix == null) {
                    LOG.log(Level.WARNING, "no goalPrefix in {0}", jar);
                    continue;
                }
                Element mojos = XMLUtil.findElement(root, "mojos", null);
                if (mojos == null) {
                    LOG.log(Level.WARNING, "no mojos in {0}", jar);
                    continue;
                }
                for (Element mojo : XMLUtil.findSubElements(mojos)) {
                    if (!mojo.getTagName().equals("mojo")) {
                        continue;
                    }
                    Element goal = XMLUtil.findElement(mojo, "goal", null);
                    if (goal == null) {
                        LOG.log(Level.WARNING, "mojo missing goal in {0}", jar);
                        continue;
                    }
                    result.add(XMLUtil.findText(goalPrefix).trim() + ':' + XMLUtil.findText(goal).trim());
                }
                break;
            }
        }
    }
    LOG.log(Level.FINE, "found goal names: {0}", result);
    return result;
}
 
Example #30
Source File: CatalogRepoProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override protected String repository() {
    return RepositorySystem.DEFAULT_LOCAL_REPO_ID;
}