From 4cb42c34a70402166b734f483448a94172cef34c Mon Sep 17 00:00:00 2001 From: Britton Isbell Date: Wed, 13 Aug 2008 14:47:51 +0000 Subject: [PATCH] Merged back changes from sisbell-maven-2.1-profile git-svn-id: https://svn.apache.org/repos/asf/maven/components/trunk@685575 13f79535-47bb-0310-9956-ffa450edef68 --- .../error/ErrorReporterPointcutTest.java | 6 +- .../project/DefaultMavenProjectBuilder.java | 711 +++++++++++++++++- .../apache/maven/project/MavenProject.java | 169 ++--- .../maven/project/MavenProjectRestorer.java | 539 ------------- .../ArtifactModelContainerFactory.java | 3 +- .../builder/PomClassicTransformer.java | 128 +--- .../apache/maven/project/builder/Profile.java | 7 - .../maven/project/builder/ProjectBuilder.java | 2 - .../builder/impl/DefaultImportModel.java | 50 -- .../builder/impl/DefaultProjectBuilder.java | 12 +- .../DefaultProjectWorkspaceTest.java | 91 +++ .../workspace/ModelAndFileCachingTest.java | 241 ++++++ .../project/workspace/ProjectCachingTest.java | 286 +++++++ 13 files changed, 1386 insertions(+), 859 deletions(-) delete mode 100644 maven-project/src/main/java/org/apache/maven/project/MavenProjectRestorer.java delete mode 100644 maven-project/src/main/java/org/apache/maven/project/builder/Profile.java delete mode 100644 maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultImportModel.java create mode 100644 maven-project/src/test/java/org/apache/maven/project/workspace/DefaultProjectWorkspaceTest.java create mode 100644 maven-project/src/test/java/org/apache/maven/project/workspace/ModelAndFileCachingTest.java create mode 100644 maven-project/src/test/java/org/apache/maven/project/workspace/ProjectCachingTest.java diff --git a/maven-embedder/src/test/java/org/apache/maven/error/ErrorReporterPointcutTest.java b/maven-embedder/src/test/java/org/apache/maven/error/ErrorReporterPointcutTest.java index 5aa03c7165..09b709afac 100644 --- a/maven-embedder/src/test/java/org/apache/maven/error/ErrorReporterPointcutTest.java +++ b/maven-embedder/src/test/java/org/apache/maven/error/ErrorReporterPointcutTest.java @@ -848,10 +848,6 @@ public class ErrorReporterPointcutTest reporterCtl.verify(); } -/* - TODO: Disabled these unit tests due to refactoring of maven-project. DefaultMavenProjectBuilder would throw an - exception which would be recorded here. Creation is now in MavenProject, which doesn't contain an exception - in method signature. public void testReportBadManagedDependencyVersion() throws IOException @@ -888,7 +884,7 @@ public class ErrorReporterPointcutTest reporterCtl.verify(); } -*/ + public void testReportErrorCreatingArtifactRepository() throws IOException { diff --git a/maven-project/src/main/java/org/apache/maven/project/DefaultMavenProjectBuilder.java b/maven-project/src/main/java/org/apache/maven/project/DefaultMavenProjectBuilder.java index 9ecb2f07c7..37759c6bbc 100644 --- a/maven-project/src/main/java/org/apache/maven/project/DefaultMavenProjectBuilder.java +++ b/maven-project/src/main/java/org/apache/maven/project/DefaultMavenProjectBuilder.java @@ -33,18 +33,23 @@ import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactResolutionRequest; import org.apache.maven.artifact.resolver.ArtifactResolutionResult; import org.apache.maven.artifact.resolver.ArtifactResolver; +import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; +import org.apache.maven.artifact.versioning.ManagedVersionMap; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.model.Build; import org.apache.maven.model.Dependency; import org.apache.maven.model.DependencyManagement; import org.apache.maven.model.DistributionManagement; +import org.apache.maven.model.Exclusion; import org.apache.maven.model.Extension; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginManagement; +import org.apache.maven.model.Parent; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.Repository; +import org.apache.maven.model.Resource; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.profiles.MavenProfilesBuilder; import org.apache.maven.profiles.ProfileManager; @@ -67,6 +72,7 @@ import org.apache.maven.project.validation.ModelValidator; import org.apache.maven.project.workspace.ProjectWorkspace; import org.apache.maven.project.builder.PomArtifactResolver; import org.apache.maven.project.builder.ProjectBuilder; +import org.apache.maven.project.builder.PomClassicDomainModel; import org.codehaus.plexus.logging.LogEnabled; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; @@ -205,14 +211,19 @@ public class DefaultMavenProjectBuilder ArtifactRepository localRepository ) throws ProjectBuildingException { + String artifactKey = artifact.getId(); + MavenProject project = null; if ( !Artifact.LATEST_VERSION.equals( artifact.getVersion() ) && !Artifact.RELEASE_VERSION.equals( artifact.getVersion() ) ) { +// getLogger().debug( "Checking cache for project (in buildFromRepository): " + artifactKey ); project = projectWorkspace.getProject( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion() ); } if ( project == null ) { +// getLogger().debug( "Allowing buildFromRepository to proceed for: " + artifactKey ); + Model model = findModelFromRepository( artifact, remoteArtifactRepositories, localRepository ); ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setLocalRepository( localRepository ); @@ -220,6 +231,10 @@ public class DefaultMavenProjectBuilder project = buildInternal( model, config, remoteArtifactRepositories, artifact.getFile(), false, false, false ); } +// else +// { +// getLogger().debug( "Returning cached project: " + project ); +// } return project; } @@ -272,11 +287,17 @@ public class DefaultMavenProjectBuilder } } - MavenProject project = new MavenProject( superModel, artifactFactory ); + MavenProject project = new MavenProject( superModel ); + + String projectId = safeVersionlessKey( STANDALONE_SUPERPOM_GROUPID, STANDALONE_SUPERPOM_ARTIFACTID ); + + project.setManagedVersionMap( + createManagedVersionMap( projectId, superModel.getDependencyManagement(), null ) ); getLogger().debug( "Activated the following profiles for standalone super-pom: " + activeProfiles ); project.setActiveProfiles( activeProfiles ); + try { processProjectLogic( project, null, config, null, true, true ); @@ -381,11 +402,92 @@ public class DefaultMavenProjectBuilder return new MavenProjectBuildingResult( project, result ); } + // ---------------------------------------------------------------------- + // + // ---------------------------------------------------------------------- + + private Map createManagedVersionMap( String projectId, + DependencyManagement dependencyManagement, File pomFile ) + throws ProjectBuildingException + { + Map map = null; + List deps; + if ( ( dependencyManagement != null ) && ( ( deps = dependencyManagement.getDependencies() ) != null ) && ( deps.size() > 0 ) ) + { + map = new ManagedVersionMap( map ); + + if ( getLogger().isDebugEnabled() ) + { + getLogger().debug( "Adding managed dependencies for " + projectId ); + } + + for ( Iterator i = dependencyManagement.getDependencies().iterator(); i.hasNext(); ) + { + Dependency d = (Dependency) i.next(); + + try + { + VersionRange versionRange = VersionRange.createFromVersionSpec( d.getVersion() ); + + Artifact artifact = artifactFactory.createDependencyArtifact( d.getGroupId(), d.getArtifactId(), versionRange, d.getType(), + d.getClassifier(), d.getScope(), d.isOptional() ); + + if ( Artifact.SCOPE_SYSTEM.equals( d.getScope() ) && ( d.getSystemPath() != null ) ) + { + artifact.setFile( new File( d.getSystemPath() ) ); + } + + if ( getLogger().isDebugEnabled() ) + { + getLogger().debug( " " + artifact ); + } + + // If the dependencyManagement section listed exclusions, + // add them to the managed artifacts here so that transitive + // dependencies will be excluded if necessary. + + if ( ( null != d.getExclusions() ) && !d.getExclusions().isEmpty() ) + { + List exclusions = new ArrayList(); + + for ( Iterator j = d.getExclusions().iterator(); j.hasNext(); ) + { + Exclusion e = (Exclusion) j.next(); + + exclusions.add( e.getGroupId() + ":" + e.getArtifactId() ); + } + + ExcludesArtifactFilter eaf = new ExcludesArtifactFilter( exclusions ); + + artifact.setDependencyFilter( eaf ); + } + else + { + artifact.setDependencyFilter( null ); + } + + map.put( d.getManagementKey(), artifact ); + } + catch ( InvalidVersionSpecificationException e ) + { + throw new InvalidDependencyVersionException( projectId, d, pomFile, e ); + } + } + } + else if ( map == null ) + { + map = Collections.EMPTY_MAP; + } + return map; + } + private MavenProject buildFromSourceFileInternal( File projectDescriptor, ProjectBuilderConfiguration config ) throws ProjectBuildingException { - MavenProject project = null;//projectWorkspace.getProject( projectDescriptor ); +// getLogger().debug( "Checking cache-hit on project (in build*): " + projectDescriptor ); + + MavenProject project = projectWorkspace.getProject( projectDescriptor ); if ( project == null ) { @@ -577,7 +679,7 @@ public class DefaultMavenProjectBuilder { Model superModel = getSuperModel(); - MavenProject superProject = new MavenProject( superModel, artifactFactory ); + MavenProject superProject = new MavenProject( superModel ); String projectId = safeVersionlessKey( model.getGroupId(), model.getArtifactId() ); @@ -720,9 +822,14 @@ public class DefaultMavenProjectBuilder project.setFile( projectDescriptor ); } +// getLogger().debug( "Caching project: " + project.getId() + " (also keyed by file: " + project.getFile() + ")" ); + + projectWorkspace.storeProjectByCoordinate( project ); projectWorkspace.storeProjectByFile( project ); + project.setManagedVersionMap( createManagedVersionMap( projectId, project.getDependencyManagement(), projectDescriptor ) ); + return project; } @@ -875,7 +982,7 @@ public class DefaultMavenProjectBuilder Artifact parentArtifact = project.getParentArtifact(); // We will return a different project object using the new model (hence the need to return a project, not just modify the parameter) - project = new MavenProject( model, artifactFactory ); + project = new MavenProject( model ); project.setOriginalModel( originalModel ); @@ -935,6 +1042,9 @@ public class DefaultMavenProjectBuilder String projectId = safeVersionlessKey( model.getGroupId(), model.getArtifactId() ); + // TODO: these aren't taking active project artifacts into consideration in the reactor + project.setPluginArtifacts( createPluginArtifacts( projectId, project.getBuildPlugins(), pomFile ) ); + project.setReportArtifacts( createReportArtifacts( projectId, project.getReportPlugins(), pomFile ) ); project.setExtensionArtifacts( createExtensionArtifacts( projectId, project.getBuildExtensions(), pomFile ) ); @@ -999,13 +1109,518 @@ public class DefaultMavenProjectBuilder public void calculateConcreteState( MavenProject project, ProjectBuilderConfiguration config ) throws ModelInterpolationException { - new MavenProjectRestorer(pathTranslator, modelInterpolator, getLogger()).calculateConcreteState(project, config); + if ( project.isConcrete() ) + { + return; + } + + Build build = project.getBuild(); + if ( build != null ) + { + initResourceMergeIds( build.getResources() ); + initResourceMergeIds( build.getTestResources() ); + } + + Model model = ModelUtils.cloneModel( project.getModel() ); + + File basedir = project.getBasedir(); + + model = modelInterpolator.interpolate( model, basedir, config, getLogger().isDebugEnabled() ); + + List originalInterpolatedCompileSourceRoots = interpolateListOfStrings( project.getCompileSourceRoots(), + model, + project.getBasedir(), + config ); + + project.preserveCompileSourceRoots( originalInterpolatedCompileSourceRoots ); + + project.setCompileSourceRoots( originalInterpolatedCompileSourceRoots == null ? null + : translateListOfPaths( originalInterpolatedCompileSourceRoots, basedir ) ); + + List originalInterpolatedTestCompileSourceRoots = interpolateListOfStrings( project.getTestCompileSourceRoots(), + model, + project.getBasedir(), + config ); + + project.preserveTestCompileSourceRoots( originalInterpolatedTestCompileSourceRoots ); + project.setTestCompileSourceRoots( originalInterpolatedTestCompileSourceRoots == null ? null + : translateListOfPaths( originalInterpolatedTestCompileSourceRoots, basedir ) ); + + List originalInterpolatedScriptSourceRoots = interpolateListOfStrings( project.getScriptSourceRoots(), + model, + project.getBasedir(), + config ); + + project.preserveScriptSourceRoots( originalInterpolatedScriptSourceRoots ); + project.setScriptSourceRoots( originalInterpolatedScriptSourceRoots == null ? null + : translateListOfPaths( originalInterpolatedScriptSourceRoots, basedir ) ); + + Model model2 = ModelUtils.cloneModel( model ); + + pathTranslator.alignToBaseDirectory( model, basedir ); + + project.preserveBuild( model2.getBuild() ); + project.setBuild( model.getBuild() ); + + calculateConcreteProjectReferences( project, config ); + + MavenProject executionProject = project.getExecutionProject(); + if ( executionProject != null && executionProject != project ) + { + calculateConcreteState( executionProject, config ); + } + + project.setConcrete( true ); + } + + private void initResourceMergeIds( List resources ) + { + if ( resources != null ) + { + for ( Resource resource : resources ) + { + resource.initMergeId(); + } + } + } + + private void calculateConcreteProjectReferences( MavenProject project, + ProjectBuilderConfiguration config ) + throws ModelInterpolationException + { + Map projectRefs = project.getProjectReferences(); + + if ( projectRefs != null ) + { + for ( Iterator it = projectRefs.values().iterator(); it.hasNext(); ) + { + MavenProject reference = (MavenProject) it.next(); + calculateConcreteState( reference, config ); + } + } + } + + private List translateListOfPaths( List paths, File basedir ) + { + if ( paths == null ) + { + return null; + } + else if ( basedir == null ) + { + return paths; + } + + List result = new ArrayList( paths.size() ); + for ( Iterator it = paths.iterator(); it.hasNext(); ) + { + String path = (String) it.next(); + + String aligned = pathTranslator.alignToBaseDirectory( path, basedir ); + + result.add( aligned ); + } + + return result; } public void restoreDynamicState( MavenProject project, ProjectBuilderConfiguration config ) throws ModelInterpolationException { - new MavenProjectRestorer(pathTranslator, modelInterpolator, getLogger()).restoreDynamicState(project, config); + if ( !project.isConcrete() ) + { + return; + } + + restoreBuildRoots( project, config ); + restoreModelBuildSection( project, config ); + + restoreDynamicProjectReferences( project, config ); + + MavenProject executionProject = project.getExecutionProject(); + if ( executionProject != null && executionProject != project ) + { + restoreDynamicState( executionProject, config ); + } + + project.setConcrete( false ); + } + + private void restoreDynamicProjectReferences( MavenProject project, + ProjectBuilderConfiguration config ) + throws ModelInterpolationException + { + Map projectRefs = project.getProjectReferences(); + if ( projectRefs != null ) + { + for ( Iterator it = projectRefs.values().iterator(); it.hasNext(); ) + { + MavenProject projectRef = (MavenProject) it.next(); + restoreDynamicState( projectRef, config ); + } + } + } + + private void restoreBuildRoots( MavenProject project, + ProjectBuilderConfiguration config ) + throws ModelInterpolationException + { + project.setCompileSourceRoots( restoreListOfStrings( project.getDynamicCompileSourceRoots(), + project.getOriginalInterpolatedCompileSourceRoots(), + project.getCompileSourceRoots(), + project, + config ) ); + + project.setTestCompileSourceRoots( restoreListOfStrings( project.getDynamicTestCompileSourceRoots(), + project.getOriginalInterpolatedTestCompileSourceRoots(), + project.getTestCompileSourceRoots(), + project, + config ) ); + + project.setScriptSourceRoots( restoreListOfStrings( project.getDynamicScriptSourceRoots(), + project.getOriginalInterpolatedScriptSourceRoots(), + project.getScriptSourceRoots(), + project, + config ) ); + + project.clearRestorableRoots(); + } + + private void restoreModelBuildSection( MavenProject project, + ProjectBuilderConfiguration config ) + throws ModelInterpolationException + { + Build changedBuild = project.getBuild(); + Build dynamicBuild = project.getDynamicBuild(); + Build originalInterpolatedBuild = project.getOriginalInterpolatedBuild(); + + dynamicBuild.setResources( restoreResources( dynamicBuild.getResources(), + originalInterpolatedBuild.getResources(), + changedBuild.getResources(), + project, + config ) ); + + dynamicBuild.setTestResources( restoreResources( dynamicBuild.getTestResources(), + originalInterpolatedBuild.getTestResources(), + changedBuild.getTestResources(), + project, + config ) ); + + dynamicBuild.setFilters( restoreListOfStrings( dynamicBuild.getFilters(), + originalInterpolatedBuild.getFilters(), + changedBuild.getFilters(), + project, + config ) ); + + dynamicBuild.setFinalName( restoreString( dynamicBuild.getFinalName(), + originalInterpolatedBuild.getFinalName(), + changedBuild.getFinalName(), + project, + config ) ); + + dynamicBuild.setDefaultGoal( restoreString( dynamicBuild.getDefaultGoal(), + originalInterpolatedBuild.getDefaultGoal(), + changedBuild.getDefaultGoal(), + project, + config ) ); + + dynamicBuild.setSourceDirectory( restoreString( dynamicBuild.getSourceDirectory(), + originalInterpolatedBuild.getSourceDirectory(), + changedBuild.getSourceDirectory(), + project, + config ) ); + + dynamicBuild.setTestSourceDirectory( restoreString( dynamicBuild.getTestSourceDirectory(), + originalInterpolatedBuild.getTestSourceDirectory(), + changedBuild.getTestSourceDirectory(), + project, + config ) ); + + dynamicBuild.setScriptSourceDirectory( restoreString( dynamicBuild.getScriptSourceDirectory(), + originalInterpolatedBuild.getScriptSourceDirectory(), + changedBuild.getScriptSourceDirectory(), + project, + config ) ); + + dynamicBuild.setOutputDirectory( restoreString( dynamicBuild.getOutputDirectory(), + originalInterpolatedBuild.getOutputDirectory(), + changedBuild.getOutputDirectory(), + project, + config ) ); + + dynamicBuild.setTestOutputDirectory( restoreString( dynamicBuild.getTestOutputDirectory(), + originalInterpolatedBuild.getTestOutputDirectory(), + changedBuild.getTestOutputDirectory(), + project, + config ) ); + + dynamicBuild.setDirectory( restoreString( dynamicBuild.getDirectory(), + originalInterpolatedBuild.getDirectory(), + changedBuild.getDirectory(), + project, + config ) ); + + project.setBuild( dynamicBuild ); + + project.clearRestorableBuild(); + } + + private List interpolateListOfStrings( List originalStrings, + Model model, + File projectDir, + ProjectBuilderConfiguration config ) + throws ModelInterpolationException + { + if ( originalStrings == null ) + { + return null; + } + + List result = new ArrayList(); + + for ( Iterator it = originalStrings.iterator(); it.hasNext(); ) + { + String original = (String) it.next(); + String interpolated = modelInterpolator.interpolate( original, model, projectDir, config, getLogger().isDebugEnabled() ); + + result.add( interpolated ); + } + + return result; + } + + private String restoreString( String originalString, + String originalInterpolatedString, + String changedString, + MavenProject project, + ProjectBuilderConfiguration config ) + throws ModelInterpolationException + { + if ( originalString == null ) + { + return changedString; + } + else if ( changedString == null ) + { + return originalString; + } + + Model model = project.getModel(); + + String relativeChangedString; + if ( project.getBasedir() != null ) + { + relativeChangedString = pathTranslator.unalignFromBaseDirectory( changedString, project.getBasedir() ); + } + else + { + relativeChangedString = changedString; + } + + String interpolatedOriginal = modelInterpolator.interpolate( originalString, model, project.getBasedir(), config, getLogger().isDebugEnabled() ); + String interpolatedOriginal2 = modelInterpolator.interpolate( originalInterpolatedString, + model, + project.getBasedir(), config, getLogger().isDebugEnabled() ); + + String interpolatedChanged = modelInterpolator.interpolate( changedString, model, project.getBasedir(), config, getLogger().isDebugEnabled() ); + String relativeInterpolatedChanged = modelInterpolator.interpolate( relativeChangedString, model, project.getBasedir(), config, getLogger().isDebugEnabled() ); + + if ( interpolatedOriginal.equals( interpolatedChanged ) + || interpolatedOriginal2.equals( interpolatedChanged ) ) + { + return originalString; + } + else if ( interpolatedOriginal.equals( relativeInterpolatedChanged ) + || interpolatedOriginal2.equals( relativeInterpolatedChanged ) ) + { + return originalString; + } + + return relativeChangedString; + } + + private List restoreListOfStrings( List originalStrings, + List originalInterpolatedStrings, + List changedStrings, + MavenProject project, + ProjectBuilderConfiguration config ) + throws ModelInterpolationException + { + if ( originalStrings == null ) + { + return changedStrings; + } + else if ( changedStrings == null ) + { + return originalStrings; + } + + List result = new ArrayList(); + + Map orig = new HashMap(); + for ( int idx = 0; idx < originalStrings.size(); idx++ ) + { + String[] permutations = new String[2]; + + permutations[0] = (String) originalInterpolatedStrings.get( idx ); + permutations[1] = (String) originalStrings.get( idx ); + + orig.put( permutations[0], permutations ); + } + + for ( Iterator it = changedStrings.iterator(); it.hasNext(); ) + { + String changedString = (String) it.next(); + String relativeChangedString; + if ( project.getBasedir() != null ) + { + relativeChangedString = pathTranslator.unalignFromBaseDirectory( changedString, project.getBasedir() ); + } + else + { + relativeChangedString = changedString; + } + + String interpolated = modelInterpolator.interpolate( changedString, + project.getModel(), + project.getBasedir(), + config, + getLogger().isDebugEnabled() ); + + String relativeInterpolated = modelInterpolator.interpolate( relativeChangedString, + project.getModel(), + project.getBasedir(), + config, + getLogger().isDebugEnabled() ); + + String[] original = (String[]) orig.get( interpolated ); + if ( original == null ) + { + original = (String[]) orig.get( relativeInterpolated ); + } + + if ( original == null ) + { + result.add( relativeChangedString ); + } + else + { + result.add( original[1] ); + } + } + + return result; + } + + // TODO: Convert this to use the mergeId on each resource... + private List restoreResources( List originalResources, + List originalInterpolatedResources, + List changedResources, + MavenProject project, + ProjectBuilderConfiguration config ) + throws ModelInterpolationException + { + if ( originalResources == null || changedResources == null ) + { + return originalResources; + } + + List result = new ArrayList(); + + Map originalResourcesByMergeId = new HashMap(); + for ( int idx = 0; idx < originalResources.size(); idx++ ) + { + Resource[] permutations = new Resource[2]; + + permutations[0] = originalInterpolatedResources.get( idx ); + permutations[1] = originalResources.get( idx ); + + originalResourcesByMergeId.put( permutations[0].getMergeId(), permutations ); + } + + for ( Resource resource : changedResources ) + { + String mergeId = resource.getMergeId(); + if ( mergeId == null || !originalResourcesByMergeId.containsKey( mergeId ) ) + { + result.add( resource ); + } + else + { + Resource originalInterpolatedResource = originalResourcesByMergeId.get( mergeId )[0]; + Resource originalResource = originalResourcesByMergeId.get( mergeId )[1]; + + String dir = modelInterpolator.interpolate( resource.getDirectory(), project.getModel(), project.getBasedir(), config, getLogger().isDebugEnabled() ); + String oDir = originalInterpolatedResource.getDirectory(); + + if ( !dir.equals( oDir ) ) + { + originalResource.setDirectory( pathTranslator.unalignFromBaseDirectory( dir, project.getBasedir() ) ); + } + + if ( resource.getTargetPath() != null ) + { + String target = modelInterpolator.interpolate( resource.getTargetPath(), project.getModel(), project.getBasedir(), config, getLogger().isDebugEnabled() ); + + String oTarget = originalInterpolatedResource.getTargetPath(); + + if ( !target.equals( oTarget ) ) + { + originalResource.setTargetPath( pathTranslator.unalignFromBaseDirectory( target, project.getBasedir() ) ); + } + } + + originalResource.setFiltering( resource.isFiltering() ); + + originalResource.setExcludes( collectRestoredListOfPatterns( resource.getExcludes(), + originalResource.getExcludes(), + originalInterpolatedResource.getExcludes() ) ); + + originalResource.setIncludes( collectRestoredListOfPatterns( resource.getIncludes(), + originalResource.getIncludes(), + originalInterpolatedResource.getIncludes() ) ); + + result.add( originalResource ); + } + } + + return result; + } + + private List collectRestoredListOfPatterns( List patterns, + List originalPatterns, + List originalInterpolatedPatterns ) + { + LinkedHashSet collectedPatterns = new LinkedHashSet(); + + collectedPatterns.addAll( originalPatterns ); + + for ( String pattern : patterns ) + { + if ( !originalInterpolatedPatterns.contains( pattern ) ) + { + collectedPatterns.add( pattern ); + } + } + + return (List) ( collectedPatterns.isEmpty() ? Collections.emptyList() + : new ArrayList( collectedPatterns ) ); + } + + private void validateModel( Model model, + File pomFile ) + throws InvalidProjectModelException + { + // Must validate before artifact construction to make sure dependencies are good + ModelValidationResult validationResult = validator.validate( model ); + + String projectId = safeVersionlessKey( model.getGroupId(), model.getArtifactId() ); + + if ( validationResult.getMessageCount() > 0 ) + { + throw new InvalidProjectModelException( projectId, "Failed to validate POM", pomFile, + validationResult ); + } } /** @@ -1049,7 +1664,7 @@ public class DefaultMavenProjectBuilder File currentPom = it.getPOMFile(); - MavenProject project = new MavenProject( currentModel, artifactFactory ); + MavenProject project = new MavenProject( currentModel ); project.setFile( currentPom ); if ( lastProject != null ) @@ -1213,6 +1828,70 @@ public class DefaultMavenProjectBuilder } } + /** + * @deprecated use {@link #createPluginArtifacts(String, List, File)} + * @param projectId + * @param plugins + * @param pomLocation absolute path of pom file + * @return + * @throws ProjectBuildingException + */ + @Deprecated + protected Set createPluginArtifacts( String projectId, + List plugins, String pomLocation ) + throws ProjectBuildingException + { + return createPluginArtifacts( projectId, plugins, new File( pomLocation ) ); + } + + /** + * + * @param projectId + * @param plugins + * @param pomLocation pom file + * @return + * @throws ProjectBuildingException + */ + protected Set createPluginArtifacts( String projectId, + List plugins, File pomLocation ) + throws ProjectBuildingException + { + Set pluginArtifacts = new HashSet(); + + for ( Iterator i = plugins.iterator(); i.hasNext(); ) + { + Plugin p = (Plugin) i.next(); + + String version; + if ( StringUtils.isEmpty( p.getVersion() ) ) + { + version = "RELEASE"; + } + else + { + version = p.getVersion(); + } + + Artifact artifact; + try + { + artifact = artifactFactory.createPluginArtifact( p.getGroupId(), p.getArtifactId(), + VersionRange.createFromVersionSpec( version ) ); + } + catch ( InvalidVersionSpecificationException e ) + { + throw new InvalidProjectVersionException( projectId, "Plugin: " + p.getKey(), version, pomLocation, e ); + } + + if ( artifact != null ) + { + pluginArtifacts.add( artifact ); + } + } + + return pluginArtifacts; + } + /** * @deprecated use {@link #createReportArtifacts(String, List, File)} * @param projectId @@ -1407,7 +2086,7 @@ public class DefaultMavenProjectBuilder MavenProject mavenProject; try { mavenProject = projectBuilder.buildFromLocalPath(new FileInputStream(projectDescriptor), - null, null, null, resolver, + null, null, resolver, projectDescriptor.getParentFile()); } catch (IOException e) { e.printStackTrace(); @@ -1417,20 +2096,4 @@ public class DefaultMavenProjectBuilder return mavenProject.getModel(); } - - private void validateModel( Model model, - File pomFile ) - throws InvalidProjectModelException - { - // Must validate before artifact construction to make sure dependencies are good - ModelValidationResult validationResult = validator.validate( model ); - - String projectId = safeVersionlessKey( model.getGroupId(), model.getArtifactId() ); - - if ( validationResult.getMessageCount() > 0 ) - { - throw new InvalidProjectModelException( projectId, "Failed to validate POM", pomFile, - validationResult ); - } - } } diff --git a/maven-project/src/main/java/org/apache/maven/project/MavenProject.java b/maven-project/src/main/java/org/apache/maven/project/MavenProject.java index f852e88728..cb95d52355 100644 --- a/maven-project/src/main/java/org/apache/maven/project/MavenProject.java +++ b/maven-project/src/main/java/org/apache/maven/project/MavenProject.java @@ -25,22 +25,46 @@ import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; -import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter; import org.apache.maven.artifact.versioning.ManagedVersionMap; -import org.apache.maven.artifact.versioning.VersionRange; -import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; -import org.apache.maven.model.*; +import org.apache.maven.model.Build; +import org.apache.maven.model.CiManagement; +import org.apache.maven.model.Contributor; +import org.apache.maven.model.Dependency; +import org.apache.maven.model.DependencyManagement; +import org.apache.maven.model.Developer; +import org.apache.maven.model.DistributionManagement; +import org.apache.maven.model.IssueManagement; +import org.apache.maven.model.License; +import org.apache.maven.model.MailingList; +import org.apache.maven.model.Model; +import org.apache.maven.model.Organization; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.PluginExecution; +import org.apache.maven.model.PluginManagement; +import org.apache.maven.model.Prerequisites; +import org.apache.maven.model.ReportPlugin; +import org.apache.maven.model.ReportSet; +import org.apache.maven.model.Reporting; +import org.apache.maven.model.Resource; +import org.apache.maven.model.Scm; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; import org.apache.maven.project.artifact.ActiveProjectArtifact; import org.apache.maven.project.artifact.InvalidDependencyVersionException; import org.apache.maven.project.artifact.MavenMetadataSource; import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.io.IOException; import java.io.Writer; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.Stack; /** * The concern of the project is provide runtime values based on the model.

@@ -129,8 +153,6 @@ public class MavenProject private Stack previousExecutionProjects = new Stack(); - private ArtifactFactory artifactFactory; - public MavenProject() { Model model = new Model(); @@ -147,11 +169,6 @@ public class MavenProject setModel( model ); } - public MavenProject(Model model, ArtifactFactory artifactFactory) { - setModel( model ); - this.artifactFactory = artifactFactory; - } - /** * @deprecated use {@link #clone()} so subclasses can provide a copy of the same class */ @@ -179,10 +196,10 @@ public class MavenProject setArtifacts( Collections.unmodifiableSet( project.getArtifacts() ) ); } - // if ( project.getPluginArtifacts() != null ) - // { - // setPluginArtifacts( Collections.unmodifiableSet( project.getPluginArtifacts() ) ); - // } + if ( project.getPluginArtifacts() != null ) + { + setPluginArtifacts( Collections.unmodifiableSet( project.getPluginArtifacts() ) ); + } if ( project.getReportArtifacts() != null ) { @@ -1145,53 +1162,25 @@ public class MavenProject return artifactMap; } + public void setPluginArtifacts( Set pluginArtifacts ) + { + this.pluginArtifacts = pluginArtifacts; + + pluginArtifactMap = null; + } + public Set getPluginArtifacts() { - if(pluginArtifacts != null) { - return pluginArtifacts; - } - Set pa = new HashSet(); - if(artifactFactory != null) { - List plugins = getBuildPlugins(); - for ( Iterator i = plugins.iterator(); i.hasNext(); ) - { - Plugin p = (Plugin) i.next(); - - String version; - if ( StringUtils.isEmpty( p.getVersion() ) ) - { - version = "RELEASE"; - } - else - { - version = p.getVersion(); - } - - Artifact artifact; - try - { - artifact = artifactFactory.createPluginArtifact( p.getGroupId(), p.getArtifactId(), - VersionRange.createFromVersionSpec( version ) ); - } - catch ( InvalidVersionSpecificationException e ) - { - return pa; - } - - if ( artifact != null ) - { - pa.add( artifact ); - } - } - } - pluginArtifacts = pa; - pluginArtifactMap = null; return pluginArtifacts; } public Map getPluginArtifactMap() { - pluginArtifactMap = ArtifactUtils.artifactMapByVersionlessId( getPluginArtifacts() ); + if ( pluginArtifactMap == null ) + { + pluginArtifactMap = ArtifactUtils.artifactMapByVersionlessId( getPluginArtifacts() ); + } + return pluginArtifactMap; } @@ -1578,72 +1567,6 @@ public class MavenProject public Map getManagedVersionMap() { - if(managedVersionMap != null) { - return managedVersionMap; - } - - Map map = null; - if( artifactFactory != null ) { - - List deps; - DependencyManagement dependencyManagement = getDependencyManagement(); - if ( ( dependencyManagement != null ) && ( ( deps = dependencyManagement.getDependencies() ) != null ) && ( deps.size() > 0 ) ) - { - map = new ManagedVersionMap( map ); - for ( Iterator i = dependencyManagement.getDependencies().iterator(); i.hasNext(); ) - { - Dependency d = (Dependency) i.next(); - - try - { - VersionRange versionRange = VersionRange.createFromVersionSpec( d.getVersion() ); - - Artifact artifact = artifactFactory.createDependencyArtifact( d.getGroupId(), d.getArtifactId(), versionRange, d.getType(), - d.getClassifier(), d.getScope(), d.isOptional() ); - - if ( Artifact.SCOPE_SYSTEM.equals( d.getScope() ) && ( d.getSystemPath() != null ) ) - { - artifact.setFile( new File( d.getSystemPath() ) ); - } - - // If the dependencyManagement section listed exclusions, - // add them to the managed artifacts here so that transitive - // dependencies will be excluded if necessary. - - if ( ( null != d.getExclusions() ) && !d.getExclusions().isEmpty() ) - { - List exclusions = new ArrayList(); - - for ( Iterator j = d.getExclusions().iterator(); j.hasNext(); ) - { - Exclusion e = (Exclusion) j.next(); - - exclusions.add( e.getGroupId() + ":" + e.getArtifactId() ); - } - - ExcludesArtifactFilter eaf = new ExcludesArtifactFilter( exclusions ); - - artifact.setDependencyFilter( eaf ); - } - else - { - artifact.setDependencyFilter( null ); - } - - map.put( d.getManagementKey(), artifact ); - } - catch ( InvalidVersionSpecificationException e ) - { - map = Collections.EMPTY_MAP; - } - } - } - else if ( map == null ) - { - map = Collections.EMPTY_MAP; - } - } - managedVersionMap = map; return managedVersionMap; } diff --git a/maven-project/src/main/java/org/apache/maven/project/MavenProjectRestorer.java b/maven-project/src/main/java/org/apache/maven/project/MavenProjectRestorer.java deleted file mode 100644 index dc5d9cc816..0000000000 --- a/maven-project/src/main/java/org/apache/maven/project/MavenProjectRestorer.java +++ /dev/null @@ -1,539 +0,0 @@ -package org.apache.maven.project; - -import org.apache.maven.project.interpolation.ModelInterpolationException; -import org.apache.maven.project.interpolation.ModelInterpolator; -import org.apache.maven.project.path.PathTranslator; -import org.apache.maven.model.Build; -import org.apache.maven.model.Model; -import org.apache.maven.model.Resource; - -import java.util.*; -import java.io.File; -import org.codehaus.plexus.logging.Logger; - -final class MavenProjectRestorer { - - private ModelInterpolator modelInterpolator; - - private PathTranslator pathTranslator; - - private Logger logger; - - MavenProjectRestorer(PathTranslator pathTranslator, ModelInterpolator modelInterpolator, Logger logger) - { - this.pathTranslator = pathTranslator; - this.modelInterpolator = modelInterpolator; - this.logger = logger; - } - - Logger getLogger() { - return logger; - } - - void restoreDynamicState( MavenProject project, ProjectBuilderConfiguration config ) - throws ModelInterpolationException - { - if ( !project.isConcrete() ) - { - return; - } - - restoreBuildRoots( project, config ); - restoreModelBuildSection( project, config ); - - restoreDynamicProjectReferences( project, config ); - - MavenProject executionProject = project.getExecutionProject(); - if ( executionProject != null && executionProject != project ) - { - restoreDynamicState( executionProject, config ); - } - - project.setConcrete( false ); - } - - void calculateConcreteState( MavenProject project, ProjectBuilderConfiguration config ) - throws ModelInterpolationException - { - if ( project.isConcrete() ) - { - return; - } - - Build build = project.getBuild(); - if ( build != null ) - { - initResourceMergeIds( build.getResources() ); - initResourceMergeIds( build.getTestResources() ); - } - - Model model = ModelUtils.cloneModel( project.getModel() ); - - File basedir = project.getBasedir(); - - model = modelInterpolator.interpolate( model, basedir, config, getLogger().isDebugEnabled() ); - - List originalInterpolatedCompileSourceRoots = interpolateListOfStrings( project.getCompileSourceRoots(), - model, - project.getBasedir(), - config ); - - project.preserveCompileSourceRoots( originalInterpolatedCompileSourceRoots ); - - project.setCompileSourceRoots( originalInterpolatedCompileSourceRoots == null ? null - : translateListOfPaths( originalInterpolatedCompileSourceRoots, basedir ) ); - - List originalInterpolatedTestCompileSourceRoots = interpolateListOfStrings( project.getTestCompileSourceRoots(), - model, - project.getBasedir(), - config ); - - project.preserveTestCompileSourceRoots( originalInterpolatedTestCompileSourceRoots ); - project.setTestCompileSourceRoots( originalInterpolatedTestCompileSourceRoots == null ? null - : translateListOfPaths( originalInterpolatedTestCompileSourceRoots, basedir ) ); - - List originalInterpolatedScriptSourceRoots = interpolateListOfStrings( project.getScriptSourceRoots(), - model, - project.getBasedir(), - config ); - - project.preserveScriptSourceRoots( originalInterpolatedScriptSourceRoots ); - project.setScriptSourceRoots( originalInterpolatedScriptSourceRoots == null ? null - : translateListOfPaths( originalInterpolatedScriptSourceRoots, basedir ) ); - - Model model2 = ModelUtils.cloneModel( model ); - - pathTranslator.alignToBaseDirectory( model, basedir ); - - project.preserveBuild( model2.getBuild() ); - project.setBuild( model.getBuild() ); - - calculateConcreteProjectReferences( project, config ); - - MavenProject executionProject = project.getExecutionProject(); - if ( executionProject != null && executionProject != project ) - { - calculateConcreteState( executionProject, config ); - } - - project.setConcrete( true ); - } - - - - private void restoreDynamicProjectReferences( MavenProject project, - ProjectBuilderConfiguration config ) - throws ModelInterpolationException - { - Map projectRefs = project.getProjectReferences(); - if ( projectRefs != null ) - { - for ( Iterator it = projectRefs.values().iterator(); it.hasNext(); ) - { - MavenProject projectRef = (MavenProject) it.next(); - restoreDynamicState( projectRef, config ); - } - } - } - - private void restoreBuildRoots( MavenProject project, - ProjectBuilderConfiguration config ) - throws ModelInterpolationException - { - project.setCompileSourceRoots( restoreListOfStrings( project.getDynamicCompileSourceRoots(), - project.getOriginalInterpolatedCompileSourceRoots(), - project.getCompileSourceRoots(), - project, - config ) ); - - project.setTestCompileSourceRoots( restoreListOfStrings( project.getDynamicTestCompileSourceRoots(), - project.getOriginalInterpolatedTestCompileSourceRoots(), - project.getTestCompileSourceRoots(), - project, - config ) ); - - project.setScriptSourceRoots( restoreListOfStrings( project.getDynamicScriptSourceRoots(), - project.getOriginalInterpolatedScriptSourceRoots(), - project.getScriptSourceRoots(), - project, - config ) ); - - project.clearRestorableRoots(); - } - - private void restoreModelBuildSection( MavenProject project, - ProjectBuilderConfiguration config ) - throws ModelInterpolationException - { - Build changedBuild = project.getBuild(); - Build dynamicBuild = project.getDynamicBuild(); - Build originalInterpolatedBuild = project.getOriginalInterpolatedBuild(); - - dynamicBuild.setResources( restoreResources( dynamicBuild.getResources(), - originalInterpolatedBuild.getResources(), - changedBuild.getResources(), - project, - config ) ); - - dynamicBuild.setTestResources( restoreResources( dynamicBuild.getTestResources(), - originalInterpolatedBuild.getTestResources(), - changedBuild.getTestResources(), - project, - config ) ); - - dynamicBuild.setFilters( restoreListOfStrings( dynamicBuild.getFilters(), - originalInterpolatedBuild.getFilters(), - changedBuild.getFilters(), - project, - config ) ); - - dynamicBuild.setFinalName( restoreString( dynamicBuild.getFinalName(), - originalInterpolatedBuild.getFinalName(), - changedBuild.getFinalName(), - project, - config ) ); - - dynamicBuild.setDefaultGoal( restoreString( dynamicBuild.getDefaultGoal(), - originalInterpolatedBuild.getDefaultGoal(), - changedBuild.getDefaultGoal(), - project, - config ) ); - - dynamicBuild.setSourceDirectory( restoreString( dynamicBuild.getSourceDirectory(), - originalInterpolatedBuild.getSourceDirectory(), - changedBuild.getSourceDirectory(), - project, - config ) ); - - dynamicBuild.setTestSourceDirectory( restoreString( dynamicBuild.getTestSourceDirectory(), - originalInterpolatedBuild.getTestSourceDirectory(), - changedBuild.getTestSourceDirectory(), - project, - config ) ); - - dynamicBuild.setScriptSourceDirectory( restoreString( dynamicBuild.getScriptSourceDirectory(), - originalInterpolatedBuild.getScriptSourceDirectory(), - changedBuild.getScriptSourceDirectory(), - project, - config ) ); - - dynamicBuild.setOutputDirectory( restoreString( dynamicBuild.getOutputDirectory(), - originalInterpolatedBuild.getOutputDirectory(), - changedBuild.getOutputDirectory(), - project, - config ) ); - - dynamicBuild.setTestOutputDirectory( restoreString( dynamicBuild.getTestOutputDirectory(), - originalInterpolatedBuild.getTestOutputDirectory(), - changedBuild.getTestOutputDirectory(), - project, - config ) ); - - dynamicBuild.setDirectory( restoreString( dynamicBuild.getDirectory(), - originalInterpolatedBuild.getDirectory(), - changedBuild.getDirectory(), - project, - config ) ); - - project.setBuild( dynamicBuild ); - - project.clearRestorableBuild(); - } - - private List interpolateListOfStrings( List originalStrings, - Model model, - File projectDir, - ProjectBuilderConfiguration config ) - throws ModelInterpolationException - { - if ( originalStrings == null ) - { - return null; - } - - List result = new ArrayList(); - - for ( Iterator it = originalStrings.iterator(); it.hasNext(); ) - { - String original = (String) it.next(); - String interpolated = modelInterpolator.interpolate( original, model, projectDir, config, getLogger().isDebugEnabled() ); - - result.add( interpolated ); - } - - return result; - } - - private String restoreString( String originalString, - String originalInterpolatedString, - String changedString, - MavenProject project, - ProjectBuilderConfiguration config ) - throws ModelInterpolationException - { - if ( originalString == null ) - { - return changedString; - } - else if ( changedString == null ) - { - return originalString; - } - - Model model = project.getModel(); - - String relativeChangedString; - if ( project.getBasedir() != null ) - { - relativeChangedString = pathTranslator.unalignFromBaseDirectory( changedString, project.getBasedir() ); - } - else - { - relativeChangedString = changedString; - } - - String interpolatedOriginal = modelInterpolator.interpolate( originalString, model, project.getBasedir(), config, getLogger().isDebugEnabled() ); - String interpolatedOriginal2 = modelInterpolator.interpolate( originalInterpolatedString, - model, - project.getBasedir(), config, getLogger().isDebugEnabled() ); - - String interpolatedChanged = modelInterpolator.interpolate( changedString, model, project.getBasedir(), config, getLogger().isDebugEnabled() ); - String relativeInterpolatedChanged = modelInterpolator.interpolate( relativeChangedString, model, project.getBasedir(), config, getLogger().isDebugEnabled() ); - - if ( interpolatedOriginal.equals( interpolatedChanged ) - || interpolatedOriginal2.equals( interpolatedChanged ) ) - { - return originalString; - } - else if ( interpolatedOriginal.equals( relativeInterpolatedChanged ) - || interpolatedOriginal2.equals( relativeInterpolatedChanged ) ) - { - return originalString; - } - - return relativeChangedString; - } - - private List restoreListOfStrings( List originalStrings, - List originalInterpolatedStrings, - List changedStrings, - MavenProject project, - ProjectBuilderConfiguration config ) - throws ModelInterpolationException - { - if ( originalStrings == null ) - { - return changedStrings; - } - else if ( changedStrings == null ) - { - return originalStrings; - } - - List result = new ArrayList(); - - Map orig = new HashMap(); - for ( int idx = 0; idx < originalStrings.size(); idx++ ) - { - String[] permutations = new String[2]; - - permutations[0] = (String) originalInterpolatedStrings.get( idx ); - permutations[1] = (String) originalStrings.get( idx ); - - orig.put( permutations[0], permutations ); - } - - for ( Iterator it = changedStrings.iterator(); it.hasNext(); ) - { - String changedString = (String) it.next(); - String relativeChangedString; - if ( project.getBasedir() != null ) - { - relativeChangedString = pathTranslator.unalignFromBaseDirectory( changedString, project.getBasedir() ); - } - else - { - relativeChangedString = changedString; - } - - String interpolated = modelInterpolator.interpolate( changedString, - project.getModel(), - project.getBasedir(), - config, - getLogger().isDebugEnabled() ); - - String relativeInterpolated = modelInterpolator.interpolate( relativeChangedString, - project.getModel(), - project.getBasedir(), - config, - getLogger().isDebugEnabled() ); - - String[] original = (String[]) orig.get( interpolated ); - if ( original == null ) - { - original = (String[]) orig.get( relativeInterpolated ); - } - - if ( original == null ) - { - result.add( relativeChangedString ); - } - else - { - result.add( original[1] ); - } - } - - return result; - } - - // TODO: Convert this to use the mergeId on each resource... - private List restoreResources( List originalResources, - List originalInterpolatedResources, - List changedResources, - MavenProject project, - ProjectBuilderConfiguration config ) - throws ModelInterpolationException - { - if ( originalResources == null || changedResources == null ) - { - return originalResources; - } - - List result = new ArrayList(); - - Map originalResourcesByMergeId = new HashMap(); - for ( int idx = 0; idx < originalResources.size(); idx++ ) - { - Resource[] permutations = new Resource[2]; - - permutations[0] = originalInterpolatedResources.get( idx ); - permutations[1] = originalResources.get( idx ); - - originalResourcesByMergeId.put( permutations[0].getMergeId(), permutations ); - } - - for ( Resource resource : changedResources ) - { - String mergeId = resource.getMergeId(); - if ( mergeId == null || !originalResourcesByMergeId.containsKey( mergeId ) ) - { - result.add( resource ); - } - else - { - Resource originalInterpolatedResource = originalResourcesByMergeId.get( mergeId )[0]; - Resource originalResource = originalResourcesByMergeId.get( mergeId )[1]; - - String dir = modelInterpolator.interpolate( resource.getDirectory(), project.getModel(), project.getBasedir(), config, getLogger().isDebugEnabled() ); - String oDir = originalInterpolatedResource.getDirectory(); - - if ( !dir.equals( oDir ) ) - { - originalResource.setDirectory( pathTranslator.unalignFromBaseDirectory( dir, project.getBasedir() ) ); - } - - if ( resource.getTargetPath() != null ) - { - String target = modelInterpolator.interpolate( resource.getTargetPath(), project.getModel(), project.getBasedir(), config, getLogger().isDebugEnabled() ); - - String oTarget = originalInterpolatedResource.getTargetPath(); - - if ( !target.equals( oTarget ) ) - { - originalResource.setTargetPath( pathTranslator.unalignFromBaseDirectory( target, project.getBasedir() ) ); - } - } - - originalResource.setFiltering( resource.isFiltering() ); - - originalResource.setExcludes( collectRestoredListOfPatterns( resource.getExcludes(), - originalResource.getExcludes(), - originalInterpolatedResource.getExcludes() ) ); - - originalResource.setIncludes( collectRestoredListOfPatterns( resource.getIncludes(), - originalResource.getIncludes(), - originalInterpolatedResource.getIncludes() ) ); - - result.add( originalResource ); - } - } - - return result; - } - - private List collectRestoredListOfPatterns( List patterns, - List originalPatterns, - List originalInterpolatedPatterns ) - { - LinkedHashSet collectedPatterns = new LinkedHashSet(); - - collectedPatterns.addAll( originalPatterns ); - - for ( String pattern : patterns ) - { - if ( !originalInterpolatedPatterns.contains( pattern ) ) - { - collectedPatterns.add( pattern ); - } - } - - return (List) ( collectedPatterns.isEmpty() ? Collections.emptyList() - : new ArrayList( collectedPatterns ) ); - } - - - private void initResourceMergeIds( List resources ) - { - if ( resources != null ) - { - for ( Resource resource : resources ) - { - resource.initMergeId(); - } - } - } - - private void calculateConcreteProjectReferences( MavenProject project, - ProjectBuilderConfiguration config ) - throws ModelInterpolationException - { - Map projectRefs = project.getProjectReferences(); - - if ( projectRefs != null ) - { - for ( Iterator it = projectRefs.values().iterator(); it.hasNext(); ) - { - MavenProject reference = (MavenProject) it.next(); - calculateConcreteState( reference, config ); - } - } - } - - private List translateListOfPaths( List paths, File basedir ) - { - if ( paths == null ) - { - return null; - } - else if ( basedir == null ) - { - return paths; - } - - List result = new ArrayList( paths.size() ); - for ( Iterator it = paths.iterator(); it.hasNext(); ) - { - String path = (String) it.next(); - - String aligned = pathTranslator.alignToBaseDirectory( path, basedir ); - - result.add( aligned ); - } - - return result; - } - - - -} diff --git a/maven-project/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java b/maven-project/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java index 3a1c3917f4..1f56ea5a0a 100644 --- a/maven-project/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java +++ b/maven-project/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java @@ -36,8 +36,7 @@ public final class ArtifactModelContainerFactory private static final Collection uris = Collections.unmodifiableList( Arrays.asList( - ProjectUri.DependencyManagement.Dependencies.Dependency.xUri, - ProjectUri.Dependencies.Dependency.xUri, + ProjectUri.DependencyManagement.Dependencies.Dependency.xUri, ProjectUri.Dependencies.Dependency.xUri, ProjectUri.Build.PluginManagement.Plugins.Plugin.xUri, ProjectUri.Build.PluginManagement.Plugins.Plugin.Dependencies.Dependency.xUri, diff --git a/maven-project/src/main/java/org/apache/maven/project/builder/PomClassicTransformer.java b/maven-project/src/main/java/org/apache/maven/project/builder/PomClassicTransformer.java index c2710d0b54..da31261a1d 100644 --- a/maven-project/src/main/java/org/apache/maven/project/builder/PomClassicTransformer.java +++ b/maven-project/src/main/java/org/apache/maven/project/builder/PomClassicTransformer.java @@ -20,13 +20,24 @@ package org.apache.maven.project.builder; */ import org.apache.maven.model.io.xpp3.MavenXpp3Reader; -import org.apache.maven.shared.model.*; +import org.apache.maven.shared.model.DomainModel; +import org.apache.maven.shared.model.ModelContainer; +import org.apache.maven.shared.model.ModelDataSource; +import org.apache.maven.shared.model.ModelMarshaller; +import org.apache.maven.shared.model.ModelProperty; +import org.apache.maven.shared.model.ModelTransformer; import org.apache.maven.shared.model.impl.DefaultModelDataSource; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import java.io.IOException; import java.io.StringReader; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.Map; +import java.util.HashMap; /** * Provides methods for transforming model properties into a domain model for the pom classic format and vice versa. @@ -38,7 +49,18 @@ public final class PomClassicTransformer /** * The URIs this tranformer supports */ - private static Set uris = new HashSet( Arrays.asList( ProjectUri.Build.Extensions.xUri, + private final Set uris; + + private static Map> cache = new HashMap>(); + + //private static List cache = new ArrayList(); + + /** + * Default constructor + */ + public PomClassicTransformer() + { + this.uris = new HashSet( Arrays.asList( ProjectUri.Build.Extensions.xUri, ProjectUri.Build.PluginManagement.Plugins.xUri, ProjectUri.Build.PluginManagement.Plugins.Plugin.Dependencies.xUri, ProjectUri.Build.PluginManagement.Plugins.Plugin.Dependencies.Dependency.Exclusions.xUri, @@ -91,21 +113,7 @@ public final class PomClassicTransformer "http://apache.org/maven/project/profiles/profile/build/plugins/plugin/dependencies/dependency/exclusions#collection", "http://apache.org/maven/project/profiles/profile/dependencyManagement/dependencies/dependency/exclusions#collection", "http://apache.org/maven/project/profiles/profile/reporting/plugins/plugin/reportSets#collection", - "http://apache.org/maven/project/profiles/profile/build/plugins/plugin/executions#collection" )); - - private static Map> cache = new HashMap>(); - - private Collection profiles; - - - //private static List cache = new ArrayList(); - - /** - * Default constructor - */ - public PomClassicTransformer(Collection profiles) - { - this.profiles = profiles; + "http://apache.org/maven/project/profiles/profile/build/plugins/plugin/executions#collection" ) ); } /** @@ -132,37 +140,6 @@ public final class PomClassicTransformer } } - //dependency management - ModelDataSource source = new DefaultModelDataSource(); - source.init( props, Arrays.asList( new ArtifactModelContainerFactory(), new IdModelContainerFactory() ) ); - - for(ModelContainer dependencyContainer : source.queryFor( ProjectUri.Dependencies.Dependency.xUri)) { - for ( ModelContainer managementContainer : source.queryFor( ProjectUri.DependencyManagement.Dependencies.Dependency.xUri) ) - { - managementContainer = new ArtifactModelContainerFactory().create(transformDependencyManagement(managementContainer.getProperties())); - ModelContainerAction action = dependencyContainer.containerAction(managementContainer); - if(action.equals(ModelContainerAction.JOIN) || action.equals(ModelContainerAction.DELETE)) { - source.join(dependencyContainer, managementContainer); - } - } - } - - for(ModelContainer dependencyContainer : source.queryFor( ProjectUri.Build.Plugins.Plugin.xUri)) { - for ( ModelContainer managementContainer : source.queryFor( ProjectUri.Build.PluginManagement.Plugins.Plugin.xUri) ) - { - managementContainer = new ArtifactModelContainerFactory().create(transformPluginManagement(managementContainer.getProperties())); - ModelContainerAction action = dependencyContainer.containerAction(managementContainer); - if(action.equals(ModelContainerAction.JOIN) || action.equals(ModelContainerAction.DELETE)) { - source.join(dependencyContainer, managementContainer); - } - } - } - - props = source.getModelProperties(); - // for(ModelProperty mp : props) { - // System.out.println("-" + mp); - // } - String xml = null; try { @@ -173,7 +150,7 @@ public final class PomClassicTransformer { throw new IOException( e + ":\r\n" + xml ); } - } + } /** * @see ModelTransformer#transformToModelProperties(java.util.List) @@ -208,7 +185,6 @@ public final class PomClassicTransformer List tmp = ModelMarshaller.marshallXmlToModelProperties( ( (PomClassicDomainModel) domainModel ).getInputStream(), ProjectUri.baseUri, uris ); - List clearedProperties = new ArrayList(); //Missing Version Rule @@ -372,7 +348,7 @@ public final class PomClassicTransformer tmp.removeAll( clearedProperties ); modelProperties.addAll( tmp ); - if ( domainModels.indexOf( domainModel ) == 0 ) + if ( domainModels.indexOf( domainModel ) > 0 ) { //cache.put( pomDomainModel.getId(), modelProperties ); } @@ -386,12 +362,7 @@ public final class PomClassicTransformer } */ } - return modelProperties; - // return ModelTransformerContext.transformModelProperties(modelProperties, Arrays.asList( - // new ProfileModelPropertyTransformer(), - // new PluginManagementModelPropertyTransformer(), - // new DependencyManagementModelPropertyTransformer() - // )); + return modelProperties; } /** @@ -443,46 +414,5 @@ public final class PomClassicTransformer } return null; } - - private static List transformDependencyManagement(List modelProperties) { - List transformedProperties = new ArrayList(); - for(ModelProperty mp : modelProperties) { - if(mp.getUri().startsWith(ProjectUri.DependencyManagement.xUri)) - { - transformedProperties.add(new ModelProperty( - mp.getUri().replace(ProjectUri.DependencyManagement.xUri, ProjectUri.xUri), mp.getValue())); - } - } - return transformedProperties; - } - - public static List transformPluginManagement(List modelProperties) { - List transformedProperties = new ArrayList(); - for(ModelProperty mp : modelProperties) { - if(mp.getUri().startsWith(ProjectUri.Build.PluginManagement.xUri)) - { - transformedProperties.add(new ModelProperty( - mp.getUri().replace(ProjectUri.Build.PluginManagement.xUri, ProjectUri.Build.xUri), mp.getValue())); - } - } - return transformedProperties; - } - - /* - private static class ProfileModelPropertyTransformer implements ModelPropertyTransformer { - public List transform(List modelProperties) { - List properties = new ArrayList(modelProperties); - List transformedProperties = new ArrayList(); - for(ModelProperty mp : modelProperties) { - String uri = mp.getUri().replace("profiles#collection/profile", ""); - } - return properties; - } - - public String getBaseUri() { - return ProjectUri.baseUri; - } - } - */ } diff --git a/maven-project/src/main/java/org/apache/maven/project/builder/Profile.java b/maven-project/src/main/java/org/apache/maven/project/builder/Profile.java deleted file mode 100644 index b778a2a4eb..0000000000 --- a/maven-project/src/main/java/org/apache/maven/project/builder/Profile.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.apache.maven.project.builder; - - -public class Profile { - - -} diff --git a/maven-project/src/main/java/org/apache/maven/project/builder/ProjectBuilder.java b/maven-project/src/main/java/org/apache/maven/project/builder/ProjectBuilder.java index 5782d8e71e..484b299933 100644 --- a/maven-project/src/main/java/org/apache/maven/project/builder/ProjectBuilder.java +++ b/maven-project/src/main/java/org/apache/maven/project/builder/ProjectBuilder.java @@ -22,7 +22,6 @@ package org.apache.maven.project.builder; import org.apache.maven.model.Model; import org.apache.maven.project.MavenProject; import org.apache.maven.shared.model.InterpolatorProperty; -import org.apache.maven.shared.model.ImportModel; import java.io.File; import java.io.IOException; @@ -50,7 +49,6 @@ public interface ProjectBuilder * @throws IOException if there is a problem in the construction of the maven project */ MavenProject buildFromLocalPath( InputStream pom, List inheritedModels, - Collection importModels, Collection interpolatorProperties, PomArtifactResolver resolver, File baseDirectory ) throws IOException; diff --git a/maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultImportModel.java b/maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultImportModel.java deleted file mode 100644 index aafd4a71ae..0000000000 --- a/maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultImportModel.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.apache.maven.project.builder.impl; - -import org.apache.maven.shared.model.ImportModel; -import org.apache.maven.shared.model.ModelProperty; - -import java.util.List; -import java.util.ArrayList; - -public final class DefaultImportModel implements ImportModel { - - private final String id; - - private final List modelProperties; - - public DefaultImportModel(String id, List modelProperties) { - if(id == null) - { - throw new IllegalArgumentException("id: null"); - } - - if(modelProperties == null) { - throw new IllegalArgumentException("modelProperties: null"); - } - this.id = id; - this.modelProperties = new ArrayList(modelProperties); - } - - public String getId() { - return id; - } - - public List getModelProperties() { - return new ArrayList(modelProperties); - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ImportModel that = (ImportModel) o; - - if (id != null ? !id.equals(that.getId()) : that.getId() != null) return false; - - return true; - } - - public int hashCode() { - return (id != null ? id.hashCode() : 0); - } -} diff --git a/maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultProjectBuilder.java b/maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultProjectBuilder.java index dd625e0603..ed37d7a430 100644 --- a/maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultProjectBuilder.java +++ b/maven-project/src/main/java/org/apache/maven/project/builder/impl/DefaultProjectBuilder.java @@ -35,7 +35,6 @@ import org.apache.maven.project.validation.ModelValidator; import org.apache.maven.shared.model.DomainModel; import org.apache.maven.shared.model.InterpolatorProperty; import org.apache.maven.shared.model.ModelTransformerContext; -import org.apache.maven.shared.model.ImportModel; import org.codehaus.plexus.logging.LogEnabled; import org.codehaus.plexus.logging.Logger; @@ -87,10 +86,9 @@ public final class DefaultProjectBuilder } /** - * @see ProjectBuilder#buildFromLocalPath(java.io.InputStream, java.util.List, java.util.Collection, java.util.Collection, org.apache.maven.project.builder.PomArtifactResolver, java.io.File) + * @see ProjectBuilder#buildFromLocalPath(java.io.InputStream, java.util.List, java.util.Collection, org.apache.maven.project.builder.PomArtifactResolver, java.io.File) */ public MavenProject buildFromLocalPath( InputStream pom, List inheritedModels, - Collection importModels, Collection interpolatorProperties, PomArtifactResolver resolver, File projectDirectory ) throws IOException @@ -151,16 +149,14 @@ public final class DefaultProjectBuilder domainModels.add( new PomClassicDomainModel( model ) ); } - PomClassicTransformer transformer = new PomClassicTransformer(null); + PomClassicTransformer transformer = new PomClassicTransformer(); ModelTransformerContext ctx = new ModelTransformerContext( Arrays.asList( new ArtifactModelContainerFactory(), new IdModelContainerFactory() ) ); PomClassicDomainModel transformedDomainModel = - ( (PomClassicDomainModel) ctx.transform( domainModels, transformer, transformer, importModels, properties ) ); - - + ( (PomClassicDomainModel) ctx.transform( domainModels, transformer, transformer, null, properties ) ); Model model = transformedDomainModel.getModel(); - return new MavenProject( model, artifactFactory ); + return new MavenProject( model ); } private boolean isParentLocal( Parent parent, File projectDirectory ) diff --git a/maven-project/src/test/java/org/apache/maven/project/workspace/DefaultProjectWorkspaceTest.java b/maven-project/src/test/java/org/apache/maven/project/workspace/DefaultProjectWorkspaceTest.java new file mode 100644 index 0000000000..19cfbcf408 --- /dev/null +++ b/maven-project/src/test/java/org/apache/maven/project/workspace/DefaultProjectWorkspaceTest.java @@ -0,0 +1,91 @@ +package org.apache.maven.project.workspace; + +import org.apache.maven.model.Model; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.build.model.ModelAndFile; +import org.apache.maven.workspace.DefaultMavenWorkspaceStore; +import org.codehaus.plexus.logging.Logger; +import org.codehaus.plexus.logging.console.ConsoleLogger; + +import java.io.File; + +import junit.framework.TestCase; + +public class DefaultProjectWorkspaceTest + extends TestCase +{ + + public void testStoreAndRetrieveModelAndFile() + { + ModelAndFile maf = newModelAndFile( "group", "artifact", "1" ); + + DefaultProjectWorkspace ws = newWorkspace(); + ws.storeModelAndFile( maf ); + + ModelAndFile r1 = ws.getModelAndFile( maf.getFile() ); + + assertSame( maf, r1 ); + + ModelAndFile r2 = ws.getModelAndFile( maf.getModel().getGroupId(), maf.getModel().getArtifactId(), maf.getModel().getVersion() ); + + assertSame( maf, r2 ); + } + + private DefaultProjectWorkspace newWorkspace() + { + DefaultProjectWorkspace ws = new DefaultProjectWorkspace( new DefaultMavenWorkspaceStore(), new ConsoleLogger( Logger.LEVEL_INFO, "test" ) ); + return ws; + } + + public void testStoreAndRetrieveProjectByFile_CoordinateRetrievalReturnsNull() + { + MavenProject project = newProject( "group", "artifact", "1" ); + + DefaultProjectWorkspace ws = newWorkspace(); + ws.storeProjectByFile( project ); + + assertSame( project, ws.getProject( project.getFile() ) ); + assertNull( ws.getProject( project.getGroupId(), project.getArtifactId(), project.getVersion() ) ); + } + + public void testStoreAndRetrieveProjectByCoordinate_FileRetrievalReturnsNull() + { + MavenProject project = newProject( "group", "artifact", "1" ); + + DefaultProjectWorkspace ws = newWorkspace(); + ws.storeProjectByCoordinate( project ); + + assertNull( ws.getProject( project.getFile() ) ); + assertSame( project, ws.getProject( project.getGroupId(), project.getArtifactId(), project.getVersion() ) ); + } + + private MavenProject newProject( String gid, + String aid, + String ver ) + { + File f = new File( "test-project" ); + Model model = new Model(); + model.setGroupId( gid ); + model.setArtifactId( aid ); + model.setVersion( ver ); + + MavenProject project = new MavenProject( model ); + project.setFile( f ); + return project; + } + + private ModelAndFile newModelAndFile( String gid, + String aid, + String ver ) + { + File f = new File( "test-modelAndFile" ); + Model model = new Model(); + model.setGroupId( gid ); + model.setArtifactId( aid ); + model.setVersion( ver ); + + ModelAndFile maf = new ModelAndFile( model, f, false ); + return maf; + } + +} diff --git a/maven-project/src/test/java/org/apache/maven/project/workspace/ModelAndFileCachingTest.java b/maven-project/src/test/java/org/apache/maven/project/workspace/ModelAndFileCachingTest.java new file mode 100644 index 0000000000..5da0042441 --- /dev/null +++ b/maven-project/src/test/java/org/apache/maven/project/workspace/ModelAndFileCachingTest.java @@ -0,0 +1,241 @@ +package org.apache.maven.project.workspace; + +import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; +import org.apache.maven.model.Model; +import org.apache.maven.profiles.DefaultProfileManager; +import org.apache.maven.profiles.ProfileManager; +import org.apache.maven.profiles.activation.DefaultProfileActivationContext; +import org.apache.maven.project.DefaultProjectBuilderConfiguration; +import org.apache.maven.project.ProjectBuildingException; +import org.apache.maven.project.build.model.ModelAndFile; +import org.apache.maven.project.build.model.ModelLineage; +import org.apache.maven.project.build.model.ModelLineageBuilder; +import org.apache.maven.workspace.MavenWorkspaceStore; +import org.codehaus.plexus.PlexusTestCase; +import org.codehaus.plexus.logging.Logger; +import org.codehaus.plexus.util.FileUtils; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +public class ModelAndFileCachingTest + extends PlexusTestCase +{ + + private static final String MY_PKG = ModelAndFileCachingTest.class.getPackage().getName().replace( '.', '/' ); + + private static final String MY_PATH = ModelAndFileCachingTest.class.getName() + .replace( '.', '/' ) + + ".class"; + + private ProjectWorkspace projectWorkspace; + + private MavenWorkspaceStore workspaceStore; + + private ModelLineageBuilder lineageBuilder; + + private ArtifactRepositoryFactory repoFactory; + + private ProfileManager profileManager; + + private ArtifactRepository localRepo; + + private ArtifactFactory artifactFactory; + + private List dirsToDelete = new ArrayList(); + + public void setUp() + throws Exception + { + super.setUp(); + getContainer().getLoggerManager().setThresholds( Logger.LEVEL_DEBUG ); + + projectWorkspace = (ProjectWorkspace) lookup( ProjectWorkspace.class ); + workspaceStore = (MavenWorkspaceStore) lookup( MavenWorkspaceStore.class ); + lineageBuilder = (ModelLineageBuilder) lookup( ModelLineageBuilder.class ); + repoFactory = (ArtifactRepositoryFactory) lookup( ArtifactRepositoryFactory.class ); + artifactFactory = (ArtifactFactory) lookup( ArtifactFactory.class ); + + File localRepoDir = File.createTempFile( "local-repo.", ".tmp" ); + localRepoDir.delete(); + localRepoDir.mkdirs(); + + dirsToDelete.add( localRepoDir ); + + localRepo = repoFactory.createLocalRepository( localRepoDir ); + profileManager = new DefaultProfileManager( + getContainer(), + new DefaultProfileActivationContext( + System.getProperties(), + true ) ); + } + + public void tearDown() + throws Exception + { + workspaceStore.clear(); + + if ( !dirsToDelete.isEmpty() ) + { + for ( Iterator it = dirsToDelete.iterator(); it.hasNext(); ) + { + File dir = (File) it.next(); + try + { + FileUtils.deleteDirectory( dir ); + } + catch ( IOException e ) + { + // ignore. + } + } + } + + super.tearDown(); + } + + public void testResolveParentPom_PreferCachedInstance() + throws IOException, ProjectBuildingException + { + File childPomFile = getFile( "resolveParentPom/pom.xml" ); + + String gid = "tests"; + String aid = "resolve-parent-pom-parent"; + String ver = "1"; + + ModelAndFile maf = newModelAndFile( gid, aid, ver ); + projectWorkspace.storeModelAndFile( maf ); + + ModelLineage lineage = lineageBuilder.buildModelLineage( childPomFile, + new DefaultProjectBuilderConfiguration().setLocalRepository( localRepo ).setGlobalProfileManager( profileManager ), + Collections.EMPTY_LIST, + false, + false ); + + assertSame( maf.getModel(), lineage.getDeepestAncestorModel() ); + } + + public void testResolveParentPom_StoreByFileAndGAVIfUncached() + throws IOException, ProjectBuildingException + { + File childPomFile = getFile( "resolveParentPom/childAndParent/child/pom.xml" ); + File parentPomFile = new File( childPomFile.getParentFile().getParentFile(), "pom.xml" ); + + String gid = "tests"; + String aid = "childAndParent-parent"; + String ver = "1"; + + ModelLineage lineage = lineageBuilder.buildModelLineage( childPomFile, + new DefaultProjectBuilderConfiguration().setLocalRepository( localRepo ).setGlobalProfileManager( profileManager ), + Collections.EMPTY_LIST, + false, + true ); + + assertEquals( parentPomFile.getCanonicalPath(), lineage.getDeepestAncestorFile() + .getCanonicalPath() ); + + ModelAndFile maf1 = projectWorkspace.getModelAndFile( gid, aid, ver ); + assertNotNull( maf1 ); + assertSame( maf1.getModel(), lineage.getDeepestAncestorModel() ); + + ModelAndFile maf2 = projectWorkspace.getModelAndFile( parentPomFile ); + assertNotNull( maf2 ); + assertSame( maf2.getModel(), lineage.getDeepestAncestorModel() ); + } + + public void testReadModel_PreferModelInstanceCachedByFile() + throws IOException, ProjectBuildingException + { + File pomFile = new File( "test/pom.xml" ); + + String gid = "tests"; + String aid = "read-model"; + String ver = "1"; + + ModelAndFile maf = newModelAndFile( gid, aid, ver, pomFile ); + projectWorkspace.storeModelAndFile( maf ); + + ModelLineage lineage = lineageBuilder.buildModelLineage( pomFile, + new DefaultProjectBuilderConfiguration().setLocalRepository( localRepo ).setGlobalProfileManager( profileManager ), + Collections.EMPTY_LIST, + false, + false ); + + assertSame( maf.getModel(), lineage.getOriginatingModel() ); + } + + public void testBuildModelLineage_StoreByFileAndGAVIfUncached() + throws IOException, ProjectBuildingException + { + File pomFile = getFile( "buildModelLineage/pom.xml" ); + + String gid = "tests"; + String aid = "build-model-lineage"; + String ver = "1"; + + ModelLineage lineage = lineageBuilder.buildModelLineage( pomFile, + new DefaultProjectBuilderConfiguration().setLocalRepository( localRepo ).setGlobalProfileManager( profileManager ), + Collections.EMPTY_LIST, + false, + false ); + + assertEquals( pomFile.getCanonicalPath(), lineage.getOriginatingPOMFile() + .getCanonicalPath() ); + + ModelAndFile maf1 = projectWorkspace.getModelAndFile( gid, aid, ver ); + assertNotNull( maf1 ); + assertSame( maf1.getModel(), lineage.getOriginatingModel() ); + + ModelAndFile maf2 = projectWorkspace.getModelAndFile( pomFile ); + assertNotNull( maf2 ); + assertSame( maf2.getModel(), lineage.getOriginatingModel() ); + } + + private ModelAndFile newModelAndFile( String gid, + String aid, + String ver ) + throws IOException + { + return newModelAndFile( gid, aid, ver, File.createTempFile( "model-and-file.", ".tmp" ) ); + } + + private ModelAndFile newModelAndFile( String gid, + String aid, + String ver, + File file ) + { + Model model = new Model(); + model.setGroupId( gid ); + model.setArtifactId( aid ); + model.setVersion( ver ); + + ModelAndFile maf = new ModelAndFile( model, file, false ); + + return maf; + } + + private File getFile( String path ) + { + ClassLoader cloader = Thread.currentThread().getContextClassLoader(); + URL res = cloader.getResource( MY_PATH ); + + File myFile = new File( res.getPath() ); + + File result = new File( myFile.getParentFile(), path ); + + if ( !result.exists() ) + { + result = new File( "src/test/resources", MY_PKG + "/" + path ); + } + + return result; + } + +} diff --git a/maven-project/src/test/java/org/apache/maven/project/workspace/ProjectCachingTest.java b/maven-project/src/test/java/org/apache/maven/project/workspace/ProjectCachingTest.java new file mode 100644 index 0000000000..9280d5fced --- /dev/null +++ b/maven-project/src/test/java/org/apache/maven/project/workspace/ProjectCachingTest.java @@ -0,0 +1,286 @@ +package org.apache.maven.project.workspace; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.InvalidRepositoryException; +import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; +import org.apache.maven.model.Model; +import org.apache.maven.profiles.DefaultProfileManager; +import org.apache.maven.profiles.ProfileManager; +import org.apache.maven.profiles.activation.DefaultProfileActivationContext; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.MavenProjectBuilder; +import org.apache.maven.project.ProjectBuildingException; +import org.apache.maven.project.build.model.ModelLineageBuilder; +import org.apache.maven.workspace.MavenWorkspaceStore; +import org.codehaus.plexus.PlexusTestCase; +import org.codehaus.plexus.logging.Logger; +import org.codehaus.plexus.util.FileUtils; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +// TODO: Add conversion/tests for modelAndFileCache -> projectWorkspace stuff in simple cases. +// TODO: Add tests for project parents from cache (using model-and-file stuff, maybe?) +public class ProjectCachingTest + extends PlexusTestCase +{ + + private static final String MY_PATH = ProjectCachingTest.class.getName().replace( '.', '/' ) + + ".class"; + + private ProjectWorkspace projectWorkspace; + + private MavenWorkspaceStore workspaceStore; + + private MavenProjectBuilder projectBuilder; + + private ModelLineageBuilder lineageBuilder; + + private ArtifactRepositoryFactory repoFactory; + + private ProfileManager profileManager; + + private ArtifactRepository localRepo; + + private ArtifactFactory artifactFactory; + + private List dirsToDelete = new ArrayList(); + + public void setUp() + throws Exception + { + super.setUp(); + getContainer().getLoggerManager().setThresholds( Logger.LEVEL_DEBUG ); + + projectWorkspace = (ProjectWorkspace) lookup( ProjectWorkspace.class ); + workspaceStore = (MavenWorkspaceStore) lookup( MavenWorkspaceStore.class ); + projectBuilder = (MavenProjectBuilder) lookup( MavenProjectBuilder.class ); + lineageBuilder = (ModelLineageBuilder) lookup( ModelLineageBuilder.class ); + repoFactory = (ArtifactRepositoryFactory) lookup( ArtifactRepositoryFactory.class ); + artifactFactory = (ArtifactFactory) lookup( ArtifactFactory.class ); + + File localRepoDir = File.createTempFile( "local-repo.", ".tmp" ); + localRepoDir.delete(); + localRepoDir.mkdirs(); + + dirsToDelete.add( localRepoDir ); + + localRepo = repoFactory.createLocalRepository( localRepoDir ); + profileManager = new DefaultProfileManager( + getContainer(), + new DefaultProfileActivationContext( + System.getProperties(), + true ) ); + } + + public void tearDown() + throws Exception + { + workspaceStore.clear(); + + if ( !dirsToDelete.isEmpty() ) + { + for ( Iterator it = dirsToDelete.iterator(); it.hasNext(); ) + { + File dir = (File) it.next(); + try + { + FileUtils.deleteDirectory( dir ); + } + catch ( IOException e ) + { + // ignore. + } + } + } + + super.tearDown(); + } + + public void testBuildFromRepository_PreferCachedProject() + throws ProjectBuildingException + { + String gid = "org.apache.maven.tests"; + String aid = "buildFromRepo-checkCacheFirst"; + String ver = "1"; + + MavenProject project = newProject( gid, aid, ver ); + projectWorkspace.storeProjectByCoordinate( project ); + + Artifact artifact = artifactFactory.createProjectArtifact( gid, aid, ver ); + + MavenProject result = projectBuilder.buildFromRepository( artifact, + Collections.EMPTY_LIST, + localRepo ); + + assertSame( project, result ); + } + + public void testBuildFromRepository_StoreProjectByCoordOnlyIfUncached() + throws ProjectBuildingException, InvalidRepositoryException + { + File lrDir = getFile( "buildFromRepo" ); + File pomFile = new File( lrDir, "tests/project-caching/1/project-caching-1.pom" ); + + String gid = "tests"; + String aid = "project-caching"; + String ver = "1"; + + Artifact artifact = artifactFactory.createProjectArtifact( gid, aid, ver ); + + ArtifactRepository localRepo = repoFactory.createLocalRepository( lrDir ); + + MavenProject project = projectBuilder.buildFromRepository( artifact, + Collections.EMPTY_LIST, + localRepo ); + + MavenProject r1 = projectWorkspace.getProject( pomFile ); + + MavenProject r2 = projectWorkspace.getProject( gid, aid, ver ); + + assertNull( r1 ); + + assertSame( project, r2 ); + } + + public void testBuildFromRepository_DontCheckCacheForRELEASEMetaVersion() + throws ProjectBuildingException, InvalidRepositoryException + { + File lrDir = getFile( "buildFromRepo" ); + File pomFile = new File( lrDir, "tests/project-caching/1/project-caching-1.pom" ); + + String gid = "tests"; + String aid = "project-caching"; + String ver = "1"; + + MavenProject seed = newProject( gid, aid, ver ); + + Artifact artifact = artifactFactory.createProjectArtifact( gid, + aid, + Artifact.RELEASE_VERSION ); + + ArtifactRepository localRepo = repoFactory.createLocalRepository( lrDir ); + + MavenProject project = projectBuilder.buildFromRepository( artifact, + Collections.EMPTY_LIST, + localRepo ); + + assertNotSame( seed, project ); + + MavenProject r1 = projectWorkspace.getProject( pomFile ); + + MavenProject r2 = projectWorkspace.getProject( gid, aid, ver ); + + assertNull( r1 ); + + assertSame( project, r2 ); + } + + public void testBuildFromRepository_DontCheckCacheForLATESTMetaVersion() + throws ProjectBuildingException, InvalidRepositoryException + { + File lrDir = getFile( "buildFromRepo" ); + File pomFile = new File( lrDir, "tests/project-caching/1/project-caching-1.pom" ); + + String gid = "tests"; + String aid = "project-caching"; + String ver = "1"; + + MavenProject seed = newProject( gid, aid, ver ); + projectWorkspace.storeProjectByCoordinate( seed ); + + Artifact artifact = artifactFactory.createProjectArtifact( gid, + aid, + Artifact.RELEASE_VERSION ); + + ArtifactRepository localRepo = repoFactory.createLocalRepository( lrDir ); + + MavenProject project = projectBuilder.buildFromRepository( artifact, + Collections.EMPTY_LIST, + localRepo ); + + assertNotSame( seed, project ); + + MavenProject r1 = projectWorkspace.getProject( pomFile ); + + MavenProject r2 = projectWorkspace.getProject( gid, aid, ver ); + + assertNull( r1 ); + + assertSame( project, r2 ); + } + + public void testBuildFromFile_PreferProjectCachedByFile() + throws ProjectBuildingException, InvalidRepositoryException + { + File pomFile = getFile( "buildFromFile/pom.xml" ); + + String gid = "org.apache.maven.tests"; + String aid = "build-from-file"; + String ver = "1"; + + MavenProject seed = newProject( gid, aid, ver ); + seed.setFile( pomFile ); + + projectWorkspace.storeProjectByFile( seed ); + + MavenProject project = projectBuilder.build( pomFile, localRepo, profileManager ); + + assertSame( seed, project ); + + assertNull( projectWorkspace.getProject( gid, aid, ver ) ); + } + + public void testBuildFromFile_StoreByCoordAndFileIfUncached() + throws ProjectBuildingException, InvalidRepositoryException + { + File pomFile = getFile( "buildFromFile/pom.xml" ); + + String gid = "org.apache.maven.tests"; + String aid = "build-from-file"; + String ver = "1"; + + assertNull( projectWorkspace.getProject( pomFile ) ); + assertNull( projectWorkspace.getProject( gid, aid, ver ) ); + + MavenProject project = projectBuilder.build( pomFile, localRepo, profileManager ); + + MavenProject byFile = projectWorkspace.getProject( pomFile ); + MavenProject byCoord = projectWorkspace.getProject( gid, aid, ver ); + + assertSame( project, byFile ); + assertSame( project, byCoord ); + } + + private MavenProject newProject( String gid, + String aid, + String ver ) + { + Model model = new Model(); + model.setGroupId( gid ); + model.setArtifactId( aid ); + model.setVersion( ver ); + + MavenProject project = new MavenProject( model ); + + return project; + } + + private File getFile( String path ) + { + ClassLoader cloader = Thread.currentThread().getContextClassLoader(); + URL myRes = cloader.getResource( MY_PATH ); + + File myFile = new File( myRes.getPath() ); + + return new File( myFile.getParentFile(), path ); + } + +}