diff --git a/pom.xml b/pom.xml index 9f2b5231..89dee9e0 100644 --- a/pom.xml +++ b/pom.xml @@ -33,10 +33,8 @@ Maven Flatten Plugin - - Plugin to generate flattened POM (reduced and resolved information required for consumers of maven repositories) - and to use (install, sign, deploy) it instead of original pom.xml. - + Plugin to generate flattened POM (reduced and resolved information required for consumers of maven repositories) + and to use (install, sign, deploy) it instead of original pom.xml. https://www.mojohaus.org/flatten-maven-plugin/ @@ -64,10 +62,10 @@ rfscholte Robert Scholte rfscholte@apache.org - Europe/Amsterdam developer + Europe/Amsterdam khmarbaise @@ -80,10 +78,10 @@ sjaranowski Slawomir Jaranowski sjaranowski@apache.org - Europe/Warsaw developer + Europe/Warsaw @@ -124,8 +122,8 @@ scm:git:https://github.com/mojohaus/flatten-maven-plugin.git scm:git:ssh://git@github.com/mojohaus/flatten-maven-plugin.git - https://github.com/mojohaus/flatten-maven-plugin/tree/master HEAD + https://github.com/mojohaus/flatten-maven-plugin/tree/master @@ -283,15 +281,6 @@ org.apache.maven.plugins maven-invoker-plugin - - - - install - integration-test - verify - - - true ${project.build.directory}/it @@ -310,19 +299,20 @@ verify setup - - - - org.codehaus.mojo - mrm-maven-plugin - start - stop + install + integration-test + verify + + + + org.codehaus.mojo + mrm-maven-plugin repository.proxy.url @@ -335,6 +325,14 @@ + + + + start + stop + + + diff --git a/src/main/java/org/codehaus/mojo/flatten/AbstractFlattenMojo.java b/src/main/java/org/codehaus/mojo/flatten/AbstractFlattenMojo.java index 83bfd072..9c48435d 100644 --- a/src/main/java/org/codehaus/mojo/flatten/AbstractFlattenMojo.java +++ b/src/main/java/org/codehaus/mojo/flatten/AbstractFlattenMojo.java @@ -1,81 +1,74 @@ -package org.codehaus.mojo.flatten; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; - -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugins.annotations.Parameter; - -/** - * This is the abstract base class for {@link AbstractMojo MOJOs} that realize the different goals of this plugin. - * - * @author Joerg Hohwiller (hohwille at users.sourceforge.net) - */ -public abstract class AbstractFlattenMojo - extends AbstractMojo -{ - - /** - * The directory where the generated flattened POM file will be written to. - */ - @Parameter( defaultValue = "${project.basedir}" ) - private File outputDirectory; - - /** - * The filename of the generated flattened POM file. - */ - @Parameter( property = "flattenedPomFilename", defaultValue = ".flattened-pom.xml" ) - private String flattenedPomFilename; - - /** - * The constructor. - */ - public AbstractFlattenMojo() - { - - super(); - } - - /** - * @return the filename of the generated flattened POM file. - */ - public String getFlattenedPomFilename() - { - return this.flattenedPomFilename; - } - - /** - * @return the directory where the generated flattened POM file will be written to. - */ - public File getOutputDirectory() - { - return this.outputDirectory; - } - - /** - * @return a {@link File} instance pointing to the flattened POM. - */ - protected File getFlattenedPomFile() - { - return new File( getOutputDirectory(), getFlattenedPomFilename() ); - } - -} +package org.codehaus.mojo.flatten; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.File; + +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugins.annotations.Parameter; + +/** + * This is the abstract base class for {@link AbstractMojo MOJOs} that realize the different goals of this plugin. + * + * @author Joerg Hohwiller (hohwille at users.sourceforge.net) + */ +public abstract class AbstractFlattenMojo extends AbstractMojo { + + /** + * The directory where the generated flattened POM file will be written to. + */ + @Parameter(defaultValue = "${project.basedir}") + private File outputDirectory; + + /** + * The filename of the generated flattened POM file. + */ + @Parameter(property = "flattenedPomFilename", defaultValue = ".flattened-pom.xml") + private String flattenedPomFilename; + + /** + * The constructor. + */ + public AbstractFlattenMojo() { + + super(); + } + + /** + * @return the filename of the generated flattened POM file. + */ + public String getFlattenedPomFilename() { + return this.flattenedPomFilename; + } + + /** + * @return the directory where the generated flattened POM file will be written to. + */ + public File getOutputDirectory() { + return this.outputDirectory; + } + + /** + * @return a {@link File} instance pointing to the flattened POM. + */ + protected File getFlattenedPomFile() { + return new File(getOutputDirectory(), getFlattenedPomFilename()); + } +} diff --git a/src/main/java/org/codehaus/mojo/flatten/CleanMojo.java b/src/main/java/org/codehaus/mojo/flatten/CleanMojo.java index 7b46b406..9ff42c36 100644 --- a/src/main/java/org/codehaus/mojo/flatten/CleanMojo.java +++ b/src/main/java/org/codehaus/mojo/flatten/CleanMojo.java @@ -1,70 +1,66 @@ -package org.codehaus.mojo.flatten; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Mojo; - -/** - * This MOJO realizes the goal flatten:clean that deletes any files created by - * {@link FlattenMojo flatten:flatten} (more specific the flattened POM file which is by default - * .flattened-pom.xml). See also MOJO-2030 for - * further details. - * - * @author Joerg Hohwiller (hohwille at users.sourceforge.net) - * @since 1.0.0-beta-2 - */ -@Mojo( name = "clean", requiresProject = true, requiresDirectInvocation = false, executionStrategy = "once-per-session", - threadSafe = true ) -public class CleanMojo - extends AbstractFlattenMojo -{ - - /** - * The constructor. - */ - public CleanMojo() - { - super(); - } - - /** - * {@inheritDoc} - */ - public void execute() - throws MojoExecutionException, MojoFailureException - { - - File flattenedPomFile = getFlattenedPomFile(); - if ( flattenedPomFile.isFile() ) - { - getLog().info( "Deleting " + flattenedPomFile.getPath() ); - boolean deleted = flattenedPomFile.delete(); - if ( !deleted ) - { - throw new MojoFailureException( "Could not delete " + flattenedPomFile.getAbsolutePath() ); - } - } - } - -} +package org.codehaus.mojo.flatten; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.File; + +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.Mojo; + +/** + * This MOJO realizes the goal flatten:clean that deletes any files created by + * {@link FlattenMojo flatten:flatten} (more specific the flattened POM file which is by default + * .flattened-pom.xml). See also MOJO-2030 for + * further details. + * + * @author Joerg Hohwiller (hohwille at users.sourceforge.net) + * @since 1.0.0-beta-2 + */ +@Mojo( + name = "clean", + requiresProject = true, + requiresDirectInvocation = false, + executionStrategy = "once-per-session", + threadSafe = true) +public class CleanMojo extends AbstractFlattenMojo { + + /** + * The constructor. + */ + public CleanMojo() { + super(); + } + + /** + * {@inheritDoc} + */ + public void execute() throws MojoExecutionException, MojoFailureException { + + File flattenedPomFile = getFlattenedPomFile(); + if (flattenedPomFile.isFile()) { + getLog().info("Deleting " + flattenedPomFile.getPath()); + boolean deleted = flattenedPomFile.delete(); + if (!deleted) { + throw new MojoFailureException("Could not delete " + flattenedPomFile.getAbsolutePath()); + } + } + } +} diff --git a/src/main/java/org/codehaus/mojo/flatten/Dependencies.java b/src/main/java/org/codehaus/mojo/flatten/Dependencies.java index 01de15bb..511b5dde 100644 --- a/src/main/java/org/codehaus/mojo/flatten/Dependencies.java +++ b/src/main/java/org/codehaus/mojo/flatten/Dependencies.java @@ -30,11 +30,10 @@ * This is a simple container for {@link Dependency} objects. Rather than using a {@link List} this object allows * operations like {@link #contains(Dependency)} that work reliably even though {@link Dependency} class does not * properly implement {@link Object#equals(Object) equals}. - * + * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) */ -public class Dependencies -{ +public class Dependencies { /** @see #add(Dependency) */ private final Map key2DependencyMap; @@ -42,8 +41,7 @@ public class Dependencies /** * The constructor. */ - public Dependencies() - { + public Dependencies() { super(); this.key2DependencyMap = new HashMap<>(); @@ -54,8 +52,7 @@ public Dependencies() * . * @return the {@link java.util.Map.Entry#getKey() key} for the {@link Dependency}. */ - protected String getKey( Dependency dependency ) - { + protected String getKey(Dependency dependency) { return dependency.getManagementKey() + ":" + dependency.getClassifier(); } @@ -63,23 +60,20 @@ protected String getKey( Dependency dependency ) /** * @param dependencies the {@link List} of {@link Dependency} objects to {@link #add(Dependency) add}. */ - public void addAll( List dependencies ) - { - dependencies.forEach( this::add ); + public void addAll(List dependencies) { + dependencies.forEach(this::add); } /** * @param dependency the {@link Dependency} to add. */ - public void add( Dependency dependency ) - { - - String key = getKey( dependency ); - Dependency replaced = this.key2DependencyMap.put( key, dependency ); - if ( replaced != null ) - { - throw new IllegalStateException( "Duplicate dependency! Original: " + getKey( replaced ) + " duplicate: " - + getKey( dependency ) ); + public void add(Dependency dependency) { + + String key = getKey(dependency); + Dependency replaced = this.key2DependencyMap.put(key, dependency); + if (replaced != null) { + throw new IllegalStateException( + "Duplicate dependency! Original: " + getKey(replaced) + " duplicate: " + getKey(dependency)); } } @@ -88,33 +82,28 @@ public void add( Dependency dependency ) * @return true if the given {@link Dependency} is contained in these {@link Dependencies}, * false otherwise. */ - public boolean contains( Dependency dependency ) - { + public boolean contains(Dependency dependency) { // ATTENTION: Dependency does not have a proper equals implementation, we only check that the key is // contained. However, this should be sufficient for all reasonable scenarios... - return this.key2DependencyMap.containsKey( getKey( dependency ) ); + return this.key2DependencyMap.containsKey(getKey(dependency)); } /** - * + * * @param dependency the {@link Dependency} to resolve. * @return a full declared {@link Dependency} */ - public Dependency resolve( Dependency dependency ) - { - return this.key2DependencyMap.get( getKey( dependency ) ); + public Dependency resolve(Dependency dependency) { + return this.key2DependencyMap.get(getKey(dependency)); } - - + /** * @return a {@link List} with the {@link Dependency} objects contained in these {@link Dependencies}. */ - public List toList() - { + public List toList() { - List result = new ArrayList<>( this.key2DependencyMap.values() ); + List result = new ArrayList<>(this.key2DependencyMap.values()); return result; } - } diff --git a/src/main/java/org/codehaus/mojo/flatten/DirectDependenciesInheritanceAssembler.java b/src/main/java/org/codehaus/mojo/flatten/DirectDependenciesInheritanceAssembler.java index 8945781e..bcc878e4 100644 --- a/src/main/java/org/codehaus/mojo/flatten/DirectDependenciesInheritanceAssembler.java +++ b/src/main/java/org/codehaus/mojo/flatten/DirectDependenciesInheritanceAssembler.java @@ -18,12 +18,12 @@ */ package org.codehaus.mojo.flatten; -import java.util.HashMap; -import java.util.Map; - import javax.inject.Named; import javax.inject.Singleton; +import java.util.HashMap; +import java.util.Map; + import org.apache.maven.model.Model; import org.apache.maven.model.ModelBase; import org.apache.maven.model.building.ModelBuildingRequest; @@ -43,11 +43,9 @@ * @author kemalsoysal * @author ralfluebeck */ - @Singleton @Named -public class DirectDependenciesInheritanceAssembler extends DefaultInheritanceAssembler -{ +public class DirectDependenciesInheritanceAssembler extends DefaultInheritanceAssembler { protected InheritanceModelMerger merger = new DirectDependenciesInheritanceModelMerger(); @@ -66,19 +64,16 @@ public class DirectDependenciesInheritanceAssembler extends DefaultInheritanceAs /** * */ - public DirectDependenciesInheritanceAssembler( ) - { - } + public DirectDependenciesInheritanceAssembler() {} @Override - public void assembleModelInheritance( Model child, Model parent, ModelBuildingRequest request, - ModelProblemCollector problems ) - { + public void assembleModelInheritance( + Model child, Model parent, ModelBuildingRequest request, ModelProblemCollector problems) { Map hints = new HashMap<>(); - String childPath = child.getProperties().getProperty( CHILD_DIRECTORY_PROPERTY, child.getArtifactId() ); - hints.put( CHILD_DIRECTORY, childPath ); - hints.put( MavenModelMerger.CHILD_PATH_ADJUSTMENT, getChildPathAdjustment( child, parent, childPath ) ); - merger.merge( child, parent, false, hints ); + String childPath = child.getProperties().getProperty(CHILD_DIRECTORY_PROPERTY, child.getArtifactId()); + hints.put(CHILD_DIRECTORY, childPath); + hints.put(MavenModelMerger.CHILD_PATH_ADJUSTMENT, getChildPathAdjustment(child, parent, childPath)); + merger.merge(child, parent, false, hints); } /** @@ -90,12 +85,10 @@ public void assembleModelInheritance( Model child, Model parent, ModelBuildingRe * @param childDirectory * @return */ - private String getChildPathAdjustment( Model child, Model parent, String childDirectory ) - { + private String getChildPathAdjustment(Model child, Model parent, String childDirectory) { String adjustment = ""; - if ( parent != null ) - { + if (parent != null) { String childName = child.getArtifactId(); /* @@ -107,33 +100,28 @@ private String getChildPathAdjustment( Model child, Model parent, String childDi * URLs depending on how the model was constructed (from filesystem or from * repository). */ - if ( child.getProjectDirectory() != null ) - { + if (child.getProjectDirectory() != null) { childName = child.getProjectDirectory().getName(); } - for ( String module : parent.getModules() ) - { - module = module.replace( '\\', '/' ); + for (String module : parent.getModules()) { + module = module.replace('\\', '/'); - if ( module.regionMatches( true, module.length() - 4, ".xml", 0, 4 ) ) - { - module = module.substring( 0, module.lastIndexOf( '/' ) + 1 ); + if (module.regionMatches(true, module.length() - 4, ".xml", 0, 4)) { + module = module.substring(0, module.lastIndexOf('/') + 1); } String moduleName = module; - if ( moduleName.endsWith( "/" ) ) - { - moduleName = moduleName.substring( 0, moduleName.length() - 1 ); + if (moduleName.endsWith("/")) { + moduleName = moduleName.substring(0, moduleName.length() - 1); } - int lastSlash = moduleName.lastIndexOf( '/' ); + int lastSlash = moduleName.lastIndexOf('/'); - moduleName = moduleName.substring( lastSlash + 1 ); + moduleName = moduleName.substring(lastSlash + 1); - if ( ( moduleName.equals( childName ) || ( moduleName.equals( childDirectory ) ) ) && lastSlash >= 0 ) - { - adjustment = module.substring( 0, lastSlash ); + if ((moduleName.equals(childName) || (moduleName.equals(childDirectory))) && lastSlash >= 0) { + adjustment = module.substring(0, lastSlash); break; } } @@ -146,24 +134,20 @@ private String getChildPathAdjustment( Model child, Model parent, String childDi * InheritanceModelMerger */ protected class DirectDependenciesInheritanceModelMerger - extends DefaultInheritanceAssembler.InheritanceModelMerger - { + extends DefaultInheritanceAssembler.InheritanceModelMerger { @Override - public void merge( Model target, Model source, boolean sourceDominant, Map hints ) - { - super.merge( target, source, sourceDominant, hints ); + public void merge(Model target, Model source, boolean sourceDominant, Map hints) { + super.merge(target, source, sourceDominant, hints); } @Override - protected void mergeModelBase_Dependencies( ModelBase target, ModelBase source, boolean sourceDominant, - Map context ) - { - if ( flattenDependencyMode == null || flattenDependencyMode == FlattenDependencyMode.direct ) - { + protected void mergeModelBase_Dependencies( + ModelBase target, ModelBase source, boolean sourceDominant, Map context) { + if (flattenDependencyMode == null || flattenDependencyMode == FlattenDependencyMode.direct) { return; } - super.mergeModelBase_Dependencies( target, source, sourceDominant, context ); + super.mergeModelBase_Dependencies(target, source, sourceDominant, context); } } } diff --git a/src/main/java/org/codehaus/mojo/flatten/ElementHandling.java b/src/main/java/org/codehaus/mojo/flatten/ElementHandling.java index be14b463..cee0c0f6 100644 --- a/src/main/java/org/codehaus/mojo/flatten/ElementHandling.java +++ b/src/main/java/org/codehaus/mojo/flatten/ElementHandling.java @@ -1,52 +1,50 @@ -package org.codehaus.mojo.flatten; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This enum contains each available handling for a POM element when flattening. - * - * @author Joerg Hohwiller (hohwille at users.sourceforge.net) - * @since 1.0.0-beta-4 - */ -public enum ElementHandling -{ - - /** - * Flatten the element. For most elements this means that they will be removed and are not present in the flattened - * POM. - */ - flatten, - - /** Take the element from the effective POM. */ - expand, - - /** Take the element from the resolved POM. */ - resolve, - - /** Take the element from the interpolated POM (original POM with variables interpolated). */ - interpolate, - - /** Take the element untouched from the original POM. */ - keep, - - /** Remove the element entirely so it will not be present in flattened POM. */ - remove - -} +package org.codehaus.mojo.flatten; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/** + * This enum contains each available handling for a POM element when flattening. + * + * @author Joerg Hohwiller (hohwille at users.sourceforge.net) + * @since 1.0.0-beta-4 + */ +public enum ElementHandling { + + /** + * Flatten the element. For most elements this means that they will be removed and are not present in the flattened + * POM. + */ + flatten, + + /** Take the element from the effective POM. */ + expand, + + /** Take the element from the resolved POM. */ + resolve, + + /** Take the element from the interpolated POM (original POM with variables interpolated). */ + interpolate, + + /** Take the element untouched from the original POM. */ + keep, + + /** Remove the element entirely so it will not be present in flattened POM. */ + remove +} diff --git a/src/main/java/org/codehaus/mojo/flatten/FlattenDependencyMode.java b/src/main/java/org/codehaus/mojo/flatten/FlattenDependencyMode.java index 26dfdc93..ef5fd2f0 100644 --- a/src/main/java/org/codehaus/mojo/flatten/FlattenDependencyMode.java +++ b/src/main/java/org/codehaus/mojo/flatten/FlattenDependencyMode.java @@ -1,44 +1,43 @@ -package org.codehaus.mojo.flatten; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This enum contains the predefined modes on how to flatten the dependencies. - * - * @author Ray Tsang - * @since 1.2.0 - */ -public enum FlattenDependencyMode -{ - /** - * Flatten only the direct dependency versions. This is the default mode and compatible with - * Flatten Plugin prior to 1.2.0. - */ - direct, - - /** - * Flatten both direct and transitive dependencies. This will examine the full dependency tree, and pull up - * all transitive dependencies as a direct dependency, and setting their versions appropriately. - * - * This is recommended if you are releasing a library that uses dependency management to manage dependency - * versions. - */ - all -} +package org.codehaus.mojo.flatten; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/** + * This enum contains the predefined modes on how to flatten the dependencies. + * + * @author Ray Tsang + * @since 1.2.0 + */ +public enum FlattenDependencyMode { + /** + * Flatten only the direct dependency versions. This is the default mode and compatible with + * Flatten Plugin prior to 1.2.0. + */ + direct, + + /** + * Flatten both direct and transitive dependencies. This will examine the full dependency tree, and pull up + * all transitive dependencies as a direct dependency, and setting their versions appropriately. + * + * This is recommended if you are releasing a library that uses dependency management to manage dependency + * versions. + */ + all +} diff --git a/src/main/java/org/codehaus/mojo/flatten/FlattenDescriptor.java b/src/main/java/org/codehaus/mojo/flatten/FlattenDescriptor.java index 128186a9..ecadddae 100644 --- a/src/main/java/org/codehaus/mojo/flatten/FlattenDescriptor.java +++ b/src/main/java/org/codehaus/mojo/flatten/FlattenDescriptor.java @@ -1,536 +1,470 @@ -package org.codehaus.mojo.flatten; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.util.HashMap; -import java.util.Map; - -import org.apache.maven.model.Build; -import org.apache.maven.model.Model; -import org.codehaus.plexus.util.xml.Xpp3Dom; - -/** - * The descriptor that defines the additional POM elements that should be kept and copied to flattened POM. - * - * @author Joerg Hohwiller (hohwille at users.sourceforge.net) - * @since 1.0.0-beta-2 - */ -public class FlattenDescriptor -{ - - private final Map name2handlingMap; - - /** - * The constructor. - */ - public FlattenDescriptor() - { - super(); - this.name2handlingMap = new HashMap<>(); - } - - /** - * The constructor. - * - * @param descriptor is the raw {@link Xpp3Dom} from the MOJOs configuration. - */ - public FlattenDescriptor( Xpp3Dom descriptor ) - { - this(); - for ( PomProperty property : PomProperty.getPomProperties() ) - { - String element = property.getName(); - if ( descriptor.getChild( element ) != null ) - { - this.name2handlingMap.put( element, ElementHandling.expand ); - } - } - } - - /** - * Generic method to get a {@link ElementHandling}. - * - * @param property is the {@link PomProperty} such as {@link PomProperty#NAME}. - * @return the {@link ElementHandling}. Will be {@link ElementHandling#flatten flattened} as fallback if undefined. - */ - public ElementHandling getHandling( PomProperty property ) - { - ElementHandling handling = this.name2handlingMap.get( property.getName() ); - if ( handling == null ) - { - handling = ElementHandling.flatten; - } - return handling; - } - - /** - * Generic method to set an {@link ElementHandling}. - * - * @param property is the {@link PomProperty} such as {@link PomProperty#NAME}. - * @param handling the new {@link ElementHandling}. - */ - public void setHandling( PomProperty property, ElementHandling handling ) - { - - this.name2handlingMap.put( property.getName(), handling ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getName() name}. - */ - public ElementHandling getName() - { - return getHandling( PomProperty.NAME ); - } - - /** - * @param name the {@link #getName() name} to set. - */ - public void setName( ElementHandling name ) - { - setHandling( PomProperty.NAME, name ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getDescription() description}. - */ - public ElementHandling getDescription() - { - return getHandling( PomProperty.DESCRIPTION ); - } - - /** - * @param description the {@link #getDescription() description} to set. - */ - public void setDescription( ElementHandling description ) - { - setHandling( PomProperty.DESCRIPTION, description ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getUrl() URL}. - */ - public ElementHandling getUrl() - { - return getHandling( PomProperty.URL ); - } - - /** - * @param url the {@link #getUrl() URL} to set. - */ - public void setUrl( ElementHandling url ) - { - setHandling( PomProperty.URL, url ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getInceptionYear() inceptionYear}. - */ - public ElementHandling getInceptionYear() - { - return getHandling( PomProperty.INCEPTION_YEAR ); - } - - /** - * @param inceptionYear the inceptionYear to set - */ - public void setInceptionYear( ElementHandling inceptionYear ) - { - setHandling( PomProperty.INCEPTION_YEAR, inceptionYear ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getOrganization() organization}. - */ - public ElementHandling getOrganization() - { - return getHandling( PomProperty.ORGANIZATION ); - } - - /** - * @param organization the {@link #getOrganization() organization} to set. - */ - public void setOrganization( ElementHandling organization ) - { - setHandling( PomProperty.ORGANIZATION, organization ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getScm() SCM}. - */ - public ElementHandling getScm() - { - return getHandling( PomProperty.SCM ); - } - - /** - * @param scm the {@link #getScm() scm} to set. - */ - public void setScm( ElementHandling scm ) - { - setHandling( PomProperty.SCM, scm ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getPrerequisites() prerequisites}. - */ - public ElementHandling getPrerequisites() - { - return getHandling( PomProperty.PREREQUISITES ); - } - - /** - * @param prerequisites the {@link #getPrerequisites() prerequisites} to set. - */ - public void setPrerequisites( ElementHandling prerequisites ) - { - setHandling( PomProperty.PREREQUISITES, prerequisites ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getDevelopers() developers}. - */ - public ElementHandling getDevelopers() - { - return getHandling( PomProperty.DEVELOPERS ); - } - - /** - * @param developers the {@link #getDevelopers() developers} to set. - */ - public void setDevelopers( ElementHandling developers ) - { - setHandling( PomProperty.DEVELOPERS, developers ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getContributors() contributors}. - */ - public ElementHandling getContributors() - { - return getHandling( PomProperty.CONTRIBUTORS ); - } - - /** - * @param contributors the {@link #getContributors() contributors} to set. - */ - public void setContributors( ElementHandling contributors ) - { - setHandling( PomProperty.CONTRIBUTORS, contributors ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getMailingLists() mailingLists}. - */ - public ElementHandling getMailingLists() - { - return getHandling( PomProperty.MAILING_LISTS ); - } - - /** - * @param mailingLists the {@link #getMailingLists() mailingLists} to set. - */ - public void setMailingLists( ElementHandling mailingLists ) - { - setHandling( PomProperty.MAILING_LISTS, mailingLists ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getRepositories() repositories}. - */ - public ElementHandling getRepositories() - { - return getHandling( PomProperty.REPOSITORIES ); - } - - /** - * @param repositories the {@link #getRepositories() repositories} to set. - */ - public void setRepositories( ElementHandling repositories ) - { - setHandling( PomProperty.REPOSITORIES, repositories ); - } - - /** - * @return {@link ElementHandling} for {@link Build#getPluginManagement()} pluginManagement}. - */ - public ElementHandling getPluginManagement() - { - return getHandling( PomProperty.PLUGIN_MANAGEMENT ); - } - - /** - * @param pluginManagement the {@link #getPluginManagement() pluginManagement} to set. - */ - public void setPluginManagement( ElementHandling pluginManagement ) - { - setHandling( PomProperty.PLUGIN_MANAGEMENT, pluginManagement ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getPluginRepositories() pluginRepositories}. - */ - public ElementHandling getPluginRepositories() - { - return getHandling( PomProperty.PLUGIN_REPOSITORIES ); - } - - /** - * @param pluginRepositories the {@link #getPluginRepositories() pluginRepositories} to set. - */ - public void setPluginRepositories( ElementHandling pluginRepositories ) - { - setHandling( PomProperty.PLUGIN_REPOSITORIES, pluginRepositories ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getIssueManagement() issueManagement}. - */ - public ElementHandling getIssueManagement() - { - return getHandling( PomProperty.ISSUE_MANAGEMENT ); - } - - /** - * @param issueManagement the {@link #getIssueManagement() issueManagement} to set. - */ - public void setIssueManagement( ElementHandling issueManagement ) - { - setHandling( PomProperty.ISSUE_MANAGEMENT, issueManagement ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getCiManagement() ciManagement}. - */ - public ElementHandling getCiManagement() - { - return getHandling( PomProperty.CI_MANAGEMENT ); - } - - /** - * @param ciManagement the {@link #getCiManagement() ciManagement} to set. - */ - public void setCiManagement( ElementHandling ciManagement ) - { - setHandling( PomProperty.CI_MANAGEMENT, ciManagement ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getDistributionManagement() distributionManagement}. - */ - public ElementHandling getDistributionManagement() - { - return getHandling( PomProperty.DISTRIBUTION_MANAGEMENT ); - } - - /** - * @param distributionManagement the {@link #getDistributionManagement() distributionManagement} to set. - */ - public void setDistributionManagement( ElementHandling distributionManagement ) - { - setHandling( PomProperty.DISTRIBUTION_MANAGEMENT, distributionManagement ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getDependencyManagement() dependencyManagement}. - */ - public ElementHandling getDependencyManagement() - { - return getHandling( PomProperty.DEPENDENCY_MANAGEMENT ); - } - - /** - * @param dependencyManagement the {@link #getDependencyManagement() dependencyManagement} to set. - */ - public void setDependencyManagement( ElementHandling dependencyManagement ) - { - setHandling( PomProperty.DEPENDENCY_MANAGEMENT, dependencyManagement ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getBuild() build}. - */ - public ElementHandling getBuild() - { - return getHandling( PomProperty.BUILD ); - } - - /** - * @param build the {@link #getBuild() build} to set. - */ - public void setBuild( ElementHandling build ) - { - setHandling( PomProperty.BUILD, build ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getParent() parent}. - */ - public ElementHandling getParent() - { - return getHandling( PomProperty.PARENT ); - } - - /** - * @param parent the {@link #getParent() parent} to set. - */ - public void setParent( ElementHandling parent ) - { - setHandling( PomProperty.PARENT, parent ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getModules() modules}. - */ - public ElementHandling getModules() - { - return getHandling( PomProperty.MODULES ); - } - - /** - * @param modules the {@link #getModules() modules} to set. - */ - public void setModules( ElementHandling modules ) - { - setHandling( PomProperty.MODULES, modules ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getProperties() properties}. - */ - public ElementHandling getProperties() - { - return getHandling( PomProperty.PROPERTIES ); - } - - /** - * @param properties the {@link #getProperties() properties} to set. - */ - public void setProperties( ElementHandling properties ) - { - setHandling( PomProperty.PROPERTIES, properties ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getReporting() reporting}. - */ - public ElementHandling getReporting() - { - return getHandling( PomProperty.REPORTING ); - } - - /** - * @param reporting the {@link #getReporting() reporting} to set. - */ - public void setReporting( ElementHandling reporting ) - { - setHandling( PomProperty.REPORTING, reporting ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getDependencies() dependencies}. - */ - public ElementHandling getDependencies() - { - return getHandling( PomProperty.DEPENDENCIES ); - } - - /** - * @param dependencies the {@link #getDependencies() dependencies} to set. - */ - public void setDependencies( ElementHandling dependencies ) - { - setHandling( PomProperty.DEPENDENCIES, dependencies ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getProfiles() profiles}. - */ - public ElementHandling getProfiles() - { - return getHandling( PomProperty.PROFILES ); - } - - /** - * @param profiles the {@link #getProfiles() profiles} to set. - */ - public void setProfiles( ElementHandling profiles ) - { - setHandling( PomProperty.PROFILES, profiles ); - } - - /** - * @return {@link ElementHandling} for {@link Model#getVersion() version}. - */ - public ElementHandling getVersion() - { - return getHandling( PomProperty.VERSION ); - } - - /** - * @param version the {@link #getVersion() version} to set. - */ - public void setVersion( ElementHandling version ) - { - setHandling( PomProperty.VERSION, version ); - } - - /** - * Creates and returns a new {@link FlattenDescriptor} with the {@link ElementHandling}s merged from this and the - * given {@link FlattenDescriptor}. - * - * @param descriptor is the {@link FlattenDescriptor} to merge with this one. - * @return the merged {@link FlattenDescriptor}. - */ - public FlattenDescriptor merge( FlattenDescriptor descriptor ) - { - FlattenDescriptor result = new FlattenDescriptor(); - for ( PomProperty property : PomProperty.getPomProperties() ) - { - String name = property.getName(); - ElementHandling handling = this.name2handlingMap.get( name ); - if ( handling == null ) - { - handling = descriptor.name2handlingMap.get( name ); - } - if ( handling != null ) - { - result.name2handlingMap.put( name, handling ); - } - } - return result; - } - - /** - * @return true if none of the properties has been set explicitly, false otherwise. - */ - public boolean isEmpty() - { - for ( ElementHandling handling : this.name2handlingMap.values() ) - { - if ( handling != null ) - { - return false; - } - } - return true; - } - -} +package org.codehaus.mojo.flatten; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.HashMap; +import java.util.Map; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Model; +import org.codehaus.plexus.util.xml.Xpp3Dom; + +/** + * The descriptor that defines the additional POM elements that should be kept and copied to flattened POM. + * + * @author Joerg Hohwiller (hohwille at users.sourceforge.net) + * @since 1.0.0-beta-2 + */ +public class FlattenDescriptor { + + private final Map name2handlingMap; + + /** + * The constructor. + */ + public FlattenDescriptor() { + super(); + this.name2handlingMap = new HashMap<>(); + } + + /** + * The constructor. + * + * @param descriptor is the raw {@link Xpp3Dom} from the MOJOs configuration. + */ + public FlattenDescriptor(Xpp3Dom descriptor) { + this(); + for (PomProperty property : PomProperty.getPomProperties()) { + String element = property.getName(); + if (descriptor.getChild(element) != null) { + this.name2handlingMap.put(element, ElementHandling.expand); + } + } + } + + /** + * Generic method to get a {@link ElementHandling}. + * + * @param property is the {@link PomProperty} such as {@link PomProperty#NAME}. + * @return the {@link ElementHandling}. Will be {@link ElementHandling#flatten flattened} as fallback if undefined. + */ + public ElementHandling getHandling(PomProperty property) { + ElementHandling handling = this.name2handlingMap.get(property.getName()); + if (handling == null) { + handling = ElementHandling.flatten; + } + return handling; + } + + /** + * Generic method to set an {@link ElementHandling}. + * + * @param property is the {@link PomProperty} such as {@link PomProperty#NAME}. + * @param handling the new {@link ElementHandling}. + */ + public void setHandling(PomProperty property, ElementHandling handling) { + + this.name2handlingMap.put(property.getName(), handling); + } + + /** + * @return {@link ElementHandling} for {@link Model#getName() name}. + */ + public ElementHandling getName() { + return getHandling(PomProperty.NAME); + } + + /** + * @param name the {@link #getName() name} to set. + */ + public void setName(ElementHandling name) { + setHandling(PomProperty.NAME, name); + } + + /** + * @return {@link ElementHandling} for {@link Model#getDescription() description}. + */ + public ElementHandling getDescription() { + return getHandling(PomProperty.DESCRIPTION); + } + + /** + * @param description the {@link #getDescription() description} to set. + */ + public void setDescription(ElementHandling description) { + setHandling(PomProperty.DESCRIPTION, description); + } + + /** + * @return {@link ElementHandling} for {@link Model#getUrl() URL}. + */ + public ElementHandling getUrl() { + return getHandling(PomProperty.URL); + } + + /** + * @param url the {@link #getUrl() URL} to set. + */ + public void setUrl(ElementHandling url) { + setHandling(PomProperty.URL, url); + } + + /** + * @return {@link ElementHandling} for {@link Model#getInceptionYear() inceptionYear}. + */ + public ElementHandling getInceptionYear() { + return getHandling(PomProperty.INCEPTION_YEAR); + } + + /** + * @param inceptionYear the inceptionYear to set + */ + public void setInceptionYear(ElementHandling inceptionYear) { + setHandling(PomProperty.INCEPTION_YEAR, inceptionYear); + } + + /** + * @return {@link ElementHandling} for {@link Model#getOrganization() organization}. + */ + public ElementHandling getOrganization() { + return getHandling(PomProperty.ORGANIZATION); + } + + /** + * @param organization the {@link #getOrganization() organization} to set. + */ + public void setOrganization(ElementHandling organization) { + setHandling(PomProperty.ORGANIZATION, organization); + } + + /** + * @return {@link ElementHandling} for {@link Model#getScm() SCM}. + */ + public ElementHandling getScm() { + return getHandling(PomProperty.SCM); + } + + /** + * @param scm the {@link #getScm() scm} to set. + */ + public void setScm(ElementHandling scm) { + setHandling(PomProperty.SCM, scm); + } + + /** + * @return {@link ElementHandling} for {@link Model#getPrerequisites() prerequisites}. + */ + public ElementHandling getPrerequisites() { + return getHandling(PomProperty.PREREQUISITES); + } + + /** + * @param prerequisites the {@link #getPrerequisites() prerequisites} to set. + */ + public void setPrerequisites(ElementHandling prerequisites) { + setHandling(PomProperty.PREREQUISITES, prerequisites); + } + + /** + * @return {@link ElementHandling} for {@link Model#getDevelopers() developers}. + */ + public ElementHandling getDevelopers() { + return getHandling(PomProperty.DEVELOPERS); + } + + /** + * @param developers the {@link #getDevelopers() developers} to set. + */ + public void setDevelopers(ElementHandling developers) { + setHandling(PomProperty.DEVELOPERS, developers); + } + + /** + * @return {@link ElementHandling} for {@link Model#getContributors() contributors}. + */ + public ElementHandling getContributors() { + return getHandling(PomProperty.CONTRIBUTORS); + } + + /** + * @param contributors the {@link #getContributors() contributors} to set. + */ + public void setContributors(ElementHandling contributors) { + setHandling(PomProperty.CONTRIBUTORS, contributors); + } + + /** + * @return {@link ElementHandling} for {@link Model#getMailingLists() mailingLists}. + */ + public ElementHandling getMailingLists() { + return getHandling(PomProperty.MAILING_LISTS); + } + + /** + * @param mailingLists the {@link #getMailingLists() mailingLists} to set. + */ + public void setMailingLists(ElementHandling mailingLists) { + setHandling(PomProperty.MAILING_LISTS, mailingLists); + } + + /** + * @return {@link ElementHandling} for {@link Model#getRepositories() repositories}. + */ + public ElementHandling getRepositories() { + return getHandling(PomProperty.REPOSITORIES); + } + + /** + * @param repositories the {@link #getRepositories() repositories} to set. + */ + public void setRepositories(ElementHandling repositories) { + setHandling(PomProperty.REPOSITORIES, repositories); + } + + /** + * @return {@link ElementHandling} for {@link Build#getPluginManagement()} pluginManagement}. + */ + public ElementHandling getPluginManagement() { + return getHandling(PomProperty.PLUGIN_MANAGEMENT); + } + + /** + * @param pluginManagement the {@link #getPluginManagement() pluginManagement} to set. + */ + public void setPluginManagement(ElementHandling pluginManagement) { + setHandling(PomProperty.PLUGIN_MANAGEMENT, pluginManagement); + } + + /** + * @return {@link ElementHandling} for {@link Model#getPluginRepositories() pluginRepositories}. + */ + public ElementHandling getPluginRepositories() { + return getHandling(PomProperty.PLUGIN_REPOSITORIES); + } + + /** + * @param pluginRepositories the {@link #getPluginRepositories() pluginRepositories} to set. + */ + public void setPluginRepositories(ElementHandling pluginRepositories) { + setHandling(PomProperty.PLUGIN_REPOSITORIES, pluginRepositories); + } + + /** + * @return {@link ElementHandling} for {@link Model#getIssueManagement() issueManagement}. + */ + public ElementHandling getIssueManagement() { + return getHandling(PomProperty.ISSUE_MANAGEMENT); + } + + /** + * @param issueManagement the {@link #getIssueManagement() issueManagement} to set. + */ + public void setIssueManagement(ElementHandling issueManagement) { + setHandling(PomProperty.ISSUE_MANAGEMENT, issueManagement); + } + + /** + * @return {@link ElementHandling} for {@link Model#getCiManagement() ciManagement}. + */ + public ElementHandling getCiManagement() { + return getHandling(PomProperty.CI_MANAGEMENT); + } + + /** + * @param ciManagement the {@link #getCiManagement() ciManagement} to set. + */ + public void setCiManagement(ElementHandling ciManagement) { + setHandling(PomProperty.CI_MANAGEMENT, ciManagement); + } + + /** + * @return {@link ElementHandling} for {@link Model#getDistributionManagement() distributionManagement}. + */ + public ElementHandling getDistributionManagement() { + return getHandling(PomProperty.DISTRIBUTION_MANAGEMENT); + } + + /** + * @param distributionManagement the {@link #getDistributionManagement() distributionManagement} to set. + */ + public void setDistributionManagement(ElementHandling distributionManagement) { + setHandling(PomProperty.DISTRIBUTION_MANAGEMENT, distributionManagement); + } + + /** + * @return {@link ElementHandling} for {@link Model#getDependencyManagement() dependencyManagement}. + */ + public ElementHandling getDependencyManagement() { + return getHandling(PomProperty.DEPENDENCY_MANAGEMENT); + } + + /** + * @param dependencyManagement the {@link #getDependencyManagement() dependencyManagement} to set. + */ + public void setDependencyManagement(ElementHandling dependencyManagement) { + setHandling(PomProperty.DEPENDENCY_MANAGEMENT, dependencyManagement); + } + + /** + * @return {@link ElementHandling} for {@link Model#getBuild() build}. + */ + public ElementHandling getBuild() { + return getHandling(PomProperty.BUILD); + } + + /** + * @param build the {@link #getBuild() build} to set. + */ + public void setBuild(ElementHandling build) { + setHandling(PomProperty.BUILD, build); + } + + /** + * @return {@link ElementHandling} for {@link Model#getParent() parent}. + */ + public ElementHandling getParent() { + return getHandling(PomProperty.PARENT); + } + + /** + * @param parent the {@link #getParent() parent} to set. + */ + public void setParent(ElementHandling parent) { + setHandling(PomProperty.PARENT, parent); + } + + /** + * @return {@link ElementHandling} for {@link Model#getModules() modules}. + */ + public ElementHandling getModules() { + return getHandling(PomProperty.MODULES); + } + + /** + * @param modules the {@link #getModules() modules} to set. + */ + public void setModules(ElementHandling modules) { + setHandling(PomProperty.MODULES, modules); + } + + /** + * @return {@link ElementHandling} for {@link Model#getProperties() properties}. + */ + public ElementHandling getProperties() { + return getHandling(PomProperty.PROPERTIES); + } + + /** + * @param properties the {@link #getProperties() properties} to set. + */ + public void setProperties(ElementHandling properties) { + setHandling(PomProperty.PROPERTIES, properties); + } + + /** + * @return {@link ElementHandling} for {@link Model#getReporting() reporting}. + */ + public ElementHandling getReporting() { + return getHandling(PomProperty.REPORTING); + } + + /** + * @param reporting the {@link #getReporting() reporting} to set. + */ + public void setReporting(ElementHandling reporting) { + setHandling(PomProperty.REPORTING, reporting); + } + + /** + * @return {@link ElementHandling} for {@link Model#getDependencies() dependencies}. + */ + public ElementHandling getDependencies() { + return getHandling(PomProperty.DEPENDENCIES); + } + + /** + * @param dependencies the {@link #getDependencies() dependencies} to set. + */ + public void setDependencies(ElementHandling dependencies) { + setHandling(PomProperty.DEPENDENCIES, dependencies); + } + + /** + * @return {@link ElementHandling} for {@link Model#getProfiles() profiles}. + */ + public ElementHandling getProfiles() { + return getHandling(PomProperty.PROFILES); + } + + /** + * @param profiles the {@link #getProfiles() profiles} to set. + */ + public void setProfiles(ElementHandling profiles) { + setHandling(PomProperty.PROFILES, profiles); + } + + /** + * @return {@link ElementHandling} for {@link Model#getVersion() version}. + */ + public ElementHandling getVersion() { + return getHandling(PomProperty.VERSION); + } + + /** + * @param version the {@link #getVersion() version} to set. + */ + public void setVersion(ElementHandling version) { + setHandling(PomProperty.VERSION, version); + } + + /** + * Creates and returns a new {@link FlattenDescriptor} with the {@link ElementHandling}s merged from this and the + * given {@link FlattenDescriptor}. + * + * @param descriptor is the {@link FlattenDescriptor} to merge with this one. + * @return the merged {@link FlattenDescriptor}. + */ + public FlattenDescriptor merge(FlattenDescriptor descriptor) { + FlattenDescriptor result = new FlattenDescriptor(); + for (PomProperty property : PomProperty.getPomProperties()) { + String name = property.getName(); + ElementHandling handling = this.name2handlingMap.get(name); + if (handling == null) { + handling = descriptor.name2handlingMap.get(name); + } + if (handling != null) { + result.name2handlingMap.put(name, handling); + } + } + return result; + } + + /** + * @return true if none of the properties has been set explicitly, false otherwise. + */ + public boolean isEmpty() { + for (ElementHandling handling : this.name2handlingMap.values()) { + if (handling != null) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/org/codehaus/mojo/flatten/FlattenMode.java b/src/main/java/org/codehaus/mojo/flatten/FlattenMode.java index 12750982..21ad6c2b 100644 --- a/src/main/java/org/codehaus/mojo/flatten/FlattenMode.java +++ b/src/main/java/org/codehaus/mojo/flatten/FlattenMode.java @@ -1,161 +1,156 @@ -package org.codehaus.mojo.flatten; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Model; - -/** - * This enum contains the predefined modes how to deal with {@link FlattenDescriptor additional POM elements} when - * {@link FlattenMojo generating the flattened POM}. - * - * @author Joerg Hohwiller (hohwille at users.sourceforge.net) - * @since 1.0.0-beta-2 - */ -public enum FlattenMode -{ - /** - * For projects that want to keep all {@link FlattenDescriptor optional POM elements}. - * - * @deprecated confusing name, unstable contract. - */ - @Deprecated - minimum, - - /** - * For Open-Source-Software projects that want to keep all {@link FlattenDescriptor optional POM elements} except - * for {@link Model#getRepositories() repositories} and {@link Model#getPluginRepositories() pluginRepositories}. - */ - oss, - - /** - * Keeps all {@link FlattenDescriptor optional POM elements} that are required for - * OSS - * Repository-Hosting. - */ - ossrh, - - /** - * Like {@link #ossrh} but additionally keeps {@link Model#getDependencyManagement() dependencyManagement} and - * {@link Model#getProperties() properties}. Especially it will keep the {@link Model#getDependencyManagement() - * dependencyManagement} as-is without resolving parent influences and import-scoped dependencies. This is - * useful if your POM represents a BOM (Bill Of Material) and you do not want to deploy it as is (to remove parent and resolve version - * variables, etc.). - */ - bom, - - /** - * The default mode that removes all {@link FlattenDescriptor optional POM elements} except - * {@link Model#getRepositories() repositories}. - */ - defaults, - - /** Removes all {@link FlattenDescriptor optional POM elements}. */ - clean, - - /** Removes all {@link FlattenDescriptor optional POM elements} and dependencies. */ - fatjar, - - /** Only resolves variables revision, sha1 and changelist. Keeps everything else. - * See Maven CI Friendly for further details. - */ - resolveCiFriendliesOnly; - - - /** - * @return the {@link FlattenDescriptor} defined by this {@link FlattenMode}. - */ - public FlattenDescriptor getDescriptor() - { - - FlattenDescriptor descriptor = new FlattenDescriptor(); - switch ( this ) - { - case minimum: - descriptor.setPluginRepositories( ElementHandling.expand ); - //$FALL-THROUGH$ - case bom: - // MOJO-2041 - descriptor.setDependencyManagement( ElementHandling.keep ); - descriptor.setProperties( ElementHandling.expand ); - //$FALL-THROUGH$ - case oss: - descriptor.setCiManagement( ElementHandling.expand ); - descriptor.setContributors( ElementHandling.expand ); - descriptor.setDistributionManagement( ElementHandling.expand ); - descriptor.setInceptionYear( ElementHandling.expand ); - descriptor.setIssueManagement( ElementHandling.expand ); - descriptor.setMailingLists( ElementHandling.expand ); - descriptor.setOrganization( ElementHandling.expand ); - descriptor.setPrerequisites( ElementHandling.expand ); - //$FALL-THROUGH$ - case ossrh: - descriptor.setName( ElementHandling.expand ); - descriptor.setDescription( ElementHandling.expand ); - descriptor.setUrl( ElementHandling.expand ); - descriptor.setScm( ElementHandling.expand ); - descriptor.setDevelopers( ElementHandling.expand ); - //$FALL-THROUGH$ - case defaults: - descriptor.setRepositories( ElementHandling.expand ); - break; - case fatjar: - descriptor.setDependencies( ElementHandling.remove ); - break; - case resolveCiFriendliesOnly: - descriptor.setBuild( ElementHandling.interpolate ); - descriptor.setCiManagement( ElementHandling.interpolate ); - descriptor.setContributors( ElementHandling.interpolate ); - descriptor.setDependencies( ElementHandling.interpolate ); - descriptor.setDependencyManagement( ElementHandling.interpolate ); - descriptor.setDescription( ElementHandling.interpolate ); - descriptor.setDevelopers( ElementHandling.interpolate ); - descriptor.setDistributionManagement( ElementHandling.interpolate ); - descriptor.setInceptionYear( ElementHandling.interpolate ); - descriptor.setIssueManagement( ElementHandling.interpolate ); - descriptor.setMailingLists( ElementHandling.interpolate ); - descriptor.setModules( ElementHandling.interpolate ); - descriptor.setName( ElementHandling.interpolate ); - descriptor.setOrganization( ElementHandling.interpolate ); - descriptor.setParent( ElementHandling.resolve ); - descriptor.setPluginManagement( ElementHandling.interpolate ); - descriptor.setPluginRepositories( ElementHandling.interpolate ); - descriptor.setPrerequisites( ElementHandling.interpolate ); - descriptor.setProfiles( ElementHandling.interpolate ); - descriptor.setProperties( ElementHandling.interpolate ); - descriptor.setReporting( ElementHandling.interpolate ); - descriptor.setRepositories( ElementHandling.interpolate ); - descriptor.setScm( ElementHandling.interpolate ); - descriptor.setUrl( ElementHandling.interpolate ); - descriptor.setVersion( ElementHandling.resolve ); - break; - case clean: - // nothing to do... - break; - - default: - // nothing to do...Could not happen. - break; - } - return descriptor; - } - -} +package org.codehaus.mojo.flatten; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import org.apache.maven.model.Model; + +/** + * This enum contains the predefined modes how to deal with {@link FlattenDescriptor additional POM elements} when + * {@link FlattenMojo generating the flattened POM}. + * + * @author Joerg Hohwiller (hohwille at users.sourceforge.net) + * @since 1.0.0-beta-2 + */ +public enum FlattenMode { + /** + * For projects that want to keep all {@link FlattenDescriptor optional POM elements}. + * + * @deprecated confusing name, unstable contract. + */ + @Deprecated + minimum, + + /** + * For Open-Source-Software projects that want to keep all {@link FlattenDescriptor optional POM elements} except + * for {@link Model#getRepositories() repositories} and {@link Model#getPluginRepositories() pluginRepositories}. + */ + oss, + + /** + * Keeps all {@link FlattenDescriptor optional POM elements} that are required for + * OSS + * Repository-Hosting. + */ + ossrh, + + /** + * Like {@link #ossrh} but additionally keeps {@link Model#getDependencyManagement() dependencyManagement} and + * {@link Model#getProperties() properties}. Especially it will keep the {@link Model#getDependencyManagement() + * dependencyManagement} as-is without resolving parent influences and import-scoped dependencies. This is + * useful if your POM represents a BOM (Bill Of Material) and you do not want to deploy it as is (to remove parent and resolve version + * variables, etc.). + */ + bom, + + /** + * The default mode that removes all {@link FlattenDescriptor optional POM elements} except + * {@link Model#getRepositories() repositories}. + */ + defaults, + + /** Removes all {@link FlattenDescriptor optional POM elements}. */ + clean, + + /** Removes all {@link FlattenDescriptor optional POM elements} and dependencies. */ + fatjar, + + /** Only resolves variables revision, sha1 and changelist. Keeps everything else. + * See Maven CI Friendly for further details. + */ + resolveCiFriendliesOnly; + + /** + * @return the {@link FlattenDescriptor} defined by this {@link FlattenMode}. + */ + public FlattenDescriptor getDescriptor() { + + FlattenDescriptor descriptor = new FlattenDescriptor(); + switch (this) { + case minimum: + descriptor.setPluginRepositories(ElementHandling.expand); + // $FALL-THROUGH$ + case bom: + // MOJO-2041 + descriptor.setDependencyManagement(ElementHandling.keep); + descriptor.setProperties(ElementHandling.expand); + // $FALL-THROUGH$ + case oss: + descriptor.setCiManagement(ElementHandling.expand); + descriptor.setContributors(ElementHandling.expand); + descriptor.setDistributionManagement(ElementHandling.expand); + descriptor.setInceptionYear(ElementHandling.expand); + descriptor.setIssueManagement(ElementHandling.expand); + descriptor.setMailingLists(ElementHandling.expand); + descriptor.setOrganization(ElementHandling.expand); + descriptor.setPrerequisites(ElementHandling.expand); + // $FALL-THROUGH$ + case ossrh: + descriptor.setName(ElementHandling.expand); + descriptor.setDescription(ElementHandling.expand); + descriptor.setUrl(ElementHandling.expand); + descriptor.setScm(ElementHandling.expand); + descriptor.setDevelopers(ElementHandling.expand); + // $FALL-THROUGH$ + case defaults: + descriptor.setRepositories(ElementHandling.expand); + break; + case fatjar: + descriptor.setDependencies(ElementHandling.remove); + break; + case resolveCiFriendliesOnly: + descriptor.setBuild(ElementHandling.interpolate); + descriptor.setCiManagement(ElementHandling.interpolate); + descriptor.setContributors(ElementHandling.interpolate); + descriptor.setDependencies(ElementHandling.interpolate); + descriptor.setDependencyManagement(ElementHandling.interpolate); + descriptor.setDescription(ElementHandling.interpolate); + descriptor.setDevelopers(ElementHandling.interpolate); + descriptor.setDistributionManagement(ElementHandling.interpolate); + descriptor.setInceptionYear(ElementHandling.interpolate); + descriptor.setIssueManagement(ElementHandling.interpolate); + descriptor.setMailingLists(ElementHandling.interpolate); + descriptor.setModules(ElementHandling.interpolate); + descriptor.setName(ElementHandling.interpolate); + descriptor.setOrganization(ElementHandling.interpolate); + descriptor.setParent(ElementHandling.resolve); + descriptor.setPluginManagement(ElementHandling.interpolate); + descriptor.setPluginRepositories(ElementHandling.interpolate); + descriptor.setPrerequisites(ElementHandling.interpolate); + descriptor.setProfiles(ElementHandling.interpolate); + descriptor.setProperties(ElementHandling.interpolate); + descriptor.setReporting(ElementHandling.interpolate); + descriptor.setRepositories(ElementHandling.interpolate); + descriptor.setScm(ElementHandling.interpolate); + descriptor.setUrl(ElementHandling.interpolate); + descriptor.setVersion(ElementHandling.resolve); + break; + case clean: + // nothing to do... + break; + + default: + // nothing to do...Could not happen. + break; + } + return descriptor; + } +} diff --git a/src/main/java/org/codehaus/mojo/flatten/FlattenMojo.java b/src/main/java/org/codehaus/mojo/flatten/FlattenMojo.java index 679b0c38..f8b36c66 100644 --- a/src/main/java/org/codehaus/mojo/flatten/FlattenMojo.java +++ b/src/main/java/org/codehaus/mojo/flatten/FlattenMojo.java @@ -205,25 +205,21 @@ * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) */ -@Mojo( name = "flatten", - requiresDependencyCollection = ResolutionScope.RUNTIME, - threadSafe = true ) -public class FlattenMojo - extends AbstractFlattenMojo -{ +@Mojo(name = "flatten", requiresDependencyCollection = ResolutionScope.RUNTIME, threadSafe = true) +public class FlattenMojo extends AbstractFlattenMojo { private static final int INITIAL_POM_WRITER_SIZE = 4096; /** * The {@link MavenSession} used to get user properties. */ - @Parameter( defaultValue = "${session}", readonly = true, required = true ) + @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession session; /** * The Maven Project. */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** @@ -233,7 +229,7 @@ public class FlattenMojo * false in order to only generate the flattened POM but never set it as POM file. If * flattenMode is set to bom the default value will be true. */ - @Parameter( property = "updatePomFile" ) + @Parameter(property = "updatePomFile") private Boolean updatePomFile; /** @@ -243,21 +239,21 @@ public class FlattenMojo * handles dependencies. When keeping this property false, all profiles will stay in the * flattened-pom. */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private Boolean embedBuildProfileDependencies; /** * The {@link MojoExecution} used to get access to the raw configuration of {@link #pomElements} as empty tags are * mapped to null. */ - @Parameter( defaultValue = "${mojo}", readonly = true, required = true ) + @Parameter(defaultValue = "${mojo}", readonly = true, required = true) private MojoExecution mojoExecution; /** * The {@link Model} that defines how to handle additional POM elements. Please use flattenMode in * preference if possible. This parameter is only for ultimate flexibility. */ - @Parameter( required = false ) + @Parameter(required = false) private FlattenDescriptor pomElements; /** @@ -267,7 +263,7 @@ public class FlattenMojo * * @since 1.3.0 */ - @Parameter( defaultValue = "false", required = false ) + @Parameter(defaultValue = "false", required = false) private boolean omitExclusions; /** @@ -322,7 +318,7 @@ public class FlattenMojo * * */ - @Parameter( property = "flatten.mode", required = false ) + @Parameter(property = "flatten.mode", required = false) private FlattenMode flattenMode; /** @@ -348,7 +344,7 @@ public class FlattenMojo * * */ - @Parameter( property = "flatten.dependency.mode", required = false ) + @Parameter(property = "flatten.dependency.mode", required = false) private FlattenDependencyMode flattenDependencyMode; /** @@ -358,7 +354,7 @@ public class FlattenMojo * * @since 1.3.0 */ - @Parameter( property = "flatten.dependency.keepComments", required = false, defaultValue = "false" ) + @Parameter(property = "flatten.dependency.keepComments", required = false, defaultValue = "false") private boolean keepCommentsInPom; @Inject @@ -388,8 +384,7 @@ public class FlattenMojo /** * The constructor. */ - public FlattenMojo() - { + public FlattenMojo() { super(); } @@ -397,34 +392,29 @@ public FlattenMojo() * {@inheritDoc} */ @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { - getLog().info( "Generating flattened POM of project " + this.project.getId() + "..." ); + getLog().info("Generating flattened POM of project " + this.project.getId() + "..."); inheritanceAssembler.flattenDependencyMode = this.flattenDependencyMode; File originalPomFile = this.project.getFile(); KeepCommentsInPom commentsOfOriginalPomFile = null; - if ( keepCommentsInPom ) - { - commentsOfOriginalPomFile = KeepCommentsInPom.create( getLog(), originalPomFile ); + if (keepCommentsInPom) { + commentsOfOriginalPomFile = KeepCommentsInPom.create(getLog(), originalPomFile); } - Model flattenedPom = createFlattenedPom( originalPomFile ); - String headerComment = extractHeaderComment( originalPomFile ); + Model flattenedPom = createFlattenedPom(originalPomFile); + String headerComment = extractHeaderComment(originalPomFile); File flattenedPomFile = getFlattenedPomFile(); - writePom( flattenedPom, flattenedPomFile, headerComment, commentsOfOriginalPomFile ); + writePom(flattenedPom, flattenedPomFile, headerComment, commentsOfOriginalPomFile); - if ( isUpdatePomFile() ) - { - this.project.setPomFile( flattenedPomFile ); - this.project.setOriginalModel( flattenedPom ); + if (isUpdatePomFile()) { + this.project.setPomFile(flattenedPomFile); + this.project.setOriginalModel(flattenedPom); } } - /** * This method extracts the XML header comment if available. * @@ -433,21 +423,16 @@ public void execute() * available. * @throws MojoExecutionException if anything goes wrong. */ - protected String extractHeaderComment( File xmlFile ) - throws MojoExecutionException - { + protected String extractHeaderComment(File xmlFile) throws MojoExecutionException { - try - { + try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); SaxHeaderCommentHandler handler = new SaxHeaderCommentHandler(); - parser.setProperty( "http://xml.org/sax/properties/lexical-handler", handler ); - parser.parse( xmlFile, handler ); + parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler); + parser.parse(xmlFile, handler); return handler.getHeaderComment(); - } - catch ( Exception e ) - { - throw new MojoExecutionException( "Failed to parse XML from " + xmlFile, e ); + } catch (Exception e) { + throw new MojoExecutionException("Failed to parse XML from " + xmlFile, e); } } @@ -462,54 +447,41 @@ protected String extractHeaderComment( File xmlFile ) * before root tag). May be null if not present and to be omitted in target POM. * @throws MojoExecutionException if the operation failed (e.g. due to an {@link IOException}). */ - protected void writePom( Model pom, File pomFile, String headerComment, KeepCommentsInPom anOriginalCommentsPath ) - throws MojoExecutionException - { + protected void writePom(Model pom, File pomFile, String headerComment, KeepCommentsInPom anOriginalCommentsPath) + throws MojoExecutionException { File parentFile = pomFile.getParentFile(); - if ( !parentFile.exists() ) - { + if (!parentFile.exists()) { boolean success = parentFile.mkdirs(); - if ( !success ) - { - throw new MojoExecutionException( "Failed to create directory " + pomFile.getParent() ); + if (!success) { + throw new MojoExecutionException("Failed to create directory " + pomFile.getParent()); } } // MavenXpp3Writer could internally add the comment but does not expose such feature to API! // Instead we have to write POM XML to String and do post processing on that :( MavenXpp3Writer pomWriter = new MavenXpp3Writer(); - StringWriter stringWriter = new StringWriter( INITIAL_POM_WRITER_SIZE ); - try - { - pomWriter.write( stringWriter, pom ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Internal I/O error!", e ); + StringWriter stringWriter = new StringWriter(INITIAL_POM_WRITER_SIZE); + try { + pomWriter.write(stringWriter, pom); + } catch (IOException e) { + throw new MojoExecutionException("Internal I/O error!", e); } StringBuffer buffer = stringWriter.getBuffer(); - if ( !StringUtils.isEmpty( headerComment ) ) - { - int projectStartIndex = buffer.indexOf( "= 0 ) - { - buffer.insert( projectStartIndex, "\n" ); - } - else - { - getLog().warn( "POM XML post-processing failed: no project tag found!" ); + if (!StringUtils.isEmpty(headerComment)) { + int projectStartIndex = buffer.indexOf("= 0) { + buffer.insert(projectStartIndex, "\n"); + } else { + getLog().warn("POM XML post-processing failed: no project tag found!"); } } String xmlString; - if ( anOriginalCommentsPath == null ) - { + if (anOriginalCommentsPath == null) { xmlString = buffer.toString(); + } else { + xmlString = anOriginalCommentsPath.restoreOriginalComments(buffer.toString(), pom.getModelEncoding()); } - else - { - xmlString = anOriginalCommentsPath.restoreOriginalComments( buffer.toString(), pom.getModelEncoding() ); - } - writeStringToFile( xmlString, pomFile, pom.getModelEncoding() ); + writeStringToFile(xmlString, pomFile, pom.getModelEncoding()); } /** @@ -520,54 +492,38 @@ protected void writePom( Model pom, File pomFile, String headerComment, KeepComm * @param encoding is the encoding to use for writing the file. * @throws MojoExecutionException if anything goes wrong. */ - protected void writeStringToFile( String data, File file, String encoding ) - throws MojoExecutionException - { - if ( !"\n".equals( System.lineSeparator() ) ) - { - data = data.replace( "\n", System.lineSeparator() ); + protected void writeStringToFile(String data, File file, String encoding) throws MojoExecutionException { + if (!"\n".equals(System.lineSeparator())) { + data = data.replace("\n", System.lineSeparator()); } byte[] binaryData; - try - { - binaryData = data.getBytes( encoding ); - if ( file.isFile() && file.canRead() && file.length() == binaryData.length ) - { - try ( InputStream inputStream = Files.newInputStream( file.toPath( ) ) ) - { + try { + binaryData = data.getBytes(encoding); + if (file.isFile() && file.canRead() && file.length() == binaryData.length) { + try (InputStream inputStream = Files.newInputStream(file.toPath())) { byte[] buffer = new byte[binaryData.length]; - inputStream.read( buffer ); - if ( Arrays.equals( buffer, binaryData ) ) - { - getLog().debug( "Arrays.equals( buffer, binaryData ) " ); + inputStream.read(buffer); + if (Arrays.equals(buffer, binaryData)) { + getLog().debug("Arrays.equals( buffer, binaryData ) "); return; } - getLog().debug( "Not Arrays.equals( buffer, binaryData ) " ); - } - catch ( IOException e ) - { + getLog().debug("Not Arrays.equals( buffer, binaryData ) "); + } catch (IOException e) { // ignore those exceptions, we will overwrite the file - getLog().debug( "Issue reading file: " + file.getPath(), e ); + getLog().debug("Issue reading file: " + file.getPath(), e); } + } else { + getLog().debug("file: " + file + ",file.length(): " + file.length() + ", binaryData.length: " + + binaryData.length); } - else - { - getLog().debug( "file: " + file + ",file.length(): " + file.length() + ", binaryData.length: " - + binaryData.length ); - } - } - catch ( IOException e ) - { - throw new MojoExecutionException( "cannot read String as bytes", e ); - } - try ( OutputStream outStream = Files.newOutputStream( file.toPath( ) ) ) - { - outStream.write( binaryData ); + } catch (IOException e) { + throw new MojoExecutionException("cannot read String as bytes", e); } - catch ( IOException e ) - { - throw new MojoExecutionException( "Failed to write to " + file, e ); + try (OutputStream outStream = Files.newOutputStream(file.toPath())) { + outStream.write(binaryData); + } catch (IOException e) { + throw new MojoExecutionException("Failed to write to " + file, e); } } @@ -579,56 +535,45 @@ protected void writeStringToFile( String data, File file, String encoding ) * @throws MojoExecutionException if anything goes wrong (e.g. POM can not be processed). * @throws MojoFailureException if anything goes wrong (logical error). */ - protected Model createFlattenedPom( File pomFile ) throws MojoExecutionException, MojoFailureException - { + protected Model createFlattenedPom(File pomFile) throws MojoExecutionException, MojoFailureException { - ModelBuildingRequest buildingRequest = createModelBuildingRequest( pomFile ); - Model effectivePom = createEffectivePom( buildingRequest, isEmbedBuildProfileDependencies(), this.flattenMode ); + ModelBuildingRequest buildingRequest = createModelBuildingRequest(pomFile); + Model effectivePom = createEffectivePom(buildingRequest, isEmbedBuildProfileDependencies(), this.flattenMode); Model flattenedPom = new Model(); // keep original encoding (we could also normalize to UTF-8 here) String modelEncoding = effectivePom.getModelEncoding(); - if ( StringUtils.isEmpty( modelEncoding ) ) - { + if (StringUtils.isEmpty(modelEncoding)) { modelEncoding = "UTF-8"; } - flattenedPom.setModelEncoding( modelEncoding ); + flattenedPom.setModelEncoding(modelEncoding); Model cleanPom; - try - { - cleanPom = createCleanPom( effectivePom ); - } - catch ( Exception e ) - { - throw new MojoExecutionException( "failed to create a clean pom", e ); + try { + cleanPom = createCleanPom(effectivePom); + } catch (Exception e) { + throw new MojoExecutionException("failed to create a clean pom", e); } FlattenDescriptor descriptor = getFlattenDescriptor(); Model originalPom = getOriginalModel(); Model resolvedPom = this.project.getModel(); - Model interpolatedPom = createResolvedPom( buildingRequest ); + Model interpolatedPom = createResolvedPom(buildingRequest); // copy the configured additional POM elements... - for ( PomProperty property : PomProperty.getPomProperties() ) - { - if ( property.isElement() ) - { - Model sourceModel = getSourceModel( descriptor, property, effectivePom, originalPom, resolvedPom, - interpolatedPom, cleanPom ); - if ( sourceModel == null ) - { - if ( property.isRequired() ) - { - throw new MojoFailureException( "Property " + property.getName() - + " is required and can not be removed!" ); + for (PomProperty property : PomProperty.getPomProperties()) { + if (property.isElement()) { + Model sourceModel = getSourceModel( + descriptor, property, effectivePom, originalPom, resolvedPom, interpolatedPom, cleanPom); + if (sourceModel == null) { + if (property.isRequired()) { + throw new MojoFailureException( + "Property " + property.getName() + " is required and can not be removed!"); } - } - else - { - property.copy( sourceModel, flattenedPom ); + } else { + property.copy(sourceModel, flattenedPom); } } } @@ -636,30 +581,23 @@ protected Model createFlattenedPom( File pomFile ) throws MojoExecutionException return flattenedPom; } - private Model createResolvedPom( ModelBuildingRequest buildingRequest ) throws MojoExecutionException - { - LoggingModelProblemCollector problems = new LoggingModelProblemCollector( getLog() ); + private Model createResolvedPom(ModelBuildingRequest buildingRequest) throws MojoExecutionException { + LoggingModelProblemCollector problems = new LoggingModelProblemCollector(getLog()); Model originalModel = getOriginalModel(); - if ( this.flattenMode == FlattenMode.resolveCiFriendliesOnly ) - { - return this.modelCiFriendlyInterpolator.interpolateModel( originalModel, - this.project.getModel().getProjectDirectory(), - buildingRequest, problems ); + if (this.flattenMode == FlattenMode.resolveCiFriendliesOnly) { + return this.modelCiFriendlyInterpolator.interpolateModel( + originalModel, this.project.getModel().getProjectDirectory(), buildingRequest, problems); } - return this.modelInterpolator.interpolateModel( originalModel, this.project.getModel().getProjectDirectory(), - buildingRequest, problems ); + return this.modelInterpolator.interpolateModel( + originalModel, this.project.getModel().getProjectDirectory(), buildingRequest, problems); } - private Model getOriginalModel() throws MojoExecutionException - { + private Model getOriginalModel() throws MojoExecutionException { MavenXpp3Reader reader = new MavenXpp3Reader(); - try - { - return reader.read( Files.newInputStream( this.project.getFile( ).toPath( ) ) ); - } - catch ( IOException | XmlPullParserException e ) - { - throw new MojoExecutionException( "Error reading raw model.", e ); + try { + return reader.read(Files.newInputStream(this.project.getFile().toPath())); + } catch (IOException | XmlPullParserException e) { + throw new MojoExecutionException("Error reading raw model.", e); } } @@ -672,116 +610,105 @@ private Model getOriginalModel() throws MojoExecutionException * @return the clean POM. * @throws MojoExecutionException if anything goes wrong. */ - protected Model createCleanPom( Model effectivePom ) throws MojoExecutionException - { + protected Model createCleanPom(Model effectivePom) throws MojoExecutionException { Model cleanPom = new Model(); - cleanPom.setGroupId( effectivePom.getGroupId() ); - cleanPom.setArtifactId( effectivePom.getArtifactId() ); - cleanPom.setVersion( effectivePom.getVersion() ); - cleanPom.setPackaging( effectivePom.getPackaging() ); - cleanPom.setLicenses( effectivePom.getLicenses() ); + cleanPom.setGroupId(effectivePom.getGroupId()); + cleanPom.setArtifactId(effectivePom.getArtifactId()); + cleanPom.setVersion(effectivePom.getVersion()); + cleanPom.setPackaging(effectivePom.getPackaging()); + cleanPom.setLicenses(effectivePom.getLicenses()); // fixed to 4.0.0 forever :) - cleanPom.setModelVersion( "4.0.0" ); + cleanPom.setModelVersion("4.0.0"); // plugins with extensions must stay Build build = effectivePom.getBuild(); - if ( build != null ) - { - for ( Plugin plugin : build.getPlugins() ) - { - if ( plugin.isExtensions() ) - { + if (build != null) { + for (Plugin plugin : build.getPlugins()) { + if (plugin.isExtensions()) { Build cleanBuild = cleanPom.getBuild(); - if ( cleanBuild == null ) - { + if (cleanBuild == null) { cleanBuild = new Build(); - cleanPom.setBuild( cleanBuild ); + cleanPom.setBuild(cleanBuild); } Plugin cleanPlugin = new Plugin(); - cleanPlugin.setGroupId( plugin.getGroupId() ); - cleanPlugin.setArtifactId( plugin.getArtifactId() ); - cleanPlugin.setVersion( plugin.getVersion() ); - cleanPlugin.setExtensions( true ); - cleanBuild.addPlugin( cleanPlugin ); + cleanPlugin.setGroupId(plugin.getGroupId()); + cleanPlugin.setArtifactId(plugin.getArtifactId()); + cleanPlugin.setVersion(plugin.getVersion()); + cleanPlugin.setExtensions(true); + cleanBuild.addPlugin(cleanPlugin); } } } // transform profiles... Dependencies managedDependencies = new Dependencies(); - if ( effectivePom.getDependencyManagement() != null - && effectivePom.getDependencyManagement().getDependencies() != null ) - { - managedDependencies.addAll( effectivePom.getDependencyManagement().getDependencies() ); + if (effectivePom.getDependencyManagement() != null + && effectivePom.getDependencyManagement().getDependencies() != null) { + managedDependencies.addAll(effectivePom.getDependencyManagement().getDependencies()); } - for ( Profile profile : effectivePom.getProfiles() ) - { - if ( !isEmbedBuildProfileDependencies() || !isBuildTimeDriven( profile.getActivation() ) ) - { - if ( !isEmpty( profile.getDependencies() ) || !isEmpty( profile.getRepositories() ) ) - { + for (Profile profile : effectivePom.getProfiles()) { + if (!isEmbedBuildProfileDependencies() || !isBuildTimeDriven(profile.getActivation())) { + if (!isEmpty(profile.getDependencies()) || !isEmpty(profile.getRepositories())) { List strippedDependencies = new ArrayList<>(); - for ( Dependency dep : profile.getDependencies() ) - { + for (Dependency dep : profile.getDependencies()) { Dependency parsedDep = dep.clone(); - if ( managedDependencies.contains( parsedDep ) ) - { - parsedDep.setVersion( managedDependencies.resolve( parsedDep ).getVersion() ); - String managedDepScope = managedDependencies.resolve( parsedDep ).getScope(); - if ( managedDepScope != null ) - { - parsedDep.setScope( managedDepScope ); + if (managedDependencies.contains(parsedDep)) { + parsedDep.setVersion( + managedDependencies.resolve(parsedDep).getVersion()); + String managedDepScope = + managedDependencies.resolve(parsedDep).getScope(); + if (managedDepScope != null) { + parsedDep.setScope(managedDepScope); } - if ( parsedDep.getScope() == null ) - { - parsedDep.setScope( "compile" ); + if (parsedDep.getScope() == null) { + parsedDep.setScope("compile"); } - String managedDepOptional = managedDependencies.resolve( parsedDep ).getOptional(); - if ( managedDepOptional != null ) - { - parsedDep.setOptional( managedDepOptional ); + String managedDepOptional = + managedDependencies.resolve(parsedDep).getOptional(); + if (managedDepOptional != null) { + parsedDep.setOptional(managedDepOptional); } - if ( parsedDep.getOptional() == null ) - { - parsedDep.setOptional( "false" ); + if (parsedDep.getOptional() == null) { + parsedDep.setOptional("false"); } } - Dependency flattenedDep = createFlattenedDependency( parsedDep ); - if ( flattenedDep != null ) - { - strippedDependencies.add( flattenedDep ); + Dependency flattenedDep = createFlattenedDependency(parsedDep); + if (flattenedDep != null) { + strippedDependencies.add(flattenedDep); } } - if ( !strippedDependencies.isEmpty() || !isEmpty( profile.getRepositories() ) ) - { + if (!strippedDependencies.isEmpty() || !isEmpty(profile.getRepositories())) { Profile strippedProfile = new Profile(); - strippedProfile.setId( profile.getId() ); - strippedProfile.setActivation( profile.getActivation() ); - strippedProfile.setDependencies( strippedDependencies.isEmpty() ? null : strippedDependencies ); - strippedProfile.setRepositories( profile.getRepositories() ); - cleanPom.addProfile( strippedProfile ); + strippedProfile.setId(profile.getId()); + strippedProfile.setActivation(profile.getActivation()); + strippedProfile.setDependencies(strippedDependencies.isEmpty() ? null : strippedDependencies); + strippedProfile.setRepositories(profile.getRepositories()); + cleanPom.addProfile(strippedProfile); } } } } // transform dependencies... - List dependencies = createFlattenedDependencies( effectivePom ); - cleanPom.setDependencies( dependencies ); + List dependencies = createFlattenedDependencies(effectivePom); + cleanPom.setDependencies(dependencies); return cleanPom; } - private Model getSourceModel( FlattenDescriptor descriptor, PomProperty property, Model effectivePom, - Model originalPom, Model resolvedPom, Model interpolatedPom, Model cleanPom ) - { - - ElementHandling handling = descriptor.getHandling( property ); - getLog().debug( "Property " + property.getName() + " will be handled using " + handling - + " in flattened POM." ); - switch ( handling ) - { + private Model getSourceModel( + FlattenDescriptor descriptor, + PomProperty property, + Model effectivePom, + Model originalPom, + Model resolvedPom, + Model interpolatedPom, + Model cleanPom) { + + ElementHandling handling = descriptor.getHandling(property); + getLog().debug("Property " + property.getName() + " will be handled using " + handling + " in flattened POM."); + switch (handling) { case expand: return effectivePom; case keep: @@ -795,7 +722,7 @@ private Model getSourceModel( FlattenDescriptor descriptor, PomProperty prope case remove: return null; default: - throw new IllegalStateException( handling.toString() ); + throw new IllegalStateException(handling.toString()); } } @@ -806,17 +733,13 @@ private Model getSourceModel( FlattenDescriptor descriptor, PomProperty prope * @return the flattened {@link List} of {@link Repository} elements or null if null was * given. */ - protected static List createFlattenedRepositories( List repositories ) - { - if ( repositories != null ) - { - List flattenedRepositories = new ArrayList<>( repositories.size() ); - for ( Repository repo : repositories ) - { + protected static List createFlattenedRepositories(List repositories) { + if (repositories != null) { + List flattenedRepositories = new ArrayList<>(repositories.size()); + for (Repository repo : repositories) { // filter inherited repository section from super POM (see MOJO-2042)... - if ( !isCentralRepositoryFromSuperPom( repo ) ) - { - flattenedRepositories.add( repo ); + if (!isCentralRepositoryFromSuperPom(repo)) { + flattenedRepositories.add(repo); } } return flattenedRepositories; @@ -824,39 +747,28 @@ protected static List createFlattenedRepositories( List return repositories; } - private FlattenDescriptor getFlattenDescriptor() - throws MojoFailureException - { + private FlattenDescriptor getFlattenDescriptor() throws MojoFailureException { FlattenDescriptor descriptor = this.pomElements; - if ( descriptor == null ) - { + if (descriptor == null) { FlattenMode mode = this.flattenMode; - if ( mode == null ) - { + if (mode == null) { mode = FlattenMode.defaults; - } - else if ( this.flattenMode == FlattenMode.minimum ) - { - getLog().warn( "FlattenMode " + FlattenMode.minimum + " is deprecated!" ); + } else if (this.flattenMode == FlattenMode.minimum) { + getLog().warn("FlattenMode " + FlattenMode.minimum + " is deprecated!"); } descriptor = mode.getDescriptor(); - if ( "maven-plugin".equals( this.project.getPackaging() ) ) - { - descriptor.setPrerequisites( ElementHandling.expand ); + if ("maven-plugin".equals(this.project.getPackaging())) { + descriptor.setPrerequisites(ElementHandling.expand); } - } - else - { - if ( descriptor.isEmpty() ) - { + } else { + if (descriptor.isEmpty()) { // legacy approach... // Can't use Model itself as empty elements are never null, so you can't recognize if it was set or not - Xpp3Dom rawDescriptor = this.mojoExecution.getConfiguration().getChild( "pomElements" ); - descriptor = new FlattenDescriptor( rawDescriptor ); + Xpp3Dom rawDescriptor = this.mojoExecution.getConfiguration().getChild("pomElements"); + descriptor = new FlattenDescriptor(rawDescriptor); } - if ( this.flattenMode != null ) - { - descriptor = descriptor.merge( this.flattenMode.getDescriptor() ); + if (this.flattenMode != null) { + descriptor = descriptor.merge(this.flattenMode.getDescriptor()); } } return descriptor; @@ -869,12 +781,9 @@ else if ( this.flattenMode == FlattenMode.minimum ) * @param repo is the {@link Repository} section to check. * @return true if maven central default configuration, false otherwise. */ - private static boolean isCentralRepositoryFromSuperPom( Repository repo ) - { - if ( repo != null ) - { - if ( "central".equals( repo.getId() ) ) - { + private static boolean isCentralRepositoryFromSuperPom(Repository repo) { + if (repo != null) { + if ("central".equals(repo.getId())) { RepositoryPolicy snapshots = repo.getSnapshots(); return snapshots != null && !snapshots.isEnabled(); } @@ -882,35 +791,35 @@ private static boolean isCentralRepositoryFromSuperPom( Repository repo ) return false; } - private ModelBuildingRequest createModelBuildingRequest( File pomFile ) - { + private ModelBuildingRequest createModelBuildingRequest(File pomFile) { - RequestTrace trace = new RequestTrace( pomFile ); + RequestTrace trace = new RequestTrace(pomFile); String context = mojoExecution.getExecutionId(); - FlattenModelResolver resolver = new FlattenModelResolver( session.getRepositorySession(), repositorySystem, - trace, context, RepositoryUtils.toRepos( session.getProjectBuildingRequest().getRemoteRepositories() ), - getReactorModelsFromSession() ); + FlattenModelResolver resolver = new FlattenModelResolver( + session.getRepositorySession(), + repositorySystem, + trace, + context, + RepositoryUtils.toRepos(session.getProjectBuildingRequest().getRemoteRepositories()), + getReactorModelsFromSession()); Properties userProperties = this.session.getUserProperties(); List activeProfiles = this.session.getRequest().getActiveProfiles(); return new DefaultModelBuildingRequest() - .setUserProperties( userProperties ) - .setSystemProperties( System.getProperties() ) - .setPomFile( pomFile ) - .setModelResolver( resolver ) - .setActiveProfileIds( activeProfiles ); + .setUserProperties(userProperties) + .setSystemProperties(System.getProperties()) + .setPomFile(pomFile) + .setModelResolver(resolver) + .setActiveProfileIds(activeProfiles); } - private List getReactorModelsFromSession() - { + private List getReactorModelsFromSession() { // robust approach for 'special' environments like m2e (Eclipse plugin) which don't provide allProjects List models = this.session.getAllProjects(); - if ( models == null ) - { + if (models == null) { models = this.session.getProjects(); } - if ( models == null ) - { + if (models == null) { models = Collections.emptyList(); } return models; @@ -925,66 +834,53 @@ private List getReactorModelsFromSession() * @return the parsed and calculated effective POM. * @throws MojoExecutionException if anything goes wrong. */ - protected Model createEffectivePom( ModelBuildingRequest buildingRequest, - final boolean embedBuildProfileDependencies, final FlattenMode flattenMode ) - throws MojoExecutionException - { + protected Model createEffectivePom( + ModelBuildingRequest buildingRequest, + final boolean embedBuildProfileDependencies, + final FlattenMode flattenMode) + throws MojoExecutionException { ModelBuildingResult buildingResult; - try - { - ProfileInjector customInjector = ( model, profile, request, problems ) -> - { + try { + ProfileInjector customInjector = (model, profile, request, problems) -> { Properties merged = new Properties(); - merged.putAll( model.getProperties() ); - merged.putAll( profile.getProperties() ); - model.setProperties( merged ); + merged.putAll(model.getProperties()); + merged.putAll(profile.getProperties()); + model.setProperties(merged); // Copied from org.apache.maven.model.profile.DefaultProfileInjector DependencyManagement profileDependencyManagement = profile.getDependencyManagement(); - if ( profileDependencyManagement != null ) - { + if (profileDependencyManagement != null) { DependencyManagement modelDependencyManagement = model.getDependencyManagement(); - if ( modelDependencyManagement == null ) - { + if (modelDependencyManagement == null) { modelDependencyManagement = new DependencyManagement(); - model.setDependencyManagement( modelDependencyManagement ); + model.setDependencyManagement(modelDependencyManagement); } List src = profileDependencyManagement.getDependencies(); - if ( !src.isEmpty() ) - { + if (!src.isEmpty()) { List tgt = modelDependencyManagement.getDependencies(); - Map mergedDependencies = - new LinkedHashMap<>( ( src.size() + tgt.size() ) * 2 ); + Map mergedDependencies = new LinkedHashMap<>((src.size() + tgt.size()) * 2); - for ( Dependency element : tgt ) - { - mergedDependencies.put( element.getManagementKey(), element ); + for (Dependency element : tgt) { + mergedDependencies.put(element.getManagementKey(), element); } - for ( Dependency element : src ) - { + for (Dependency element : src) { String key = element.getManagementKey(); - if ( !mergedDependencies.containsKey( key ) ) - { - mergedDependencies.put( key, element ); + if (!mergedDependencies.containsKey(key)) { + mergedDependencies.put(key, element); } } - modelDependencyManagement - .setDependencies( new ArrayList<>( mergedDependencies.values() ) ); + modelDependencyManagement.setDependencies(new ArrayList<>(mergedDependencies.values())); } } }; - buildingResult = - modelBuilderThreadSafetyWorkaround.build( - buildingRequest, customInjector, new DefaultProfileSelector() - ); - } - catch ( ModelBuildingException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + buildingResult = modelBuilderThreadSafetyWorkaround.build( + buildingRequest, customInjector, new DefaultProfileSelector()); + } catch (ModelBuildingException e) { + throw new MojoExecutionException(e.getMessage(), e); } Model effectivePom = buildingResult.getEffectiveModel(); @@ -995,7 +891,7 @@ buildingRequest, customInjector, new DefaultProfileSelector() // effectivePom.getProjectDirectory(), buildingRequest, problems ); // remove Repositories from super POM (central) - effectivePom.setRepositories( createFlattenedRepositories( effectivePom.getRepositories() ) ); + effectivePom.setRepositories(createFlattenedRepositories(effectivePom.getRepositories())); return effectivePom; } @@ -1006,10 +902,8 @@ buildingRequest, customInjector, new DefaultProfileSelector() * @return true if null or {@link Collection#isEmpty() empty}, false * otherwise. */ - private boolean isEmpty( Collection collection ) - { - if ( collection == null ) - { + private boolean isEmpty(Collection collection) { + if (collection == null) { return true; } return collection.isEmpty(); @@ -1020,8 +914,7 @@ private boolean isEmpty( Collection collection ) * effect (variables and dependencies) are resolved and embedded into the flattened POM while the profile * itself is stripped. Otherwise if false the profiles will remain untouched. */ - public boolean isEmbedBuildProfileDependencies() - { + public boolean isEmbedBuildProfileDependencies() { return this.embedBuildProfileDependencies; } @@ -1030,14 +923,12 @@ public boolean isEmbedBuildProfileDependencies() * @return true if the given {@link Activation} is build-time driven, false otherwise (if * it is triggered by OS or JDK). */ - protected static boolean isBuildTimeDriven( Activation activation ) - { + protected static boolean isBuildTimeDriven(Activation activation) { - if ( activation == null ) - { + if (activation == null) { return true; } - return StringUtils.isEmpty( activation.getJdk() ) && activation.getOs() == null; + return StringUtils.isEmpty(activation.getJdk()) && activation.getOs() == null; } /** @@ -1048,50 +939,39 @@ protected static boolean isBuildTimeDriven( Activation activation ) * @return the {@link List} of {@link Dependency dependencies}. * @throws MojoExecutionException if anything goes wrong. */ - protected List createFlattenedDependencies( Model effectiveModel ) - throws MojoExecutionException - { + protected List createFlattenedDependencies(Model effectiveModel) throws MojoExecutionException { List flattenedDependencies = new ArrayList<>(); // resolve all direct and inherited dependencies... - try - { - createFlattenedDependencies( effectiveModel, flattenedDependencies ); - } - catch ( Exception e ) - { - throw new MojoExecutionException( "unable to create flattened dependencies", e ); + try { + createFlattenedDependencies(effectiveModel, flattenedDependencies); + } catch (Exception e) { + throw new MojoExecutionException("unable to create flattened dependencies", e); } - if ( isEmbedBuildProfileDependencies() ) - { + if (isEmbedBuildProfileDependencies()) { Model projectModel = this.project.getModel(); Dependencies modelDependencies = new Dependencies(); - modelDependencies.addAll( projectModel.getDependencies() ); - for ( Profile profile : projectModel.getProfiles() ) - { + modelDependencies.addAll(projectModel.getDependencies()); + for (Profile profile : projectModel.getProfiles()) { // build-time driven activation (by property or file)? - if ( isBuildTimeDriven( profile.getActivation() ) ) - { + if (isBuildTimeDriven(profile.getActivation())) { List profileDependencies = profile.getDependencies(); - for ( Dependency profileDependency : profileDependencies ) - { - if ( modelDependencies.contains( profileDependency ) ) - { + for (Dependency profileDependency : profileDependencies) { + if (modelDependencies.contains(profileDependency)) { // our assumption here is that the profileDependency has been added to model because of // this build-time driven profile. Therefore we need to add it to the flattened POM. // Non build-time driven profiles will remain in the flattened POM with their dependencies // and // allow dynamic dependencies due to OS or JDK. - Dependency resolvedProfileDependency = modelDependencies.resolve( profileDependency ); - if ( omitExclusions ) - { - resolvedProfileDependency.setExclusions( Collections.emptyList() ); + Dependency resolvedProfileDependency = modelDependencies.resolve(profileDependency); + if (omitExclusions) { + resolvedProfileDependency.setExclusions(Collections.emptyList()); } - flattenedDependencies.add( resolvedProfileDependency ); + flattenedDependencies.add(resolvedProfileDependency); } } } } - getLog().debug( "Resolved " + flattenedDependencies.size() + " dependency/-ies for flattened POM." ); + getLog().debug("Resolved " + flattenedDependencies.size() + " dependency/-ies for flattened POM."); } return flattenedDependencies; } @@ -1102,15 +982,12 @@ protected List createFlattenedDependencies( Model effectiveModel ) * @param projectDependencies is the effective POM {@link Model}'s current dependencies * @param flattenedDependencies is the {@link List} where to add the collected {@link Dependency dependencies}. */ - private void createFlattenedDependenciesDirect( List projectDependencies, - List flattenedDependencies ) - { - for ( Dependency projectDependency : projectDependencies ) - { - Dependency flattenedDependency = createFlattenedDependency( projectDependency ); - if ( flattenedDependency != null ) - { - flattenedDependencies.add( flattenedDependency ); + private void createFlattenedDependenciesDirect( + List projectDependencies, List flattenedDependencies) { + for (Dependency projectDependency : projectDependencies) { + Dependency flattenedDependency = createFlattenedDependency(projectDependency); + if (flattenedDependency != null) { + flattenedDependencies.add(flattenedDependency); } } } @@ -1141,137 +1018,117 @@ private void createFlattenedDependenciesDirect( List projectDependen * @throws DependencyCollectionException * @throws ArtifactDescriptorException */ - private void createFlattenedDependenciesAll( List projectDependencies, - List managedDependencies, - List flattenedDependencies ) - throws ArtifactDescriptorException, DependencyCollectionException - { + private void createFlattenedDependenciesAll( + List projectDependencies, + List managedDependencies, + List flattenedDependencies) + throws ArtifactDescriptorException, DependencyCollectionException { final Queue dependencyNodeLinkedList = new LinkedList<>(); final Set processedDependencies = new HashSet<>(); final Artifact projectArtifact = this.project.getArtifact(); CollectRequest collectRequest = new CollectRequest(); - collectRequest.setRepositories( project.getRemotePluginRepositories() ); - collectRequest.setRootArtifact( RepositoryUtils.toArtifact( projectArtifact ) ); - for ( Dependency dependency : projectDependencies ) - { - collectRequest.addDependency( RepositoryUtils.toDependency( dependency, - session.getRepositorySession().getArtifactTypeRegistry() ) ); + collectRequest.setRepositories(project.getRemotePluginRepositories()); + collectRequest.setRootArtifact(RepositoryUtils.toArtifact(projectArtifact)); + for (Dependency dependency : projectDependencies) { + collectRequest.addDependency(RepositoryUtils.toDependency( + dependency, session.getRepositorySession().getArtifactTypeRegistry())); } - for ( Artifact artifact : project.getArtifacts() ) - { - collectRequest.addDependency( RepositoryUtils.toDependency( artifact, null ) ); + for (Artifact artifact : project.getArtifacts()) { + collectRequest.addDependency(RepositoryUtils.toDependency(artifact, null)); } - for ( Dependency dependency : managedDependencies ) - { - collectRequest.addManagedDependency( RepositoryUtils.toDependency( dependency, - session.getRepositorySession().getArtifactTypeRegistry() ) ); + for (Dependency dependency : managedDependencies) { + collectRequest.addManagedDependency(RepositoryUtils.toDependency( + dependency, session.getRepositorySession().getArtifactTypeRegistry())); } - DefaultRepositorySystemSession derived = new DefaultRepositorySystemSession( session.getRepositorySession() ); - derived.setConfigProperty( ConflictResolver.CONFIG_PROP_VERBOSE, true ); - derived.setConfigProperty( DependencyManagerUtils.CONFIG_PROP_VERBOSE, true ); + DefaultRepositorySystemSession derived = new DefaultRepositorySystemSession(session.getRepositorySession()); + derived.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true); + derived.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, true); - CollectResult collectResult = - repositorySystem.collectDependencies( derived, collectRequest ); + CollectResult collectResult = repositorySystem.collectDependencies(derived, collectRequest); final DependencyNode root = collectResult.getRoot(); - final Set directDependencyKeys = Stream - .concat( - projectDependencies.stream() - .map( this::getKey ), - project.getArtifacts().stream() - .map( this::getKey ) ) - .collect( Collectors.toSet() ); - - root.accept( new DependencyVisitor() - { + final Set directDependencyKeys = Stream.concat( + projectDependencies.stream().map(this::getKey), + project.getArtifacts().stream().map(this::getKey)) + .collect(Collectors.toSet()); + + root.accept(new DependencyVisitor() { @Override - public boolean visitEnter( DependencyNode node ) - { - if ( root == node ) - { + public boolean visitEnter(DependencyNode node) { + if (root == node) { return true; } - if ( JavaScopes.PROVIDED.equals( node.getDependency().getScope() ) ) - { - String dependencyKey = getKey( node.getDependency() ); - if ( !directDependencyKeys.contains( dependencyKey ) ) - { + if (JavaScopes.PROVIDED.equals(node.getDependency().getScope())) { + String dependencyKey = getKey(node.getDependency()); + if (!directDependencyKeys.contains(dependencyKey)) { return false; // skip non-direct provided ones } } - if ( node.getDependency().isOptional() ) - { + if (node.getDependency().isOptional()) { return false; // skip optional ones } - dependencyNodeLinkedList.add( node ); + dependencyNodeLinkedList.add(node); return true; } @Override - public boolean visitLeave( DependencyNode node ) - { + public boolean visitLeave(DependencyNode node) { return true; } - } ); + }); - while ( !dependencyNodeLinkedList.isEmpty() ) - { + while (!dependencyNodeLinkedList.isEmpty()) { DependencyNode node = dependencyNodeLinkedList.poll(); org.eclipse.aether.graph.Dependency d = node.getDependency(); - Artifact artifact = RepositoryUtils.toArtifact( node.getArtifact() ); + Artifact artifact = RepositoryUtils.toArtifact(node.getArtifact()); Dependency dependency = new Dependency(); - dependency.setGroupId( artifact.getGroupId() ); - dependency.setArtifactId( artifact.getArtifactId() ); - dependency.setVersion( artifact.getBaseVersion() ); - dependency.setClassifier( artifact.getClassifier() ); - dependency.setOptional( d.isOptional() ); - dependency.setScope( d.getScope() ); - dependency.setType( artifact.getType() ); - - if ( !omitExclusions ) - { + dependency.setGroupId(artifact.getGroupId()); + dependency.setArtifactId(artifact.getArtifactId()); + dependency.setVersion(artifact.getBaseVersion()); + dependency.setClassifier(artifact.getClassifier()); + dependency.setOptional(d.isOptional()); + dependency.setScope(d.getScope()); + dependency.setType(artifact.getType()); + + if (!omitExclusions) { List exclusions = new LinkedList<>(); - org.eclipse.aether.artifact.Artifact aetherArtifact = - new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), null, artifact.getVersion() ); - ArtifactDescriptorRequest request = new ArtifactDescriptorRequest( aetherArtifact, null, null ); + org.eclipse.aether.artifact.Artifact aetherArtifact = new DefaultArtifact( + artifact.getGroupId(), artifact.getArtifactId(), null, artifact.getVersion()); + ArtifactDescriptorRequest request = new ArtifactDescriptorRequest(aetherArtifact, null, null); ArtifactDescriptorResult artifactDescriptorResult = - repositorySystem.readArtifactDescriptor( this.session.getRepositorySession(), request ); + repositorySystem.readArtifactDescriptor(this.session.getRepositorySession(), request); - for ( org.eclipse.aether.graph.Dependency artifactDependency - : artifactDescriptorResult.getDependencies() ) - { - if ( JavaScopes.TEST.equals( artifactDependency.getScope() ) ) - { + for (org.eclipse.aether.graph.Dependency artifactDependency : + artifactDescriptorResult.getDependencies()) { + if (JavaScopes.TEST.equals(artifactDependency.getScope())) { continue; } Exclusion exclusion = new Exclusion(); - exclusion.setGroupId( artifactDependency.getArtifact().getGroupId() ); - exclusion.setArtifactId( artifactDependency.getArtifact().getArtifactId() ); - exclusions.add( exclusion ); + exclusion.setGroupId(artifactDependency.getArtifact().getGroupId()); + exclusion.setArtifactId(artifactDependency.getArtifact().getArtifactId()); + exclusions.add(exclusion); } - dependency.setExclusions( exclusions ); + dependency.setExclusions(exclusions); } // convert dependency to string for the set, since Dependency doesn't implement equals, etc. String dependencyString = dependency.getManagementKey(); - if ( !processedDependencies.add( dependencyString ) ) - { + if (!processedDependencies.add(dependencyString)) { continue; } - Dependency flattenedDependency = createFlattenedDependency( dependency ); - if ( flattenedDependency != null ) - { - flattenedDependencies.add( flattenedDependency ); + Dependency flattenedDependency = createFlattenedDependency(dependency); + if (flattenedDependency != null) { + flattenedDependencies.add(flattenedDependency); } } } @@ -1280,33 +1137,32 @@ public boolean visitLeave( DependencyNode node ) * Keep in sync with {@link #getKey(org.eclipse.aether.graph.Dependency)} * and {@link #getKey(Dependency)}. */ - private String getKey( Artifact a ) - { - final String ext = artifactHandlerManager.getArtifactHandler( a.getType() ).getExtension(); + private String getKey(Artifact a) { + final String ext = + artifactHandlerManager.getArtifactHandler(a.getType()).getExtension(); return a.getGroupId() + ":" + a.getArtifactId() + ":" + ext - + ( a.getClassifier() != null ? ":" + a.getClassifier() : "" ); + + (a.getClassifier() != null ? ":" + a.getClassifier() : ""); } /** * Keep in sync with {@link #getKey(org.eclipse.aether.graph.Dependency)} * and {@link #getKey(Artifact)} */ - private String getKey( Dependency d ) - { - final String ext = artifactHandlerManager.getArtifactHandler( d.getType() ).getExtension(); + private String getKey(Dependency d) { + final String ext = + artifactHandlerManager.getArtifactHandler(d.getType()).getExtension(); return d.getGroupId() + ":" + d.getArtifactId() + ":" + ext - + ( d.getClassifier() != null ? ":" + d.getClassifier() : "" ); + + (d.getClassifier() != null ? ":" + d.getClassifier() : ""); } /** * Keep in sync with {@link #getKey(Dependency)} * and {@link #getKey(Artifact)}. */ - private String getKey( org.eclipse.aether.graph.Dependency dependency ) - { + private String getKey(org.eclipse.aether.graph.Dependency dependency) { final org.eclipse.aether.artifact.Artifact a = dependency.getArtifact(); return a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getExtension() - + ( !a.getClassifier().isEmpty() ? ":" + a.getClassifier() : "" ); + + (!a.getClassifier().isEmpty() ? ":" + a.getClassifier() : ""); } /** @@ -1316,30 +1172,25 @@ private String getKey( org.eclipse.aether.graph.Dependency dependency ) * @param flattenedDependencies is the {@link List} where to add the collected {@link Dependency dependencies}. * @throws MojoExecutionException if anything goes wrong. */ - protected void createFlattenedDependencies( Model effectiveModel, List flattenedDependencies ) - throws MojoExecutionException - { - getLog().debug( "Resolving dependencies of " + effectiveModel.getId() ); + protected void createFlattenedDependencies(Model effectiveModel, List flattenedDependencies) + throws MojoExecutionException { + getLog().debug("Resolving dependencies of " + effectiveModel.getId()); // this.project.getDependencies() already contains the inherited dependencies but also those from profiles // List projectDependencies = currentProject.getOriginalModel().getDependencies(); List projectDependencies = effectiveModel.getDependencies(); - if ( flattenDependencyMode == null | flattenDependencyMode == FlattenDependencyMode.direct ) - { - createFlattenedDependenciesDirect( projectDependencies, flattenedDependencies ); - } - else if ( flattenDependencyMode == FlattenDependencyMode.all ) - { - try - { - createFlattenedDependenciesAll( projectDependencies, + if (flattenDependencyMode == null | flattenDependencyMode == FlattenDependencyMode.direct) { + createFlattenedDependenciesDirect(projectDependencies, flattenedDependencies); + } else if (flattenDependencyMode == FlattenDependencyMode.all) { + try { + createFlattenedDependenciesAll( + projectDependencies, effectiveModel.getDependencyManagement() != null - ? effectiveModel.getDependencyManagement().getDependencies() : Collections.emptyList(), - flattenedDependencies ); - } - catch ( Exception e ) - { - throw new MojoExecutionException( "caught exception when flattening dependencies", e ); + ? effectiveModel.getDependencyManagement().getDependencies() + : Collections.emptyList(), + flattenedDependencies); + } catch (Exception e) { + throw new MojoExecutionException("caught exception when flattening dependencies", e); } } } @@ -1349,16 +1200,13 @@ else if ( flattenDependencyMode == FlattenDependencyMode.all ) * @return the flattened {@link Dependency} or null if the given {@link Dependency} is NOT relevant for * flattened POM. */ - protected Dependency createFlattenedDependency( Dependency projectDependency ) - { - if ( JavaScopes.TEST.equals( projectDependency.getScope() ) ) - { + protected Dependency createFlattenedDependency(Dependency projectDependency) { + if (JavaScopes.TEST.equals(projectDependency.getScope())) { return null; } - if ( omitExclusions ) - { - projectDependency.setExclusions( Collections.emptyList() ); + if (omitExclusions) { + projectDependency.setExclusions(Collections.emptyList()); } return projectDependency; @@ -1368,19 +1216,14 @@ protected Dependency createFlattenedDependency( Dependency projectDependency ) * @return true if the generated flattened POM shall be {@link MavenProject#setFile(java.io.File) set} * as POM artifact of the {@link MavenProject}, false otherwise. */ - public boolean isUpdatePomFile() - { + public boolean isUpdatePomFile() { - if ( this.updatePomFile == null ) - { - if ( this.flattenMode == FlattenMode.bom ) - { + if (this.updatePomFile == null) { + if (this.flattenMode == FlattenMode.bom) { return true; } - return !this.project.getPackaging().equals( "pom" ); - } - else - { + return !this.project.getPackaging().equals("pom"); + } else { return this.updatePomFile.booleanValue(); } } @@ -1389,9 +1232,7 @@ public boolean isUpdatePomFile() * This class is a simple SAX handler that extracts the first comment located before the root tag in an XML * document. */ - private class SaxHeaderCommentHandler - extends DefaultHandler2 - { + private class SaxHeaderCommentHandler extends DefaultHandler2 { /** * true if root tag has already been visited, false otherwise. @@ -1406,8 +1247,7 @@ private class SaxHeaderCommentHandler /** * The constructor. */ - SaxHeaderCommentHandler() - { + SaxHeaderCommentHandler() { super(); this.rootTagSeen = false; @@ -1416,8 +1256,7 @@ private class SaxHeaderCommentHandler /** * @return the XML comment from the header of the document or null if not present. */ - public String getHeaderComment() - { + public String getHeaderComment() { return this.headerComment; } @@ -1426,19 +1265,13 @@ public String getHeaderComment() * {@inheritDoc} */ @Override - public void comment( char[] ch, int start, int length ) - throws SAXException - { - - if ( !this.rootTagSeen ) - { - if ( this.headerComment == null ) - { - this.headerComment = new String( ch, start, length ); - } - else - { - getLog().warn( "Ignoring multiple XML header comment!" ); + public void comment(char[] ch, int start, int length) throws SAXException { + + if (!this.rootTagSeen) { + if (this.headerComment == null) { + this.headerComment = new String(ch, start, length); + } else { + getLog().warn("Ignoring multiple XML header comment!"); } } } @@ -1447,12 +1280,9 @@ public void comment( char[] ch, int start, int length ) * {@inheritDoc} */ @Override - public void startElement( String uri, String localName, String qName, Attributes atts ) - throws SAXException - { + public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { this.rootTagSeen = true; } } - } diff --git a/src/main/java/org/codehaus/mojo/flatten/KeepCommentsInPom.java b/src/main/java/org/codehaus/mojo/flatten/KeepCommentsInPom.java index e99b8877..1bfe6577 100644 --- a/src/main/java/org/codehaus/mojo/flatten/KeepCommentsInPom.java +++ b/src/main/java/org/codehaus/mojo/flatten/KeepCommentsInPom.java @@ -1,272 +1,241 @@ -package org.codehaus.mojo.flatten; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiConsumer; - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.logging.Log; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.bootstrap.DOMImplementationRegistry; -import org.w3c.dom.ls.DOMImplementationLS; -import org.w3c.dom.ls.LSOutput; -import org.w3c.dom.ls.LSSerializer; -import org.xml.sax.SAXException; - -/** - * Helper class to keep the comments how they have been in the original pom.xml While reading with - * {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} the comments are not placed into the - * {@link org.apache.maven.model.Model} and so {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} is not able to - * re-write those comments. - *

- * Workaround (maybe until core is fixed) is to remember all the comments and restore them after MavenXpp3Writer has - * created the new flattened pom.xml. - *

- * Current restriction on non-unique child nodes is that this class finds the node back due to the position in the file, - * that may lead to mis-re-added comments e.g. on multiple added dependencies (but for e.g. resolveCiFriendliesOnly the - * nodes keep stable) - */ -class KeepCommentsInPom -{ - - /** - * Create an instance with collected current comments of the passed pom.xml file. - */ - static KeepCommentsInPom create( Log aLog, File aOriginalPomFile ) throws MojoExecutionException - { - KeepCommentsInPom tempKeepCommentsInPom = new KeepCommentsInPom(); - tempKeepCommentsInPom.setLog( aLog ); - tempKeepCommentsInPom.loadComments( aOriginalPomFile ); - return tempKeepCommentsInPom; - } - - private Log log; - - /** - * The unique path list for an original node (the comments are stored via the referenced previousSibling) - */ - private Map commentsPaths; - - /** - * - */ - KeepCommentsInPom() - { - super(); - } - - /** - * load all current comments and text fragments from xml file - * - * @param anOriginalPomFile the pom.xml - */ - private void loadComments( File anOriginalPomFile ) throws MojoExecutionException - { - commentsPaths = new HashMap<>(); - DocumentBuilderFactory tempDBF = DocumentBuilderFactory.newInstance(); - DocumentBuilder tempDB; - try - { - tempDB = tempDBF.newDocumentBuilder(); - Document tempPom = tempDB.parse( anOriginalPomFile ); - Node tempNode = tempPom.getDocumentElement(); - walkOverNodes( tempNode, ".", ( node, nodePath ) -> - { - // collectNodesByPathNames - commentsPaths.put( nodePath, node ); - } ); - } - catch ( ParserConfigurationException | SAXException | IOException e ) - { - throw new MojoExecutionException( "Cannot load comments from " + anOriginalPomFile, e ); - } - } - - /** - * Walk over the pom hierarchy of the Document. - * - * @param Node the current Node - * @param String the unique path in the parent - * @param aConsumer Function to be called with the toBeCollected/found node. - */ - private void walkOverNodes( Node aNode, String aParentPath, BiConsumer aConsumer ) - { - String tempNodeName = aNode.getNodeName(); - if ( log.isDebugEnabled() ) - { - log.debug( "walkOverNodes: aParentPath=" + aParentPath + " tempNodeName=" + tempNodeName ); - } - String tempNodePath = aParentPath + "\t" + tempNodeName; - aConsumer.accept( aNode, tempNodePath ); - NodeList tempChilds = aNode.getChildNodes(); - // Copy the childs as aConsumer may change the node sequence (add a comment) - List tempCopiedChilds = new ArrayList<>(); - Map tempChildWithSameName = new HashMap<>(); - for ( int i = 0; i < tempChilds.getLength(); i++ ) - { - Node tempItem = tempChilds.item( i ); - if ( tempItem.getNodeType() != Node.TEXT_NODE && tempItem.getNodeType() != Node.COMMENT_NODE ) - { - // Take real nodes to find them back by number - String tempChildNodeName = tempItem.getNodeName(); - Integer tempChildWithSameNameCount = tempChildWithSameName.get( tempChildNodeName ); - if ( tempChildWithSameNameCount == null ) - { - tempChildWithSameNameCount = 1; - } - else - { - tempChildWithSameNameCount += 1; - } - tempChildWithSameName.put( tempChildNodeName, tempChildWithSameNameCount ); - tempCopiedChilds.add( tempItem ); - } - } - Map tempChildWithSameNameCounters = new HashMap<>(); - for ( Node tempCopiedChild : tempCopiedChilds ) - { - String tempChildNodeName = tempCopiedChild.getNodeName(); - if ( tempChildWithSameName.get( tempChildNodeName ) > 1 ) - { - Integer tempChildWithSameNameCounter = tempChildWithSameNameCounters.get( tempChildNodeName ); - if ( tempChildWithSameNameCounter == null ) - { - tempChildWithSameNameCounter = 1; - } - else - { - tempChildWithSameNameCounter += 1; - } - tempChildWithSameNameCounters.put( tempChildNodeName, tempChildWithSameNameCounter ); - // add a counter to find back the correct node. - walkOverNodes( tempCopiedChild, tempNodePath + "\t" + tempChildWithSameNameCounter, aConsumer ); - } - else - { - // unique child names - walkOverNodes( tempCopiedChild, tempNodePath, aConsumer ); - } - } - } - - /** - * @param String the XML written by {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} - */ - public String restoreOriginalComments( String anXml, String aModelEncoding ) throws MojoExecutionException - { - DocumentBuilderFactory tempDBF = DocumentBuilderFactory.newInstance(); - DocumentBuilder tempDB; - try - { - tempDB = tempDBF.newDocumentBuilder(); - String tempEncoding = aModelEncoding == null ? "UTF-8" : aModelEncoding; // default encoding UTF-8 when - // nothing in pom model. - Document tempPom = tempDB.parse( new ByteArrayInputStream( anXml.getBytes( tempEncoding ) ) ); - Node tempNode = tempPom.getDocumentElement(); - walkOverNodes( tempNode, ".", ( newNode, nodePath ) -> - { - Node tempOriginalNode = commentsPaths.get( nodePath ); - if ( tempOriginalNode != null ) - { - String tempOriginalNodeName = tempOriginalNode.getNodeName(); - if ( tempOriginalNodeName.equals( newNode.getNodeName() ) ) - { - // found matching node - Node tempRefChild = newNode; - Node tempPotentialCommentOrText = tempOriginalNode.getPreviousSibling(); - while ( tempPotentialCommentOrText != null - && tempPotentialCommentOrText.getNodeType() == Node.TEXT_NODE ) - { - // skip text in the original xml node - tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling(); - } - while ( tempPotentialCommentOrText != null - && tempPotentialCommentOrText.getNodeType() == Node.COMMENT_NODE ) - { - // copy the node to be able to call previoussibling for next element - Node tempRefPrevious = tempRefChild.getPreviousSibling(); - String tempWhitespaceTextBeforeRefNode = null; - if ( tempRefPrevious != null && tempRefPrevious.getNodeType() == Node.TEXT_NODE ) - { - tempWhitespaceTextBeforeRefNode = tempRefPrevious.getNodeValue(); - } - Node tempNewComment; - tempNewComment = tempPom.createComment( tempPotentialCommentOrText.getNodeValue() ); - tempRefChild.getParentNode().insertBefore( tempNewComment, tempRefChild ); - // copy the whitespaces between comment and refNode - if ( tempWhitespaceTextBeforeRefNode != null ) - { - tempRefChild.getParentNode().insertBefore( - tempPom.createTextNode( tempWhitespaceTextBeforeRefNode ), tempRefChild ); - } - - tempRefChild = tempNewComment; - - tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling(); - while ( tempPotentialCommentOrText != null - && tempPotentialCommentOrText.getNodeType() == Node.TEXT_NODE ) - { - // skip text in the original xml node - tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling(); - } - } - } - } - } ); - return writeDocumentToString( tempPom ); - } - catch ( ParserConfigurationException | SAXException | IOException | ClassNotFoundException - | InstantiationException | IllegalAccessException | ClassCastException e ) - { - throw new MojoExecutionException( "Cannot add comments", e ); - } - } - - /** - * Use an LSSerializer to keep whitespaces added by MavenXpp3Writer - * - * @param Document the pom to write to String. - */ - private String writeDocumentToString( Document aPom ) - throws ClassNotFoundException, InstantiationException, IllegalAccessException - { - DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); - DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation( "LS" ); - LSOutput output = impl.createLSOutput(); - output.setEncoding( "UTF-8" ); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - output.setByteStream( outStream ); - LSSerializer writer = impl.createLSSerializer(); - writer.write( aPom, output ); - return outStream.toString(); - } - - /** - * @see #log - */ - public Log getLog() - { - return log; - } - - /** - * @see #log - */ - public void setLog( Log aLog ) - { - log = aLog; - } - -} +package org.codehaus.mojo.flatten; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; + +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.logging.Log; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.bootstrap.DOMImplementationRegistry; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSOutput; +import org.w3c.dom.ls.LSSerializer; +import org.xml.sax.SAXException; + +/** + * Helper class to keep the comments how they have been in the original pom.xml While reading with + * {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} the comments are not placed into the + * {@link org.apache.maven.model.Model} and so {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} is not able to + * re-write those comments. + *

+ * Workaround (maybe until core is fixed) is to remember all the comments and restore them after MavenXpp3Writer has + * created the new flattened pom.xml. + *

+ * Current restriction on non-unique child nodes is that this class finds the node back due to the position in the file, + * that may lead to mis-re-added comments e.g. on multiple added dependencies (but for e.g. resolveCiFriendliesOnly the + * nodes keep stable) + */ +class KeepCommentsInPom { + + /** + * Create an instance with collected current comments of the passed pom.xml file. + */ + static KeepCommentsInPom create(Log aLog, File aOriginalPomFile) throws MojoExecutionException { + KeepCommentsInPom tempKeepCommentsInPom = new KeepCommentsInPom(); + tempKeepCommentsInPom.setLog(aLog); + tempKeepCommentsInPom.loadComments(aOriginalPomFile); + return tempKeepCommentsInPom; + } + + private Log log; + + /** + * The unique path list for an original node (the comments are stored via the referenced previousSibling) + */ + private Map commentsPaths; + + /** + * + */ + KeepCommentsInPom() { + super(); + } + + /** + * load all current comments and text fragments from xml file + * + * @param anOriginalPomFile the pom.xml + */ + private void loadComments(File anOriginalPomFile) throws MojoExecutionException { + commentsPaths = new HashMap<>(); + DocumentBuilderFactory tempDBF = DocumentBuilderFactory.newInstance(); + DocumentBuilder tempDB; + try { + tempDB = tempDBF.newDocumentBuilder(); + Document tempPom = tempDB.parse(anOriginalPomFile); + Node tempNode = tempPom.getDocumentElement(); + walkOverNodes(tempNode, ".", (node, nodePath) -> { + // collectNodesByPathNames + commentsPaths.put(nodePath, node); + }); + } catch (ParserConfigurationException | SAXException | IOException e) { + throw new MojoExecutionException("Cannot load comments from " + anOriginalPomFile, e); + } + } + + /** + * Walk over the pom hierarchy of the Document. + * + * @param Node the current Node + * @param String the unique path in the parent + * @param aConsumer Function to be called with the toBeCollected/found node. + */ + private void walkOverNodes(Node aNode, String aParentPath, BiConsumer aConsumer) { + String tempNodeName = aNode.getNodeName(); + if (log.isDebugEnabled()) { + log.debug("walkOverNodes: aParentPath=" + aParentPath + " tempNodeName=" + tempNodeName); + } + String tempNodePath = aParentPath + "\t" + tempNodeName; + aConsumer.accept(aNode, tempNodePath); + NodeList tempChilds = aNode.getChildNodes(); + // Copy the childs as aConsumer may change the node sequence (add a comment) + List tempCopiedChilds = new ArrayList<>(); + Map tempChildWithSameName = new HashMap<>(); + for (int i = 0; i < tempChilds.getLength(); i++) { + Node tempItem = tempChilds.item(i); + if (tempItem.getNodeType() != Node.TEXT_NODE && tempItem.getNodeType() != Node.COMMENT_NODE) { + // Take real nodes to find them back by number + String tempChildNodeName = tempItem.getNodeName(); + Integer tempChildWithSameNameCount = tempChildWithSameName.get(tempChildNodeName); + if (tempChildWithSameNameCount == null) { + tempChildWithSameNameCount = 1; + } else { + tempChildWithSameNameCount += 1; + } + tempChildWithSameName.put(tempChildNodeName, tempChildWithSameNameCount); + tempCopiedChilds.add(tempItem); + } + } + Map tempChildWithSameNameCounters = new HashMap<>(); + for (Node tempCopiedChild : tempCopiedChilds) { + String tempChildNodeName = tempCopiedChild.getNodeName(); + if (tempChildWithSameName.get(tempChildNodeName) > 1) { + Integer tempChildWithSameNameCounter = tempChildWithSameNameCounters.get(tempChildNodeName); + if (tempChildWithSameNameCounter == null) { + tempChildWithSameNameCounter = 1; + } else { + tempChildWithSameNameCounter += 1; + } + tempChildWithSameNameCounters.put(tempChildNodeName, tempChildWithSameNameCounter); + // add a counter to find back the correct node. + walkOverNodes(tempCopiedChild, tempNodePath + "\t" + tempChildWithSameNameCounter, aConsumer); + } else { + // unique child names + walkOverNodes(tempCopiedChild, tempNodePath, aConsumer); + } + } + } + + /** + * @param String the XML written by {@link org.apache.maven.model.io.xpp3.MavenXpp3Writer} + */ + public String restoreOriginalComments(String anXml, String aModelEncoding) throws MojoExecutionException { + DocumentBuilderFactory tempDBF = DocumentBuilderFactory.newInstance(); + DocumentBuilder tempDB; + try { + tempDB = tempDBF.newDocumentBuilder(); + String tempEncoding = aModelEncoding == null ? "UTF-8" : aModelEncoding; // default encoding UTF-8 when + // nothing in pom model. + Document tempPom = tempDB.parse(new ByteArrayInputStream(anXml.getBytes(tempEncoding))); + Node tempNode = tempPom.getDocumentElement(); + walkOverNodes(tempNode, ".", (newNode, nodePath) -> { + Node tempOriginalNode = commentsPaths.get(nodePath); + if (tempOriginalNode != null) { + String tempOriginalNodeName = tempOriginalNode.getNodeName(); + if (tempOriginalNodeName.equals(newNode.getNodeName())) { + // found matching node + Node tempRefChild = newNode; + Node tempPotentialCommentOrText = tempOriginalNode.getPreviousSibling(); + while (tempPotentialCommentOrText != null + && tempPotentialCommentOrText.getNodeType() == Node.TEXT_NODE) { + // skip text in the original xml node + tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling(); + } + while (tempPotentialCommentOrText != null + && tempPotentialCommentOrText.getNodeType() == Node.COMMENT_NODE) { + // copy the node to be able to call previoussibling for next element + Node tempRefPrevious = tempRefChild.getPreviousSibling(); + String tempWhitespaceTextBeforeRefNode = null; + if (tempRefPrevious != null && tempRefPrevious.getNodeType() == Node.TEXT_NODE) { + tempWhitespaceTextBeforeRefNode = tempRefPrevious.getNodeValue(); + } + Node tempNewComment; + tempNewComment = tempPom.createComment(tempPotentialCommentOrText.getNodeValue()); + tempRefChild.getParentNode().insertBefore(tempNewComment, tempRefChild); + // copy the whitespaces between comment and refNode + if (tempWhitespaceTextBeforeRefNode != null) { + tempRefChild + .getParentNode() + .insertBefore( + tempPom.createTextNode(tempWhitespaceTextBeforeRefNode), tempRefChild); + } + + tempRefChild = tempNewComment; + + tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling(); + while (tempPotentialCommentOrText != null + && tempPotentialCommentOrText.getNodeType() == Node.TEXT_NODE) { + // skip text in the original xml node + tempPotentialCommentOrText = tempPotentialCommentOrText.getPreviousSibling(); + } + } + } + } + }); + return writeDocumentToString(tempPom); + } catch (ParserConfigurationException + | SAXException + | IOException + | ClassNotFoundException + | InstantiationException + | IllegalAccessException + | ClassCastException e) { + throw new MojoExecutionException("Cannot add comments", e); + } + } + + /** + * Use an LSSerializer to keep whitespaces added by MavenXpp3Writer + * + * @param Document the pom to write to String. + */ + private String writeDocumentToString(Document aPom) + throws ClassNotFoundException, InstantiationException, IllegalAccessException { + DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); + DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); + LSOutput output = impl.createLSOutput(); + output.setEncoding("UTF-8"); + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + output.setByteStream(outStream); + LSSerializer writer = impl.createLSSerializer(); + writer.write(aPom, output); + return outStream.toString(); + } + + /** + * @see #log + */ + public Log getLog() { + return log; + } + + /** + * @see #log + */ + public void setLog(Log aLog) { + log = aLog; + } +} diff --git a/src/main/java/org/codehaus/mojo/flatten/LoggingModelProblemCollector.java b/src/main/java/org/codehaus/mojo/flatten/LoggingModelProblemCollector.java index 5d7390d9..d250849a 100644 --- a/src/main/java/org/codehaus/mojo/flatten/LoggingModelProblemCollector.java +++ b/src/main/java/org/codehaus/mojo/flatten/LoggingModelProblemCollector.java @@ -1,57 +1,52 @@ -package org.codehaus.mojo.flatten; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.building.ModelProblemCollector; -import org.apache.maven.model.building.ModelProblemCollectorRequest; -import org.apache.maven.plugin.logging.Log; - -/** - * This is an implementation of {@link ModelProblemCollector} that is logging all problems. - * - * @author Joerg Hohwiller (hohwille at users.sourceforge.net) - * @since 1.0.0-beta-4 - */ -public class LoggingModelProblemCollector - implements ModelProblemCollector -{ - - private final Log logger; - - /** - * The constructor. - * - * @param logger is the {@link Log}. - */ - public LoggingModelProblemCollector( Log logger ) - { - super(); - this.logger = logger; - } - - /** - * {@inheritDoc} - */ - public void add( ModelProblemCollectorRequest req ) - { - this.logger.warn( req.getMessage(), req.getException() ); - } - -} +package org.codehaus.mojo.flatten; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import org.apache.maven.model.building.ModelProblemCollector; +import org.apache.maven.model.building.ModelProblemCollectorRequest; +import org.apache.maven.plugin.logging.Log; + +/** + * This is an implementation of {@link ModelProblemCollector} that is logging all problems. + * + * @author Joerg Hohwiller (hohwille at users.sourceforge.net) + * @since 1.0.0-beta-4 + */ +public class LoggingModelProblemCollector implements ModelProblemCollector { + + private final Log logger; + + /** + * The constructor. + * + * @param logger is the {@link Log}. + */ + public LoggingModelProblemCollector(Log logger) { + super(); + this.logger = logger; + } + + /** + * {@inheritDoc} + */ + public void add(ModelProblemCollectorRequest req) { + this.logger.warn(req.getMessage(), req.getException()); + } +} diff --git a/src/main/java/org/codehaus/mojo/flatten/ModelBuilderThreadSafetyWorkaround.java b/src/main/java/org/codehaus/mojo/flatten/ModelBuilderThreadSafetyWorkaround.java index 167135ad..d7f98242 100644 --- a/src/main/java/org/codehaus/mojo/flatten/ModelBuilderThreadSafetyWorkaround.java +++ b/src/main/java/org/codehaus/mojo/flatten/ModelBuilderThreadSafetyWorkaround.java @@ -57,8 +57,7 @@ * @since 1.2.3 */ @Named -public class ModelBuilderThreadSafetyWorkaround -{ +public class ModelBuilderThreadSafetyWorkaround { @Inject private ModelProcessor modelProcessor; @@ -106,30 +105,30 @@ public class ModelBuilderThreadSafetyWorkaround @Inject private ReportingConverter reportingConverter; - public ModelBuildingResult build( ModelBuildingRequest buildingRequest, ProfileInjector customInjector, - ProfileSelector customSelector ) - throws ModelBuildingException - { + public ModelBuildingResult build( + ModelBuildingRequest buildingRequest, ProfileInjector customInjector, ProfileSelector customSelector) + throws ModelBuildingException { // note: there is neither DefaultModelBuilder.get*(), nor DefaultModelBuilder.clone() - return new DefaultModelBuilderFactory().newInstance() - .setProfileInjector( customInjector ) - .setProfileSelector( customSelector ) - // apply currently active ModelProcessor etc. to support extensions like jgitver - .setDependencyManagementImporter( dependencyManagementImporter ) - .setDependencyManagementInjector( dependencyManagementInjector ) - .setInheritanceAssembler( inheritanceAssembler ) - .setLifecycleBindingsInjector( lifecycleBindingsInjector ) - .setModelInterpolator( modelInterpolator ) - .setModelNormalizer( modelNormalizer ) - .setModelPathTranslator( modelPathTranslator ) - .setModelProcessor( modelProcessor ) - .setModelUrlNormalizer( modelUrlNormalizer ) - .setModelValidator( modelValidator ) - .setPluginConfigurationExpander( pluginConfigurationExpander ) - .setPluginManagementInjector( pluginManagementInjector ) - .setReportConfigurationExpander( reportConfigurationExpander ) - .setReportingConverter( reportingConverter ) - .setSuperPomProvider( superPomProvider ) - .build( buildingRequest ); + return new DefaultModelBuilderFactory() + .newInstance() + .setProfileInjector(customInjector) + .setProfileSelector(customSelector) + // apply currently active ModelProcessor etc. to support extensions like jgitver + .setDependencyManagementImporter(dependencyManagementImporter) + .setDependencyManagementInjector(dependencyManagementInjector) + .setInheritanceAssembler(inheritanceAssembler) + .setLifecycleBindingsInjector(lifecycleBindingsInjector) + .setModelInterpolator(modelInterpolator) + .setModelNormalizer(modelNormalizer) + .setModelPathTranslator(modelPathTranslator) + .setModelProcessor(modelProcessor) + .setModelUrlNormalizer(modelUrlNormalizer) + .setModelValidator(modelValidator) + .setPluginConfigurationExpander(pluginConfigurationExpander) + .setPluginManagementInjector(pluginManagementInjector) + .setReportConfigurationExpander(reportConfigurationExpander) + .setReportingConverter(reportingConverter) + .setSuperPomProvider(superPomProvider) + .build(buildingRequest); } } diff --git a/src/main/java/org/codehaus/mojo/flatten/PomProperty.java b/src/main/java/org/codehaus/mojo/flatten/PomProperty.java index 96f39620..79e0d828 100644 --- a/src/main/java/org/codehaus/mojo/flatten/PomProperty.java +++ b/src/main/java/org/codehaus/mojo/flatten/PomProperty.java @@ -1,712 +1,632 @@ -package org.codehaus.mojo.flatten; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Properties; - -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.Parent; -import org.apache.maven.model.PluginManagement; -import org.apache.maven.model.Prerequisites; -import org.apache.maven.model.Profile; -import org.apache.maven.model.Reporting; -import org.apache.maven.model.Repository; -import org.apache.maven.model.Scm; - -/** - * This class reflects a property of a {@link Model POM}. It contains {@link #getPomProperties() all available - * properties} as constants and allows generic access to {@link #get(Model) read} and {@link #set(Model, Object) write} - * the property via a {@link Model}. - * - * @param is the generic type of the {@link #get(Model) property value}. - * @author Joerg Hohwiller (hohwille at users.sourceforge.net) - * @since 1.0.0-beta-4 - */ -public abstract class PomProperty -{ - - /** @see Model#getArtifactId() */ - public static final PomProperty ARTIFACT_ID = new PomProperty( "artifactId", String.class ) - { - @Override - public String get( Model model ) - { - return model.getArtifactId(); - } - - @Override - public void set( Model model, String value ) - { - model.setArtifactId( value ); - } - }; - - /** @see Model#getBuild() */ - public static final PomProperty BUILD = new PomProperty( "build", Build.class ) - { - @Override - public Build get( Model model ) - { - return model.getBuild(); - } - - @Override - public void set( Model model, Build value ) - { - model.setBuild( value ); - } - }; - - /** @see Model#getCiManagement() */ - public static final PomProperty CI_MANAGEMENT = - new PomProperty( "ciManagement", CiManagement.class ) - { - @Override - public CiManagement get( Model model ) - { - return model.getCiManagement(); - } - - @Override - public void set( Model model, CiManagement value ) - { - model.setCiManagement( value ); - } - }; - - /** @see Model#getContributors() */ - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public static final PomProperty> CONTRIBUTORS = - new PomProperty>( "contributors", (Class) List.class ) - { - @Override - public List get( Model model ) - { - return model.getContributors(); - } - - @Override - public void set( Model model, List value ) - { - model.setContributors( value ); - } - }; - - /** @see Model#getDependencies() */ - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public static final PomProperty> DEPENDENCIES = - new PomProperty>( "dependencies", (Class) List.class ) - { - @Override - public List get( Model model ) - { - return model.getDependencies(); - } - - @Override - public void set( Model model, List value ) - { - model.setDependencies( value ); - } - }; - - /** @see Model#getDependencyManagement() */ - public static final PomProperty DEPENDENCY_MANAGEMENT = - new PomProperty( "dependencyManagement", DependencyManagement.class ) - { - @Override - public DependencyManagement get( Model model ) - { - return model.getDependencyManagement(); - } - - @Override - public void set( Model model, DependencyManagement value ) - { - model.setDependencyManagement( value ); - } - }; - - /** @see Model#getDescription() */ - public static final PomProperty DESCRIPTION = new PomProperty( "description", String.class ) - { - @Override - public String get( Model model ) - { - return model.getDescription(); - } - - @Override - public void set( Model model, String value ) - { - model.setDescription( value ); - } - }; - - /** @see Model#getDevelopers() */ - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public static final PomProperty> DEVELOPERS = - new PomProperty>( "developers", (Class) List.class ) - { - @Override - public List get( Model model ) - { - return model.getDevelopers(); - } - - @Override - public void set( Model model, List value ) - { - model.setDevelopers( value ); - } - }; - - /** @see Model#getDistributionManagement() */ - public static final PomProperty DISTRIBUTION_MANAGEMENT = - new PomProperty( "distributionManagement", DistributionManagement.class ) - { - @Override - public DistributionManagement get( Model model ) - { - return model.getDistributionManagement(); - } - - @Override - public void set( Model model, DistributionManagement value ) - { - model.setDistributionManagement( value ); - } - }; - - /** @see Model#getGroupId() */ - public static final PomProperty GROUP_ID = new PomProperty( "groupId", String.class ) - { - @Override - public String get( Model model ) - { - return model.getGroupId(); - } - - @Override - public void set( Model model, String value ) - { - model.setGroupId( value ); - } - }; - - /** @see Model#getInceptionYear() */ - public static final PomProperty INCEPTION_YEAR = new PomProperty( "inceptionYear", String.class ) - { - @Override - public String get( Model model ) - { - return model.getInceptionYear(); - } - - @Override - public void set( Model model, String value ) - { - model.setInceptionYear( value ); - } - }; - - /** @see Model#getIssueManagement() */ - public static final PomProperty ISSUE_MANAGEMENT = - new PomProperty( "issueManagement", IssueManagement.class ) - { - @Override - public IssueManagement get( Model model ) - { - return model.getIssueManagement(); - } - - @Override - public void set( Model model, IssueManagement value ) - { - model.setIssueManagement( value ); - } - }; - - /** @see Model#getLicenses() */ - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public static final PomProperty> LICENSES = - new PomProperty>( "licenses", (Class) List.class ) - { - @Override - public List get( Model model ) - { - return model.getLicenses(); - } - - @Override - public void set( Model model, List value ) - { - model.setLicenses( value ); - } - }; - - /** @see Model#getMailingLists() */ - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public static final PomProperty> MAILING_LISTS = - new PomProperty>( "mailingLists", (Class) List.class ) - { - @Override - public List get( Model model ) - { - return model.getMailingLists(); - } - - @Override - public void set( Model model, List value ) - { - model.setMailingLists( value ); - } - }; - - /** @see Model#getModelEncoding() */ - public static final PomProperty MODEL_ENCODING = new PomProperty( "modelEncoding", String.class ) - { - @Override - public String get( Model model ) - { - return model.getModelEncoding(); - } - - @Override - public void set( Model model, String value ) - { - model.setModelEncoding( value ); - } - }; - - /** @see Model#getModelVersion() */ - public static final PomProperty MODEL_VERSION = new PomProperty( "modelVersion", String.class ) - { - @Override - public String get( Model model ) - { - return model.getModelVersion(); - } - - @Override - public void set( Model model, String value ) - { - model.setModelVersion( value ); - } - }; - - /** @see Model#getModules() */ - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public static final PomProperty> MODULES = - new PomProperty>( "modules", (Class) List.class ) - { - @Override - public List get( Model model ) - { - return model.getModules(); - } - - @Override - public void set( Model model, List value ) - { - model.setModules( value ); - } - }; - - /** @see Model#getName() */ - public static final PomProperty NAME = new PomProperty( "name", String.class ) - { - @Override - public String get( Model model ) - { - return model.getName(); - } - - @Override - public void set( Model model, String value ) - { - model.setName( value ); - } - }; - - /** @see Model#getOrganization() */ - public static final PomProperty ORGANIZATION = - new PomProperty( "organization", Organization.class ) - { - @Override - public Organization get( Model model ) - { - return model.getOrganization(); - } - - @Override - public void set( Model model, Organization value ) - { - model.setOrganization( value ); - } - }; - - /** @see Model#getPackaging() */ - public static final PomProperty PACKAGING = new PomProperty( "packaging", String.class ) - { - @Override - public String get( Model model ) - { - return model.getPackaging(); - } - - @Override - public void set( Model model, String value ) - { - model.setPackaging( value ); - } - }; - - /** @see Model#getParent() */ - public static final PomProperty PARENT = new PomProperty( "parent", Parent.class ) - { - @Override - public Parent get( Model model ) - { - return model.getParent(); - } - - @Override - public void set( Model model, Parent value ) - { - model.setParent( value ); - } - }; - - /** @see Build#getPluginManagement() */ - public static final PomProperty PLUGIN_MANAGEMENT = - new PomProperty( "pluginManagement", PluginManagement.class ) - { - @Override - public PluginManagement get( Model model ) - { - if ( model.getBuild() == null ) - { - return null; - } - return model.getBuild().getPluginManagement(); - } - - @Override - public void set( Model model, PluginManagement value ) - { - if ( model.getBuild() == null ) - { - model.setBuild( new Build() ); - } - model.getBuild().setPluginManagement( value ); - } - }; - - /** @see Model#getPluginRepositories() */ - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public static final PomProperty> PLUGIN_REPOSITORIES = - new PomProperty>( "pluginRepositories", (Class) List.class ) - { - @Override - public List get( Model model ) - { - return model.getPluginRepositories(); - } - - @Override - public void set( Model model, List value ) - { - model.setPluginRepositories( value ); - } - }; - - /** @see Model#getPomFile() */ - public static final PomProperty POM_FILE = new PomProperty( "pomFile", File.class ) - { - @Override - public File get( Model model ) - { - return model.getPomFile(); - } - - @Override - public void set( Model model, File value ) - { - model.setPomFile( value ); - } - }; - - /** @see Model#getPrerequisites() */ - public static final PomProperty PREREQUISITES = - new PomProperty( "prerequisites", Prerequisites.class ) - { - @Override - public Prerequisites get( Model model ) - { - return model.getPrerequisites(); - } - - @Override - public void set( Model model, Prerequisites value ) - { - model.setPrerequisites( value ); - } - }; - - /** @see Model#getProfiles() */ - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public static final PomProperty> PROFILES = - new PomProperty>( "profiles", (Class) List.class ) - { - @Override - public List get( Model model ) - { - return model.getProfiles(); - } - - @Override - public void set( Model model, List value ) - { - model.setProfiles( value ); - } - }; - - /** @see Model#getProperties() */ - public static final PomProperty PROPERTIES = - new PomProperty( "properties", Properties.class ) - { - @Override - public Properties get( Model model ) - { - return model.getProperties(); - } - - @Override - public void set( Model model, Properties value ) - { - model.setProperties( value ); - } - }; - - /** @see Model#getReporting() */ - public static final PomProperty REPORTING = new PomProperty( "reporting", Reporting.class ) - { - @Override - public Reporting get( Model model ) - { - return model.getReporting(); - } - - @Override - public void set( Model model, Reporting value ) - { - model.setReporting( value ); - } - }; - - /** @see Model#getPluginRepositories() */ - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public static final PomProperty> REPOSITORIES = - new PomProperty>( "repositories", (Class) List.class ) - { - @Override - public List get( Model model ) - { - return model.getRepositories(); - } - - @Override - public void set( Model model, List value ) - { - model.setRepositories( value ); - } - }; - - /** @see Model#getScm() */ - public static final PomProperty SCM = new PomProperty( "scm", Scm.class ) - { - @Override - public Scm get( Model model ) - { - return model.getScm(); - } - - @Override - public void set( Model model, Scm value ) - { - model.setScm( value ); - } - }; - - /** @see Model#getUrl() */ - public static final PomProperty URL = new PomProperty( "url", String.class ) - { - @Override - public String get( Model model ) - { - return model.getUrl(); - } - - @Override - public void set( Model model, String value ) - { - model.setUrl( value ); - } - }; - - /** @see Model#getVersion() */ - public static final PomProperty VERSION = new PomProperty( "version", String.class ) - { - @Override - public String get( Model model ) - { - return model.getVersion(); - } - - @Override - public void set( Model model, String value ) - { - model.setVersion( value ); - } - }; - - private static final PomProperty[] POM_PROPERTIES_ARRAY = new PomProperty[] { ARTIFACT_ID, BUILD, - CI_MANAGEMENT, CONTRIBUTORS, DEPENDENCIES, DEPENDENCY_MANAGEMENT, DESCRIPTION, DEVELOPERS, - DISTRIBUTION_MANAGEMENT, GROUP_ID, INCEPTION_YEAR, ISSUE_MANAGEMENT, LICENSES, MAILING_LISTS, MODEL_ENCODING, - MODEL_VERSION, MODULES, NAME, ORGANIZATION, PACKAGING, PARENT, PLUGIN_MANAGEMENT, PLUGIN_REPOSITORIES, POM_FILE, - PREREQUISITES, PROFILES, PROPERTIES, REPORTING, REPOSITORIES, SCM, URL, VERSION }; - - private static final List> POM_PROPERTIES = - Collections.unmodifiableList( Arrays.asList( POM_PROPERTIES_ARRAY ) ); - - private final String name; - - private final Class valueType; - - /** - * The constructor. - * - * @param name - see {@link #getName()}. - * @param valueType - see {@link #getValueType()}. - */ - public PomProperty( String name, Class valueType ) - { - super(); - this.name = name; - this.valueType = valueType; - } - - /** - * @return name - */ - public String getName() - { - return this.name; - } - - /** - * @return {@link Class} reflecting the type of the {@link #get(Model) property value}. - */ - public Class getValueType() - { - return this.valueType; - } - - /** - * @return true if required for flattened POM, false otherwise. - */ - public boolean isRequired() - { - return this == GROUP_ID || this == ARTIFACT_ID || this == VERSION; - } - - /** - * @return true if this property represents an XML element of the POM representation, - * false otherwise (if an internal property such as {@link Model#getPomFile()}). - */ - public boolean isElement() - { - - if ( this == POM_FILE ) - { - return false; - } - return this != MODEL_ENCODING; - } - - /** - * Generic getter for reading a {@link PomProperty} from a {@link Model}. - * - * @param model is the {@link Model} to read from. - * @return the value of the property to read identified by this {@link PomProperty}. - */ - public abstract V get( Model model ); - - /** - * Generic setter for writing a {@link PomProperty} in a {@link Model}. - * - * @param model is the {@link Model} to write to. - * @param value is the value of the property to write identified by this {@link PomProperty}. - */ - public abstract void set( Model model, V value ); - - /** - * Copies the value identified by this {@link PomProperty} from the given source {@link Model} to the - * given target {@link Model}. - * - * @param source is the {@link Model} to copy from (read). - * @param target is the {@link Model} to copy to (write). - */ - public void copy( Model source, Model target ) - { - - V value = get( source ); - if ( value != null ) - { - set( target, value ); - } - } - - /** - * @return an {@link Collections#unmodifiableList(List) unmodifiable} {@link List} with all {@link PomProperty - * properties}. - */ - public static List> getPomProperties() - { - return POM_PROPERTIES; - } - -} +package org.codehaus.mojo.flatten; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + +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.Parent; +import org.apache.maven.model.PluginManagement; +import org.apache.maven.model.Prerequisites; +import org.apache.maven.model.Profile; +import org.apache.maven.model.Reporting; +import org.apache.maven.model.Repository; +import org.apache.maven.model.Scm; + +/** + * This class reflects a property of a {@link Model POM}. It contains {@link #getPomProperties() all available + * properties} as constants and allows generic access to {@link #get(Model) read} and {@link #set(Model, Object) write} + * the property via a {@link Model}. + * + * @param is the generic type of the {@link #get(Model) property value}. + * @author Joerg Hohwiller (hohwille at users.sourceforge.net) + * @since 1.0.0-beta-4 + */ +public abstract class PomProperty { + + /** @see Model#getArtifactId() */ + public static final PomProperty ARTIFACT_ID = new PomProperty("artifactId", String.class) { + @Override + public String get(Model model) { + return model.getArtifactId(); + } + + @Override + public void set(Model model, String value) { + model.setArtifactId(value); + } + }; + + /** @see Model#getBuild() */ + public static final PomProperty BUILD = new PomProperty("build", Build.class) { + @Override + public Build get(Model model) { + return model.getBuild(); + } + + @Override + public void set(Model model, Build value) { + model.setBuild(value); + } + }; + + /** @see Model#getCiManagement() */ + public static final PomProperty CI_MANAGEMENT = + new PomProperty("ciManagement", CiManagement.class) { + @Override + public CiManagement get(Model model) { + return model.getCiManagement(); + } + + @Override + public void set(Model model, CiManagement value) { + model.setCiManagement(value); + } + }; + + /** @see Model#getContributors() */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public static final PomProperty> CONTRIBUTORS = + new PomProperty>("contributors", (Class) List.class) { + @Override + public List get(Model model) { + return model.getContributors(); + } + + @Override + public void set(Model model, List value) { + model.setContributors(value); + } + }; + + /** @see Model#getDependencies() */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public static final PomProperty> DEPENDENCIES = + new PomProperty>("dependencies", (Class) List.class) { + @Override + public List get(Model model) { + return model.getDependencies(); + } + + @Override + public void set(Model model, List value) { + model.setDependencies(value); + } + }; + + /** @see Model#getDependencyManagement() */ + public static final PomProperty DEPENDENCY_MANAGEMENT = + new PomProperty("dependencyManagement", DependencyManagement.class) { + @Override + public DependencyManagement get(Model model) { + return model.getDependencyManagement(); + } + + @Override + public void set(Model model, DependencyManagement value) { + model.setDependencyManagement(value); + } + }; + + /** @see Model#getDescription() */ + public static final PomProperty DESCRIPTION = new PomProperty("description", String.class) { + @Override + public String get(Model model) { + return model.getDescription(); + } + + @Override + public void set(Model model, String value) { + model.setDescription(value); + } + }; + + /** @see Model#getDevelopers() */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public static final PomProperty> DEVELOPERS = + new PomProperty>("developers", (Class) List.class) { + @Override + public List get(Model model) { + return model.getDevelopers(); + } + + @Override + public void set(Model model, List value) { + model.setDevelopers(value); + } + }; + + /** @see Model#getDistributionManagement() */ + public static final PomProperty DISTRIBUTION_MANAGEMENT = + new PomProperty("distributionManagement", DistributionManagement.class) { + @Override + public DistributionManagement get(Model model) { + return model.getDistributionManagement(); + } + + @Override + public void set(Model model, DistributionManagement value) { + model.setDistributionManagement(value); + } + }; + + /** @see Model#getGroupId() */ + public static final PomProperty GROUP_ID = new PomProperty("groupId", String.class) { + @Override + public String get(Model model) { + return model.getGroupId(); + } + + @Override + public void set(Model model, String value) { + model.setGroupId(value); + } + }; + + /** @see Model#getInceptionYear() */ + public static final PomProperty INCEPTION_YEAR = new PomProperty("inceptionYear", String.class) { + @Override + public String get(Model model) { + return model.getInceptionYear(); + } + + @Override + public void set(Model model, String value) { + model.setInceptionYear(value); + } + }; + + /** @see Model#getIssueManagement() */ + public static final PomProperty ISSUE_MANAGEMENT = + new PomProperty("issueManagement", IssueManagement.class) { + @Override + public IssueManagement get(Model model) { + return model.getIssueManagement(); + } + + @Override + public void set(Model model, IssueManagement value) { + model.setIssueManagement(value); + } + }; + + /** @see Model#getLicenses() */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public static final PomProperty> LICENSES = + new PomProperty>("licenses", (Class) List.class) { + @Override + public List get(Model model) { + return model.getLicenses(); + } + + @Override + public void set(Model model, List value) { + model.setLicenses(value); + } + }; + + /** @see Model#getMailingLists() */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public static final PomProperty> MAILING_LISTS = + new PomProperty>("mailingLists", (Class) List.class) { + @Override + public List get(Model model) { + return model.getMailingLists(); + } + + @Override + public void set(Model model, List value) { + model.setMailingLists(value); + } + }; + + /** @see Model#getModelEncoding() */ + public static final PomProperty MODEL_ENCODING = new PomProperty("modelEncoding", String.class) { + @Override + public String get(Model model) { + return model.getModelEncoding(); + } + + @Override + public void set(Model model, String value) { + model.setModelEncoding(value); + } + }; + + /** @see Model#getModelVersion() */ + public static final PomProperty MODEL_VERSION = new PomProperty("modelVersion", String.class) { + @Override + public String get(Model model) { + return model.getModelVersion(); + } + + @Override + public void set(Model model, String value) { + model.setModelVersion(value); + } + }; + + /** @see Model#getModules() */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public static final PomProperty> MODULES = + new PomProperty>("modules", (Class) List.class) { + @Override + public List get(Model model) { + return model.getModules(); + } + + @Override + public void set(Model model, List value) { + model.setModules(value); + } + }; + + /** @see Model#getName() */ + public static final PomProperty NAME = new PomProperty("name", String.class) { + @Override + public String get(Model model) { + return model.getName(); + } + + @Override + public void set(Model model, String value) { + model.setName(value); + } + }; + + /** @see Model#getOrganization() */ + public static final PomProperty ORGANIZATION = + new PomProperty("organization", Organization.class) { + @Override + public Organization get(Model model) { + return model.getOrganization(); + } + + @Override + public void set(Model model, Organization value) { + model.setOrganization(value); + } + }; + + /** @see Model#getPackaging() */ + public static final PomProperty PACKAGING = new PomProperty("packaging", String.class) { + @Override + public String get(Model model) { + return model.getPackaging(); + } + + @Override + public void set(Model model, String value) { + model.setPackaging(value); + } + }; + + /** @see Model#getParent() */ + public static final PomProperty PARENT = new PomProperty("parent", Parent.class) { + @Override + public Parent get(Model model) { + return model.getParent(); + } + + @Override + public void set(Model model, Parent value) { + model.setParent(value); + } + }; + + /** @see Build#getPluginManagement() */ + public static final PomProperty PLUGIN_MANAGEMENT = + new PomProperty("pluginManagement", PluginManagement.class) { + @Override + public PluginManagement get(Model model) { + if (model.getBuild() == null) { + return null; + } + return model.getBuild().getPluginManagement(); + } + + @Override + public void set(Model model, PluginManagement value) { + if (model.getBuild() == null) { + model.setBuild(new Build()); + } + model.getBuild().setPluginManagement(value); + } + }; + + /** @see Model#getPluginRepositories() */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public static final PomProperty> PLUGIN_REPOSITORIES = + new PomProperty>("pluginRepositories", (Class) List.class) { + @Override + public List get(Model model) { + return model.getPluginRepositories(); + } + + @Override + public void set(Model model, List value) { + model.setPluginRepositories(value); + } + }; + + /** @see Model#getPomFile() */ + public static final PomProperty POM_FILE = new PomProperty("pomFile", File.class) { + @Override + public File get(Model model) { + return model.getPomFile(); + } + + @Override + public void set(Model model, File value) { + model.setPomFile(value); + } + }; + + /** @see Model#getPrerequisites() */ + public static final PomProperty PREREQUISITES = + new PomProperty("prerequisites", Prerequisites.class) { + @Override + public Prerequisites get(Model model) { + return model.getPrerequisites(); + } + + @Override + public void set(Model model, Prerequisites value) { + model.setPrerequisites(value); + } + }; + + /** @see Model#getProfiles() */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public static final PomProperty> PROFILES = + new PomProperty>("profiles", (Class) List.class) { + @Override + public List get(Model model) { + return model.getProfiles(); + } + + @Override + public void set(Model model, List value) { + model.setProfiles(value); + } + }; + + /** @see Model#getProperties() */ + public static final PomProperty PROPERTIES = + new PomProperty("properties", Properties.class) { + @Override + public Properties get(Model model) { + return model.getProperties(); + } + + @Override + public void set(Model model, Properties value) { + model.setProperties(value); + } + }; + + /** @see Model#getReporting() */ + public static final PomProperty REPORTING = new PomProperty("reporting", Reporting.class) { + @Override + public Reporting get(Model model) { + return model.getReporting(); + } + + @Override + public void set(Model model, Reporting value) { + model.setReporting(value); + } + }; + + /** @see Model#getPluginRepositories() */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public static final PomProperty> REPOSITORIES = + new PomProperty>("repositories", (Class) List.class) { + @Override + public List get(Model model) { + return model.getRepositories(); + } + + @Override + public void set(Model model, List value) { + model.setRepositories(value); + } + }; + + /** @see Model#getScm() */ + public static final PomProperty SCM = new PomProperty("scm", Scm.class) { + @Override + public Scm get(Model model) { + return model.getScm(); + } + + @Override + public void set(Model model, Scm value) { + model.setScm(value); + } + }; + + /** @see Model#getUrl() */ + public static final PomProperty URL = new PomProperty("url", String.class) { + @Override + public String get(Model model) { + return model.getUrl(); + } + + @Override + public void set(Model model, String value) { + model.setUrl(value); + } + }; + + /** @see Model#getVersion() */ + public static final PomProperty VERSION = new PomProperty("version", String.class) { + @Override + public String get(Model model) { + return model.getVersion(); + } + + @Override + public void set(Model model, String value) { + model.setVersion(value); + } + }; + + private static final PomProperty[] POM_PROPERTIES_ARRAY = new PomProperty[] { + ARTIFACT_ID, + BUILD, + CI_MANAGEMENT, + CONTRIBUTORS, + DEPENDENCIES, + DEPENDENCY_MANAGEMENT, + DESCRIPTION, + DEVELOPERS, + DISTRIBUTION_MANAGEMENT, + GROUP_ID, + INCEPTION_YEAR, + ISSUE_MANAGEMENT, + LICENSES, + MAILING_LISTS, + MODEL_ENCODING, + MODEL_VERSION, + MODULES, + NAME, + ORGANIZATION, + PACKAGING, + PARENT, + PLUGIN_MANAGEMENT, + PLUGIN_REPOSITORIES, + POM_FILE, + PREREQUISITES, + PROFILES, + PROPERTIES, + REPORTING, + REPOSITORIES, + SCM, + URL, + VERSION + }; + + private static final List> POM_PROPERTIES = + Collections.unmodifiableList(Arrays.asList(POM_PROPERTIES_ARRAY)); + + private final String name; + + private final Class valueType; + + /** + * The constructor. + * + * @param name - see {@link #getName()}. + * @param valueType - see {@link #getValueType()}. + */ + public PomProperty(String name, Class valueType) { + super(); + this.name = name; + this.valueType = valueType; + } + + /** + * @return name + */ + public String getName() { + return this.name; + } + + /** + * @return {@link Class} reflecting the type of the {@link #get(Model) property value}. + */ + public Class getValueType() { + return this.valueType; + } + + /** + * @return true if required for flattened POM, false otherwise. + */ + public boolean isRequired() { + return this == GROUP_ID || this == ARTIFACT_ID || this == VERSION; + } + + /** + * @return true if this property represents an XML element of the POM representation, + * false otherwise (if an internal property such as {@link Model#getPomFile()}). + */ + public boolean isElement() { + + if (this == POM_FILE) { + return false; + } + return this != MODEL_ENCODING; + } + + /** + * Generic getter for reading a {@link PomProperty} from a {@link Model}. + * + * @param model is the {@link Model} to read from. + * @return the value of the property to read identified by this {@link PomProperty}. + */ + public abstract V get(Model model); + + /** + * Generic setter for writing a {@link PomProperty} in a {@link Model}. + * + * @param model is the {@link Model} to write to. + * @param value is the value of the property to write identified by this {@link PomProperty}. + */ + public abstract void set(Model model, V value); + + /** + * Copies the value identified by this {@link PomProperty} from the given source {@link Model} to the + * given target {@link Model}. + * + * @param source is the {@link Model} to copy from (read). + * @param target is the {@link Model} to copy to (write). + */ + public void copy(Model source, Model target) { + + V value = get(source); + if (value != null) { + set(target, value); + } + } + + /** + * @return an {@link Collections#unmodifiableList(List) unmodifiable} {@link List} with all {@link PomProperty + * properties}. + */ + public static List> getPomProperties() { + return POM_PROPERTIES; + } +} diff --git a/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolator.java b/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolator.java index 7ec0b5b7..dd8d13ba 100644 --- a/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolator.java +++ b/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolator.java @@ -26,25 +26,22 @@ import org.apache.maven.model.building.ModelProblemCollector; /** -* A shameless replacement of ModelInterpolator from maven-model-builder. -* Made because of class loading issues that ensued when using ModelInterpolator interface. -*/ -public interface CiInterpolator -{ - - /** - * Interpolates expressions in the specified model. Note that implementations are free to either interpolate the - * provided model directly or to create a clone of the model and interpolate the clone. Callers should always use - * the returned model and must not rely on the input model being updated. - * - * @param model The model to interpolate, must not be {@code null}. - * @param projectDir The project directory, may be {@code null} if the model does not belong to a local project but - * to some artifact's metadata. - * @param request The model building request that holds further settings, must not be {@code null}. - * @param problems The container used to collect problems that were encountered, must not be {@code null}. - * @return The interpolated model, never {@code null}. - */ - Model interpolateModel( Model model, File projectDir, ModelBuildingRequest request, - ModelProblemCollector problems ); + * A shameless replacement of ModelInterpolator from maven-model-builder. + * Made because of class loading issues that ensued when using ModelInterpolator interface. + */ +public interface CiInterpolator { + /** + * Interpolates expressions in the specified model. Note that implementations are free to either interpolate the + * provided model directly or to create a clone of the model and interpolate the clone. Callers should always use + * the returned model and must not rely on the input model being updated. + * + * @param model The model to interpolate, must not be {@code null}. + * @param projectDir The project directory, may be {@code null} if the model does not belong to a local project but + * to some artifact's metadata. + * @param request The model building request that holds further settings, must not be {@code null}. + * @param problems The container used to collect problems that were encountered, must not be {@code null}. + * @return The interpolated model, never {@code null}. + */ + Model interpolateModel(Model model, File projectDir, ModelBuildingRequest request, ModelProblemCollector problems); } diff --git a/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolatorImpl.java b/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolatorImpl.java index 098dd136..c943de07 100644 --- a/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolatorImpl.java +++ b/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolatorImpl.java @@ -39,8 +39,7 @@ * see {@link org.codehaus.plexus.interpolation.StringSearchInterpolator}. * This interpolates only the Maven CI Friendly variables revision, sha1 and changelist. */ -public class CiInterpolatorImpl implements Interpolator -{ +public class CiInterpolatorImpl implements Interpolator { private final Map existingAnswers = new HashMap(); @@ -58,74 +57,62 @@ public class CiInterpolatorImpl implements Interpolator private final String endExpr; - public CiInterpolatorImpl() - { + public CiInterpolatorImpl() { this.startExpr = DEFAULT_START_EXPR; this.endExpr = DEFAULT_END_EXPR; } - public CiInterpolatorImpl( String startExpr, String endExpr ) - { + public CiInterpolatorImpl(String startExpr, String endExpr) { this.startExpr = startExpr; this.endExpr = endExpr; } - /** * {@inheritDoc} */ @Override - public void addValueSource( ValueSource valueSource ) - { - valueSources.add( valueSource ); + public void addValueSource(ValueSource valueSource) { + valueSources.add(valueSource); } /** * {@inheritDoc} */ @Override - public void removeValuesSource( ValueSource valueSource ) - { - valueSources.remove( valueSource ); + public void removeValuesSource(ValueSource valueSource) { + valueSources.remove(valueSource); } /** * {@inheritDoc} */ @Override - public void addPostProcessor( InterpolationPostProcessor postProcessor ) - { - postProcessors.add( postProcessor ); + public void addPostProcessor(InterpolationPostProcessor postProcessor) { + postProcessors.add(postProcessor); } /** * {@inheritDoc} */ @Override - public void removePostProcessor( InterpolationPostProcessor postProcessor ) - { - postProcessors.remove( postProcessor ); + public void removePostProcessor(InterpolationPostProcessor postProcessor) { + postProcessors.remove(postProcessor); } @Override - public String interpolate( String input, String thisPrefixPattern ) - throws InterpolationException - { - return interpolate( input, new SimpleRecursionInterceptor() ); + public String interpolate(String input, String thisPrefixPattern) throws InterpolationException { + return interpolate(input, new SimpleRecursionInterceptor()); } @Override - public String interpolate( String input, String thisPrefixPattern, RecursionInterceptor recursionInterceptor ) - throws InterpolationException - { - return interpolate( input, recursionInterceptor ); + public String interpolate(String input, String thisPrefixPattern, RecursionInterceptor recursionInterceptor) + throws InterpolationException { + return interpolate(input, recursionInterceptor); } @Override - public String interpolate( String input ) - throws InterpolationException - { - return interpolate( input, new SimpleRecursionInterceptor() ); + public String interpolate(String input) throws InterpolationException { + return interpolate(input, new SimpleRecursionInterceptor()); } /** @@ -133,82 +120,64 @@ public String interpolate( String input ) * nested expressions. */ @Override - public String interpolate( String input, RecursionInterceptor recursionInterceptor ) - throws InterpolationException - { - try - { - return interpolate( input, recursionInterceptor, new HashSet<>() ); - } - finally - { - if ( !cacheAnswers ) - { + public String interpolate(String input, RecursionInterceptor recursionInterceptor) throws InterpolationException { + try { + return interpolate(input, recursionInterceptor, new HashSet<>()); + } finally { + if (!cacheAnswers) { existingAnswers.clear(); } } } - private String interpolate( String input, RecursionInterceptor recursionInterceptor, Set unresolvable ) - throws InterpolationException - { - if ( input == null ) - { + private String interpolate(String input, RecursionInterceptor recursionInterceptor, Set unresolvable) + throws InterpolationException { + if (input == null) { // return empty String to prevent NPE too return ""; } - StringBuilder result = new StringBuilder( input.length() * 2 ); + StringBuilder result = new StringBuilder(input.length() * 2); int startIdx; int endIdx = -1; - while ( ( startIdx = input.indexOf( startExpr, endIdx + 1 ) ) > -1 ) - { - result.append( input, endIdx + 1, startIdx ); + while ((startIdx = input.indexOf(startExpr, endIdx + 1)) > -1) { + result.append(input, endIdx + 1, startIdx); - endIdx = input.indexOf( endExpr, startIdx + 1 ); - if ( endIdx < 0 ) - { + endIdx = input.indexOf(endExpr, startIdx + 1); + if (endIdx < 0) { break; } - final String wholeExpr = input.substring( startIdx, endIdx + endExpr.length() ); - String realExpr = wholeExpr.substring( startExpr.length(), wholeExpr.length() - endExpr.length() ); + final String wholeExpr = input.substring(startIdx, endIdx + endExpr.length()); + String realExpr = wholeExpr.substring(startExpr.length(), wholeExpr.length() - endExpr.length()); boolean resolved = false; - if ( !unresolvable.contains( wholeExpr ) ) - { - if ( realExpr.startsWith( "." ) ) - { - realExpr = realExpr.substring( 1 ); + if (!unresolvable.contains(wholeExpr)) { + if (realExpr.startsWith(".")) { + realExpr = realExpr.substring(1); } - if ( recursionInterceptor.hasRecursiveExpression( realExpr ) ) - { - throw new InterpolationCycleException( recursionInterceptor, realExpr, wholeExpr ); + if (recursionInterceptor.hasRecursiveExpression(realExpr)) { + throw new InterpolationCycleException(recursionInterceptor, realExpr, wholeExpr); } - recursionInterceptor.expressionResolutionStarted( realExpr ); - try - { - Object value = existingAnswers.get( realExpr ); - if ( !wholeExpr.equals( "${revision}" ) - && !wholeExpr.contains( "${sha1}" ) - && !wholeExpr.contains( "${changelist}" ) ) - { + recursionInterceptor.expressionResolutionStarted(realExpr); + try { + Object value = existingAnswers.get(realExpr); + if (!wholeExpr.equals("${revision}") + && !wholeExpr.contains("${sha1}") + && !wholeExpr.contains("${changelist}")) { value = realExpr; } Object bestAnswer = null; - for ( ValueSource valueSource : valueSources ) - { - if ( value != null ) - { + for (ValueSource valueSource : valueSources) { + if (value != null) { break; } - value = valueSource.getValue( realExpr ); + value = valueSource.getValue(realExpr); - if ( value != null && value.toString().contains( wholeExpr ) ) - { + if (value != null && value.toString().contains(wholeExpr)) { bestAnswer = value; value = null; } @@ -217,22 +186,17 @@ private String interpolate( String input, RecursionInterceptor recursionIntercep // this is the simplest recursion check to catch exact recursion // (non synonym), and avoid the extra effort of more string // searching. - if ( value == null && bestAnswer != null ) - { - throw new InterpolationCycleException( recursionInterceptor, realExpr, wholeExpr ); + if (value == null && bestAnswer != null) { + throw new InterpolationCycleException(recursionInterceptor, realExpr, wholeExpr); } - if ( value != null ) - { - value = interpolate( String.valueOf( value ), recursionInterceptor, unresolvable ); - - if ( !postProcessors.isEmpty() ) - { - for ( InterpolationPostProcessor postProcessor : postProcessors ) - { - Object newVal = postProcessor.execute( realExpr, value ); - if ( newVal != null ) - { + if (value != null) { + value = interpolate(String.valueOf(value), recursionInterceptor, unresolvable); + + if (!postProcessors.isEmpty()) { + for (InterpolationPostProcessor postProcessor : postProcessors) { + Object newVal = postProcessor.execute(realExpr, value); + if (newVal != null) { value = newVal; break; } @@ -243,35 +207,27 @@ private String interpolate( String input, RecursionInterceptor recursionIntercep // result = matcher.replaceFirst( stringValue ); // but this could result in multiple lookups of stringValue, and replaceAll is not correct // behaviour - result.append( value ); + result.append(value); resolved = true; + } else { + unresolvable.add(wholeExpr); } - else - { - unresolvable.add( wholeExpr ); - } - } - finally - { - recursionInterceptor.expressionResolutionFinished( realExpr ); + } finally { + recursionInterceptor.expressionResolutionFinished(realExpr); } } - if ( !resolved ) - { - result.append( wholeExpr ); + if (!resolved) { + result.append(wholeExpr); } endIdx += endExpr.length() - 1; } - if ( endIdx == -1 && startIdx > -1 ) - { - result.append( input, startIdx, input.length() ); - } - else if ( endIdx < input.length() ) - { - result.append( input, endIdx + 1, input.length() ); + if (endIdx == -1 && startIdx > -1) { + result.append(input, startIdx, input.length()); + } else if (endIdx < input.length()) { + result.append(input, endIdx + 1, input.length()); } return result.toString(); @@ -287,15 +243,12 @@ else if ( endIdx < input.length() ) * {@link Throwable} instances. */ @Override - public List getFeedback() - { + public List getFeedback() { List messages = new ArrayList(); - for ( ValueSource vs : valueSources ) - { + for (ValueSource vs : valueSources) { List feedback = vs.getFeedback(); - if ( feedback != null && !feedback.isEmpty() ) - { - messages.addAll( feedback ); + if (feedback != null && !feedback.isEmpty()) { + messages.addAll(feedback); } } @@ -306,31 +259,24 @@ public List getFeedback() * Clear the feedback messages from previous interpolate(..) calls. */ @Override - public void clearFeedback() - { - for ( ValueSource vs : valueSources ) - { + public void clearFeedback() { + for (ValueSource vs : valueSources) { vs.clearFeedback(); } } @Override - public boolean isCacheAnswers() - { + public boolean isCacheAnswers() { return cacheAnswers; } @Override - public void setCacheAnswers( boolean cacheAnswers ) - { + public void setCacheAnswers(boolean cacheAnswers) { this.cacheAnswers = cacheAnswers; } @Override - public void clearAnswers() - { + public void clearAnswers() { existingAnswers.clear(); } - } - diff --git a/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiModelInterpolator.java b/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiModelInterpolator.java index f8e13425..51086420 100644 --- a/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiModelInterpolator.java +++ b/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiModelInterpolator.java @@ -63,19 +63,17 @@ * * IMPORTANT: this is a legacy Plexus component, with manually authored descriptor in src/main/resources! */ -public class CiModelInterpolator implements CiInterpolator, ModelInterpolator -{ +public class CiModelInterpolator implements CiInterpolator, ModelInterpolator { - private static final List PROJECT_PREFIXES = Arrays.asList( "pom.", "project." ); + private static final List PROJECT_PREFIXES = Arrays.asList("pom.", "project."); private static final Collection TRANSLATED_PATH_EXPRESSIONS; - private static final Map, InterpolateObjectAction.CacheItem> CACHED_ENTRIES = new ConcurrentHashMap<>( - 80, 0.75f, 2 ); + private static final Map, InterpolateObjectAction.CacheItem> CACHED_ENTRIES = + new ConcurrentHashMap<>(80, 0.75f, 2); // Empirical data from 3.x, actual =40 - static - { + static { Collection translatedPrefixes = new HashSet<>(); // MNG-1927, MNG-2124, MNG-3355: @@ -85,13 +83,13 @@ public class CiModelInterpolator implements CiInterpolator, ModelInterpolator // Afterward, we'll double back and translate any paths that weren't // covered during interpolation via the // code below... - translatedPrefixes.add( "build.directory" ); - translatedPrefixes.add( "build.outputDirectory" ); - translatedPrefixes.add( "build.testOutputDirectory" ); - translatedPrefixes.add( "build.sourceDirectory" ); - translatedPrefixes.add( "build.testSourceDirectory" ); - translatedPrefixes.add( "build.scriptSourceDirectory" ); - translatedPrefixes.add( "reporting.outputDirectory" ); + translatedPrefixes.add("build.directory"); + translatedPrefixes.add("build.outputDirectory"); + translatedPrefixes.add("build.testOutputDirectory"); + translatedPrefixes.add("build.sourceDirectory"); + translatedPrefixes.add("build.testSourceDirectory"); + translatedPrefixes.add("build.scriptSourceDirectory"); + translatedPrefixes.add("reporting.outputDirectory"); TRANSLATED_PATH_EXPRESSIONS = translatedPrefixes; } @@ -105,85 +103,66 @@ public class CiModelInterpolator implements CiInterpolator, ModelInterpolator private UrlNormalizer urlNormalizer; - public CiModelInterpolator() - { + public CiModelInterpolator() { this.interpolator = createInterpolator(); - this.recursionInterceptor = new PrefixAwareRecursionInterceptor( PROJECT_PREFIXES ); + this.recursionInterceptor = new PrefixAwareRecursionInterceptor(PROJECT_PREFIXES); } - public Model interpolateModel( Model model, File projectDir, ModelBuildingRequest config, - ModelProblemCollector problems ) - { - interpolateObject( model, model, projectDir, config, problems ); + public Model interpolateModel( + Model model, File projectDir, ModelBuildingRequest config, ModelProblemCollector problems) { + interpolateObject(model, model, projectDir, config, problems); return model; } - protected void interpolateObject( Object obj, Model model, File projectDir, ModelBuildingRequest config, - ModelProblemCollector problems ) - { - try - { - List valueSources = createValueSources( model, projectDir, config, problems ); - List postProcessors = - createPostProcessors( model, projectDir, config ); + protected void interpolateObject( + Object obj, Model model, File projectDir, ModelBuildingRequest config, ModelProblemCollector problems) { + try { + List valueSources = createValueSources(model, projectDir, config, problems); + List postProcessors = createPostProcessors(model, projectDir, config); - new InterpolateObjectAction( obj, valueSources, postProcessors, this, problems ).run(); - } - finally - { + new InterpolateObjectAction(obj, valueSources, postProcessors, this, problems).run(); + } finally { getInterpolator().clearAnswers(); } } - protected String interpolateInternal( String src, List valueSources, - List postProcessors, - ModelProblemCollector problems ) - { - if ( src != null && !src.contains( "${revision}" ) && !src.contains( "${sha1}" ) && !src.contains( - "${changelist}" ) ) - { + protected String interpolateInternal( + String src, + List valueSources, + List postProcessors, + ModelProblemCollector problems) { + if (src != null && !src.contains("${revision}") && !src.contains("${sha1}") && !src.contains("${changelist}")) { return src; } String result = src; - synchronized ( this ) - { - - for ( ValueSource vs : valueSources ) - { - getInterpolator().addValueSource( vs ); + synchronized (this) { + for (ValueSource vs : valueSources) { + getInterpolator().addValueSource(vs); } - for ( InterpolationPostProcessor postProcessor : postProcessors ) - { - getInterpolator().addPostProcessor( postProcessor ); + for (InterpolationPostProcessor postProcessor : postProcessors) { + getInterpolator().addPostProcessor(postProcessor); } - try - { - try - { - result = getInterpolator().interpolate( result, getRecursionInterceptor() ); - } - catch ( InterpolationException e ) - { - problems.add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE ) - .setMessage( e.getMessage() ).setException( e ) ); + try { + try { + result = getInterpolator().interpolate(result, getRecursionInterceptor()); + } catch (InterpolationException e) { + problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE) + .setMessage(e.getMessage()) + .setException(e)); } getInterpolator().clearFeedback(); - } - finally - { - for ( ValueSource vs : valueSources ) - { - getInterpolator().removeValuesSource( vs ); + } finally { + for (ValueSource vs : valueSources) { + getInterpolator().removeValuesSource(vs); } - for ( InterpolationPostProcessor postProcessor : postProcessors ) - { - getInterpolator().removePostProcessor( postProcessor ); + for (InterpolationPostProcessor postProcessor : postProcessors) { + getInterpolator().removePostProcessor(postProcessor); } } } @@ -191,16 +170,14 @@ protected String interpolateInternal( String src, List va return result; } - protected Interpolator createInterpolator() - { + protected Interpolator createInterpolator() { CiInterpolatorImpl interpolator = new CiInterpolatorImpl(); - interpolator.setCacheAnswers( true ); + interpolator.setCacheAnswers(true); return interpolator; } - private static final class InterpolateObjectAction implements Runnable - { + private static final class InterpolateObjectAction implements Runnable { private final LinkedList interpolationTargets; @@ -212,16 +189,17 @@ private static final class InterpolateObjectAction implements Runnable private final ModelProblemCollector problems; - InterpolateObjectAction( Object target, List valueSources, - List postProcessors, - CiModelInterpolator modelInterpolator, - ModelProblemCollector problems ) - { + InterpolateObjectAction( + Object target, + List valueSources, + List postProcessors, + CiModelInterpolator modelInterpolator, + ModelProblemCollector problems) { this.valueSources = valueSources; this.postProcessors = postProcessors; this.interpolationTargets = new LinkedList<>(); - interpolationTargets.add( target ); + interpolationTargets.add(target); this.modelInterpolator = modelInterpolator; @@ -229,283 +207,210 @@ private static final class InterpolateObjectAction implements Runnable } @Override - public void run() - { - while ( !interpolationTargets.isEmpty() ) - { + public void run() { + while (!interpolationTargets.isEmpty()) { Object obj = interpolationTargets.removeFirst(); - traverseObjectWithParents( obj.getClass(), obj ); + traverseObjectWithParents(obj.getClass(), obj); } } - private String interpolate( String value ) - { - return modelInterpolator.interpolateInternal( value, valueSources, postProcessors, problems ); + private String interpolate(String value) { + return modelInterpolator.interpolateInternal(value, valueSources, postProcessors, problems); } - private void traverseObjectWithParents( Class cls, Object target ) - { - if ( cls == null ) - { + private void traverseObjectWithParents(Class cls, Object target) { + if (cls == null) { return; } - CacheItem cacheEntry = getCacheEntry( cls ); - if ( cacheEntry.isArray() ) - { - evaluateArray( target, this ); - } - else if ( cacheEntry.isQualifiedForInterpolation ) - { - cacheEntry.interpolate( target, this ); + CacheItem cacheEntry = getCacheEntry(cls); + if (cacheEntry.isArray()) { + evaluateArray(target, this); + } else if (cacheEntry.isQualifiedForInterpolation) { + cacheEntry.interpolate(target, this); - traverseObjectWithParents( cls.getSuperclass(), target ); + traverseObjectWithParents(cls.getSuperclass(), target); } } - private CacheItem getCacheEntry( Class cls ) - { - CacheItem cacheItem = CACHED_ENTRIES.get( cls ); - if ( cacheItem == null ) - { - cacheItem = new CacheItem( cls ); - CACHED_ENTRIES.put( cls, cacheItem ); + private CacheItem getCacheEntry(Class cls) { + CacheItem cacheItem = CACHED_ENTRIES.get(cls); + if (cacheItem == null) { + cacheItem = new CacheItem(cls); + CACHED_ENTRIES.put(cls, cacheItem); } return cacheItem; } - private static void evaluateArray( Object target, InterpolateObjectAction ctx ) - { - int len = Array.getLength( target ); - for ( int i = 0; i < len; i++ ) - { - Object value = Array.get( target, i ); - if ( value != null ) - { - if ( String.class == value.getClass() ) - { - String interpolated = ctx.interpolate( (String) value ); - - if ( !interpolated.equals( value ) ) - { - Array.set( target, i, interpolated ); + private static void evaluateArray(Object target, InterpolateObjectAction ctx) { + int len = Array.getLength(target); + for (int i = 0; i < len; i++) { + Object value = Array.get(target, i); + if (value != null) { + if (String.class == value.getClass()) { + String interpolated = ctx.interpolate((String) value); + + if (!interpolated.equals(value)) { + Array.set(target, i, interpolated); } - } - else - { - ctx.interpolationTargets.add( value ); + } else { + ctx.interpolationTargets.add(value); } } } } - private static class CacheItem - { + private static class CacheItem { private final boolean isArray; private final boolean isQualifiedForInterpolation; private final CacheField[] fields; - private boolean isQualifiedForInterpolation( Class cls ) - { - return !cls.getName().startsWith( "java" ); + private boolean isQualifiedForInterpolation(Class cls) { + return !cls.getName().startsWith("java"); } - private boolean isQualifiedForInterpolation( Field field, Class fieldType ) - { - if ( Map.class.equals( fieldType ) && "locations".equals( field.getName() ) ) - { + private boolean isQualifiedForInterpolation(Field field, Class fieldType) { + if (Map.class.equals(fieldType) && "locations".equals(field.getName())) { return false; } // noinspection SimplifiableIfStatement - if ( fieldType.isPrimitive() ) - { + if (fieldType.isPrimitive()) { return false; } - return !"parent".equals( field.getName() ); + return !"parent".equals(field.getName()); } - CacheItem( Class clazz ) - { - this.isQualifiedForInterpolation = isQualifiedForInterpolation( clazz ); + CacheItem(Class clazz) { + this.isQualifiedForInterpolation = isQualifiedForInterpolation(clazz); this.isArray = clazz.isArray(); List fields = new ArrayList<>(); - for ( Field currentField : clazz.getDeclaredFields() ) - { + for (Field currentField : clazz.getDeclaredFields()) { Class type = currentField.getType(); - if ( isQualifiedForInterpolation( currentField, type ) ) - { - if ( String.class == type ) - { - if ( !Modifier.isFinal( currentField.getModifiers() ) ) - { - fields.add( new StringField( currentField ) ); + if (isQualifiedForInterpolation(currentField, type)) { + if (String.class == type) { + if (!Modifier.isFinal(currentField.getModifiers())) { + fields.add(new StringField(currentField)); } - } - else if ( List.class.isAssignableFrom( type ) ) - { - fields.add( new ListField( currentField ) ); - } - else if ( Collection.class.isAssignableFrom( type ) ) - { - throw new RuntimeException( "We dont interpolate into collections, use a list instead" ); - } - else if ( Map.class.isAssignableFrom( type ) ) - { - fields.add( new MapField( currentField ) ); - } - else - { - fields.add( new ObjectField( currentField ) ); + } else if (List.class.isAssignableFrom(type)) { + fields.add(new ListField(currentField)); + } else if (Collection.class.isAssignableFrom(type)) { + throw new RuntimeException("We dont interpolate into collections, use a list instead"); + } else if (Map.class.isAssignableFrom(type)) { + fields.add(new MapField(currentField)); + } else { + fields.add(new ObjectField(currentField)); } } - } - this.fields = fields.toArray( new CacheField[0] ); - + this.fields = fields.toArray(new CacheField[0]); } - public void interpolate( Object target, InterpolateObjectAction interpolateObjectAction ) - { - for ( CacheField field : fields ) - { - field.interpolate( target, interpolateObjectAction ); + public void interpolate(Object target, InterpolateObjectAction interpolateObjectAction) { + for (CacheField field : fields) { + field.interpolate(target, interpolateObjectAction); } } - public boolean isArray() - { + public boolean isArray() { return isArray; } } - abstract static class CacheField - { + abstract static class CacheField { protected final Field field; - CacheField( Field field ) - { + CacheField(Field field) { this.field = field; } - void interpolate( Object target, InterpolateObjectAction interpolateObjectAction ) - { - synchronized ( field ) - { + void interpolate(Object target, InterpolateObjectAction interpolateObjectAction) { + synchronized (field) { boolean isAccessible = field.isAccessible(); - field.setAccessible( true ); - try - { - doInterpolate( target, interpolateObjectAction ); - } - catch ( IllegalArgumentException e ) - { - interpolateObjectAction.problems - .add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE ) - .setMessage( "Failed to interpolate field3: " + field + " on class: " - + field.getType().getName() ) - .setException( e ) ); // todo: Not entirely + field.setAccessible(true); + try { + doInterpolate(target, interpolateObjectAction); + } catch (IllegalArgumentException e) { + interpolateObjectAction.problems.add( + new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE) + .setMessage("Failed to interpolate field3: " + field + " on class: " + + field.getType().getName()) + .setException(e)); // todo: Not entirely // the same message - } - catch ( IllegalAccessException e ) - { - interpolateObjectAction.problems - .add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE ) - .setMessage( "Failed to interpolate field4: " + field + " on class: " - + field.getType().getName() ) - .setException( e ) ); - } - finally - { - field.setAccessible( isAccessible ); + } catch (IllegalAccessException e) { + interpolateObjectAction.problems.add( + new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE) + .setMessage("Failed to interpolate field4: " + field + " on class: " + + field.getType().getName()) + .setException(e)); + } finally { + field.setAccessible(isAccessible); } } - } - abstract void doInterpolate( Object target, InterpolateObjectAction ctx ) throws IllegalAccessException; + abstract void doInterpolate(Object target, InterpolateObjectAction ctx) throws IllegalAccessException; } - static final class StringField extends CacheField - { - StringField( Field field ) - { - super( field ); + static final class StringField extends CacheField { + StringField(Field field) { + super(field); } @Override - void doInterpolate( Object target, InterpolateObjectAction ctx ) throws IllegalAccessException - { - String value = (String) field.get( target ); - if ( value == null ) - { + void doInterpolate(Object target, InterpolateObjectAction ctx) throws IllegalAccessException { + String value = (String) field.get(target); + if (value == null) { return; } - String interpolated = ctx.interpolate( value ); + String interpolated = ctx.interpolate(value); - if ( !interpolated.equals( value ) ) - { - field.set( target, interpolated ); + if (!interpolated.equals(value)) { + field.set(target, interpolated); } } } - static final class ListField extends CacheField - { - ListField( Field field ) - { - super( field ); + static final class ListField extends CacheField { + ListField(Field field) { + super(field); } @Override - void doInterpolate( Object target, InterpolateObjectAction ctx ) throws IllegalAccessException - { - @SuppressWarnings( "unchecked" ) - List c = (List) field.get( target ); - if ( c == null ) - { + void doInterpolate(Object target, InterpolateObjectAction ctx) throws IllegalAccessException { + @SuppressWarnings("unchecked") + List c = (List) field.get(target); + if (c == null) { return; } int size = c.size(); Object value; - for ( int i = 0; i < size; i++ ) - { - - value = c.get( i ); - - if ( value != null ) - { - if ( String.class == value.getClass() ) - { - String interpolated = ctx.interpolate( (String) value ); - - if ( !interpolated.equals( value ) ) - { - try - { - c.set( i, interpolated ); - } - catch ( UnsupportedOperationException e ) - { + for (int i = 0; i < size; i++) { + + value = c.get(i); + + if (value != null) { + if (String.class == value.getClass()) { + String interpolated = ctx.interpolate((String) value); + + if (!interpolated.equals(value)) { + try { + c.set(i, interpolated); + } catch (UnsupportedOperationException e) { return; } } - } - else - { - if ( value.getClass().isArray() ) - { - evaluateArray( value, ctx ); - } - else - { - ctx.interpolationTargets.add( value ); + } else { + if (value.getClass().isArray()) { + evaluateArray(value, ctx); + } else { + ctx.interpolationTargets.add(value); } } } @@ -513,212 +418,175 @@ void doInterpolate( Object target, InterpolateObjectAction ctx ) throws IllegalA } } - static final class MapField extends CacheField - { - MapField( Field field ) - { - super( field ); + static final class MapField extends CacheField { + MapField(Field field) { + super(field); } @Override - void doInterpolate( Object target, InterpolateObjectAction ctx ) throws IllegalAccessException - { - @SuppressWarnings( "unchecked" ) - Map m = (Map) field.get( target ); - if ( m == null || m.isEmpty() ) - { + void doInterpolate(Object target, InterpolateObjectAction ctx) throws IllegalAccessException { + @SuppressWarnings("unchecked") + Map m = (Map) field.get(target); + if (m == null || m.isEmpty()) { return; } - for ( Map.Entry entry : m.entrySet() ) - { + for (Map.Entry entry : m.entrySet()) { Object value = entry.getValue(); - if ( value == null ) - { + if (value == null) { continue; } - if ( String.class == value.getClass() ) - { - String interpolated = ctx.interpolate( (String) value ); + if (String.class == value.getClass()) { + String interpolated = ctx.interpolate((String) value); - if ( !interpolated.equals( value ) ) - { - try - { - entry.setValue( interpolated ); - } - catch ( UnsupportedOperationException ignore ) - { + if (!interpolated.equals(value)) { + try { + entry.setValue(interpolated); + } catch (UnsupportedOperationException ignore) { // nop } } - } - else if ( value.getClass().isArray() ) - { - evaluateArray( value, ctx ); - } - else - { - ctx.interpolationTargets.add( value ); + } else if (value.getClass().isArray()) { + evaluateArray(value, ctx); + } else { + ctx.interpolationTargets.add(value); } } } } - static final class ObjectField extends CacheField - { + static final class ObjectField extends CacheField { private final boolean isArray; - ObjectField( Field field ) - { - super( field ); + ObjectField(Field field) { + super(field); this.isArray = field.getType().isArray(); } @Override - void doInterpolate( Object target, InterpolateObjectAction ctx ) throws IllegalAccessException - { - Object value = field.get( target ); - if ( value != null ) - { - if ( isArray ) - { - evaluateArray( value, ctx ); - } - else - { - ctx.interpolationTargets.add( value ); + void doInterpolate(Object target, InterpolateObjectAction ctx) throws IllegalAccessException { + Object value = field.get(target); + if (value != null) { + if (isArray) { + evaluateArray(value, ctx); + } else { + ctx.interpolationTargets.add(value); } } } } - } - protected List createValueSources( final Model model, final File projectDir, - final ModelBuildingRequest config, - final ModelProblemCollector problems ) - { + protected List createValueSources( + final Model model, + final File projectDir, + final ModelBuildingRequest config, + final ModelProblemCollector problems) { Properties modelProperties = model.getProperties(); - ValueSource modelValueSource1 = new PrefixedObjectValueSource( PROJECT_PREFIXES, model, false ); - if ( config.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 ) - { - modelValueSource1 = new ProblemDetectingValueSource( modelValueSource1, "pom.", "project.", problems ); + ValueSource modelValueSource1 = new PrefixedObjectValueSource(PROJECT_PREFIXES, model, false); + if (config.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0) { + modelValueSource1 = new ProblemDetectingValueSource(modelValueSource1, "pom.", "project.", problems); } - ValueSource modelValueSource2 = new ObjectBasedValueSource( model ); - if ( config.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 ) - { - modelValueSource2 = new ProblemDetectingValueSource( modelValueSource2, "", "project.", problems ); + ValueSource modelValueSource2 = new ObjectBasedValueSource(model); + if (config.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0) { + modelValueSource2 = new ProblemDetectingValueSource(modelValueSource2, "", "project.", problems); } // NOTE: Order counts here! - List valueSources = new ArrayList<>( 9 ); - - if ( projectDir != null ) - { - ValueSource basedirValueSource = new PrefixedValueSourceWrapper( new AbstractValueSource( false ) - { - public Object getValue( String expression ) - { - if ( "basedir".equals( expression ) ) - { - return projectDir.getAbsolutePath(); - } - return null; - } - }, PROJECT_PREFIXES, true ); - valueSources.add( basedirValueSource ); - - ValueSource baseUriValueSource = new PrefixedValueSourceWrapper( new AbstractValueSource( false ) - { - public Object getValue( String expression ) - { - if ( "baseUri".equals( expression ) ) - { - return projectDir.getAbsoluteFile().toURI().toString(); - } - return null; - } - }, PROJECT_PREFIXES, false ); - valueSources.add( baseUriValueSource ); - valueSources.add( new BuildTimestampValueSource( config.getBuildStartTime(), modelProperties ) ); + List valueSources = new ArrayList<>(9); + + if (projectDir != null) { + ValueSource basedirValueSource = new PrefixedValueSourceWrapper( + new AbstractValueSource(false) { + public Object getValue(String expression) { + if ("basedir".equals(expression)) { + return projectDir.getAbsolutePath(); + } + return null; + } + }, + PROJECT_PREFIXES, + true); + valueSources.add(basedirValueSource); + + ValueSource baseUriValueSource = new PrefixedValueSourceWrapper( + new AbstractValueSource(false) { + public Object getValue(String expression) { + if ("baseUri".equals(expression)) { + return projectDir.getAbsoluteFile().toURI().toString(); + } + return null; + } + }, + PROJECT_PREFIXES, + false); + valueSources.add(baseUriValueSource); + valueSources.add(new BuildTimestampValueSource(config.getBuildStartTime(), modelProperties)); } - valueSources.add( modelValueSource1 ); + valueSources.add(modelValueSource1); - valueSources.add( new MapBasedValueSource( config.getUserProperties() ) ); + valueSources.add(new MapBasedValueSource(config.getUserProperties())); - valueSources.add( new MapBasedValueSource( modelProperties ) ); + valueSources.add(new MapBasedValueSource(modelProperties)); - valueSources.add( new MapBasedValueSource( config.getSystemProperties() ) ); + valueSources.add(new MapBasedValueSource(config.getSystemProperties())); - valueSources.add( new AbstractValueSource( false ) - { - public Object getValue( String expression ) - { - return config.getSystemProperties().getProperty( "env." + expression ); + valueSources.add(new AbstractValueSource(false) { + public Object getValue(String expression) { + return config.getSystemProperties().getProperty("env." + expression); } - } ); + }); - valueSources.add( modelValueSource2 ); + valueSources.add(modelValueSource2); return valueSources; } - protected List createPostProcessors( final Model model, final File projectDir, - final ModelBuildingRequest config ) - { - List processors = new ArrayList<>( 2 ); - if ( projectDir != null ) - { - processors.add( new PathTranslatingPostProcessor( PROJECT_PREFIXES, TRANSLATED_PATH_EXPRESSIONS, projectDir, - pathTranslator ) ); + protected List createPostProcessors( + final Model model, final File projectDir, final ModelBuildingRequest config) { + List processors = new ArrayList<>(2); + if (projectDir != null) { + processors.add(new PathTranslatingPostProcessor( + PROJECT_PREFIXES, TRANSLATED_PATH_EXPRESSIONS, projectDir, pathTranslator)); } - processors.add( new UrlNormalizingPostProcessor( urlNormalizer ) ); + processors.add(new UrlNormalizingPostProcessor(urlNormalizer)); return processors; } - protected RecursionInterceptor getRecursionInterceptor() - { + protected RecursionInterceptor getRecursionInterceptor() { return recursionInterceptor; } - protected void setRecursionInterceptor( RecursionInterceptor recursionInterceptor ) - { + protected void setRecursionInterceptor(RecursionInterceptor recursionInterceptor) { this.recursionInterceptor = recursionInterceptor; } - protected final Interpolator getInterpolator() - { + protected final Interpolator getInterpolator() { return interpolator; } - class BuildTimestampValueSource extends AbstractValueSource - { + class BuildTimestampValueSource extends AbstractValueSource { private final MavenBuildTimestamp mavenBuildTimestamp; - BuildTimestampValueSource( Date startTime, Properties properties ) - { - super( false ); - this.mavenBuildTimestamp = new MavenBuildTimestamp( startTime, properties ); + BuildTimestampValueSource(Date startTime, Properties properties) { + super(false); + this.mavenBuildTimestamp = new MavenBuildTimestamp(startTime, properties); } - public Object getValue( String expression ) - { - if ( "build.timestamp".equals( expression ) || "maven.build.timestamp".equals( expression ) ) - { + public Object getValue(String expression) { + if ("build.timestamp".equals(expression) || "maven.build.timestamp".equals(expression)) { return mavenBuildTimestamp.formattedTimestamp(); } return null; } } - class ProblemDetectingValueSource implements ValueSource - { + class ProblemDetectingValueSource implements ValueSource { private final ValueSource valueSource; @@ -728,107 +596,90 @@ class ProblemDetectingValueSource implements ValueSource private final ModelProblemCollector problems; - ProblemDetectingValueSource( ValueSource valueSource, String bannedPrefix, String newPrefix, - ModelProblemCollector problems ) - { + ProblemDetectingValueSource( + ValueSource valueSource, String bannedPrefix, String newPrefix, ModelProblemCollector problems) { this.valueSource = valueSource; this.bannedPrefix = bannedPrefix; this.newPrefix = newPrefix; this.problems = problems; } - public Object getValue( String expression ) - { - Object value = valueSource.getValue( expression ); + public Object getValue(String expression) { + Object value = valueSource.getValue(expression); - if ( value != null && expression.startsWith( bannedPrefix ) ) - { + if (value != null && expression.startsWith(bannedPrefix)) { String msg = "The expression ${" + expression + "} is deprecated."; - if ( newPrefix != null && newPrefix.length() > 0 ) - { - msg += " Please use ${" + newPrefix + expression.substring( bannedPrefix.length() ) + "} instead."; + if (newPrefix != null && newPrefix.length() > 0) { + msg += " Please use ${" + newPrefix + expression.substring(bannedPrefix.length()) + "} instead."; } - problems.add( new ModelProblemCollectorRequest( Severity.WARNING, Version.V20 ).setMessage( msg ) ); + problems.add(new ModelProblemCollectorRequest(Severity.WARNING, Version.V20).setMessage(msg)); } return value; } - @SuppressWarnings( "unchecked" ) - public List getFeedback() - { + @SuppressWarnings("unchecked") + public List getFeedback() { return valueSource.getFeedback(); } - public void clearFeedback() - { + public void clearFeedback() { valueSource.clearFeedback(); } - } - class PathTranslatingPostProcessor implements InterpolationPostProcessor - { + class PathTranslatingPostProcessor implements InterpolationPostProcessor { private final Collection unprefixedPathKeys; private final File projectDir; private final PathTranslator pathTranslator; private final List expressionPrefixes; - PathTranslatingPostProcessor( List expressionPrefixes, Collection unprefixedPathKeys, - File projectDir, PathTranslator pathTranslator ) - { + PathTranslatingPostProcessor( + List expressionPrefixes, + Collection unprefixedPathKeys, + File projectDir, + PathTranslator pathTranslator) { this.expressionPrefixes = expressionPrefixes; this.unprefixedPathKeys = unprefixedPathKeys; this.projectDir = projectDir; this.pathTranslator = pathTranslator; } - public Object execute( String expression, Object value ) - { - if ( value != null ) - { - expression = ValueSourceUtils.trimPrefix( expression, expressionPrefixes, true ); + public Object execute(String expression, Object value) { + if (value != null) { + expression = ValueSourceUtils.trimPrefix(expression, expressionPrefixes, true); - if ( unprefixedPathKeys.contains( expression ) ) - { - return pathTranslator.alignToBaseDirectory( String.valueOf( value ), projectDir ); + if (unprefixedPathKeys.contains(expression)) { + return pathTranslator.alignToBaseDirectory(String.valueOf(value), projectDir); } } return null; } - } - class UrlNormalizingPostProcessor implements InterpolationPostProcessor - { - + class UrlNormalizingPostProcessor implements InterpolationPostProcessor { private UrlNormalizer normalizer; - UrlNormalizingPostProcessor( UrlNormalizer normalizer ) - { + UrlNormalizingPostProcessor(UrlNormalizer normalizer) { this.normalizer = normalizer; } - public Object execute( String expression, Object value ) - { + public Object execute(String expression, Object value) { Set expressions = new HashSet<>(); - expressions.add( "project.url" ); - expressions.add( "project.scm.url" ); - expressions.add( "project.scm.connection" ); - expressions.add( "project.scm.developerConnection" ); - expressions.add( "project.distributionManagement.site.url" ); - - if ( value != null && expressions.contains( expression ) ) - { - return normalizer.normalize( value.toString() ); + expressions.add("project.url"); + expressions.add("project.scm.url"); + expressions.add("project.scm.connection"); + expressions.add("project.scm.developerConnection"); + expressions.add("project.distributionManagement.site.url"); + + if (value != null && expressions.contains(expression)) { + return normalizer.normalize(value.toString()); } return null; } - } - } diff --git a/src/main/java/org/codehaus/mojo/flatten/model/resolution/FlattenModelResolver.java b/src/main/java/org/codehaus/mojo/flatten/model/resolution/FlattenModelResolver.java index c7ef4429..44635338 100644 --- a/src/main/java/org/codehaus/mojo/flatten/model/resolution/FlattenModelResolver.java +++ b/src/main/java/org/codehaus/mojo/flatten/model/resolution/FlattenModelResolver.java @@ -1,200 +1,182 @@ -package org.codehaus.mojo.flatten.model.resolution; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.List; - -import org.apache.maven.model.Parent; -import org.apache.maven.model.Repository; -import org.apache.maven.model.building.FileModelSource; -import org.apache.maven.model.building.ModelSource; -import org.apache.maven.model.resolution.ModelResolver; -import org.apache.maven.model.resolution.UnresolvableModelException; -import org.apache.maven.project.MavenProject; -import org.eclipse.aether.RepositorySystem; -import org.eclipse.aether.RepositorySystemSession; -import org.eclipse.aether.RequestTrace; -import org.eclipse.aether.artifact.Artifact; -import org.eclipse.aether.artifact.DefaultArtifact; -import org.eclipse.aether.repository.RemoteRepository; -import org.eclipse.aether.resolution.ArtifactRequest; -import org.eclipse.aether.resolution.ArtifactResolutionException; -import org.eclipse.aether.resolution.VersionRangeRequest; -import org.eclipse.aether.resolution.VersionRangeResolutionException; -import org.eclipse.aether.resolution.VersionRangeResult; - -/** - * This is a custom implementation of {@link ModelResolver} to emulate the maven POM resolution in order to build the - * flattened POM. - * - * @see org.codehaus.mojo.flatten.FlattenMojo - * @author Robert Scholte - */ -public class FlattenModelResolver - implements ModelResolver -{ - private final RepositorySystemSession session; - - private final RepositorySystem repositorySystem; - - private final RequestTrace trace; - - private final String context; - - private final List repositories; - - /** The modules of the project being built. */ - private final ReactorModelPool reactorModelPool; - - /** - * The constructor. - */ - public FlattenModelResolver( RepositorySystemSession session, - RepositorySystem repositorySystem, - RequestTrace trace, - String context, - List repositories, - List reactorModels ) - { - this.session = session; - this.repositorySystem = repositorySystem; - this.trace = trace; - this.context = context; - this.repositories = repositories; - - this.reactorModelPool = new ReactorModelPool(); - reactorModelPool.addProjects( reactorModels ); - } - - private FlattenModelResolver( FlattenModelResolver other ) - { - this.session = other.session; - this.repositorySystem = other.repositorySystem; - this.trace = other.trace; - this.context = other.context; - this.repositories = other.repositories; - this.reactorModelPool = other.reactorModelPool; - } - - /** - * {@inheritDoc} - */ - public ModelSource resolveModel( String groupId, String artifactId, String version ) - throws UnresolvableModelException - { - File pomFile = reactorModelPool.find( groupId, artifactId, version ); - if ( pomFile == null ) - { - Artifact pomArtifact = new DefaultArtifact( groupId, artifactId, "", "pom", version ); - - try - { - ArtifactRequest request = new ArtifactRequest( pomArtifact, repositories, context ); - request.setTrace( trace ); - pomArtifact = repositorySystem.resolveArtifact( session, request ).getArtifact(); - } - catch ( ArtifactResolutionException e ) - { - throw new UnresolvableModelException( e.getMessage(), groupId, artifactId, version, e ); - } - - pomFile = pomArtifact.getFile(); - } - return new FileModelSource( pomFile ); - } - - /** - * {@inheritDoc} - */ - public void addRepository( Repository repository ) - { - // ignoring... artifact resolution via repository should already have happened before by maven core. - } - - /** - * {@inheritDoc} - */ - public ModelResolver newCopy() - { - return new FlattenModelResolver( this ); - } - - /** - * Resolves the POM for the specified parent. - * - * @param parent the parent coordinates to resolve, must not be {@code null} - * @return The source of the requested POM, never {@code null} - * @since Apache-Maven-3.2.2 (MNG-5639) - */ - public ModelSource resolveModel( Parent parent ) - throws UnresolvableModelException - { - Artifact artifact = new DefaultArtifact( parent.getGroupId(), parent.getArtifactId(), "", "pom", - parent.getVersion() ); - - VersionRangeRequest versionRangeRequest = new VersionRangeRequest( artifact, repositories, context ); - versionRangeRequest.setTrace( trace ); - - try - { - VersionRangeResult versionRangeResult = - repositorySystem.resolveVersionRange( session, versionRangeRequest ); - - if ( versionRangeResult.getHighestVersion() == null ) - { - throw new UnresolvableModelException( "No versions matched the requested range '" + parent.getVersion() - + "'", parent.getGroupId(), parent.getArtifactId(), - parent.getVersion() ); - - } - - if ( versionRangeResult.getVersionConstraint() != null - && versionRangeResult.getVersionConstraint().getRange() != null - && versionRangeResult.getVersionConstraint().getRange().getUpperBound() == null ) - { - throw new UnresolvableModelException( "The requested version range '" + parent.getVersion() - + "' does not specify an upper bound", parent.getGroupId(), - parent.getArtifactId(), parent.getVersion() ); - - } - - parent.setVersion( versionRangeResult.getHighestVersion().toString() ); - } - catch ( VersionRangeResolutionException e ) - { - throw new UnresolvableModelException( e.getMessage(), parent.getGroupId(), parent.getArtifactId(), - parent.getVersion(), e ); - - } - - return resolveModel( parent.getGroupId(), parent.getArtifactId(), parent.getVersion() ); - } - - /** - * @param repository The repository to add to the internal search chain, must not be {@code null}. - * @param replace {true} when repository with same id should be replaced, otherwise {@code false}. - * @since Apache-Maven-3.2.3 (MNG-5663) - */ - public void addRepository( Repository repository, boolean replace ) - { - // ignoring... artifact resolution via repository should already have happened before by maven core. - } -} +package org.codehaus.mojo.flatten.model.resolution; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.File; +import java.util.List; + +import org.apache.maven.model.Parent; +import org.apache.maven.model.Repository; +import org.apache.maven.model.building.FileModelSource; +import org.apache.maven.model.building.ModelSource; +import org.apache.maven.model.resolution.ModelResolver; +import org.apache.maven.model.resolution.UnresolvableModelException; +import org.apache.maven.project.MavenProject; +import org.eclipse.aether.RepositorySystem; +import org.eclipse.aether.RepositorySystemSession; +import org.eclipse.aether.RequestTrace; +import org.eclipse.aether.artifact.Artifact; +import org.eclipse.aether.artifact.DefaultArtifact; +import org.eclipse.aether.repository.RemoteRepository; +import org.eclipse.aether.resolution.ArtifactRequest; +import org.eclipse.aether.resolution.ArtifactResolutionException; +import org.eclipse.aether.resolution.VersionRangeRequest; +import org.eclipse.aether.resolution.VersionRangeResolutionException; +import org.eclipse.aether.resolution.VersionRangeResult; + +/** + * This is a custom implementation of {@link ModelResolver} to emulate the maven POM resolution in order to build the + * flattened POM. + * + * @see org.codehaus.mojo.flatten.FlattenMojo + * @author Robert Scholte + */ +public class FlattenModelResolver implements ModelResolver { + private final RepositorySystemSession session; + + private final RepositorySystem repositorySystem; + + private final RequestTrace trace; + + private final String context; + + private final List repositories; + + /** The modules of the project being built. */ + private final ReactorModelPool reactorModelPool; + + /** + * The constructor. + */ + public FlattenModelResolver( + RepositorySystemSession session, + RepositorySystem repositorySystem, + RequestTrace trace, + String context, + List repositories, + List reactorModels) { + this.session = session; + this.repositorySystem = repositorySystem; + this.trace = trace; + this.context = context; + this.repositories = repositories; + + this.reactorModelPool = new ReactorModelPool(); + reactorModelPool.addProjects(reactorModels); + } + + private FlattenModelResolver(FlattenModelResolver other) { + this.session = other.session; + this.repositorySystem = other.repositorySystem; + this.trace = other.trace; + this.context = other.context; + this.repositories = other.repositories; + this.reactorModelPool = other.reactorModelPool; + } + + /** + * {@inheritDoc} + */ + public ModelSource resolveModel(String groupId, String artifactId, String version) + throws UnresolvableModelException { + File pomFile = reactorModelPool.find(groupId, artifactId, version); + if (pomFile == null) { + Artifact pomArtifact = new DefaultArtifact(groupId, artifactId, "", "pom", version); + + try { + ArtifactRequest request = new ArtifactRequest(pomArtifact, repositories, context); + request.setTrace(trace); + pomArtifact = repositorySystem.resolveArtifact(session, request).getArtifact(); + } catch (ArtifactResolutionException e) { + throw new UnresolvableModelException(e.getMessage(), groupId, artifactId, version, e); + } + + pomFile = pomArtifact.getFile(); + } + return new FileModelSource(pomFile); + } + + /** + * {@inheritDoc} + */ + public void addRepository(Repository repository) { + // ignoring... artifact resolution via repository should already have happened before by maven core. + } + + /** + * {@inheritDoc} + */ + public ModelResolver newCopy() { + return new FlattenModelResolver(this); + } + + /** + * Resolves the POM for the specified parent. + * + * @param parent the parent coordinates to resolve, must not be {@code null} + * @return The source of the requested POM, never {@code null} + * @since Apache-Maven-3.2.2 (MNG-5639) + */ + public ModelSource resolveModel(Parent parent) throws UnresolvableModelException { + Artifact artifact = + new DefaultArtifact(parent.getGroupId(), parent.getArtifactId(), "", "pom", parent.getVersion()); + + VersionRangeRequest versionRangeRequest = new VersionRangeRequest(artifact, repositories, context); + versionRangeRequest.setTrace(trace); + + try { + VersionRangeResult versionRangeResult = repositorySystem.resolveVersionRange(session, versionRangeRequest); + + if (versionRangeResult.getHighestVersion() == null) { + throw new UnresolvableModelException( + "No versions matched the requested range '" + parent.getVersion() + "'", + parent.getGroupId(), + parent.getArtifactId(), + parent.getVersion()); + } + + if (versionRangeResult.getVersionConstraint() != null + && versionRangeResult.getVersionConstraint().getRange() != null + && versionRangeResult.getVersionConstraint().getRange().getUpperBound() == null) { + throw new UnresolvableModelException( + "The requested version range '" + parent.getVersion() + "' does not specify an upper bound", + parent.getGroupId(), + parent.getArtifactId(), + parent.getVersion()); + } + + parent.setVersion(versionRangeResult.getHighestVersion().toString()); + } catch (VersionRangeResolutionException e) { + throw new UnresolvableModelException( + e.getMessage(), parent.getGroupId(), parent.getArtifactId(), parent.getVersion(), e); + } + + return resolveModel(parent.getGroupId(), parent.getArtifactId(), parent.getVersion()); + } + + /** + * @param repository The repository to add to the internal search chain, must not be {@code null}. + * @param replace {true} when repository with same id should be replaced, otherwise {@code false}. + * @since Apache-Maven-3.2.3 (MNG-5663) + */ + public void addRepository(Repository repository, boolean replace) { + // ignoring... artifact resolution via repository should already have happened before by maven core. + } +} diff --git a/src/main/java/org/codehaus/mojo/flatten/model/resolution/ReactorModelPool.java b/src/main/java/org/codehaus/mojo/flatten/model/resolution/ReactorModelPool.java index caef2f57..7808b8ac 100644 --- a/src/main/java/org/codehaus/mojo/flatten/model/resolution/ReactorModelPool.java +++ b/src/main/java/org/codehaus/mojo/flatten/model/resolution/ReactorModelPool.java @@ -32,63 +32,51 @@ * * @author Christoph Böhme */ -class ReactorModelPool -{ +class ReactorModelPool { private final Map models = new HashMap<>(); - public File find( String groupId, String artifactId, String version ) - { - return models.get( new Coordinates( groupId, artifactId, version ) ); + public File find(String groupId, String artifactId, String version) { + return models.get(new Coordinates(groupId, artifactId, version)); } - public void addProjects( List projects ) - { - projects.forEach( this::addProject ); + public void addProjects(List projects) { + projects.forEach(this::addProject); } - public void addProject( MavenProject project ) - { - Coordinates coordinates = new Coordinates( project.getGroupId(), project.getArtifactId(), - project.getVersion() ); - models.put( coordinates, project.getFile() ); + public void addProject(MavenProject project) { + Coordinates coordinates = new Coordinates(project.getGroupId(), project.getArtifactId(), project.getVersion()); + models.put(coordinates, project.getFile()); } - private static final class Coordinates - { + private static final class Coordinates { final String groupId; final String artifactId; final String version; - Coordinates( String groupId, String artifactId, String version ) - { + Coordinates(String groupId, String artifactId, String version) { this.groupId = groupId; this.artifactId = artifactId; this.version = version; } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; } - if ( obj instanceof Coordinates ) - { + if (obj instanceof Coordinates) { Coordinates other = (Coordinates) obj; - return artifactId.equals( other.artifactId ) && groupId.equals( other.groupId ) - && version.equals( other.version ); + return artifactId.equals(other.artifactId) + && groupId.equals(other.groupId) + && version.equals(other.version); } return false; } @Override - public int hashCode() - { - return Objects.hash( artifactId, groupId, version ); + public int hashCode() { + return Objects.hash(artifactId, groupId, version); } - } - } diff --git a/src/test/java/org/codehaus/mojo/flatten/CreateEffectivePomTest.java b/src/test/java/org/codehaus/mojo/flatten/CreateEffectivePomTest.java index 92381283..e7bee870 100644 --- a/src/test/java/org/codehaus/mojo/flatten/CreateEffectivePomTest.java +++ b/src/test/java/org/codehaus/mojo/flatten/CreateEffectivePomTest.java @@ -45,8 +45,7 @@ * * @author hohwille */ -public class CreateEffectivePomTest -{ +public class CreateEffectivePomTest { @Rule public MojoRule rule = new MojoRule(); @@ -56,47 +55,51 @@ public class CreateEffectivePomTest * @throws Exception if something goes wrong. */ @Test - public void testCreateEffectivePom() - throws Exception - { + public void testCreateEffectivePom() throws Exception { String magicValue = "magic-value"; Properties userProperties = new Properties(); - userProperties.setProperty( "cmd.test.property", magicValue ); + userProperties.setProperty("cmd.test.property", magicValue); - File pomFile = new File( "src/test/resources/cmdpropertysubstituion/pom.xml" ); - MavenProject mavenProject = rule.readMavenProject( pomFile.getParentFile() ); + File pomFile = new File("src/test/resources/cmdpropertysubstituion/pom.xml"); + MavenProject mavenProject = rule.readMavenProject(pomFile.getParentFile()); - MavenSession session = rule.newMavenSession( mavenProject ); - FlattenModelResolver resolver = new FlattenModelResolver( session.getRepositorySession(), - null, null, null, Collections.emptyList(), Collections.singletonList( mavenProject ) ); - ModelBuildingRequest buildingRequest = - new DefaultModelBuildingRequest().setPomFile( pomFile ).setModelResolver( resolver ) - .setUserProperties( userProperties ); + MavenSession session = rule.newMavenSession(mavenProject); + FlattenModelResolver resolver = new FlattenModelResolver( + session.getRepositorySession(), + null, + null, + null, + Collections.emptyList(), + Collections.singletonList(mavenProject)); + ModelBuildingRequest buildingRequest = new DefaultModelBuildingRequest() + .setPomFile(pomFile) + .setModelResolver(resolver) + .setUserProperties(userProperties); - FlattenMojo tested = (FlattenMojo) rule.lookupConfiguredMojo( mavenProject, "flatten" ); - rule.setVariableValueToObject( tested, "modelBuilderThreadSafetyWorkaround", - buildModelBuilderThreadSafetyWorkaroundForTest() ); - Model effectivePom = tested.createEffectivePom( buildingRequest, false, FlattenMode.defaults ); - assertThat( effectivePom.getName() ).isEqualTo( magicValue ); + FlattenMojo tested = (FlattenMojo) rule.lookupConfiguredMojo(mavenProject, "flatten"); + rule.setVariableValueToObject( + tested, "modelBuilderThreadSafetyWorkaround", buildModelBuilderThreadSafetyWorkaroundForTest()); + Model effectivePom = tested.createEffectivePom(buildingRequest, false, FlattenMode.defaults); + assertThat(effectivePom.getName()).isEqualTo(magicValue); } /** * @return ModelBuilderThreadSafetyWorkaround with a reduced scope for this simple test */ - private ModelBuilderThreadSafetyWorkaround buildModelBuilderThreadSafetyWorkaroundForTest() - { - return new ModelBuilderThreadSafetyWorkaround() - { + private ModelBuilderThreadSafetyWorkaround buildModelBuilderThreadSafetyWorkaroundForTest() { + return new ModelBuilderThreadSafetyWorkaround() { @Override - public ModelBuildingResult build( ModelBuildingRequest buildingRequest, ProfileInjector customInjector, - ProfileSelector customSelector ) - throws ModelBuildingException - { - return new DefaultModelBuilderFactory().newInstance() - .setProfileInjector( customInjector ) - .setProfileSelector( customSelector ) - .build( buildingRequest ); + public ModelBuildingResult build( + ModelBuildingRequest buildingRequest, + ProfileInjector customInjector, + ProfileSelector customSelector) + throws ModelBuildingException { + return new DefaultModelBuilderFactory() + .newInstance() + .setProfileInjector(customInjector) + .setProfileSelector(customSelector) + .build(buildingRequest); } }; } diff --git a/src/test/java/org/codehaus/mojo/flatten/FlattenMojoOmitExclusionsTest.java b/src/test/java/org/codehaus/mojo/flatten/FlattenMojoOmitExclusionsTest.java index 3350df4b..fa92ab4b 100644 --- a/src/test/java/org/codehaus/mojo/flatten/FlattenMojoOmitExclusionsTest.java +++ b/src/test/java/org/codehaus/mojo/flatten/FlattenMojoOmitExclusionsTest.java @@ -1,85 +1,73 @@ -package org.codehaus.mojo.flatten; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; - -import org.apache.maven.model.Model; -import org.apache.maven.model.io.xpp3.MavenXpp3Reader; -import org.apache.maven.plugin.testing.MojoRule; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; - -import static org.junit.Assert.fail; - -/** - * Test case for the omitexclusions configuration option. - */ -public class FlattenMojoOmitExclusionsTest -{ - - private static final String PATH = "src/test/resources/omit-exclusions/"; - private static final String FLATTENED_POM = PATH + ".flattened-pom.xml"; - - @Rule - public MojoRule rule = new MojoRule(); - - - /** - * Verify that when the omit exclusions configuration option is set then the - * exclusions stanza of any dependencies is not copied into the flattened - * POM. - */ - @Test - public void testOmitExclusions() throws Exception - { - // -- Given... - // - MavenProject project = rule.readMavenProject( new File( PATH ) ); - FlattenMojo flattenMojo = (FlattenMojo) rule.lookupConfiguredMojo( project, "flatten" ); - - // -- When... - // - flattenMojo.execute(); - - // -- Then... - // - readPom( FLATTENED_POM ) - .getDependencies() - .stream() - .filter( dep -> !dep.getExclusions().isEmpty() ) - .findAny() - .ifPresent( dep -> fail( "No exclusions should be present in flattened POM." ) ); - } - - - private static Model readPom( String pomFilePath ) throws IOException, XmlPullParserException - { - try ( FileInputStream input = new FileInputStream( new File( pomFilePath ) ) ) - { - return new MavenXpp3Reader().read( input ); - } - } - - - /** - * After test method. Removes flattened-pom.xml file which is created during test. - * - * @throws IOException if can't remove file. - */ - @After - public void removeFlattenedPom() throws IOException - { - File flattenedPom = new File( FLATTENED_POM ); - if ( flattenedPom.exists() ) - { - if ( !flattenedPom.delete() ) - { - throw new IOException( "Can't delete " + flattenedPom ); - } - } - } -} +package org.codehaus.mojo.flatten; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +import org.apache.maven.model.Model; +import org.apache.maven.model.io.xpp3.MavenXpp3Reader; +import org.apache.maven.plugin.testing.MojoRule; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import org.junit.After; +import org.junit.Rule; +import org.junit.Test; + +import static org.junit.Assert.fail; + +/** + * Test case for the omitexclusions configuration option. + */ +public class FlattenMojoOmitExclusionsTest { + + private static final String PATH = "src/test/resources/omit-exclusions/"; + private static final String FLATTENED_POM = PATH + ".flattened-pom.xml"; + + @Rule + public MojoRule rule = new MojoRule(); + + /** + * Verify that when the omit exclusions configuration option is set then the + * exclusions stanza of any dependencies is not copied into the flattened + * POM. + */ + @Test + public void testOmitExclusions() throws Exception { + // -- Given... + // + MavenProject project = rule.readMavenProject(new File(PATH)); + FlattenMojo flattenMojo = (FlattenMojo) rule.lookupConfiguredMojo(project, "flatten"); + + // -- When... + // + flattenMojo.execute(); + + // -- Then... + // + readPom(FLATTENED_POM).getDependencies().stream() + .filter(dep -> !dep.getExclusions().isEmpty()) + .findAny() + .ifPresent(dep -> fail("No exclusions should be present in flattened POM.")); + } + + private static Model readPom(String pomFilePath) throws IOException, XmlPullParserException { + try (FileInputStream input = new FileInputStream(new File(pomFilePath))) { + return new MavenXpp3Reader().read(input); + } + } + + /** + * After test method. Removes flattened-pom.xml file which is created during test. + * + * @throws IOException if can't remove file. + */ + @After + public void removeFlattenedPom() throws IOException { + File flattenedPom = new File(FLATTENED_POM); + if (flattenedPom.exists()) { + if (!flattenedPom.delete()) { + throw new IOException("Can't delete " + flattenedPom); + } + } + } +} diff --git a/src/test/java/org/codehaus/mojo/flatten/FlattenMojoTest.java b/src/test/java/org/codehaus/mojo/flatten/FlattenMojoTest.java index 45610a55..f2649fd8 100644 --- a/src/test/java/org/codehaus/mojo/flatten/FlattenMojoTest.java +++ b/src/test/java/org/codehaus/mojo/flatten/FlattenMojoTest.java @@ -39,11 +39,10 @@ * * @author dehasi */ -public class FlattenMojoTest -{ +public class FlattenMojoTest { private static final String PATH = - "src/test/resources/resolve-properties-ci-do-not-interpolate-profile-activation-file/"; + "src/test/resources/resolve-properties-ci-do-not-interpolate-profile-activation-file/"; private static final String POM = PATH + "pom.xml"; private static final String FLATTENED_POM = PATH + ".flattened-pom.xml"; @@ -56,27 +55,22 @@ public class FlattenMojoTest * @throws Exception if something goes wrong. */ @Test - public void keepsProfileActivationFile() throws Exception - { - MavenProject project = rule.readMavenProject( new File( PATH ) ); - FlattenMojo flattenMojo = (FlattenMojo) rule.lookupConfiguredMojo( project, "flatten" ); + public void keepsProfileActivationFile() throws Exception { + MavenProject project = rule.readMavenProject(new File(PATH)); + FlattenMojo flattenMojo = (FlattenMojo) rule.lookupConfiguredMojo(project, "flatten"); flattenMojo.execute(); - assertThat( profileActivationFile( FLATTENED_POM ) ) - .isEqualTo( profileActivationFile( POM ) ); + assertThat(profileActivationFile(FLATTENED_POM)).isEqualTo(profileActivationFile(POM)); } - private static String profileActivationFile( String pom ) throws Exception - { - return readPom( pom ).getProfiles().get( 0 ).getActivation().getFile().getExists(); + private static String profileActivationFile(String pom) throws Exception { + return readPom(pom).getProfiles().get(0).getActivation().getFile().getExists(); } - private static Model readPom( String pomFilePath ) throws IOException, XmlPullParserException - { - try ( FileInputStream input = new FileInputStream( new File( pomFilePath ) ) ) - { - return new MavenXpp3Reader().read( input ); + private static Model readPom(String pomFilePath) throws IOException, XmlPullParserException { + try (FileInputStream input = new FileInputStream(new File(pomFilePath))) { + return new MavenXpp3Reader().read(input); } } @@ -86,14 +80,11 @@ private static Model readPom( String pomFilePath ) throws IOException, XmlPullPa * @throws IOException if can't remove file. */ @After - public void removeFlattenedPom() throws IOException - { - File flattenedPom = new File( FLATTENED_POM ); - if ( flattenedPom.exists() ) - { - if ( !flattenedPom.delete() ) - { - throw new IOException( "Can't delete " + flattenedPom ); + public void removeFlattenedPom() throws IOException { + File flattenedPom = new File(FLATTENED_POM); + if (flattenedPom.exists()) { + if (!flattenedPom.delete()) { + throw new IOException("Can't delete " + flattenedPom); } } } diff --git a/src/test/java/org/codehaus/mojo/flatten/KeepCommentsInPomTest.java b/src/test/java/org/codehaus/mojo/flatten/KeepCommentsInPomTest.java index 1621a06d..b0dd350f 100644 --- a/src/test/java/org/codehaus/mojo/flatten/KeepCommentsInPomTest.java +++ b/src/test/java/org/codehaus/mojo/flatten/KeepCommentsInPomTest.java @@ -38,8 +38,7 @@ /** * Test-Case for {@link FlattenMojo}. */ -public class KeepCommentsInPomTest -{ +public class KeepCommentsInPomTest { private static final String PATH = "src/test/resources/keep-comments-in-pom/"; private static final String TEST_TARGET_PATH = "target/test/resources/keep-comments-in-pom/"; @@ -49,15 +48,15 @@ public class KeepCommentsInPomTest * Expected result since jdk11 with updated xml header and properties sequence. */ private static final String EXPECTED_FLATTENED_POM_JDK11 = PATH + "expected-flattened-pom-jdk11.xml"; - private static final Pattern NEW_LINE_PATTERN = Pattern.compile( "\\n|\\r\\n?" ); + + private static final Pattern NEW_LINE_PATTERN = Pattern.compile("\\n|\\r\\n?"); @Rule public MojoRule rule = new MojoRule(); @Before - public void setup() - { - new File( TEST_TARGET_PATH ).mkdirs(); + public void setup() { + new File(TEST_TARGET_PATH).mkdirs(); } /** @@ -66,23 +65,22 @@ public void setup() * @throws Exception if something goes wrong. */ @Test - public void keepsProfileActivationFile() throws Exception - { - MavenProject project = rule.readMavenProject( new File( PATH ) ); - FlattenMojo flattenMojo = (FlattenMojo) rule.lookupConfiguredMojo( project, "flatten" ); + public void keepsProfileActivationFile() throws Exception { + MavenProject project = rule.readMavenProject(new File(PATH)); + FlattenMojo flattenMojo = (FlattenMojo) rule.lookupConfiguredMojo(project, "flatten"); - DefaultPlexusConfiguration tempPluginConfiguration = new DefaultPlexusConfiguration( "test" ); - tempPluginConfiguration.addChild( "outputDirectory", TEST_TARGET_PATH ); - tempPluginConfiguration.addChild( "keepCommentsInPom", "true" ); - rule.configureMojo( flattenMojo, tempPluginConfiguration ); + DefaultPlexusConfiguration tempPluginConfiguration = new DefaultPlexusConfiguration("test"); + tempPluginConfiguration.addChild("outputDirectory", TEST_TARGET_PATH); + tempPluginConfiguration.addChild("keepCommentsInPom", "true"); + rule.configureMojo(flattenMojo, tempPluginConfiguration); // execute writes new FLATTENED_POM flattenMojo.execute(); - Path expectedContentFile = Paths.get( isJdk8() ? EXPECTED_FLATTENED_POM : EXPECTED_FLATTENED_POM_JDK11 ); - Path actualContentFile = Paths.get( FLATTENED_POM ); - assertThat( actualContentFile ).hasSameTextualContentAs( expectedContentFile ); - assertHasLineSeparator( actualContentFile , System.lineSeparator() ); + Path expectedContentFile = Paths.get(isJdk8() ? EXPECTED_FLATTENED_POM : EXPECTED_FLATTENED_POM_JDK11); + Path actualContentFile = Paths.get(FLATTENED_POM); + assertThat(actualContentFile).hasSameTextualContentAs(expectedContentFile); + assertHasLineSeparator(actualContentFile, System.lineSeparator()); } /** @@ -90,37 +88,31 @@ public void keepsProfileActivationFile() throws Exception * * @return true when runtime is JDK11 */ - private boolean isJdk8() - { + private boolean isJdk8() { // With Java 9 can be switched to java.lang.Runtime.version() - String tempPropertyVersion = System.getProperty( "java.version" ); - if ( tempPropertyVersion.startsWith( "1.8." ) ) - { + String tempPropertyVersion = System.getProperty("java.version"); + if (tempPropertyVersion.startsWith("1.8.")) { return true; } return false; } - private static void assertHasLineSeparator( final Path file, final String expectedSeparator ) throws IOException - { - try ( Scanner scanner = new Scanner( file ) ) - { + private static void assertHasLineSeparator(final Path file, final String expectedSeparator) throws IOException { + try (Scanner scanner = new Scanner(file)) { int lineNr = 0; String actualSeparator; - while ( ( actualSeparator = scanner.findWithinHorizon( NEW_LINE_PATTERN, 0 ) ) != null ) - { + while ((actualSeparator = scanner.findWithinHorizon(NEW_LINE_PATTERN, 0)) != null) { lineNr++; - if ( !expectedSeparator.equals( actualSeparator ) ) - { - final String actualDesc = actualSeparator.replace( "\r", "CR" ).replace( "\n", "LF" ); - final String expectedDesc = expectedSeparator.replace( "\r", "CR" ).replace( "\n", "LF" ); - throw new AssertionError( - String.format( - "\nLine %d of path %s has %s as line separator.\nExpected line separator: %s.", - lineNr, file, actualDesc, expectedDesc ) ); + if (!expectedSeparator.equals(actualSeparator)) { + final String actualDesc = + actualSeparator.replace("\r", "CR").replace("\n", "LF"); + final String expectedDesc = + expectedSeparator.replace("\r", "CR").replace("\n", "LF"); + throw new AssertionError(String.format( + "\nLine %d of path %s has %s as line separator.\nExpected line separator: %s.", + lineNr, file, actualDesc, expectedDesc)); } } } } - }