Search in sources :

Example 6 with ProjectBuildingResult

use of org.apache.maven.project.ProjectBuildingResult in project maven-archetype by apache.

the class ArchetyperRoundtripIT method testArchetyper.

public void testArchetyper() throws Exception {
    ArchetypeManager archetype = (ArchetypeManager) lookup(ArchetypeManager.ROLE);
    ProjectBuilder projectBuilder = lookup(ProjectBuilder.class);
    ArtifactRepository localRepository = createRepository(new File(getBasedir(), "target" + File.separator + "test-classes" + File.separator + "repositories" + File.separator + "local").toURI().toURL().toExternalForm(), "local-repo");
    ArtifactRepository centralRepository = createRepository(new File(getBasedir(), "target" + File.separator + "test-classes" + File.separator + "repositories" + File.separator + "central").toURI().toURL().toExternalForm(), "central-repo");
    // (1) create a project from scratch
    // (2) create an archetype from the project
    // (3) create our own archetype catalog properties in memory
    // (4) create our own archetype catalog describing the archetype we just created
    // (5) deploy the archetype we just created
    // (6) create a project form the archetype we just created
    // ------------------------------------------------------------------------
    // 
    // ------------------------------------------------------------------------
    // (1) create a project from scratch
    // File sourceProject = new File( getBasedir(  ), "target/test-classes/projects/roundtrip-1-project" );
    File workingProject = new File(getBasedir(), "target" + File.separator + "test-classes" + File.separator + "projects" + File.separator + "roundtrip-1-project");
    FileUtils.forceDelete(new File(workingProject, "target"));
    // (2) create an archetype from the project
    File pom = new File(workingProject, "pom.xml");
    ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest();
    MavenRepositorySystemSession repositorySession = new MavenRepositorySystemSession();
    repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManager(localRepository.getBasedir()));
    buildingRequest.setRepositorySession(repositorySession);
    MavenProject project = projectBuilder.build(pom, buildingRequest).getProject();
    Properties properties = new Properties();
    properties.setProperty("someProperty", "someValue");
    ArchetypeCreationRequest acr = new ArchetypeCreationRequest().setProject(project).setLocalRepository(localRepository).setProperties(properties).setPostPhase("package");
    ArchetypeCreationResult creationResult = archetype.createArchetypeFromProject(acr);
    if (creationResult.getCause() != null) {
        throw creationResult.getCause();
    }
    // (3) create our own archetype catalog properties in memory
    File catalogDirectory = new File(getBasedir(), "target" + File.separator + "catalog");
    catalogDirectory.mkdirs();
    File catalogFile = new File(catalogDirectory, "archetype-catalog.xml");
    // (5) install the archetype we just created
    File generatedArchetypeDirectory = new File(project.getBasedir(), "target" + File.separator + "generated-sources" + File.separator + "archetype");
    File generatedArchetypePom = new File(generatedArchetypeDirectory, "pom.xml");
    ProjectBuildingResult buildingResult = projectBuilder.build(generatedArchetypePom, buildingRequest);
    MavenProject generatedArchetypeProject = projectBuilder.build(generatedArchetypePom, buildingRequest).getProject();
    ModelInterpolator modelInterpolator = (ModelInterpolator) lookup(ModelInterpolator.ROLE);
    Model generatedArchetypeModel = modelInterpolator.interpolate(generatedArchetypeProject.getModel(), generatedArchetypePom.getParentFile(), new DefaultProjectBuilderConfiguration(), true);
    File archetypeDirectory = new File(generatedArchetypeDirectory, "src" + File.separator + "main" + File.separator + "resources");
    File archetypeArchive = archetype.archiveArchetype(archetypeDirectory, new File(generatedArchetypeModel.getBuild().getDirectory()), generatedArchetypeModel.getBuild().getFinalName());
    String baseName = StringUtils.replace(generatedArchetypeProject.getGroupId(), ".", File.separator) + File.separator + generatedArchetypeProject.getArtifactId() + File.separator + generatedArchetypeProject.getVersion() + File.separator + generatedArchetypeProject.getBuild().getFinalName();
    File archetypeInRepository = new File(centralRepository.getBasedir(), baseName + ".jar");
    File archetypePomInRepository = new File(centralRepository.getBasedir(), baseName + ".pom");
    archetypeInRepository.getParentFile().mkdirs();
    FileUtils.copyFile(archetypeArchive, archetypeInRepository);
    FileUtils.copyFile(generatedArchetypePom, archetypePomInRepository);
    // (4) create our own archetype catalog describing the archetype we just created
    ArchetypeCatalog catalog = new ArchetypeCatalog();
    Archetype generatedArchetype = new Archetype();
    generatedArchetype.setGroupId(generatedArchetypeProject.getGroupId());
    generatedArchetype.setArtifactId(generatedArchetypeProject.getArtifactId());
    generatedArchetype.setVersion(generatedArchetypeProject.getVersion());
    generatedArchetype.setRepository("http://localhost:" + port + "/repo");
    catalog.addArchetype(generatedArchetype);
    ArchetypeCatalogXpp3Writer catalogWriter = new ArchetypeCatalogXpp3Writer();
    Writer writer = new FileWriter(catalogFile);
    catalogWriter.write(writer, catalog);
    IOUtils.closeQuietly(writer);
    // (6) create a project form the archetype we just created
    String outputDirectory = new File(getBasedir(), "target" + File.separator + "test-classes" + File.separator + "projects" + File.separator + "roundtrip-1-recreatedproject").getAbsolutePath();
    FileUtils.forceDelete(outputDirectory);
    ArchetypeGenerationRequest agr = new ArchetypeGenerationRequest().setArchetypeGroupId(generatedArchetypeProject.getGroupId()).setArchetypeArtifactId(generatedArchetypeProject.getArtifactId()).setArchetypeVersion(generatedArchetypeProject.getVersion()).setGroupId("com.mycompany").setArtifactId("myapp").setVersion("1.0-SNAPSHOT").setPackage("com.mycompany.myapp").setProperties(properties).setOutputDirectory(outputDirectory).setLocalRepository(localRepository).setArchetypeRepository("http://localhost:" + port + "/repo/").setProjectBuildingRequest(buildingRequest);
    ArchetypeGenerationResult generationResult = archetype.generateProjectFromArchetype(agr);
    if (generationResult.getCause() != null) {
        throw generationResult.getCause();
    }
    // ASSERT symbol_pound replacement (archetype-180 archetype-183)
    String content = FileUtils.fileRead(outputDirectory + File.separator + "myapp" + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + "com" + File.separator + "mycompany" + File.separator + "myapp" + File.separator + "App.java");
    System.err.println("content=" + content);
    assertTrue(content.indexOf("//A   #\\{some}") > 0);
    assertTrue(content.indexOf("//B   #{some}") > 0);
    assertTrue(content.indexOf("//C   #{some other}") > 0);
    assertTrue(content.indexOf("//D   \\#{some other}") > 0);
    assertTrue(content.indexOf("//E   #{}") > 0);
    assertTrue(content.indexOf("//F   {some}") > 0);
    assertTrue(content.indexOf("//G   ${someOtherProperty}") > 0);
    assertTrue(content.indexOf("//H   ${someValue}") > 0);
    assertTrue(content.indexOf("/*") > 0);
    assertTrue(content.indexOf("  A   #\\{some}") > 0);
    assertTrue(content.indexOf("  B   #{some}") > 0);
    assertTrue(content.indexOf("  C   #{some other}") > 0);
    assertTrue(content.indexOf("  D   \\#{some other}") > 0);
    assertTrue(content.indexOf("  E   #{}") > 0);
    assertTrue(content.indexOf("  F   {some}") > 0);
    assertTrue(content.indexOf("  G   ${someOtherProperty}") > 0);
    assertTrue(content.indexOf("  H   ${someValue}") > 0);
// Assert symbol_dollar archetype-138
}
Also used : ModelInterpolator(org.apache.maven.project.interpolation.ModelInterpolator) Archetype(org.apache.maven.archetype.catalog.Archetype) DefaultProjectBuilderConfiguration(org.apache.maven.project.DefaultProjectBuilderConfiguration) ArchetypeCatalogXpp3Writer(org.apache.maven.archetype.catalog.io.xpp3.ArchetypeCatalogXpp3Writer) FileWriter(java.io.FileWriter) ArchetypeGenerationRequest(org.apache.maven.archetype.ArchetypeGenerationRequest) ArtifactRepository(org.apache.maven.artifact.repository.ArtifactRepository) MavenArtifactRepository(org.apache.maven.artifact.repository.MavenArtifactRepository) MavenRepositorySystemSession(org.apache.maven.repository.internal.MavenRepositorySystemSession) Properties(java.util.Properties) ArchetypeCreationResult(org.apache.maven.archetype.ArchetypeCreationResult) ArchetypeManager(org.apache.maven.archetype.ArchetypeManager) ProjectBuildingRequest(org.apache.maven.project.ProjectBuildingRequest) DefaultProjectBuildingRequest(org.apache.maven.project.DefaultProjectBuildingRequest) SimpleLocalRepositoryManager(org.sonatype.aether.impl.internal.SimpleLocalRepositoryManager) ProjectBuilder(org.apache.maven.project.ProjectBuilder) MavenProject(org.apache.maven.project.MavenProject) ProjectBuildingResult(org.apache.maven.project.ProjectBuildingResult) Model(org.apache.maven.model.Model) ArchetypeGenerationResult(org.apache.maven.archetype.ArchetypeGenerationResult) ArchetypeCreationRequest(org.apache.maven.archetype.ArchetypeCreationRequest) ArchetypeCatalog(org.apache.maven.archetype.catalog.ArchetypeCatalog) File(java.io.File) DefaultProjectBuildingRequest(org.apache.maven.project.DefaultProjectBuildingRequest) FileWriter(java.io.FileWriter) Writer(java.io.Writer) ArchetypeCatalogXpp3Writer(org.apache.maven.archetype.catalog.io.xpp3.ArchetypeCatalogXpp3Writer)

Example 7 with ProjectBuildingResult

use of org.apache.maven.project.ProjectBuildingResult in project drools by kiegroup.

the class MavenEmbedder method readProjects.

public List<MavenProject> readProjects(File mavenProject, boolean recursive) throws ProjectBuildingException, MavenEmbedderException {
    ClassLoader originalCl = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(componentProvider.getSystemClassLoader());
        List<ProjectBuildingResult> results = buildProjects(mavenProject, recursive);
        List<MavenProject> projects = new ArrayList<MavenProject>(results.size());
        for (ProjectBuildingResult result : results) {
            projects.add(result.getProject());
        }
        return projects;
    } finally {
        Thread.currentThread().setContextClassLoader(originalCl);
    }
}
Also used : MavenProject(org.apache.maven.project.MavenProject) ProjectBuildingResult(org.apache.maven.project.ProjectBuildingResult) ArrayList(java.util.ArrayList)

Example 8 with ProjectBuildingResult

use of org.apache.maven.project.ProjectBuildingResult in project drools by kiegroup.

the class MavenEmbedder method readProject.

// ----------------------------------------------------------------------
// Project
// ----------------------------------------------------------------------
public MavenProject readProject(final InputStream mavenProjectStream) throws ProjectBuildingException, MavenEmbedderException {
    ModelSource modelSource = new ModelSource() {

        @Override
        public InputStream getInputStream() {
            return mavenProjectStream;
        }

        @Override
        public String getLocation() {
            return "";
        }
    };
    ClassLoader originalCl = Thread.currentThread().getContextClassLoader();
    try {
        org.eclipse.aether.artifact.Artifact lastArtifact = null;
        do {
            Thread.currentThread().setContextClassLoader(componentProvider.getSystemClassLoader());
            ProjectBuilder projectBuilder = componentProvider.lookup(ProjectBuilder.class);
            // BZ-1007894: Check if added dependencies are resolvable.
            ProjectBuildingResult result = projectBuilder.build(modelSource, getProjectBuildingRequest());
            if (result != null && result.getDependencyResolutionResult() != null && !result.getDependencyResolutionResult().getCollectionErrors().isEmpty()) {
                // A dependency resolution error has been produced. It can contains some error. Throw the first one to the client, so the user will fix every one sequentially.
                final Exception depedencyResolutionException = result.getDependencyResolutionResult().getCollectionErrors().get(0);
                if (depedencyResolutionException instanceof ArtifactDescriptorException) {
                    final org.eclipse.aether.artifact.Artifact artifact = ((ArtifactDescriptorException) depedencyResolutionException).getResult().getArtifact();
                    if (!artifact.equals(lastArtifact)) {
                        tryRemoveLocalArtifact(artifact);
                        lastArtifact = artifact;
                        continue;
                    }
                }
                if (depedencyResolutionException != null) {
                    throw new MavenEmbedderException(depedencyResolutionException.getMessage(), depedencyResolutionException);
                }
            }
            return (result == null || result.getProject() == null) ? null : result.getProject();
        } while (true);
    } catch (ComponentLookupException e) {
        throw new MavenEmbedderException(e.getMessage(), e);
    } finally {
        Thread.currentThread().setContextClassLoader(originalCl);
        try {
            mavenProjectStream.close();
        } catch (IOException e) {
        }
    }
}
Also used : ProjectBuilder(org.apache.maven.project.ProjectBuilder) ProjectBuildingResult(org.apache.maven.project.ProjectBuildingResult) Artifact(org.eclipse.aether.artifact.Artifact) ComponentLookupException(org.codehaus.plexus.component.repository.exception.ComponentLookupException) IOException(java.io.IOException) ArtifactDescriptorException(org.eclipse.aether.resolution.ArtifactDescriptorException) ModelSource(org.apache.maven.model.building.ModelSource) SettingsBuildingException(org.apache.maven.settings.building.SettingsBuildingException) ComponentLookupException(org.codehaus.plexus.component.repository.exception.ComponentLookupException) ArtifactDescriptorException(org.eclipse.aether.resolution.ArtifactDescriptorException) ProjectBuildingException(org.apache.maven.project.ProjectBuildingException) InvalidRepositoryException(org.apache.maven.artifact.InvalidRepositoryException) IOException(java.io.IOException) MavenExecutionRequestPopulationException(org.apache.maven.execution.MavenExecutionRequestPopulationException)

Example 9 with ProjectBuildingResult

use of org.apache.maven.project.ProjectBuildingResult in project che by eclipse.

the class MavenServerImpl method internalResolveProject.

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, () -> {
        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();
}
Also used : RepositorySystemSession(org.eclipse.aether.RepositorySystemSession) DefaultRepositorySystemSession(org.eclipse.aether.DefaultRepositorySystemSession) LegacySupport(org.apache.maven.plugin.LegacySupport) MavenExecutionRequest(org.apache.maven.execution.MavenExecutionRequest) DefaultMavenExecutionRequest(org.apache.maven.execution.DefaultMavenExecutionRequest) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProjectBuildingException(org.apache.maven.project.ProjectBuildingException) InitializationException(org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException) ModelInterpolationException(org.apache.maven.project.interpolation.ModelInterpolationException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(java.rmi.RemoteException) InvalidProjectModelException(org.apache.maven.project.InvalidProjectModelException) SettingsBuildingException(org.apache.maven.settings.building.SettingsBuildingException) ComponentLookupException(org.codehaus.plexus.component.repository.exception.ComponentLookupException) MavenExecutionException(org.apache.maven.MavenExecutionException) ArtifactResolutionException(org.eclipse.aether.resolution.ArtifactResolutionException) InvalidRepositoryException(org.apache.maven.artifact.InvalidRepositoryException) MavenExecutionRequestPopulationException(org.apache.maven.execution.MavenExecutionRequestPopulationException) ArtifactResolver(org.apache.maven.artifact.resolver.ArtifactResolver) CheArtifactResolver(org.eclipse.che.maven.CheArtifactResolver) DefaultArtifactResolver(org.eclipse.aether.internal.impl.DefaultArtifactResolver) ProjectBuilder(org.apache.maven.project.ProjectBuilder) MavenProject(org.apache.maven.project.MavenProject) DefaultRepositorySystemSession(org.eclipse.aether.DefaultRepositorySystemSession) ProjectBuildingResult(org.apache.maven.project.ProjectBuildingResult) ArtifactResolutionRequest(org.apache.maven.artifact.resolver.ArtifactResolutionRequest) ArtifactResolutionResult(org.apache.maven.artifact.resolver.ArtifactResolutionResult)

Example 10 with ProjectBuildingResult

use of org.apache.maven.project.ProjectBuildingResult in project che by eclipse.

the class EffectivePomWriter method getEffectivePom.

public static String getEffectivePom(MavenServerImpl server, final File pom, List<String> activeProfiles, List<String> inactiveProfiles) {
    StringWriter stringWriter = new StringWriter();
    try {
        MavenExecutionRequest request = server.newMavenRequest(pom, activeProfiles, inactiveProfiles, Collections.emptyList());
        server.runMavenRequest(request, () -> {
            try {
                ProjectBuilder builder = server.getMavenComponent(ProjectBuilder.class);
                ProjectBuildingResult projectBuildingResult = builder.build(new File(pom.getPath()), request.getProjectBuildingRequest());
                MavenProject project = projectBuildingResult.getProject();
                XMLWriter writer = new PrettyPrintXMLWriter(stringWriter, "    ");
                writeHeader(writer);
                writeEffectivePom(project, writer);
            } catch (ProjectBuildingException | MojoExecutionException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        });
    } catch (Exception e) {
        return null;
    }
    return stringWriter.toString();
}
Also used : ProjectBuildingException(org.apache.maven.project.ProjectBuildingException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MavenExecutionRequest(org.apache.maven.execution.MavenExecutionRequest) PrettyPrintXMLWriter(org.codehaus.plexus.util.xml.PrettyPrintXMLWriter) XMLWriter(org.codehaus.plexus.util.xml.XMLWriter) PrettyPrintXMLWriter(org.codehaus.plexus.util.xml.PrettyPrintXMLWriter) ProjectBuildingException(org.apache.maven.project.ProjectBuildingException) JDOMException(org.jdom.JDOMException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) StringWriter(java.io.StringWriter) ProjectBuilder(org.apache.maven.project.ProjectBuilder) MavenProject(org.apache.maven.project.MavenProject) ProjectBuildingResult(org.apache.maven.project.ProjectBuildingResult) File(java.io.File)

Aggregations

ProjectBuildingResult (org.apache.maven.project.ProjectBuildingResult)15 MavenProject (org.apache.maven.project.MavenProject)9 ProjectBuilder (org.apache.maven.project.ProjectBuilder)9 ProjectBuildingException (org.apache.maven.project.ProjectBuildingException)9 DefaultProjectBuildingRequest (org.apache.maven.project.DefaultProjectBuildingRequest)6 ProjectBuildingRequest (org.apache.maven.project.ProjectBuildingRequest)6 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)4 MavenExecutionRequest (org.apache.maven.execution.MavenExecutionRequest)4 File (java.io.File)3 Artifact (org.apache.maven.artifact.Artifact)3 Writer (java.io.Writer)2 RemoteException (java.rmi.RemoteException)2 Properties (java.util.Properties)2 InvalidRepositoryException (org.apache.maven.artifact.InvalidRepositoryException)2 DefaultMavenExecutionRequest (org.apache.maven.execution.DefaultMavenExecutionRequest)2 DefaultMavenExecutionResult (org.apache.maven.execution.DefaultMavenExecutionResult)2 MavenExecutionResult (org.apache.maven.execution.MavenExecutionResult)2 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)2 ComponentLookupException (org.codehaus.plexus.component.repository.exception.ComponentLookupException)2