Example usage for org.apache.maven.project DefaultDependencyResolutionRequest DefaultDependencyResolutionRequest

List of usage examples for org.apache.maven.project DefaultDependencyResolutionRequest DefaultDependencyResolutionRequest

Introduction

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

Prototype

public DefaultDependencyResolutionRequest(MavenProject project, RepositorySystemSession session) 

Source Link

Usage

From source file:com.github.lucapino.manifest.ManifestMojo.java

License:Apache License

public Set<Artifact> getDependencyArtifacts(MavenProject project, RepositorySystemSession repoSession,
        ProjectDependenciesResolver projectDependenciesResolver) throws MojoExecutionException {

    DefaultDependencyResolutionRequest dependencyResolutionRequest = new DefaultDependencyResolutionRequest(
            project, repoSession);/*from  w  w w  . j  a v a2s  .  com*/
    DependencyResolutionResult dependencyResolutionResult;

    try {
        dependencyResolutionResult = projectDependenciesResolver.resolve(dependencyResolutionRequest);
    } catch (DependencyResolutionException ex) {
        throw new MojoExecutionException(ex.getMessage(), ex);
    }

    Set artifacts = new LinkedHashSet();
    if (dependencyResolutionResult.getDependencyGraph() != null
            && !dependencyResolutionResult.getDependencyGraph().getChildren().isEmpty()) {
        RepositoryUtils.toArtifacts(artifacts, dependencyResolutionResult.getDependencyGraph().getChildren(),
                Collections.singletonList(project.getArtifact().getId()), null);
    }
    return artifacts;
}

From source file:com.mastfrog.maven.merge.configuration.MergeConfigurationMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    // XXX a LOT of duplicate code here
    Log log = super.getLog();
    log.info("Merging properties files");
    if (repoSession == null) {
        throw new MojoFailureException("RepositorySystemSession is null");
    }/*  w ww  .j a  v a  2 s .com*/
    List<File> jars = new ArrayList<>();
    List<String> exclude = new LinkedList<>();
    for (String ex : this.exclude.split(",")) {
        ex = ex.trim();
        ex = ex.replace('.', '/');
        exclude.add(ex);
    }
    try {
        DependencyResolutionResult result = resolver
                .resolve(new DefaultDependencyResolutionRequest(project, repoSession));
        log.info("FOUND " + result.getDependencies().size() + " dependencies");
        for (Dependency d : result.getDependencies()) {
            switch (d.getScope()) {
            case "test":
            case "provided":
                break;
            default:
                File f = d.getArtifact().getFile();
                if (f.getName().endsWith(".jar") && f.isFile() && f.canRead()) {
                    jars.add(f);
                }
            }
        }
    } catch (DependencyResolutionException ex) {
        throw new MojoExecutionException("Collecting dependencies failed", ex);
    }

    Map<String, Properties> m = new LinkedHashMap<>();

    Map<String, Set<String>> linesForName = new LinkedHashMap<>();
    Map<String, Integer> fileCountForName = new HashMap<>();

    boolean buildMergedJar = mainClass != null && !"none".equals(mainClass);
    JarOutputStream jarOut = null;
    Set<String> seen = new HashSet<>();

    try {
        if (buildMergedJar) {
            try {
                File outDir = new File(project.getBuild().getOutputDirectory()).getParentFile();
                File jar = new File(outDir, project.getBuild().getFinalName() + ".jar");
                if (!jar.exists()) {
                    throw new MojoExecutionException("Could not find jar " + jar);
                }
                try (JarFile jf = new JarFile(jar)) {
                    Manifest manifest = new Manifest(jf.getManifest());
                    if (mainClass != null) {
                        manifest.getMainAttributes().putValue("Main-Class", mainClass);
                    }
                    String jn = jarName == null || "none".equals(jarName) ? strip(mainClass) : jarName;
                    File outJar = new File(outDir, jn + ".jar");
                    log.info("Will build merged JAR " + outJar);
                    if (outJar.equals(jar)) {
                        throw new MojoExecutionException(
                                "Merged jar and output jar are the same file: " + outJar);
                    }
                    if (!outJar.exists()) {
                        outJar.createNewFile();
                    }
                    jarOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)),
                            manifest);
                    jarOut.setLevel(9);
                    jarOut.setComment("Merged jar created by " + getClass().getName());
                    Enumeration<JarEntry> en = jf.entries();
                    while (en.hasMoreElements()) {
                        JarEntry e = en.nextElement();
                        String name = e.getName();
                        for (String s : exclude) {
                            if (name.startsWith(s)) {
                                continue;
                            }
                        }
                        //                            if (!seen.contains(name)) {
                        switch (name) {
                        case "META-INF/MANIFEST.MF":
                        case "META-INF/":
                            break;
                        case "META-INF/LICENSE":
                        case "META-INF/LICENSE.txt":
                        case "META-INF/http/pages.list":
                        case "META-INF/http/modules.list":
                        case "META-INF/http/numble.list":
                        case "META-INF/settings/namespaces.list":
                            Set<String> s = linesForName.get(name);
                            if (s == null) {
                                s = new LinkedHashSet<>();
                                linesForName.put(name, s);
                            }
                            Integer ct = fileCountForName.get(name);
                            if (ct == null) {
                                ct = 1;
                            }
                            fileCountForName.put(name, ct);
                            try (InputStream in = jf.getInputStream(e)) {
                                s.addAll(readLines(in));
                            }
                            break;
                        default:
                            if (name.startsWith("META-INF/services/") && !name.endsWith("/")) {
                                Set<String> s2 = linesForName.get(name);
                                if (s2 == null) {
                                    s2 = new HashSet<>();
                                    linesForName.put(name, s2);
                                }
                                Integer ct2 = fileCountForName.get(name);
                                if (ct2 == null) {
                                    ct2 = 1;
                                }
                                fileCountForName.put(name, ct2);
                                try (InputStream in = jf.getInputStream(e)) {
                                    s2.addAll(readLines(in));
                                }
                                seen.add(name);
                            } else if (PAT.matcher(name).matches()) {
                                log.info("Include " + name);
                                Properties p = new Properties();
                                try (InputStream in = jf.getInputStream(e)) {
                                    p.load(in);
                                }
                                Properties all = m.get(name);
                                if (all == null) {
                                    all = p;
                                    m.put(name, p);
                                } else {
                                    for (String key : p.stringPropertyNames()) {
                                        if (all.containsKey(key)) {
                                            Object old = all.get(key);
                                            Object nue = p.get(key);
                                            if (!Objects.equal(old, nue)) {
                                                log.warn(key + '=' + nue + " in " + jar + '!' + name
                                                        + " overrides " + key + '=' + old);
                                            }
                                        }
                                    }
                                    all.putAll(p);
                                }
                            } else if (!seen.contains(name) && !SIG1.matcher(name).find()
                                    && !SIG2.matcher(name).find() && !SIG3.matcher(name).find()) {
                                log.info("Bundle " + name);
                                JarEntry je = new JarEntry(name);
                                je.setTime(e.getTime());
                                try {
                                    jarOut.putNextEntry(je);
                                } catch (ZipException ex) {
                                    throw new MojoExecutionException("Exception putting zip entry " + name, ex);
                                }
                                try (InputStream in = jf.getInputStream(e)) {
                                    copy(in, jarOut);
                                }
                                jarOut.closeEntry();
                                seen.add(name);
                            } else {
                                System.err.println("Skip " + name);
                            }
                        }
                        //                            }
                        seen.add(e.getName());
                    }
                }
            } catch (IOException ex) {
                throw new MojoExecutionException("Failed to create merged jar", ex);
            }
        }

        for (File f : jars) {
            log.info("Merge JAR " + f);
            try (JarFile jar = new JarFile(f)) {
                Enumeration<JarEntry> en = jar.entries();
                while (en.hasMoreElements()) {
                    JarEntry entry = en.nextElement();
                    String name = entry.getName();
                    for (String s : exclude) {
                        if (name.startsWith(s)) {
                            continue;
                        }
                    }
                    if (PAT.matcher(name).matches()) {
                        log.info("Include " + name + " in " + f);
                        Properties p = new Properties();
                        try (InputStream in = jar.getInputStream(entry)) {
                            p.load(in);
                        }
                        Properties all = m.get(name);
                        if (all == null) {
                            all = p;
                            m.put(name, p);
                        } else {
                            for (String key : p.stringPropertyNames()) {
                                if (all.containsKey(key)) {
                                    Object old = all.get(key);
                                    Object nue = p.get(key);
                                    if (!Objects.equal(old, nue)) {
                                        log.warn(key + '=' + nue + " in " + f + '!' + name + " overrides " + key
                                                + '=' + old);
                                    }
                                }
                            }
                            all.putAll(p);
                        }
                    } else if (SERVICES.matcher(name).matches()
                            || "META-INF/settings/namespaces.list".equals(name)
                            || "META-INF/http/pages.list".equals(name)
                            || "META-INF/http/modules.list".equals(name)
                            || "META-INF/http/numble.list".equals(name)) {
                        log.info("Include " + name + " in " + f);
                        try (InputStream in = jar.getInputStream(entry)) {
                            List<String> lines = readLines(in);
                            Set<String> all = linesForName.get(name);
                            if (all == null) {
                                all = new LinkedHashSet<>();
                                linesForName.put(name, all);
                            }
                            all.addAll(lines);
                        }
                        Integer ct = fileCountForName.get(name);
                        if (ct == null) {
                            ct = 1;
                        } else {
                            ct++;
                        }
                        fileCountForName.put(name, ct);
                    } else if (jarOut != null) {
                        //                            if (!seen.contains(name)) {
                        switch (name) {
                        case "META-INF/MANIFEST.MF":
                        case "META-INF/":
                            break;
                        case "META-INF/LICENSE":
                        case "META-INF/LICENSE.txt":
                        case "META-INF/settings/namespaces.list":
                        case "META-INF/http/pages.list":
                        case "META-INF/http/numble.list":
                        case "META-INF/http/modules.list":
                            Set<String> s = linesForName.get(name);
                            if (s == null) {
                                s = new LinkedHashSet<>();
                                linesForName.put(name, s);
                            }
                            Integer ct = fileCountForName.get(name);
                            if (ct == null) {
                                ct = 1;
                            }
                            fileCountForName.put(name, ct);
                            try (InputStream in = jar.getInputStream(entry)) {
                                s.addAll(readLines(in));
                            }
                            break;
                        default:
                            if (!seen.contains(name)) {
                                if (!SIG1.matcher(name).find() && !SIG2.matcher(name).find()
                                        && !SIG3.matcher(name).find()) {
                                    JarEntry je = new JarEntry(name);
                                    je.setTime(entry.getTime());
                                    try {
                                        jarOut.putNextEntry(je);
                                    } catch (ZipException ex) {
                                        throw new MojoExecutionException("Exception putting zip entry " + name,
                                                ex);
                                    }
                                    try (InputStream in = jar.getInputStream(entry)) {
                                        copy(in, jarOut);
                                    }
                                    jarOut.closeEntry();
                                }
                            } else {
                                if (!name.endsWith("/") && !name.startsWith("META-INF")) {
                                    log.warn("Saw more than one " + name + ".  One will clobber the other.");
                                }
                            }
                        }
                        //                            } else {
                        //                                if (!name.endsWith("/") && !name.startsWith("META-INF")) {
                        //                                    log.warn("Saw more than one " + name + ".  One will clobber the other.");
                        //                                }
                        //                            }
                        seen.add(name);
                    }
                }
            } catch (IOException ex) {
                throw new MojoExecutionException("Error opening " + f, ex);
            }
        }
        if (!m.isEmpty()) {
            log.warn("Writing merged files: " + m.keySet());
        } else {
            return;
        }
        String outDir = project.getBuild().getOutputDirectory();
        File dir = new File(outDir);
        // Don't bother rewriting META-INF/services files of which there is
        // only one
        //            for (Map.Entry<String, Integer> e : fileCountForName.entrySet()) {
        //                if (e.getValue() == 1) {
        //                    linesForName.remove(e.getKey());
        //                }
        //            }
        for (Map.Entry<String, Set<String>> e : linesForName.entrySet()) {
            File outFile = new File(dir, e.getKey());
            log.info("Merge configurating rewriting " + outFile);
            Set<String> lines = e.getValue();
            if (!outFile.exists()) {
                try {
                    Path path = outFile.toPath();
                    if (!Files.exists(path.getParent())) {
                        Files.createDirectories(path.getParent());
                    }
                    path = Files.createFile(path);
                    outFile = path.toFile();
                } catch (IOException ex) {
                    throw new MojoFailureException("Could not create " + outFile, ex);
                }
            }
            if (!outFile.isDirectory()) {
                try (FileOutputStream out = new FileOutputStream(outFile)) {
                    try (PrintStream ps = new PrintStream(out)) {
                        for (String line : lines) {
                            ps.println(line);
                        }
                    }
                } catch (IOException ex) {
                    throw new MojoFailureException("Exception writing " + outFile, ex);
                }
            }
            if (jarOut != null) {
                log.warn("Concatenating " + fileCountForName.get(e.getKey()) + " copies of " + e.getKey());
                JarEntry je = new JarEntry(e.getKey());
                try {
                    jarOut.putNextEntry(je);
                    PrintStream ps = new PrintStream(jarOut);
                    for (String line : lines) {
                        ps.println(line);
                    }
                    jarOut.closeEntry();
                } catch (IOException ex) {
                    throw new MojoFailureException("Exception writing " + outFile, ex);
                }
            }
        }
        for (Map.Entry<String, Properties> e : m.entrySet()) {
            File outFile = new File(dir, e.getKey());
            Properties local = new Properties();
            if (outFile.exists()) {
                try {
                    try (InputStream in = new FileInputStream(outFile)) {
                        local.load(in);
                    }
                } catch (IOException ioe) {
                    throw new MojoExecutionException("Could not read " + outFile, ioe);
                }
            } else {
                try {
                    Path path = outFile.toPath();
                    if (!Files.exists(path.getParent())) {
                        Files.createDirectories(path.getParent());
                    }
                    path = Files.createFile(path);
                    outFile = path.toFile();
                } catch (IOException ex) {
                    throw new MojoFailureException("Could not create " + outFile, ex);
                }
            }
            Properties merged = e.getValue();
            for (String key : local.stringPropertyNames()) {
                if (merged.containsKey(key) && !Objects.equal(local.get(key), merged.get(key))) {
                    log.warn("Overriding key=" + merged.get(key) + " with locally defined key="
                            + local.get(key));
                }
            }
            merged.putAll(local);
            try {
                log.info("Saving merged properties to " + outFile);
                try (FileOutputStream out = new FileOutputStream(outFile)) {
                    merged.store(out, getClass().getName());
                }
            } catch (IOException ex) {
                throw new MojoExecutionException("Failed to write " + outFile, ex);
            }
            if (jarOut != null) {
                JarEntry props = new JarEntry(e.getKey());
                try {
                    jarOut.putNextEntry(props);
                    merged.store(jarOut, getClass().getName() + " merged " + e.getKey());
                    jarOut.closeEntry();
                } catch (IOException ex) {
                    throw new MojoExecutionException("Failed to write jar entry " + e.getKey(), ex);
                }
            }
            File copyTo = new File(dir.getParentFile(), "settings");
            if (!copyTo.exists()) {
                copyTo.mkdirs();
            }
            File toFile = new File(copyTo, outFile.getName());
            try {
                Files.copy(outFile.toPath(), toFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                throw new MojoExecutionException("Failed to copy " + outFile + " to " + toFile, ex);
            }
        }
    } finally {
        if (jarOut != null) {
            try {
                jarOut.close();
            } catch (IOException ex) {
                throw new MojoExecutionException("Failed to close Jar", ex);
            }
        }
    }
}

From source file:net.sf.taverna.t2.maven.plugins.MavenOsgiUtils.java

License:Apache License

public Set<BundleArtifact> getBundleDependencies(String... scopes) throws MojoExecutionException {
    ScopeDependencyFilter scopeFilter = new ScopeDependencyFilter(Arrays.asList(scopes), null);

    DefaultDependencyResolutionRequest dependencyResolutionRequest = new DefaultDependencyResolutionRequest(
            project, repositorySystemSession);
    dependencyResolutionRequest.setResolutionFilter(scopeFilter);

    DependencyResolutionResult dependencyResolutionResult;
    try {/*from   w w w  .  ja v  a 2  s  .  c o m*/
        dependencyResolutionResult = projectDependenciesResolver.resolve(dependencyResolutionRequest);
    } catch (DependencyResolutionException ex) {
        throw new MojoExecutionException(ex.getMessage(), ex);
    }

    DependencyNode dependencyGraph = dependencyResolutionResult.getDependencyGraph();
    if (dependencyGraph != null) {
        checkBundleDependencies(dependencyGraph.getChildren());
        return getBundleArtifacts(dependencyGraph.getChildren());
    } else {
        return new HashSet<BundleArtifact>();
    }
}

From source file:org.heneveld.maven.license_audit.AbstractLicensingMojo.java

protected void resolveDependencies() throws MojoExecutionException {
    DependencyResolutionResult depRes;//from www  . java2 s  .c o m
    try {
        DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(
                mavenSession.getRepositorySession());
        ((DefaultRepositorySystemSession) repositorySession).setDependencySelector(
                newRootScopeDependencySelector(repositorySession.getDependencySelector(), 0));
        DefaultDependencyResolutionRequest depReq = new DefaultDependencyResolutionRequest(project,
                repositorySession);
        depRes = depsResolver.resolve(depReq);
    } catch (DependencyResolutionException e) {
        throw new MojoExecutionException("Cannot resolve dependencies for " + project, e);
    }
    rootDependencyGraph = depRes.getDependencyGraph();
    getLog().debug("Dependency graph with scopes " + includeDependencyScopes + ":");
    dump("", rootDependencyGraph);

    projectByIdCache.put(Coords.of(project).normal(), project);
    collectDeps(rootDependencyGraph, project, 0);
}

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

License:Apache License

/**
 * copied from {@link DefaultProjectBuilder#resolveDependencies(MavenProject, RepositorySystemSession)}
 *//*  w ww  .java 2 s .  c  o  m*/
private DependencyResolutionResult resolveDependencies(MavenProject project, RepositorySystemSession session) {
    DependencyResolutionResult resolutionResult;

    try {
        ProjectDependenciesResolver dependencyResolver = getComponent(ProjectDependenciesResolver.class);
        DefaultDependencyResolutionRequest resolution = new DefaultDependencyResolutionRequest(project,
                session);
        resolutionResult = dependencyResolver.resolve(resolution);
    } catch (DependencyResolutionException e) {
        resolutionResult = e.getResult();
    }

    Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
    if (resolutionResult.getDependencyGraph() != null) {
        RepositoryUtils.toArtifacts(artifacts, resolutionResult.getDependencyGraph().getChildren(),
                Collections.singletonList(project.getArtifact().getId()), null);

        // Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved or not
        LocalRepositoryManager lrm = session.getLocalRepositoryManager();
        for (Artifact artifact : artifacts) {
            if (!artifact.isResolved()) {
                String path = lrm.getPathForLocalArtifact(RepositoryUtils.toArtifact(artifact));
                artifact.setFile(new File(lrm.getRepository().getBasedir(), path));
            }
        }
    }
    project.setResolvedArtifacts(artifacts);
    project.setArtifacts(artifacts);

    return resolutionResult;
}

From source file:org.jvnet.hudson.plugins.mavendepsupdate.MavenUpdateChecker.java

License:Apache License

public MavenUpdateCheckerResult call() throws IOException {
    ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();

    try {/*w w w  . ja va  2s .  c om*/

        PluginFirstClassLoader pluginFirstClassLoader = getPluginFirstClassLoader();
        Thread.currentThread().setContextClassLoader(pluginFirstClassLoader);
        String classLoaderName = getClass().getClassLoader().toString();

        mavenUpdateCheckerResult.addDebugLine(classLoaderName);
        PlexusContainer plexusContainer = getPlexusContainer(pluginFirstClassLoader);

        Thread.currentThread().setContextClassLoader(plexusContainer.getContainerRealm());
        mavenUpdateCheckerResult.addDebugLine("ok for new DefaultPlexusContainer( conf ) ");
        mavenUpdateCheckerResult.addDebugLine("Thread.currentThread().getContextClassLoader() "
                + Thread.currentThread().getContextClassLoader());
        mavenUpdateCheckerResult.addDebugLine("Thread.currentThread().getContextClassLoader().parent "
                + (Thread.currentThread().getContextClassLoader().getParent() == null ? "null"
                        : Thread.currentThread().getContextClassLoader().getParent().toString()));
        mavenUpdateCheckerResult.addDebugLine(
                "classLoader  urls " + Arrays.asList(plexusContainer.getContainerRealm().getURLs()));
        ProjectBuilder projectBuilder = plexusContainer.lookup(ProjectBuilder.class);

        // FIXME load userProperties from the job
        Properties userProperties = this.userProperties == null ? new Properties() : this.userProperties;

        userProperties.put("java.home", jdkHome);

        ProjectBuildingRequest projectBuildingRequest = getProjectBuildingRequest(userProperties,
                plexusContainer);

        // check plugins too
        projectBuildingRequest.setProcessPlugins(true);
        // force snapshots update

        projectBuildingRequest.setResolveDependencies(true);

        List<ProjectBuildingResult> projectBuildingResults = projectBuilder
                .build(Arrays.asList(new File(rootPomPath)), true, projectBuildingRequest);

        ProjectDependenciesResolver projectDependenciesResolver = plexusContainer
                .lookup(ProjectDependenciesResolver.class);

        List<MavenProject> mavenProjects = new ArrayList<MavenProject>(projectBuildingResults.size());

        for (ProjectBuildingResult projectBuildingResult : projectBuildingResults) {
            mavenProjects.add(projectBuildingResult.getProject());
        }

        ProjectSorter projectSorter = new ProjectSorter(mavenProjects);

        // use the projects reactor model as a workspaceReader
        // if reactors are not available remotely dependencies resolve will failed
        // due to artifact not found

        final Map<String, MavenProject> projectMap = getProjectMap(mavenProjects);
        WorkspaceReader reactorRepository = new ReactorReader(projectMap);

        MavenRepositorySystemSession mavenRepositorySystemSession = (MavenRepositorySystemSession) projectBuildingRequest
                .getRepositorySession();

        mavenRepositorySystemSession.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS);

        mavenRepositorySystemSession.setWorkspaceReader(reactorRepository);

        MavenPluginManager mavenPluginManager = plexusContainer.lookup(MavenPluginManager.class);

        for (MavenProject mavenProject : projectSorter.getSortedProjects()) {
            LOGGER.info("resolve dependencies for project " + mavenProject.getId());

            DefaultDependencyResolutionRequest dependencyResolutionRequest = new DefaultDependencyResolutionRequest(
                    mavenProject, mavenRepositorySystemSession);

            try {
                DependencyResolutionResult dependencyResolutionResult = projectDependenciesResolver
                        .resolve(dependencyResolutionRequest);
            } catch (DependencyResolutionException e) {
                mavenUpdateCheckerResult.addDebugLine(e.getMessage());
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                mavenUpdateCheckerResult.addDebugLine("skip:" + sw.toString());
            }
            if (checkPlugins) {
                for (Plugin plugin : mavenProject.getBuildPlugins()) {
                    // only for SNAPSHOT
                    if (StringUtils.endsWith(plugin.getVersion(), "SNAPSHOT")) {
                        mavenPluginManager.getPluginDescriptor(plugin,
                                mavenProject.getRemotePluginRepositories(), mavenRepositorySystemSession);
                    }
                }
            }

        }
        SnapshotTransfertListener snapshotTransfertListener = (SnapshotTransfertListener) projectBuildingRequest
                .getRepositorySession().getTransferListener();

        if (snapshotTransfertListener.isSnapshotDownloaded()) {
            mavenUpdateCheckerResult.addFilesUpdatedNames(snapshotTransfertListener.getSnapshots());
        }

    } catch (Exception e) {
        mavenUpdateCheckerResult.addDebugLine(e.getMessage());
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        mavenUpdateCheckerResult.addDebugLine("skip:" + sw.toString());
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassLoader);
    }
    return mavenUpdateCheckerResult;
}

From source file:org.phpmaven.pear.impl.PearUtility.java

License:Apache License

private void installFromMavenRepository(final String groupId, final String artifactId, final String version,
        final boolean ignoreCore) throws PhpException {
    final Artifact artifact = this.resolveArtifact(groupId, artifactId, version, "pom", null);
    final File pomFile = artifact.getFile();
    final ProjectBuildingRequest pbr = new DefaultProjectBuildingRequest(
            this.session.getProjectBuildingRequest());
    try {//  ww  w . j av a 2s.co m
        pbr.setProcessPlugins(false);
        final ProjectBuildingResult pbres = this.projectBuilder.build(pomFile, pbr);
        final MavenProject project = pbres.getProject();
        final DependencyResolutionRequest drr = new DefaultDependencyResolutionRequest(project,
                session.getRepositorySession());
        final DependencyResolutionResult drres = this.dependencyResolver.resolve(drr);
        // dependencies may be duplicate. ensure we have only one version (the newest).
        final Map<String, org.sonatype.aether.graph.Dependency> deps = new HashMap<String, org.sonatype.aether.graph.Dependency>();
        for (final org.sonatype.aether.graph.Dependency dep : drres.getDependencies()) {
            final String key = dep.getArtifact().getGroupId() + ":" + dep.getArtifact().getArtifactId();
            if (!deps.containsKey(key)) {
                deps.put(key, dep);
            } else {
                final org.sonatype.aether.graph.Dependency dep2 = deps.get(key);
                final org.sonatype.aether.version.Version ver = SCHEME
                        .parseVersion(dep.getArtifact().getVersion());
                final org.sonatype.aether.version.Version ver2 = SCHEME
                        .parseVersion(dep2.getArtifact().getVersion());
                if (ver2.compareTo(ver) < 0) {
                    deps.put(key, dep);
                }
            }
        }
        final List<File> filesToInstall = new ArrayList<File>();
        // first the dependencies
        // this.log.debug(
        // "resolving tgz and project for " +
        // groupId + ":" +
        // artifactId + ":" +
        // version);
        this.resolveTgz(groupId, artifactId, version, filesToInstall, ignoreCore);
        this.resolveChannels(project);
        for (final org.sonatype.aether.graph.Dependency dep : deps.values()) {
            // this.log.debug(
            // "resolving tgz and project for " +
            // dep.getArtifact().getGroupId() + ":" +
            // dep.getArtifact().getArtifactId() + ":" +
            // dep.getArtifact().getVersion());
            if (ignoreCore && this.isMavenCorePackage(dep.getArtifact().getGroupId(),
                    dep.getArtifact().getArtifactId())) {
                // ignore core packages
                continue;
            }
            this.resolveTgz(dep.getArtifact().getGroupId(), dep.getArtifact().getArtifactId(),
                    dep.getArtifact().getVersion(), filesToInstall, ignoreCore);
            final Artifact depPomArtifact = this.resolveArtifact(dep.getArtifact().getGroupId(),
                    dep.getArtifact().getArtifactId(), dep.getArtifact().getVersion(), "pom", null);
            final File depPomFile = depPomArtifact.getFile();
            final ProjectBuildingResult depPbres = this.projectBuilder.build(depPomFile, pbr);
            final MavenProject depProject = depPbres.getProject();
            this.resolveChannels(depProject);
        }

        Collections.reverse(filesToInstall);
        for (final File file : filesToInstall) {
            this.executePearCmd("install --force --nodeps \"" + file.getAbsolutePath() + "\"");
        }
    } catch (final InvalidVersionSpecificationException ex) {
        throw new PhpCoreException(ex);
    } catch (final ProjectBuildingException ex) {
        throw new PhpCoreException(ex);
    } catch (final DependencyResolutionException ex) {
        throw new PhpCoreException(ex);
    }
}

From source file:org.sourcepit.b2.internal.maven.DefaultModuleArtifactResolver.java

License:Apache License

private SetMultimap<Artifact, String> resolveModuleDependencies(final MavenSession session,
        MavenProject project, final String scope) {
    final Map<DependencyNode, String> moduleNodeToClassifiers = new LinkedHashMap<DependencyNode, String>();
    final DependencyFilter resolutionFilter = new DependencyFilter() {
        public boolean accept(DependencyNode node, List<DependencyNode> parents) {
            Artifact moduleArtifact = getModuleArtifact(node);
            if (moduleArtifact != null) {
                final String classifier = moduleArtifact.getClassifier();

                final Artifact newArtifact;
                newArtifact = new DefaultArtifact(moduleArtifact.getGroupId(), moduleArtifact.getArtifactId(),
                        "", moduleArtifact.getExtension(), moduleArtifact.getVersion(),
                        moduleArtifact.getProperties(), moduleArtifact.getFile());
                node.setArtifact(newArtifact);

                moduleNodeToClassifiers.put(node, classifier);
            }/*from  w ww  .  j  a  v  a 2 s.  c  o  m*/
            return true;
        }

        private Artifact getModuleArtifact(DependencyNode node) {
            if (node.getDependency() != null) {
                final Dependency dependency = node.getDependency();
                if (dependency.getArtifact() != null) {
                    final Artifact artifact = dependency.getArtifact();
                    if ("module".equals(artifact.getExtension())) {
                        return artifact;
                    }
                }
            }
            return null;
        }
    };

    final DependencySelector dependencySelector = createDependencySelector(scope);

    final AbstractForwardingRepositorySystemSession systemSession = new AbstractForwardingRepositorySystemSession() {
        @Override
        public DependencySelector getDependencySelector() {
            return dependencySelector;
        }

        @Override
        protected RepositorySystemSession getSession() {
            return session.getRepositorySession();
        }
    };

    final DefaultDependencyResolutionRequest request;
    request = new DefaultDependencyResolutionRequest(project, systemSession);
    request.setResolutionFilter(resolutionFilter);

    try {
        dependenciesResolver.resolve(request);
    } catch (DependencyResolutionException e) {
        throw Exceptions.pipe(e);
    }

    final SetMultimap<Artifact, String> artifactToClassifiers = LinkedHashMultimap.create();
    for (Entry<DependencyNode, String> entry : moduleNodeToClassifiers.entrySet()) {
        DependencyNode dependencyNode = entry.getKey();
        artifactToClassifiers.get(dependencyNode.getDependency().getArtifact()).add(entry.getValue());
    }
    return artifactToClassifiers;
}