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

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

Introduction

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

Prototype

public Map<String, Artifact> getManagedVersionMap() 

Source Link

Usage

From source file:com.github.zhve.ideaplugin.ArtifactDependencyResolver.java

License:Apache License

private void tryResolve(MavenProject project, Set<Artifact> reactorArtifacts, List<Artifact> remoteData,
        List<Artifact> reactorData, List<Artifact> remoteUnresolvedList) {
    // search//from w  w  w  .  jav  a  2 s.c om
    ArtifactResolutionResult resolutionResult;
    log.info("Before:");
    for (Artifact a : remoteUnresolvedList)
        log.info("  " + a.getId() + ":" + a.getScope());
    log.info("");
    try {
        resolutionResult = artifactResolver.resolveTransitively(
                new LinkedHashSet<Artifact>(remoteUnresolvedList), project.getArtifact(),
                project.getManagedVersionMap(), localRepository, project.getRemoteArtifactRepositories(),
                artifactMetadataSource);
        // save search result
        log.info("After:");
        for (Object resolutionNode : resolutionResult.getArtifactResolutionNodes()) {
            Artifact art = ((ResolutionNode) resolutionNode).getArtifact();
            if (reactorArtifacts.contains(art)) {
                if (!reactorData.contains(art)) {
                    reactorData.add(art);
                    log.info("R " + art.getId() + ":" + art.getScope());
                } else {
                    log.info("D " + art.getId() + ":" + art.getScope());
                }
            } else {
                log.info("  " + art.getId() + ":" + art.getScope());
                remoteData.add(art);
            }
        }
        // clear unresolved
        remoteUnresolvedList.clear();
    } catch (ArtifactResolutionException e) {
        log.error(e.getMessage());
        remoteData.addAll(remoteUnresolvedList);
    } catch (ArtifactNotFoundException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.technophobia.substeps.runner.ForkedRunner.java

License:Open Source License

@SuppressWarnings("unchecked")
private List<String> resolveStepImplementationArtifacts() throws MojoExecutionException {

    final List<String> stepImplementationArtifactJars = Lists.newArrayList();
    if (this.stepImplementationArtifacts != null) {
        for (final String stepImplementationArtifactString : this.stepImplementationArtifacts) {

            final String[] artifactDetails = stepImplementationArtifactString.split(":");

            if (artifactDetails.length != 3) {
                throw new MojoExecutionException(
                        "Invalid artifact format found in substepImplementationArtifact, must be in format groupId:artifactId:version but was '"
                                + stepImplementationArtifactString + "'");
            }/*  w  w w . ja v a 2 s. c o m*/

            try {

                final Artifact stepImplementationJarArtifact = this.artifactFactory.createArtifact(
                        artifactDetails[0], artifactDetails[1], artifactDetails[2], "test", "jar");
                this.artifactResolver.resolve(stepImplementationJarArtifact, this.remoteRepositories,
                        this.localRepository);

                addArtifactPath(stepImplementationArtifactJars, stepImplementationJarArtifact);

                final Artifact stepImplementationPomArtifact = this.artifactFactory.createArtifact(
                        artifactDetails[0], artifactDetails[1], artifactDetails[2], "test", "pom");
                this.artifactResolver.resolve(stepImplementationPomArtifact, this.remoteRepositories,
                        this.localRepository);
                final MavenProject stepImplementationProject = this.mavenProjectBuilder.buildFromRepository(
                        stepImplementationPomArtifact, this.remoteRepositories, this.localRepository);
                final Set<Artifact> stepImplementationArtifacts = stepImplementationProject
                        .createArtifacts(this.artifactFactory, null, null);

                final Set<Artifact> transitiveDependencies = this.artifactResolver
                        .resolveTransitively(stepImplementationArtifacts, stepImplementationPomArtifact,
                                stepImplementationProject.getManagedVersionMap(), this.localRepository,
                                this.remoteRepositories, this.artifactMetadataSource)
                        .getArtifacts();

                for (final Artifact transitiveDependency : transitiveDependencies) {
                    addArtifactPath(stepImplementationArtifactJars, transitiveDependency);
                }

            } catch (final ArtifactResolutionException e) {

                throw new MojoExecutionException("Unable to resolve artifact for substep implementation '"
                        + stepImplementationArtifactString + "'", e);

            } catch (final ProjectBuildingException e) {

                throw new MojoExecutionException("Unable to resolve artifact for substep implementation '"
                        + stepImplementationArtifactString + "'", e);
            } catch (final InvalidDependencyVersionException e) {

                throw new MojoExecutionException("Unable to resolve artifact for substep implementation '"
                        + stepImplementationArtifactString + "'", e);
            } catch (final ArtifactNotFoundException e) {

                throw new MojoExecutionException("Unable to resolve artifact for substep implementation '"
                        + stepImplementationArtifactString + "'", e);
            }

        }
    }
    return stepImplementationArtifactJars;
}

From source file:eu.monnetproject.framework.bndannotation.BNDAnnotationProcessor.java

License:Apache License

private void resolveClassLoader() throws Exception {

    final Artifact pomArtifact = artifactFactory.createArtifact(project.getGroupId(), project.getArtifactId(),
            project.getVersion(), null, "pom");
    final MavenProject pomProject = mavenProjectBuilder.buildFromRepository(pomArtifact, remoteRepositories,
            localRepository);//from  ww  w  .j  a  v a2s .  c  o m
    final Set<?> resolvedArtifacts = pomProject.createArtifacts(this.artifactFactory, null, null);
    final ArtifactFilter filter = new ScopeArtifactFilter("compile");
    final ArtifactResolutionResult arr = resolver.resolveTransitively(resolvedArtifacts, pomArtifact,
            pomProject.getManagedVersionMap(), localRepository, remoteRepositories, artifactMetadataSource,
            filter);
    @SuppressWarnings("unchecked")
    Set<Artifact> artifacts = arr.getArtifacts();
    Set<URL> urls = new HashSet<URL>();
    for (Artifact artifact : artifacts) {
        urls.add(artifact.getFile().toURI().toURL());
    }

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<URLClassLoader> sysclass = URLClassLoader.class;

    try {
        Method method = sysclass.getDeclaredMethod("addURL", new Class<?>[] { URL.class });
        method.setAccessible(true);
        for (URL url : urls) {
            method.invoke(sysloader, new Object[] { url });
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new IOException("Error, could not add URL to system classloader");
    }
}

From source file:npanday.executable.impl.NetPluginExecutableFactoryImpl.java

License:Apache License

public NetExecutable getPluginRunner(MavenProject project, Artifact pluginArtifact,
        Set<Artifact> additionalDependencies, VendorRequirement vendorRequirement,
        ArtifactRepository localRepository, List<String> commands, File targetDir, String npandayVersion) throws

PlatformUnsupportedException, ArtifactResolutionException, ArtifactNotFoundException {

    Set dependencies = Sets.newHashSet(pluginArtifact);
    if (additionalDependencies != null) {
        dependencies.addAll(additionalDependencies);
    }//from   ww  w.  j av a  2  s. c  o m

    // need to resolve what we can here since we need the path!
    Set<Artifact> artifacts = makeAvailable(project.getArtifact(), project.getManagedVersionMap(), dependencies,
            targetDir, localRepository,
            // TODO: consider, if this must be getRemotePluginRepositories()!!
            project.getRemoteArtifactRepositories());

    commands.add("startProcessAssembly=" + pluginArtifact.getFile().getAbsolutePath());

    String pluginArtifactPath = findArtifact(artifacts, "NPanday.Plugin").getFile().getAbsolutePath();
    commands.add("pluginArtifactPath=" + pluginArtifactPath);

    return getArtifactExecutable(project, createPluginRunnerArtifact(npandayVersion), dependencies,
            vendorRequirement, localRepository, commands, targetDir);
}

From source file:npanday.executable.impl.NetPluginExecutableFactoryImpl.java

License:Apache License

public NetExecutable getArtifactExecutable(MavenProject project, Artifact executableArtifact,
        Set<Artifact> additionalDependencies, VendorRequirement vendorRequirement,
        ArtifactRepository localRepository, List<String> commands, File targetDir) throws

PlatformUnsupportedException, ArtifactResolutionException, ArtifactNotFoundException {
    Set dependencies = Sets.newHashSet(executableArtifact);
    if (additionalDependencies != null) {
        dependencies.addAll(additionalDependencies);
    }//from w w w .j a v a  2  s  .c  o m

    makeAvailable(project.getArtifact(), project.getManagedVersionMap(), dependencies, targetDir,
            localRepository,
            // TODO: consider, if this must be getRemotePluginRepositories()!!
            project.getRemoteArtifactRepositories());

    File artifactPath = executableArtifact.getFile();

    if (commands == null) {
        commands = new ArrayList<String>();
    }

    // TODO: this should be a separate implementation of NetExecutable, configured only for MONO!!!

    VendorInfo vendorInfo;
    try {
        vendorInfo = processor.process(vendorRequirement);
    } catch (IllegalStateException e) {
        throw new PlatformUnsupportedException(
                "NPANDAY-066-010: Illegal State: Vendor Info = " + vendorRequirement, e);
    }

    if (vendorInfo.getVendor() == null || vendorInfo.getFrameworkVersion() == null) {
        throw new PlatformUnsupportedException("NPANDAY-066-020: Missing Vendor Information: " + vendorInfo);
    }
    getLogger().debug("NPANDAY-066-003: Found Vendor: " + vendorInfo);

    List<String> modifiedCommands = new ArrayList<String>();
    String exe = null;

    if (vendorInfo.getVendor().equals(Vendor.MONO)) {
        List<File> executablePaths = vendorInfo.getExecutablePaths();
        if (executablePaths != null) {
            for (File executablePath : executablePaths) {
                if (new File(executablePath.getAbsolutePath(), "mono.exe").exists()) {
                    exe = new File(executablePath.getAbsolutePath(), "mono.exe").getAbsolutePath();
                    commands.add("vendor=MONO");//if forked process, it needs to know.
                    break;
                }
            }
        }

        if (exe == null) {
            getLogger().info(
                    "NPANDAY-066-005: Executable path for mono does not exist. Will attempt to execute MONO using"
                            + " the main PATH variable.");
            exe = "mono";
            commands.add("vendor=MONO");//if forked process, it needs to know.
        }
        modifiedCommands.add(artifactPath.getAbsolutePath());
        for (String command : commands) {
            modifiedCommands.add(command);
        }
    } else {
        exe = artifactPath.getAbsolutePath();
        modifiedCommands = commands;
    }
    //TODO: DotGNU on Linux?
    ExecutableConfig executableConfig = new ExecutableConfig();
    executableConfig.setExecutionPaths(Arrays.asList(exe));
    executableConfig.setCommands(modifiedCommands);

    try {
        repositoryExecutableContext.init(executableConfig);
    } catch (InitializationException e) {
        throw new PlatformUnsupportedException(
                "NPANDAY-066-006: Unable to initialize the repository executable context", e);
    }

    try {
        return repositoryExecutableContext.getNetExecutable();
    } catch (ExecutionException e) {
        throw new PlatformUnsupportedException("NPANDAY-066-004: Unable to find net executable", e);
    }
}

From source file:npanday.resolver.NPandayDependencyResolution.java

License:Apache License

public Set<Artifact> require(MavenProject project, ArtifactRepository localRepository, ArtifactFilter filter)
        throws ArtifactResolutionException {
    long startTime = System.currentTimeMillis();

    artifactResolver.initializeWithFilter(filter);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("NPANDAY-148-007: Resolving dependencies for " + project.getArtifact());
    }//from   w w w  . j a  va  2s .  c om

    try {
        if (project.getDependencyArtifacts() == null) {
            createArtifactsForMaven2BackCompat(project);
        }

        ArtifactResolutionResult result = artifactResolver.resolveTransitively(project.getDependencyArtifacts(),
                project.getArtifact(), project.getManagedVersionMap(), localRepository,
                project.getRemoteArtifactRepositories(), metaDataSource, filter);

        /*
        * WORKAROUND: transitive dependencies are not cached in MavenProject; in order to let
        * them "live" for following mojo executions, we'll add the custom resolved
        * dependencies to the projects DIRECT dependencies
        * */

        Set<Artifact> dependencyArtifacts = new HashSet<Artifact>(project.getDependencyArtifacts());
        addResolvedSpecialsToProjectDependencies(result, dependencyArtifacts);

        // Add custom contribute dependencies to maven project dependencies
        dependencyArtifacts.addAll(artifactResolver.getCustomDependenciesCache());
        project.setDependencyArtifacts(dependencyArtifacts);

        Set<Artifact> resultRequire = Sets.newLinkedHashSet(result.getArtifacts());
        resultRequire.addAll(artifactResolver.getCustomDependenciesCache());

        if (getLogger().isInfoEnabled()) {
            long endTime = System.currentTimeMillis();
            getLogger()
                    .info("NPANDAY-148-009: Took " + (endTime - startTime) + "ms to resolve dependencies for "
                            + project.getArtifact() + " with filter " + filter.toString());
        }

        return resultRequire;
    } catch (ArtifactResolutionException e) {
        throw new ArtifactResolutionException("NPANDAY-148-001: Could not resolve project dependencies",
                project.getArtifact(), e);
    } catch (ArtifactNotFoundException e) {
        throw new ArtifactResolutionException("NPANDAY-148-002: Could not resolve project dependencies",
                project.getArtifact(), e);
    } catch (InvalidDependencyVersionException e) {
        throw new ArtifactResolutionException("NPANDAY-148-003: Could not resolve project dependencies",
                project.getArtifact(), e);
    }
}

From source file:org.apache.geronimo.mavenplugins.car.AbstractCarMojo.java

License:Apache License

protected void getDependencies(MavenProject project, boolean useTransitiveDependencies)
        throws MojoExecutionException {

    DependencyTreeResolutionListener listener = new DependencyTreeResolutionListener(getLogger());

    DependencyNode rootNode;/*  w w  w  . ja  v  a  2s .  c  om*/
    try {
        Map managedVersions = project.getManagedVersionMap();

        Set dependencyArtifacts = project.getDependencyArtifacts();

        if (dependencyArtifacts == null) {
            dependencyArtifacts = project.createArtifacts(artifactFactory, null, null);
        }
        ArtifactResolutionResult result = artifactCollector.collect(dependencyArtifacts, project.getArtifact(),
                managedVersions, localRepository, project.getRemoteArtifactRepositories(),
                artifactMetadataSource, null, Collections.singletonList(listener));

        this.dependencyArtifacts = result.getArtifacts();
        rootNode = listener.getRootNode();
    } catch (ArtifactResolutionException exception) {
        throw new MojoExecutionException("Cannot build project dependency tree", exception);
    } catch (InvalidDependencyVersionException e) {
        throw new MojoExecutionException("Invalid dependency version for artifact " + project.getArtifact());
    }

    Scanner scanner = new Scanner();
    scanner.scan(rootNode, useTransitiveDependencies);
    localDependencies = scanner.localDependencies.keySet();
    treeListing = scanner.getLog();
}

From source file:org.apache.synapse.maven.xar.AbstractXarMojo.java

License:Apache License

/**
 * Get the set of artifacts that are provided by Synapse at runtime.
 * /*from   w  ww .  j a va 2 s . co m*/
 * @return
 * @throws MojoExecutionException
 */
private Set<Artifact> getSynapseRuntimeArtifacts() throws MojoExecutionException {
    Log log = getLog();
    log.debug("Looking for synapse-core artifact in XAR project dependencies ...");
    Artifact synapseCore = null;
    for (Iterator<?> it = project.getDependencyArtifacts().iterator(); it.hasNext();) {
        Artifact artifact = (Artifact) it.next();
        if (artifact.getGroupId().equals("org.apache.synapse")
                && artifact.getArtifactId().equals("synapse-core")) {
            synapseCore = artifact;
            break;
        }
    }
    if (synapseCore == null) {
        throw new MojoExecutionException("Could not locate dependency on synapse-core");
    }

    log.debug("Loading project data for " + synapseCore + " ...");
    MavenProject synapseCoreProject;
    try {
        synapseCoreProject = projectBuilder.buildFromRepository(synapseCore, remoteArtifactRepositories,
                localRepository);
    } catch (ProjectBuildingException e) {
        throw new MojoExecutionException("Unable to retrieve project information for " + synapseCore, e);
    }
    Set<Artifact> synapseRuntimeDeps;
    try {
        synapseRuntimeDeps = synapseCoreProject.createArtifacts(artifactFactory, Artifact.SCOPE_RUNTIME,
                new TypeArtifactFilter("jar"));
    } catch (InvalidDependencyVersionException e) {
        throw new MojoExecutionException("Unable to get project dependencies for " + synapseCore, e);
    }
    log.debug("Direct runtime dependencies for " + synapseCore + " :");
    logArtifacts(synapseRuntimeDeps);

    log.debug("Resolving transitive dependencies for " + synapseCore + " ...");
    try {
        synapseRuntimeDeps = artifactCollector.collect(synapseRuntimeDeps, synapseCoreProject.getArtifact(),
                synapseCoreProject.getManagedVersionMap(), localRepository, remoteArtifactRepositories,
                artifactMetadataSource, null, Collections.singletonList(new DebugResolutionListener(logger)))
                .getArtifacts();
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Unable to resolve transitive dependencies for " + synapseCore);
    }
    log.debug("All runtime dependencies for " + synapseCore + " :");
    logArtifacts(synapseRuntimeDeps);

    return synapseRuntimeDeps;
}

From source file:org.eclipse.che.maven.server.MavenServerImpl.java

License:Open Source License

private MavenResult internalResolveProject(File pom, List<String> activeProfiles, List<String> inactiveProfiles,
        List<ResolutionListener> dependencyTreeResolutionListeners) {

    MavenExecutionRequest request = newMavenRequest(pom, activeProfiles, inactiveProfiles,
            Collections.emptyList());
    request.setUpdateSnapshots(updateSnapshots);

    AtomicReference<MavenResult> reference = new AtomicReference<>();
    runMavenRequest(request, () -> {/*from   ww  w . j  a v a  2  s  .  co  m*/
        try {
            ProjectBuilder builder = getMavenComponent(ProjectBuilder.class);

            List<ProjectBuildingResult> resultList = builder.build(Collections.singletonList(pom), false,
                    request.getProjectBuildingRequest());
            ProjectBuildingResult result = resultList.get(0);
            MavenProject mavenProject = result.getProject();
            RepositorySystemSession repositorySession = getMavenComponent(LegacySupport.class)
                    .getRepositorySession();
            if (repositorySession instanceof DefaultRepositorySystemSession) {
                ((DefaultRepositorySystemSession) repositorySession)
                        .setTransferListener(new ArtifactTransferListener(mavenProgressNotifier));
                if (workspaceCache != null) {
                    ((DefaultRepositorySystemSession) repositorySession)
                            .setWorkspaceReader(new MavenWorkspaceReader(workspaceCache));
                }

            }

            List<Exception> exceptions = new ArrayList<>();

            loadExtensions(mavenProject, exceptions);
            mavenProject.setDependencyArtifacts(
                    mavenProject.createArtifacts(getMavenComponent(ArtifactFactory.class), null, null));

            ArtifactResolutionRequest resolutionRequest = new ArtifactResolutionRequest();
            resolutionRequest.setArtifact(mavenProject.getArtifact());
            resolutionRequest.setRemoteRepositories(mavenProject.getRemoteArtifactRepositories());
            resolutionRequest.setArtifactDependencies(mavenProject.getDependencyArtifacts());
            resolutionRequest.setListeners(dependencyTreeResolutionListeners);
            resolutionRequest.setLocalRepository(localRepo);
            resolutionRequest.setManagedVersionMap(mavenProject.getManagedVersionMap());
            resolutionRequest.setResolveTransitively(true);
            resolutionRequest.setResolveRoot(false);
            ArtifactResolver resolver = getMavenComponent(ArtifactResolver.class);
            ArtifactResolutionResult resolve = resolver.resolve(resolutionRequest);
            mavenProject.setArtifacts(resolve.getArtifacts());
            reference.set(new MavenResult(mavenProject, exceptions));

        } catch (Exception e) {
            reference.set(new MavenResult(null, null, Collections.singletonList(e)));
        }
    });
    return reference.get();
}

From source file:org.eclipse.m2e.editor.composites.DependencyLabelProvider.java

License:Open Source License

private Image getImage(String groupId, String artifactId, String version, boolean isManaged) {
    // XXX need to resolve actual dependencies (i.e. inheritance, dependency management or properties)
    // XXX need to handle version ranges

    if ((version == null || version.indexOf("${") > -1) && pomEditor != null) { //$NON-NLS-1$
        MavenProject mavenProject = pomEditor.getMavenProject();
        if (mavenProject != null) {
            Artifact artifact = mavenProject.getArtifactMap().get(groupId + ":" + artifactId); //$NON-NLS-1$
            if (artifact != null) {
                version = artifact.getVersion();
            }// w ww .  j  a  va2s .  c om
            if (version == null || version.indexOf("${") > -1) { //$NON-NLS-1$
                Collection<Artifact> artifacts = mavenProject.getManagedVersionMap().values();
                for (Artifact a : artifacts) {
                    if (a.getGroupId().equals(groupId) && a.getArtifactId().equals(artifactId)) {
                        version = a.getVersion();
                        break;
                    }
                }
            }
        }
    }

    if (groupId != null && artifactId != null && version != null) {
        IMavenProjectRegistry projectManager = MavenPlugin.getMavenProjectRegistry();
        IMavenProjectFacade projectFacade = projectManager.getMavenProject(groupId, artifactId, version);
        if (projectFacade != null) {
            return isManaged
                    ? MavenImages.getOverlayImage(MavenImages.PATH_PROJECT, MavenImages.PATH_LOCK,
                            IDecoration.BOTTOM_LEFT)
                    : MavenEditorImages.IMG_PROJECT;
        }
    }
    return isManaged
            ? MavenImages.getOverlayImage(MavenImages.PATH_JAR, MavenImages.PATH_LOCK, IDecoration.BOTTOM_LEFT)
            : MavenEditorImages.IMG_JAR;
}