Example usage for org.apache.maven.project DependencyResolutionResult getDependencies

List of usage examples for org.apache.maven.project DependencyResolutionResult getDependencies

Introduction

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

Prototype

List<Dependency> getDependencies();

Source Link

Document

Gets the transitive dependencies of the project that were not excluded by DependencyResolutionRequest#getResolutionFilter() .

Usage

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");
    }//from  www.  j  a  va 2  s .co m
    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:org.jboss.forge.addon.maven.projects.facets.MavenDependencyFacet.java

License:Open Source License

@Override
public List<Dependency> getEffectiveDependencies() {
    List<Dependency> result = new ArrayList<>();

    MavenFacetImpl maven = getFaceted().getFacet(MavenFacetImpl.class);
    try {//  www  . j av a2 s.  co  m
        ProjectBuildingResult projectBuildingResult = maven.getProjectBuildingResult();
        DependencyResolutionResult dependencyResolutionResult = projectBuildingResult
                .getDependencyResolutionResult();
        List<Dependency> deps = MavenDependencyAdapter
                .fromAetherList(dependencyResolutionResult.getDependencies());

        for (Dependency dependency : deps) {
            result.add(resolveProperties(dependency));
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Could not resolve managed dependencies in project ["
                + maven.getModelResource().getFullyQualifiedName() + "]. ", e);
    }

    return result;
}

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

License:Apache License

@Nonnull
public MavenExecutionResult doResolveProject(@Nonnull final File file,
        @Nonnull final List<String> activeProfiles, @Nonnull final List<String> inactiveProfiles,
        final List<ResolutionListener> listeners) throws RemoteException {
    final MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles,
            Collections.<String>emptyList());

    request.setUpdateSnapshots(myAlwaysUpdateSnapshots);

    final AtomicReference<MavenExecutionResult> ref = new AtomicReference<MavenExecutionResult>();

    executeWithMavenSession(request, new Runnable() {
        @Override//from w w w . j av a 2 s .c  o  m
        public void run() {
            try {
                // copied from DefaultMavenProjectBuilder.buildWithDependencies
                ProjectBuilder builder = getComponent(ProjectBuilder.class);

                CustomMaven3ModelInterpolator2 modelInterpolator = (CustomMaven3ModelInterpolator2) getComponent(
                        ModelInterpolator.class);

                String savedLocalRepository = modelInterpolator.getLocalRepository();
                modelInterpolator.setLocalRepository(request.getLocalRepositoryPath().getAbsolutePath());
                List<ProjectBuildingResult> results;

                try {
                    // Don't use build(File projectFile, ProjectBuildingRequest request) , because it don't use cache !!!!!!!! (see http://devnet.jetbrains.com/message/5500218)
                    results = builder.build(Collections.singletonList(new File(file.getPath())), false,
                            request.getProjectBuildingRequest());
                } finally {
                    modelInterpolator.setLocalRepository(savedLocalRepository);
                }

                ProjectBuildingResult buildingResult = results.get(0);

                MavenProject project = buildingResult.getProject();

                RepositorySystemSession repositorySession = getComponent(LegacySupport.class)
                        .getRepositorySession();
                if (repositorySession instanceof DefaultRepositorySystemSession) {
                    ((DefaultRepositorySystemSession) repositorySession)
                            .setTransferListener(new Maven30TransferListenerAdapter(myCurrentIndicator));

                    if (myWorkspaceMap != null) {
                        ((DefaultRepositorySystemSession) repositorySession)
                                .setWorkspaceReader(new Maven30WorkspaceReader(myWorkspaceMap));
                    }
                }

                List<Exception> exceptions = new ArrayList<Exception>();
                loadExtensions(project, exceptions);

                //Artifact projectArtifact = project.getArtifact();
                //Map managedVersions = project.getManagedVersionMap();
                //ArtifactMetadataSource metadataSource = getComponent(ArtifactMetadataSource.class);
                project.setDependencyArtifacts(
                        project.createArtifacts(getComponent(ArtifactFactory.class), null, null));
                //

                if (USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING) {
                    ArtifactResolutionRequest resolutionRequest = new ArtifactResolutionRequest();
                    resolutionRequest.setArtifactDependencies(project.getDependencyArtifacts());
                    resolutionRequest.setArtifact(project.getArtifact());
                    resolutionRequest.setManagedVersionMap(project.getManagedVersionMap());
                    resolutionRequest.setLocalRepository(myLocalRepository);
                    resolutionRequest.setRemoteRepositories(project.getRemoteArtifactRepositories());
                    resolutionRequest.setListeners(listeners);

                    resolutionRequest.setResolveRoot(false);
                    resolutionRequest.setResolveTransitively(true);

                    ArtifactResolver resolver = getComponent(ArtifactResolver.class);
                    ArtifactResolutionResult result = resolver.resolve(resolutionRequest);

                    project.setArtifacts(result.getArtifacts());
                    // end copied from DefaultMavenProjectBuilder.buildWithDependencies
                    ref.set(new MavenExecutionResult(project, exceptions));
                } else {
                    final DependencyResolutionResult dependencyResolutionResult = resolveDependencies(project,
                            repositorySession);
                    final List<Dependency> dependencies = dependencyResolutionResult.getDependencies();

                    Set<Artifact> artifacts = new LinkedHashSet<Artifact>(dependencies.size());
                    for (Dependency dependency : dependencies) {
                        final Artifact artifact = RepositoryUtils.toArtifact(dependency.getArtifact());
                        artifact.setScope(dependency.getScope());
                        artifact.setOptional(dependency.isOptional());
                        artifacts.add(artifact);
                        resolveAsModule(artifact);
                    }

                    project.setArtifacts(artifacts);
                    ref.set(new MavenExecutionResult(project, dependencyResolutionResult, exceptions));
                }
            } catch (Exception e) {
                ref.set(handleException(e));
            }
        }
    });

    return ref.get();
}

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

License:Apache License

@Nonnull
public MavenExecutionResult doResolveProject(@Nonnull final File file,
        @Nonnull final List<String> activeProfiles, @Nonnull final List<String> inactiveProfiles,
        final List<ResolutionListener> listeners) throws RemoteException {
    final MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles,
            Collections.<String>emptyList());

    request.setUpdateSnapshots(myAlwaysUpdateSnapshots);

    final AtomicReference<MavenExecutionResult> ref = new AtomicReference<MavenExecutionResult>();

    executeWithMavenSession(request, new Runnable() {
        @Override//from   ww w  .  j  a  v  a 2  s  .  c  o  m
        public void run() {
            try {
                // copied from DefaultMavenProjectBuilder.buildWithDependencies
                ProjectBuilder builder = getComponent(ProjectBuilder.class);

                CustomMaven3ModelInterpolator2 modelInterpolator = (CustomMaven3ModelInterpolator2) getComponent(
                        ModelInterpolator.class);

                String savedLocalRepository = modelInterpolator.getLocalRepository();
                modelInterpolator.setLocalRepository(request.getLocalRepositoryPath().getAbsolutePath());
                List<ProjectBuildingResult> results;

                try {
                    // Don't use build(File projectFile, ProjectBuildingRequest request) , because it don't use cache !!!!!!!! (see http://devnet.jetbrains.com/message/5500218)
                    results = builder.build(Collections.singletonList(new File(file.getPath())), false,
                            request.getProjectBuildingRequest());
                } finally {
                    modelInterpolator.setLocalRepository(savedLocalRepository);
                }

                ProjectBuildingResult buildingResult = results.get(0);

                MavenProject project = buildingResult.getProject();

                RepositorySystemSession repositorySession = getComponent(LegacySupport.class)
                        .getRepositorySession();
                if (repositorySession instanceof DefaultRepositorySystemSession) {
                    ((DefaultRepositorySystemSession) repositorySession)
                            .setTransferListener(new TransferListenerAdapter(myCurrentIndicator));

                    if (myWorkspaceMap != null) {
                        ((DefaultRepositorySystemSession) repositorySession)
                                .setWorkspaceReader(new Maven32WorkspaceReader(myWorkspaceMap));
                    }
                }

                List<Exception> exceptions = new ArrayList<Exception>();
                loadExtensions(project, exceptions);

                //Artifact projectArtifact = project.getArtifact();
                //Map managedVersions = project.getManagedVersionMap();
                //ArtifactMetadataSource metadataSource = getComponent(ArtifactMetadataSource.class);
                project.setDependencyArtifacts(
                        project.createArtifacts(getComponent(ArtifactFactory.class), null, null));
                //

                if (USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING) {
                    ArtifactResolutionRequest resolutionRequest = new ArtifactResolutionRequest();
                    resolutionRequest.setArtifactDependencies(project.getDependencyArtifacts());
                    resolutionRequest.setArtifact(project.getArtifact());
                    resolutionRequest.setManagedVersionMap(project.getManagedVersionMap());
                    resolutionRequest.setLocalRepository(myLocalRepository);
                    resolutionRequest.setRemoteRepositories(project.getRemoteArtifactRepositories());
                    resolutionRequest.setListeners(listeners);

                    resolutionRequest.setResolveRoot(false);
                    resolutionRequest.setResolveTransitively(true);

                    ArtifactResolver resolver = getComponent(ArtifactResolver.class);
                    ArtifactResolutionResult result = resolver.resolve(resolutionRequest);

                    project.setArtifacts(result.getArtifacts());
                    // end copied from DefaultMavenProjectBuilder.buildWithDependencies
                    ref.set(new MavenExecutionResult(project, exceptions));
                } else {
                    final DependencyResolutionResult dependencyResolutionResult = resolveDependencies(project,
                            repositorySession);
                    final List<Dependency> dependencies = dependencyResolutionResult.getDependencies();

                    Set<Artifact> artifacts = new LinkedHashSet<Artifact>(dependencies.size());
                    for (Dependency dependency : dependencies) {
                        final Artifact artifact = RepositoryUtils.toArtifact(dependency.getArtifact());
                        artifact.setScope(dependency.getScope());
                        artifact.setOptional(dependency.isOptional());
                        artifacts.add(artifact);
                        resolveAsModule(artifact);
                    }

                    project.setArtifacts(artifacts);
                    ref.set(new MavenExecutionResult(project, dependencyResolutionResult, exceptions));
                }
            } catch (Exception e) {
                ref.set(handleException(e));
            }
        }
    });

    return ref.get();
}

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 {/*w  w  w  .  ja v  a2  s .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.springframework.cloud.function.compiler.java.DependencyResolver.java

License:Apache License

public List<Dependency> dependencies(final Resource resource, final Properties properties) {
    initialize();/*from ww w.  j a  va  2s.  c om*/
    try {
        ProjectBuildingRequest request = getProjectBuildingRequest(properties);
        request.setResolveDependencies(true);
        synchronized (DependencyResolver.class) {
            ProjectBuildingResult result = this.projectBuilder
                    .build(new PropertiesModelSource(properties, resource), request);
            DependencyResolver.globals = null;
            DependencyResolutionResult dependencies = result.getDependencyResolutionResult();
            if (!dependencies.getUnresolvedDependencies().isEmpty()) {
                StringBuilder builder = new StringBuilder();
                for (Dependency dependency : dependencies.getUnresolvedDependencies()) {
                    List<Exception> errors = dependencies.getResolutionErrors(dependency);
                    for (Exception exception : errors) {
                        if (builder.length() > 0) {
                            builder.append("\n");
                        }
                        builder.append(exception.getMessage());
                    }
                }
                throw new RuntimeException(builder.toString());
            }
            return runtime(dependencies.getDependencies());
        }
    } catch (ProjectBuildingException | NoLocalRepositoryManagerException e) {
        throw new IllegalStateException("Cannot build model", e);
    }
}

From source file:org.wildfly.swarm.plugin.MavenDependenciesResolver.java

License:Apache License

public Set<MavenDependencyData> gatherTransitiveDependencies(MavenProject fractionProject)
        throws DependencyResolutionException, ProjectBuildingException, IOException {

    MavenProject project = mockProjectDependingOn(fractionProject);

    DefaultDependencyResolutionRequest request = new DefaultDependencyResolutionRequest();
    request.setMavenProject(project);// w  w w. j  a  va  2  s  .c  o  m
    request.setRepositorySession(session);
    DependencyResolutionResult resolutionResult = dependencyResolver.resolve(request);

    List<Dependency> dependencies = resolutionResult.getDependencies();
    Set<MavenDependencyData> result = dependencies.stream()
            .filter(d -> d.getArtifact().getFile().getName().endsWith(".jar"))
            .filter(d -> appropriateScopes.contains(d.getScope()))
            .map(org.eclipse.aether.graph.Dependency::getArtifact).map(MavenDependencyData::new)
            .collect(Collectors.toSet());

    result.forEach(this::addCheckSum);
    return result;
}