View Javadoc
1   package org.apache.maven.archetype.creator;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.File;
23  import java.io.FileInputStream;
24  import java.io.FileNotFoundException;
25  import java.io.FileOutputStream;
26  import java.io.IOException;
27  import java.io.InputStream;
28  import java.io.OutputStream;
29  import java.io.Reader;
30  import java.io.Writer;
31  import java.util.ArrayList;
32  import java.util.Arrays;
33  import java.util.Collections;
34  import java.util.HashMap;
35  import java.util.HashSet;
36  import java.util.Iterator;
37  import java.util.List;
38  import java.util.Map;
39  import java.util.Properties;
40  import java.util.Set;
41  
42  import org.apache.commons.collections.CollectionUtils;
43  import org.apache.maven.archetype.ArchetypeCreationRequest;
44  import org.apache.maven.archetype.ArchetypeCreationResult;
45  import org.apache.maven.archetype.common.ArchetypeFilesResolver;
46  import org.apache.maven.archetype.common.Constants;
47  import org.apache.maven.archetype.common.PomManager;
48  import org.apache.maven.archetype.common.util.FileCharsetDetector;
49  import org.apache.maven.archetype.common.util.ListScanner;
50  import org.apache.maven.archetype.common.util.PathUtils;
51  import org.apache.maven.archetype.exception.TemplateCreationException;
52  import org.apache.maven.archetype.metadata.ArchetypeDescriptor;
53  import org.apache.maven.archetype.metadata.FileSet;
54  import org.apache.maven.archetype.metadata.ModuleDescriptor;
55  import org.apache.maven.archetype.metadata.RequiredProperty;
56  import org.apache.maven.archetype.metadata.io.xpp3.ArchetypeDescriptorXpp3Writer;
57  import org.apache.maven.model.Build;
58  import org.apache.maven.model.Dependency;
59  import org.apache.maven.model.Extension;
60  import org.apache.maven.model.Model;
61  import org.apache.maven.model.Plugin;
62  import org.apache.maven.model.PluginManagement;
63  import org.apache.maven.model.Profile;
64  import org.apache.maven.model.Resource;
65  import org.apache.maven.project.MavenProject;
66  import org.apache.maven.project.ProjectBuildingRequest;
67  import org.apache.maven.shared.invoker.DefaultInvocationRequest;
68  import org.apache.maven.shared.invoker.InvocationRequest;
69  import org.apache.maven.shared.invoker.InvocationResult;
70  import org.apache.maven.shared.invoker.Invoker;
71  import org.codehaus.plexus.component.annotations.Component;
72  import org.codehaus.plexus.component.annotations.Requirement;
73  import org.codehaus.plexus.logging.AbstractLogEnabled;
74  import org.codehaus.plexus.util.DirectoryScanner;
75  import org.codehaus.plexus.util.FileUtils;
76  import org.codehaus.plexus.util.IOUtil;
77  import org.codehaus.plexus.util.ReaderFactory;
78  import org.codehaus.plexus.util.StringUtils;
79  import org.codehaus.plexus.util.WriterFactory;
80  import org.codehaus.plexus.util.xml.Xpp3Dom;
81  import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
82  
83  import static org.apache.commons.io.IOUtils.write;
84  
85  /**
86   * Create a 2.x Archetype project from a project. Since 2.0-alpha-5, an integration-test named "basic" is created along
87   * the archetype itself to provide immediate test when building the archetype.
88   */
89  @Component( role = ArchetypeCreator.class, hint = "fileset" )
90  public class FilesetArchetypeCreator
91      extends AbstractLogEnabled
92      implements ArchetypeCreator
93  {
94      private static final String DEFAULT_OUTPUT_DIRECTORY =
95          "target" + File.separator + "generated-sources" + File.separator + "archetype";
96  
97      @Requirement
98      private ArchetypeFilesResolver archetypeFilesResolver;
99  
100     @Requirement
101     private PomManager pomManager;
102     
103     @Requirement
104     private Invoker invoker;
105 
106     @Override
107     public void createArchetype( ArchetypeCreationRequest request, ArchetypeCreationResult result )
108     {
109         MavenProject project = request.getProject();
110         List<String> languages = request.getLanguages();
111         List<String> filtereds = request.getFiltereds();
112         String defaultEncoding = request.getDefaultEncoding();
113         boolean preserveCData = request.isPreserveCData();
114         boolean keepParent = request.isKeepParent();
115         boolean partialArchetype = request.isPartialArchetype();
116         File outputDirectory = request.getOutputDirectory();
117         File basedir = project.getBasedir();
118 
119         Properties properties = new Properties();
120         Properties configurationProperties = new Properties();
121         if ( request.getProperties() != null )
122         {
123             properties.putAll( request.getProperties() );
124             configurationProperties.putAll( request.getProperties() );
125         }
126 
127         extractPropertiesFromProject( project, properties, configurationProperties, request.getPackageName() );
128 
129         if ( outputDirectory == null )
130         {
131             getLogger().debug( "No output directory defined, using default: " + DEFAULT_OUTPUT_DIRECTORY );
132             outputDirectory = FileUtils.resolveFile( basedir, DEFAULT_OUTPUT_DIRECTORY );
133         }
134         outputDirectory.mkdirs();
135 
136         getLogger().debug( "Creating archetype in " + outputDirectory );
137 
138         try
139         {
140             File archetypePomFile = createArchetypeProjectPom( project, request.getProjectBuildingRequest(),
141                                                                configurationProperties, outputDirectory );
142 
143             File archetypeResourcesDirectory = new File( outputDirectory, getTemplateOutputDirectory() );
144 
145             File archetypeFilesDirectory = new File( archetypeResourcesDirectory, Constants.ARCHETYPE_RESOURCES );
146             getLogger().debug( "Archetype's files output directory " + archetypeFilesDirectory );
147 
148             File archetypeDescriptorFile = new File( archetypeResourcesDirectory, Constants.ARCHETYPE_DESCRIPTOR );
149             archetypeDescriptorFile.getParentFile().mkdirs();
150 
151             File archetypePostGenerationScript =
152                 new File( archetypeResourcesDirectory, Constants.ARCHETYPE_POST_GENERATION_SCRIPT );
153             archetypePostGenerationScript.getParentFile().mkdirs();
154 
155             if ( request.getProject().getBuild() != null && CollectionUtils.isNotEmpty(
156                 request.getProject().getBuild().getResources() ) )
157             {
158                 for ( Resource resource : request.getProject().getBuild().getResources() )
159                 {
160                     File inputFile = new File(
161                         resource.getDirectory() + File.separator + Constants.ARCHETYPE_POST_GENERATION_SCRIPT );
162                     if ( inputFile.exists() )
163                     {
164                         FileUtils.copyFile( inputFile, archetypePostGenerationScript );
165                     }
166                 }
167             }
168 
169             getLogger().debug( "Starting archetype's descriptor " + project.getArtifactId() );
170             ArchetypeDescriptor archetypeDescriptor = new ArchetypeDescriptor();
171 
172             archetypeDescriptor.setName( project.getArtifactId() );
173             archetypeDescriptor.setPartial( partialArchetype );
174 
175             addRequiredProperties( archetypeDescriptor, properties );
176 
177             // TODO ensure reverseProperties contains NO dotted properties
178             Properties reverseProperties = getReversedProperties( archetypeDescriptor, properties );
179             // reverseProperties.remove( Constants.GROUP_ID );
180 
181             // TODO ensure pomReversedProperties contains NO dotted properties
182             Properties pomReversedProperties = getReversedProperties( archetypeDescriptor, properties );
183             // pomReversedProperties.remove( Constants.PACKAGE );
184 
185             String packageName = configurationProperties.getProperty( Constants.PACKAGE );
186 
187             Model pom = pomManager.readPom( project.getFile() );
188 
189             List<String> excludePatterns =
190                 configurationProperties.getProperty( Constants.EXCLUDE_PATTERNS ) != null
191                     ? Arrays.asList(
192                     StringUtils.split( configurationProperties.getProperty( Constants.EXCLUDE_PATTERNS ), "," ) )
193                     : Collections.<String>emptyList();
194 
195             List<String> fileNames = resolveFileNames( pom, basedir, excludePatterns );
196             if ( getLogger().isDebugEnabled() )
197             {
198                 getLogger().debug( "Scanned for files " + fileNames.size() );
199 
200                 for ( String name : fileNames )
201                 {
202                     getLogger().debug( "- " + name );
203                 }
204             }
205 
206             List<FileSet> filesets = resolveFileSets( packageName, fileNames, languages, filtereds, defaultEncoding );
207             getLogger().debug( "Resolved filesets for " + archetypeDescriptor.getName() );
208 
209             archetypeDescriptor.setFileSets( filesets );
210 
211             createArchetypeFiles( reverseProperties, filesets, packageName, basedir, archetypeFilesDirectory,
212                                   defaultEncoding, excludePatterns );
213             getLogger().debug( "Created files for " + archetypeDescriptor.getName() );
214 
215             setParentArtifactId( reverseProperties, configurationProperties.getProperty( Constants.ARTIFACT_ID ) );
216 
217             for ( String moduleId : pom.getModules() )
218             {
219                 String rootArtifactId = configurationProperties.getProperty( Constants.ARTIFACT_ID );
220                 String moduleIdDirectory = moduleId;
221 
222                 if ( moduleId.indexOf( rootArtifactId ) >= 0 )
223                 {
224                     moduleIdDirectory = StringUtils.replace( moduleId, rootArtifactId, "__rootArtifactId__" );
225                 }
226 
227                 getLogger().debug( "Creating module " + moduleId );
228 
229                 ModuleDescriptor moduleDescriptor =
230                     createModule( reverseProperties, rootArtifactId, moduleId, packageName,
231                                   FileUtils.resolveFile( basedir, moduleId ),
232                                   new File( archetypeFilesDirectory, moduleIdDirectory ), languages, filtereds,
233                                   defaultEncoding, preserveCData, keepParent );
234 
235                 archetypeDescriptor.addModule( moduleDescriptor );
236 
237                 getLogger().debug(
238                     "Added module " + moduleDescriptor.getName() + " in " + archetypeDescriptor.getName() );
239             }
240 
241             restoreParentArtifactId( reverseProperties, null );
242             restoreArtifactId( reverseProperties, configurationProperties.getProperty( Constants.ARTIFACT_ID ) );
243 
244             createPoms( pom, configurationProperties.getProperty( Constants.ARTIFACT_ID ),
245                         configurationProperties.getProperty( Constants.ARTIFACT_ID ), archetypeFilesDirectory, basedir,
246                         project.getFile(), pomReversedProperties, preserveCData, keepParent );
247             getLogger().debug( "Created Archetype " + archetypeDescriptor.getName() + " template pom(s)" );
248 
249             
250             try ( Writer out = WriterFactory.newXmlWriter( archetypeDescriptorFile ) )
251             {
252                 ArchetypeDescriptorXpp3Writer writer = new ArchetypeDescriptorXpp3Writer();
253 
254                 writer.write( out, archetypeDescriptor );
255 
256                 getLogger().debug( "Archetype " + archetypeDescriptor.getName() + " descriptor written" );
257             }
258 
259             createArchetypeBasicIt( archetypeDescriptor, outputDirectory );
260 
261             // Copy archetype integration tests.
262             File archetypeIntegrationTestInputFolder =
263                 new File( basedir, Constants.SRC + File.separator + "it" + File.separator + "projects" );
264             File archetypeIntegrationTestOutputFolder = new File( outputDirectory,
265                                                                   Constants.SRC + File.separator + Constants.TEST
266                                                                       + File.separator + Constants.RESOURCES
267                                                                       + File.separator + "projects" );
268 
269             if ( archetypeIntegrationTestInputFolder.exists() )
270             {
271                 getLogger().info( "Copying: " + archetypeIntegrationTestInputFolder.getAbsolutePath() + " into "
272                                       + archetypeIntegrationTestOutputFolder.getAbsolutePath() );
273 
274                 FileUtils.copyDirectoryStructure( archetypeIntegrationTestInputFolder,
275                                                   archetypeIntegrationTestOutputFolder );
276 
277             }
278             InvocationRequest internalRequest = new DefaultInvocationRequest();
279             internalRequest.setPomFile( archetypePomFile );
280             internalRequest.setUserSettingsFile( request.getSettingsFile() );
281             internalRequest.setGoals( Collections.singletonList( request.getPostPhase() ) );
282             if ( request.getLocalRepository() != null )
283             {
284                 internalRequest.setLocalRepositoryDirectory( new File( request.getLocalRepository().getBasedir() ) );
285             }
286             
287             String httpsProtocols = System.getProperty( "https.protocols" );
288             if ( httpsProtocols != null )
289             {
290                 Properties userProperties = new Properties();
291                 userProperties.setProperty( "https.protocols", httpsProtocols );
292                 internalRequest.setProperties( userProperties );
293             }
294 
295             InvocationResult invokerResult = invoker.execute( internalRequest );
296             if ( invokerResult.getExitCode() != 0 )
297             {
298                 if ( invokerResult.getExecutionException() != null )
299                 {
300                     throw invokerResult.getExecutionException();
301                 }
302                 else
303                 {
304                     throw new Exception( "Invoker process ended with result different than 0!" );
305                 }
306             }
307 
308         }
309         catch ( Exception e )
310         {
311             result.setCause( e );
312         }
313     }
314 
315     /**
316      * Create an archetype IT, ie goals.txt and archetype.properties in src/test/resources/projects/basic.
317      *
318      * @param archetypeDescriptor
319      * @param generatedSourcesDirectory
320      * @throws IOException
321      * @since 2.0-alpha-5
322      */
323     private void createArchetypeBasicIt( ArchetypeDescriptor archetypeDescriptor, File generatedSourcesDirectory )
324         throws IOException
325     {
326         String basic =
327             Constants.SRC + File.separator + Constants.TEST + File.separator + Constants.RESOURCES + File.separator
328                 + "projects" + File.separator + "basic";
329         File basicItDirectory = new File( generatedSourcesDirectory, basic );
330         basicItDirectory.mkdirs();
331 
332         File archetypePropertiesFile = new File( basicItDirectory, "archetype.properties" );
333         if ( !archetypePropertiesFile.exists() && !archetypePropertiesFile.createNewFile() )
334         {
335             getLogger().warn( "Could not create new file \"" + archetypePropertiesFile.getPath()
336                     + "\" or the file already exists." );
337         }
338 
339         try ( InputStream in = FilesetArchetypeCreator.class.getResourceAsStream( "archetype.properties" );
340               OutputStream out = new FileOutputStream( archetypePropertiesFile ) )
341         {
342             Properties archetypeProperties = new Properties();
343             archetypeProperties.load( in );
344 
345             for ( RequiredProperty req : archetypeDescriptor.getRequiredProperties() )
346             {
347                 archetypeProperties.put( req.getKey(), req.getDefaultValue() );
348             }
349 
350             archetypeProperties.store( out, null );
351         }
352 
353         copyResource( "goal.txt", new File( basicItDirectory, "goal.txt" ) );
354 
355         getLogger().debug( "Added basic integration test" );
356     }
357 
358     private void extractPropertiesFromProject( MavenProject project, Properties properties,
359                                                Properties configurationProperties, String packageName )
360     {
361         if ( !properties.containsKey( Constants.GROUP_ID ) )
362         {
363             properties.setProperty( Constants.GROUP_ID, project.getGroupId() );
364         }
365         configurationProperties.setProperty( Constants.GROUP_ID, properties.getProperty( Constants.GROUP_ID ) );
366 
367         if ( !properties.containsKey( Constants.ARTIFACT_ID ) )
368         {
369             properties.setProperty( Constants.ARTIFACT_ID, project.getArtifactId() );
370         }
371         configurationProperties.setProperty( Constants.ARTIFACT_ID, properties.getProperty( Constants.ARTIFACT_ID ) );
372 
373         if ( !properties.containsKey( Constants.VERSION ) )
374         {
375             properties.setProperty( Constants.VERSION, project.getVersion() );
376         }
377         configurationProperties.setProperty( Constants.VERSION, properties.getProperty( Constants.VERSION ) );
378 
379         if ( packageName != null )
380         {
381             properties.setProperty( Constants.PACKAGE, packageName );
382         }
383         else if ( !properties.containsKey( Constants.PACKAGE ) )
384         {
385             properties.setProperty( Constants.PACKAGE, project.getGroupId() );
386         }
387         configurationProperties.setProperty( Constants.PACKAGE, properties.getProperty( Constants.PACKAGE ) );
388     }
389 
390     /**
391      * Create the archetype project pom.xml file, that will be used to build the archetype.
392      */
393     private File createArchetypeProjectPom( MavenProject project, ProjectBuildingRequest buildingRequest,
394                                             Properties configurationProperties, File projectDir )
395         throws TemplateCreationException, IOException
396     {
397         Model model = new Model();
398         model.setModelVersion( "4.0.0" );
399         // these values should be retrieved from the request with sensible defaults
400         model.setGroupId( configurationProperties.getProperty( Constants.ARCHETYPE_GROUP_ID, project.getGroupId() ) );
401         model.setArtifactId(
402             configurationProperties.getProperty( Constants.ARCHETYPE_ARTIFACT_ID, project.getArtifactId() ) );
403         model.setVersion( configurationProperties.getProperty( Constants.ARCHETYPE_VERSION, project.getVersion() ) );
404         model.setPackaging( "maven-archetype" );
405         model.setName(
406             configurationProperties.getProperty( Constants.ARCHETYPE_ARTIFACT_ID, project.getArtifactId() ) );
407         model.setUrl( configurationProperties.getProperty( Constants.ARCHETYPE_URL, project.getUrl() ) );
408         model.setDescription(
409             configurationProperties.getProperty( Constants.ARCHETYPE_DESCRIPTION, project.getDescription() ) );
410         model.setLicenses( project.getLicenses() );
411         model.setDevelopers( project.getDevelopers() );
412         model.setScm( project.getScm() );
413         Build build = new Build();
414         model.setBuild( build );
415 
416         // In many cases where we are behind a firewall making Archetypes for work mates we want
417         // to simply be able to deploy the archetypes once we have created them. In order to do
418         // this we want to utilize information from the project we are creating the archetype from.
419         // This will be a fully working project that has been testing and inherits from a POM
420         // that contains deployment information, along with any extensions required for deployment.
421         // We don't want to create archetypes that cannot be deployed after we create them. People
422         // might want to edit the archetype POM but they should not have too.
423 
424         if ( project.getParent() != null )
425         {
426             MavenProject p = project.getParent();
427 
428             if ( p.getDistributionManagement() != null )
429             {
430                 model.setDistributionManagement( p.getDistributionManagement() );
431             }
432 
433             if ( p.getBuildExtensions() != null )
434             {
435                 for ( Extension be : p.getBuildExtensions() )
436                 {
437                     model.getBuild().addExtension( be );
438                 }
439             }
440         }
441 
442         Extension extension = new Extension();
443         extension.setGroupId( "org.apache.maven.archetype" );
444         extension.setArtifactId( "archetype-packaging" );
445         extension.setVersion( getArchetypeVersion() );
446         model.getBuild().addExtension( extension );
447 
448         Plugin plugin = new Plugin();
449         plugin.setGroupId( "org.apache.maven.plugins" );
450         plugin.setArtifactId( "maven-archetype-plugin" );
451         plugin.setVersion( getArchetypeVersion() );
452 
453         PluginManagement pluginManagement = new PluginManagement();
454         pluginManagement.addPlugin( plugin );
455         model.getBuild().setPluginManagement( pluginManagement );
456 
457         getLogger().debug( "Creating archetype's pom" );
458 
459         File archetypePomFile = new File( projectDir, Constants.ARCHETYPE_POM );
460 
461         archetypePomFile.getParentFile().mkdirs();
462 
463         copyResource( "pom-prototype.xml", archetypePomFile );
464 
465         pomManager.writePom( model, archetypePomFile, archetypePomFile );
466 
467         return archetypePomFile;
468     }
469 
470     private void copyResource( String name, File destination )
471         throws IOException
472     {
473         if ( !destination.exists() && !destination.createNewFile() )
474         {
475             getLogger().warn( "Could not create new file \"" + destination.getPath()
476                     + "\" or the file already exists." );
477         }
478 
479         try ( InputStream in = FilesetArchetypeCreator.class.getResourceAsStream( name );
480               OutputStream out = new FileOutputStream( destination ) )
481         {
482             IOUtil.copy( in, out );
483         }
484     }
485 
486     private void addRequiredProperties( ArchetypeDescriptor archetypeDescriptor, Properties properties )
487     {
488         Properties requiredProperties = new Properties();
489         requiredProperties.putAll( properties );
490         requiredProperties.remove( Constants.ARCHETYPE_GROUP_ID );
491         requiredProperties.remove( Constants.ARCHETYPE_ARTIFACT_ID );
492         requiredProperties.remove( Constants.ARCHETYPE_VERSION );
493         requiredProperties.remove( Constants.GROUP_ID );
494         requiredProperties.remove( Constants.ARTIFACT_ID );
495         requiredProperties.remove( Constants.VERSION );
496         requiredProperties.remove( Constants.PACKAGE );
497         requiredProperties.remove( Constants.EXCLUDE_PATTERNS );
498 
499         for ( Iterator<?> propertiesIterator = requiredProperties.keySet().iterator(); propertiesIterator.hasNext(); )
500         {
501             String propertyKey = (String) propertiesIterator.next();
502 
503             RequiredProperty requiredProperty = new RequiredProperty();
504             requiredProperty.setKey( propertyKey );
505             requiredProperty.setDefaultValue( requiredProperties.getProperty( propertyKey ) );
506 
507             archetypeDescriptor.addRequiredProperty( requiredProperty );
508 
509             getLogger().debug(
510                 "Adding requiredProperty " + propertyKey + "=" + requiredProperties.getProperty( propertyKey )
511                     + " to archetype's descriptor" );
512         }
513     }
514 
515     private void createModulePoms( Properties pomReversedProperties, String rootArtifactId, String packageName,
516                                    File basedir, File archetypeFilesDirectory, boolean preserveCData,
517                                    boolean keepParent )
518         throws FileNotFoundException, IOException, XmlPullParserException
519     {
520         Model pom = pomManager.readPom( FileUtils.resolveFile( basedir, Constants.ARCHETYPE_POM ) );
521 
522         String parentArtifactId = pomReversedProperties.getProperty( Constants.PARENT_ARTIFACT_ID );
523         String artifactId = pom.getArtifactId();
524         setParentArtifactId( pomReversedProperties, pomReversedProperties.getProperty( Constants.ARTIFACT_ID ) );
525         setArtifactId( pomReversedProperties, pom.getArtifactId() );
526 
527         for ( String subModuleId : pom.getModules() )
528         {
529             String subModuleIdDirectory = subModuleId;
530 
531             if ( subModuleId.indexOf( rootArtifactId ) >= 0 )
532             {
533                 subModuleIdDirectory = StringUtils.replace( subModuleId, rootArtifactId, "__rootArtifactId__" );
534             }
535 
536             createModulePoms( pomReversedProperties, rootArtifactId, packageName,
537                               FileUtils.resolveFile( basedir, subModuleId ),
538                               FileUtils.resolveFile( archetypeFilesDirectory, subModuleIdDirectory ), preserveCData,
539                               keepParent );
540         }
541 
542         createModulePom( pom, rootArtifactId, archetypeFilesDirectory, pomReversedProperties,
543                          FileUtils.resolveFile( basedir, Constants.ARCHETYPE_POM ), preserveCData, keepParent );
544 
545         restoreParentArtifactId( pomReversedProperties, parentArtifactId );
546         restoreArtifactId( pomReversedProperties, artifactId );
547     }
548 
549     private void createPoms( Model pom, String rootArtifactId, String artifactId, File archetypeFilesDirectory,
550                              File basedir, File rootPom, Properties pomReversedProperties, boolean preserveCData,
551                              boolean keepParent )
552         throws IOException, FileNotFoundException, XmlPullParserException
553     {
554         setArtifactId( pomReversedProperties, pom.getArtifactId() );
555 
556         for ( String moduleId : pom.getModules() )
557         {
558             String moduleIdDirectory = moduleId;
559 
560             if ( moduleId.indexOf( rootArtifactId ) >= 0 )
561             {
562                 moduleIdDirectory = StringUtils.replace( moduleId, rootArtifactId, "__rootArtifactId__" );
563             }
564 
565             createModulePoms( pomReversedProperties, rootArtifactId, moduleId,
566                               FileUtils.resolveFile( basedir, moduleId ),
567                               new File( archetypeFilesDirectory, moduleIdDirectory ), preserveCData, keepParent );
568         }
569 
570         restoreParentArtifactId( pomReversedProperties, null );
571         restoreArtifactId( pomReversedProperties, artifactId );
572 
573         createArchetypePom( pom, archetypeFilesDirectory, pomReversedProperties, rootPom, preserveCData, keepParent );
574     }
575 
576     private String getPackageInPathFormat( String aPackage )
577     {
578         return StringUtils.replace( aPackage, ".", "/" );
579     }
580 
581     private void rewriteReferences( Model pom, String rootArtifactId, String groupId )
582     {
583         // rewrite Dependencies
584         if ( pom.getDependencies() != null && !pom.getDependencies().isEmpty() )
585         {
586             for ( Dependency dependency : pom.getDependencies() )
587             {
588                 rewriteDependencyReferences( dependency, rootArtifactId, groupId );
589             }
590         }
591 
592         // rewrite DependencyManagement
593         if ( pom.getDependencyManagement() != null && pom.getDependencyManagement().getDependencies() != null
594             && !pom.getDependencyManagement().getDependencies().isEmpty() )
595         {
596             for ( Dependency dependency : pom.getDependencyManagement().getDependencies() )
597             {
598                 rewriteDependencyReferences( dependency, rootArtifactId, groupId );
599             }
600         }
601 
602         // rewrite Plugins
603         if ( pom.getBuild() != null && pom.getBuild().getPlugins() != null && !pom.getBuild().getPlugins().isEmpty() )
604         {
605             for ( Plugin plugin : pom.getBuild().getPlugins() )
606             {
607                 rewritePluginReferences( plugin, rootArtifactId, groupId );
608             }
609         }
610 
611         // rewrite PluginManagement
612         if ( pom.getBuild() != null && pom.getBuild().getPluginManagement() != null
613             && pom.getBuild().getPluginManagement().getPlugins() != null
614             && !pom.getBuild().getPluginManagement().getPlugins().isEmpty() )
615         {
616             for ( Plugin plugin : pom.getBuild().getPluginManagement().getPlugins() )
617             {
618                 rewritePluginReferences( plugin, rootArtifactId, groupId );
619             }
620         }
621 
622         // rewrite Profiles
623         if ( pom.getProfiles() != null )
624         {
625             for ( Profile profile : pom.getProfiles() )
626             {
627                 // rewrite Dependencies
628                 if ( profile.getDependencies() != null && !profile.getDependencies().isEmpty() )
629                 {
630                     for ( Dependency dependency : profile.getDependencies() )
631                     {
632                         rewriteDependencyReferences( dependency, rootArtifactId, groupId );
633                     }
634                 }
635 
636                 // rewrite DependencyManagement
637                 if ( profile.getDependencyManagement() != null
638                     && profile.getDependencyManagement().getDependencies() != null
639                     && !profile.getDependencyManagement().getDependencies().isEmpty() )
640                 {
641                     for ( Dependency dependency : profile.getDependencyManagement().getDependencies() )
642                     {
643                         rewriteDependencyReferences( dependency, rootArtifactId, groupId );
644                     }
645                 }
646 
647                 // rewrite Plugins
648                 if ( profile.getBuild() != null && profile.getBuild().getPlugins() != null
649                     && !profile.getBuild().getPlugins().isEmpty() )
650                 {
651                     for ( Plugin plugin : profile.getBuild().getPlugins() )
652                     {
653                         rewritePluginReferences( plugin, rootArtifactId, groupId );
654                     }
655                 }
656 
657                 // rewrite PluginManagement
658                 if ( profile.getBuild() != null && profile.getBuild().getPluginManagement() != null
659                     && profile.getBuild().getPluginManagement().getPlugins() != null
660                     && !profile.getBuild().getPluginManagement().getPlugins().isEmpty() )
661                 {
662                     for ( Plugin plugin : profile.getBuild().getPluginManagement().getPlugins() )
663                     {
664                         rewritePluginReferences( plugin, rootArtifactId, groupId );
665                     }
666                 }
667             }
668         }
669     }
670 
671     private void rewriteDependencyReferences( Dependency dependency, String rootArtifactId, String groupId )
672     {
673         if ( dependency.getArtifactId() != null && dependency.getArtifactId().indexOf( rootArtifactId ) >= 0 )
674         {
675             if ( dependency.getGroupId() != null )
676             {
677                 dependency.setGroupId(
678                     StringUtils.replace( dependency.getGroupId(), groupId, "${" + Constants.GROUP_ID + "}" ) );
679             }
680 
681             dependency.setArtifactId(
682                 StringUtils.replace( dependency.getArtifactId(), rootArtifactId, "${rootArtifactId}" ) );
683 
684             if ( dependency.getVersion() != null )
685             {
686                 dependency.setVersion( "${" + Constants.VERSION + "}" );
687             }
688         }
689     }
690 
691     private void rewritePluginReferences( Plugin plugin, String rootArtifactId, String groupId )
692     {
693         if ( plugin.getArtifactId() != null && plugin.getArtifactId().indexOf( rootArtifactId ) >= 0 )
694         {
695             if ( plugin.getGroupId() != null )
696             {
697                 String g = StringUtils.replace( plugin.getGroupId(), groupId, "${" + Constants.GROUP_ID + "}" );
698                 plugin.setGroupId( g );
699             }
700 
701             plugin.setArtifactId( StringUtils.replace( plugin.getArtifactId(), rootArtifactId, "${rootArtifactId}" ) );
702 
703             if ( plugin.getVersion() != null )
704             {
705                 plugin.setVersion( "${" + Constants.VERSION + "}" );
706             }
707         }
708 
709         if ( plugin.getArtifactId() != null && "maven-ear-plugin".equals( plugin.getArtifactId() ) )
710         {
711             rewriteEARPluginReferences( plugin, rootArtifactId, groupId );
712         }
713     }
714 
715     private void rewriteEARPluginReferences( Plugin plugin, String rootArtifactId, String groupId )
716     {
717         Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration();
718         if ( configuration != null )
719         {
720             Xpp3Dom[] modules = configuration.getChild( "modules" ).getChildren();
721             for ( int i = 0; i < modules.length; i++ )
722             {
723                 Xpp3Dom module = modules[i];
724                 Xpp3Dom moduleGroupId = module.getChild( "groupId" );
725                 Xpp3Dom moduleArtifactId = module.getChild( "artifactId" );
726                 Xpp3Dom moduleBundleFileName = module.getChild( "bundleFileName" );
727                 Xpp3Dom moduleModuleId = module.getChild( "moduleId" );
728                 Xpp3Dom moduleContextRoot = module.getChild( "contextRoot" );
729 
730                 if ( moduleGroupId != null )
731                 {
732                     moduleGroupId.setValue(
733                         StringUtils.replace( moduleGroupId.getValue(), groupId, "${" + Constants.GROUP_ID + "}" ) );
734                 }
735 
736                 if ( moduleArtifactId != null )
737                 {
738                     moduleArtifactId.setValue(
739                         StringUtils.replace( moduleArtifactId.getValue(), rootArtifactId, "${rootArtifactId}" ) );
740                 }
741 
742                 if ( moduleBundleFileName != null )
743                 {
744                     moduleBundleFileName.setValue(
745                         StringUtils.replace( moduleBundleFileName.getValue(), rootArtifactId, "${rootArtifactId}" ) );
746                 }
747 
748                 if ( moduleModuleId != null )
749                 {
750                     moduleModuleId.setValue(
751                         StringUtils.replace( moduleModuleId.getValue(), rootArtifactId, "${rootArtifactId}" ) );
752                 }
753 
754                 if ( moduleContextRoot != null )
755                 {
756                     moduleContextRoot.setValue(
757                         StringUtils.replace( moduleContextRoot.getValue(), rootArtifactId, "${rootArtifactId}" ) );
758                 }
759             }
760         }
761     }
762 
763     private void setArtifactId( Properties properties, String artifactId )
764     {
765         properties.setProperty( Constants.ARTIFACT_ID, artifactId );
766     }
767 
768     private List<String> concatenateToList( List<String> toConcatenate, String with )
769     {
770         List<String> result = new ArrayList<>( toConcatenate.size() );
771 
772         for ( String concatenate : toConcatenate )
773         {
774             result.add( ( ( with.length() > 0 ) ? ( with + "/" + concatenate ) : concatenate ) );
775         }
776 
777         return result;
778     }
779 
780     private List<String> addLists( List<String> list, List<String> other )
781     {
782         List<String> result = new ArrayList<>( list.size() + other.size() );
783         result.addAll( list );
784         result.addAll( other );
785         return result;
786     }
787 
788     private void copyFiles( File basedir, File archetypeFilesDirectory, String directory, List<String> fileSetResources,
789                             boolean packaged, String packageName, Properties reverseProperties )
790         throws IOException
791     {
792         String packageAsDirectory = StringUtils.replace( packageName, ".", File.separator );
793 
794         getLogger().debug( "Package as Directory: Package:" + packageName + "->" + packageAsDirectory );
795 
796         for ( String inputFileName : fileSetResources )
797         {
798             String outputFileName = packaged
799                 ? StringUtils.replace( inputFileName, packageAsDirectory + File.separator, "" )
800                 : inputFileName;
801             getLogger().debug( "InputFileName:" + inputFileName );
802             getLogger().debug( "OutputFileName:" + outputFileName );
803 
804             reverseProperties.remove( "archetype.languages" );
805 
806             String reversedOutputFilename = getReversedFilename( outputFileName, reverseProperties );
807 
808             File outputFile = new File( archetypeFilesDirectory, reversedOutputFilename );
809 
810             File inputFile = new File( basedir, inputFileName );
811 
812             outputFile.getParentFile().mkdirs();
813 
814             FileUtils.copyFile( inputFile, outputFile );
815         }
816     }
817 
818     private void createArchetypeFiles( Properties reverseProperties, List<FileSet> fileSets, String packageName,
819                                        File basedir, File archetypeFilesDirectory, String defaultEncoding,
820                                        List<String> excludePatterns )
821         throws IOException
822     {
823         getLogger().debug( "Creating Archetype/Module files from " + basedir + " to " + archetypeFilesDirectory );
824 
825         for ( FileSet fileSet : fileSets )
826         {
827             DirectoryScanner scanner = new DirectoryScanner();
828             scanner.setBasedir( basedir );
829             scanner.setIncludes( concatenateToList( fileSet.getIncludes(), fileSet.getDirectory() ).toArray(
830                 new String[fileSet.getIncludes().size()] ) );
831             scanner.setExcludes( addLists( fileSet.getExcludes(), excludePatterns ).toArray(
832                 new String[fileSet.getExcludes().size()] ) );
833             scanner.addDefaultExcludes();
834             getLogger().debug( "Using fileset " + fileSet );
835             scanner.scan();
836 
837             List<String> fileSetResources = Arrays.asList( scanner.getIncludedFiles() );
838             getLogger().debug( "Scanned " + fileSetResources.size() + " resources" );
839 
840             if ( fileSet.isFiltered() )
841             {
842                 processFileSet( basedir, archetypeFilesDirectory, fileSet.getDirectory(), fileSetResources,
843                                 fileSet.isPackaged(), packageName, reverseProperties, defaultEncoding );
844                 getLogger().debug( "Processed " + fileSet.getDirectory() + " files" );
845             }
846             else
847             {
848                 copyFiles( basedir, archetypeFilesDirectory, fileSet.getDirectory(), fileSetResources,
849                            fileSet.isPackaged(), packageName, reverseProperties );
850                 getLogger().debug( "Copied " + fileSet.getDirectory() + " files" );
851             }
852         }
853     }
854 
855     private void createArchetypePom( Model pom, File archetypeFilesDirectory, Properties pomReversedProperties,
856                                      File initialPomFile, boolean preserveCData, boolean keepParent )
857         throws IOException
858     {
859         File outputFile = FileUtils.resolveFile( archetypeFilesDirectory, Constants.ARCHETYPE_POM );
860 
861         if ( preserveCData )
862         {
863             getLogger().debug( "Preserving CDATA parts of pom" );
864             File inputFile = FileUtils.resolveFile( archetypeFilesDirectory, Constants.ARCHETYPE_POM + ".tmp" );
865 
866             FileUtils.copyFile( initialPomFile, inputFile );
867 
868             outputFile.getParentFile().mkdirs();
869 
870             try ( Reader in = ReaderFactory.newXmlReader( inputFile );
871                   Writer out = WriterFactory.newXmlWriter( outputFile ) )
872             {
873                 String initialcontent = IOUtil.toString( in );
874 
875                 String content = getReversedContent( initialcontent, pomReversedProperties );
876 
877                 IOUtil.copy( content, out );
878             }
879 
880             inputFile.delete();
881         }
882         else
883         {
884             if ( !keepParent )
885             {
886                 pom.setParent( null );
887             }
888 
889             pom.setModules( null );
890             pom.setGroupId( "${" + Constants.GROUP_ID + "}" );
891             pom.setArtifactId( "${" + Constants.ARTIFACT_ID + "}" );
892             pom.setVersion( "${" + Constants.VERSION + "}" );
893             pom.setName( getReversedPlainContent( pom.getName(), pomReversedProperties ) );
894             pom.setDescription( getReversedPlainContent( pom.getDescription(), pomReversedProperties ) );
895             pom.setUrl( getReversedPlainContent( pom.getUrl(), pomReversedProperties ) );
896 
897             rewriteReferences( pom, pomReversedProperties.getProperty( Constants.ARTIFACT_ID ),
898                                pomReversedProperties.getProperty( Constants.GROUP_ID ) );
899 
900             pomManager.writePom( pom, outputFile, initialPomFile );
901         }
902 
903         try ( Reader in = ReaderFactory.newXmlReader( initialPomFile ) )
904         {
905             String initialcontent = IOUtil.toString( in );
906 
907             Iterator<?> properties = pomReversedProperties.keySet().iterator();
908             while ( properties.hasNext() )
909             {
910                 String property = (String) properties.next();
911 
912                 if ( initialcontent.indexOf( "${" + property + "}" ) > 0 )
913                 {
914                     getLogger().warn(
915                         "Archetype uses ${" + property + "} for internal processing, but file " + initialPomFile
916                             + " contains this property already" );
917                 }
918             }
919         }
920     }
921 
922     private FileSet createFileSet( final List<String> excludes, final boolean packaged, final boolean filtered,
923                                    final String group, final List<String> includes, String defaultEncoding )
924     {
925         FileSet fileSet = new FileSet();
926 
927         fileSet.setDirectory( group );
928         fileSet.setPackaged( packaged );
929         fileSet.setFiltered( filtered );
930         fileSet.setIncludes( includes );
931         fileSet.setExcludes( excludes );
932         fileSet.setEncoding( defaultEncoding );
933 
934         getLogger().debug( "Created Fileset " + fileSet );
935 
936         return fileSet;
937     }
938 
939     private List<FileSet> createFileSets( List<String> files, int level, boolean packaged, String packageName,
940                                           boolean filtered, String defaultEncoding )
941     {
942         List<FileSet> fileSets = new ArrayList<>();
943 
944         if ( !files.isEmpty() )
945         {
946             getLogger().debug( "Creating filesets" + ( packaged ? ( " packaged (" + packageName + ")" ) : "" ) + (
947                 filtered
948                     ? " filtered"
949                     : "" ) + " at level " + level );
950             if ( level == 0 )
951             {
952                 List<String> includes = new ArrayList<>( files );
953                 List<String> excludes = new ArrayList<>();
954 
955                 if ( !includes.isEmpty() )
956                 {
957                     fileSets.add( createFileSet( excludes, packaged, filtered, "", includes, defaultEncoding ) );
958                 }
959             }
960             else
961             {
962                 Map<String, List<String>> groups = getGroupsMap( files, level );
963 
964                 for ( String group : groups.keySet() )
965                 {
966                     getLogger().debug( "Creating filesets for group " + group );
967 
968                     if ( !packaged )
969                     {
970                         fileSets.add( getUnpackagedFileSet( filtered, group, groups.get( group ), defaultEncoding ) );
971                     }
972                     else
973                     {
974                         fileSets.addAll(
975                             getPackagedFileSets( filtered, group, groups.get( group ), packageName, defaultEncoding ) );
976                     }
977                 }
978             } // end if
979 
980             getLogger().debug( "Resolved fileSets " + fileSets );
981         } // end if
982 
983         return fileSets;
984     }
985 
986     private ModuleDescriptor createModule( Properties reverseProperties, String rootArtifactId, String moduleId,
987                                            String packageName, File basedir, File archetypeFilesDirectory,
988                                            List<String> languages, List<String> filtereds, String defaultEncoding,
989                                            boolean preserveCData, boolean keepParent )
990         throws IOException, XmlPullParserException
991     {
992         ModuleDescriptor archetypeDescriptor = new ModuleDescriptor();
993         getLogger().debug( "Starting module's descriptor " + moduleId );
994 
995         archetypeFilesDirectory.mkdirs();
996         getLogger().debug( "Module's files output directory " + archetypeFilesDirectory );
997 
998         Model pom = pomManager.readPom( FileUtils.resolveFile( basedir, Constants.ARCHETYPE_POM ) );
999         String replacementId = pom.getArtifactId();
1000         String moduleDirectory = pom.getArtifactId();
1001 
1002         if ( replacementId.indexOf( rootArtifactId ) >= 0 )
1003         {
1004             replacementId = StringUtils.replace( replacementId, rootArtifactId, "${rootArtifactId}" );
1005             moduleDirectory = StringUtils.replace( moduleId, rootArtifactId, "__rootArtifactId__" );
1006         }
1007 
1008         if ( moduleId.indexOf( rootArtifactId ) >= 0 )
1009         {
1010             moduleDirectory = StringUtils.replace( moduleId, rootArtifactId, "__rootArtifactId__" );
1011         }
1012 
1013         archetypeDescriptor.setName( replacementId );
1014         archetypeDescriptor.setId( replacementId );
1015         archetypeDescriptor.setDir( moduleDirectory );
1016 
1017         setArtifactId( reverseProperties, pom.getArtifactId() );
1018 
1019         List<String> excludePatterns =
1020             reverseProperties.getProperty( Constants.EXCLUDE_PATTERNS ) != null
1021                 ? Arrays.asList( StringUtils.split( reverseProperties.getProperty( Constants.EXCLUDE_PATTERNS ), "," ) )
1022                 : Collections.<String>emptyList();
1023 
1024         List<String> fileNames = resolveFileNames( pom, basedir, excludePatterns );
1025 
1026         List<FileSet> filesets = resolveFileSets( packageName, fileNames, languages, filtereds, defaultEncoding );
1027         getLogger().debug( "Resolved filesets for module " + archetypeDescriptor.getName() );
1028 
1029         archetypeDescriptor.setFileSets( filesets );
1030 
1031         createArchetypeFiles( reverseProperties, filesets, packageName, basedir, archetypeFilesDirectory,
1032                               defaultEncoding, excludePatterns );
1033         getLogger().debug( "Created files for module " + archetypeDescriptor.getName() );
1034 
1035         String parentArtifactId = reverseProperties.getProperty( Constants.PARENT_ARTIFACT_ID );
1036         setParentArtifactId( reverseProperties, pom.getArtifactId() );
1037 
1038         for ( String subModuleId : pom.getModules() )
1039         {
1040             String subModuleIdDirectory = subModuleId;
1041             if ( subModuleId.indexOf( rootArtifactId ) >= 0 )
1042             {
1043                 subModuleIdDirectory = StringUtils.replace( subModuleId, rootArtifactId, "__rootArtifactId__" );
1044             }
1045 
1046             getLogger().debug( "Creating module " + subModuleId );
1047 
1048             ModuleDescriptor moduleDescriptor =
1049                 createModule( reverseProperties, rootArtifactId, subModuleId, packageName,
1050                               FileUtils.resolveFile( basedir, subModuleId ),
1051                               FileUtils.resolveFile( archetypeFilesDirectory, subModuleIdDirectory ), languages,
1052                               filtereds, defaultEncoding, preserveCData, keepParent );
1053 
1054             archetypeDescriptor.addModule( moduleDescriptor );
1055 
1056             getLogger().debug( "Added module " + moduleDescriptor.getName() + " in " + archetypeDescriptor.getName() );
1057         }
1058 
1059         restoreParentArtifactId( reverseProperties, parentArtifactId );
1060         restoreArtifactId( reverseProperties, pom.getArtifactId() );
1061 
1062         getLogger().debug( "Created Module " + archetypeDescriptor.getName() + " pom" );
1063 
1064         return archetypeDescriptor;
1065     }
1066 
1067     private void createModulePom( Model pom, String rootArtifactId, File archetypeFilesDirectory,
1068                                   Properties pomReversedProperties, File initialPomFile, boolean preserveCData,
1069                                   boolean keepParent )
1070         throws IOException
1071     {
1072         File outputFile = FileUtils.resolveFile( archetypeFilesDirectory, Constants.ARCHETYPE_POM );
1073 
1074         if ( preserveCData )
1075         {
1076             getLogger().debug( "Preserving CDATA parts of pom" );
1077             File inputFile = FileUtils.resolveFile( archetypeFilesDirectory, Constants.ARCHETYPE_POM + ".tmp" );
1078 
1079             FileUtils.copyFile( initialPomFile, inputFile );
1080 
1081             outputFile.getParentFile().mkdirs();
1082 
1083             try ( Reader in = ReaderFactory.newXmlReader( inputFile );
1084                   Writer out = WriterFactory.newXmlWriter( outputFile ) )
1085             {
1086                 String initialcontent = IOUtil.toString( in );
1087 
1088                 String content = getReversedContent( initialcontent, pomReversedProperties );
1089 
1090                 IOUtil.copy( content, out );
1091             }
1092 
1093             inputFile.delete();
1094         }
1095         else
1096         {
1097             if ( pom.getParent() != null )
1098             {
1099                 pom.getParent().setGroupId( StringUtils.replace( pom.getParent().getGroupId(),
1100                                                                  pomReversedProperties.getProperty(
1101                                                                      Constants.GROUP_ID ),
1102                                                                  "${" + Constants.GROUP_ID + "}" ) );
1103                 if ( pom.getParent().getArtifactId() != null
1104                     && pom.getParent().getArtifactId().indexOf( rootArtifactId ) >= 0 )
1105                 {
1106                     pom.getParent().setArtifactId(
1107                         StringUtils.replace( pom.getParent().getArtifactId(), rootArtifactId, "${rootArtifactId}" ) );
1108                 }
1109                 if ( pom.getParent().getVersion() != null )
1110                 {
1111                     pom.getParent().setVersion( "${" + Constants.VERSION + "}" );
1112                 }
1113             }
1114             pom.setModules( null );
1115 
1116             if ( pom.getGroupId() != null )
1117             {
1118                 pom.setGroupId(
1119                     StringUtils.replace( pom.getGroupId(), pomReversedProperties.getProperty( Constants.GROUP_ID ),
1120                                          "${" + Constants.GROUP_ID + "}" ) );
1121             }
1122 
1123             pom.setArtifactId( "${" + Constants.ARTIFACT_ID + "}" );
1124 
1125             if ( pom.getVersion() != null )
1126             {
1127                 pom.setVersion( "${" + Constants.VERSION + "}" );
1128             }
1129 
1130             pom.setName( getReversedPlainContent( pom.getName(), pomReversedProperties ) );
1131             pom.setDescription( getReversedPlainContent( pom.getDescription(), pomReversedProperties ) );
1132             pom.setUrl( getReversedPlainContent( pom.getUrl(), pomReversedProperties ) );
1133 
1134             rewriteReferences( pom, rootArtifactId, pomReversedProperties.getProperty( Constants.GROUP_ID ) );
1135 
1136             pomManager.writePom( pom, outputFile, initialPomFile );
1137         }
1138 
1139         try ( Reader in = ReaderFactory.newXmlReader( initialPomFile ) )
1140         {
1141             String initialcontent = IOUtil.toString( in );
1142 
1143             for ( Iterator<?> properties = pomReversedProperties.keySet().iterator(); properties.hasNext(); )
1144             {
1145                 String property = (String) properties.next();
1146 
1147                 if ( initialcontent.indexOf( "${" + property + "}" ) > 0 )
1148                 {
1149                     getLogger().warn(
1150                         "OldArchetype uses ${" + property + "} for internal processing, but file " + initialPomFile
1151                             + " contains this property already" );
1152                 }
1153             }
1154         }
1155     }
1156 
1157     private Set<String> getExtensions( List<String> files )
1158     {
1159         Set<String> extensions = new HashSet<>();
1160 
1161         for ( String file : files )
1162         {
1163             extensions.add( FileUtils.extension( file ) );
1164         }
1165 
1166         return extensions;
1167     }
1168 
1169     private Map<String, List<String>> getGroupsMap( final List<String> files, final int level )
1170     {
1171         Map<String, List<String>> groups = new HashMap<>();
1172 
1173         for ( String file : files )
1174         {
1175             String directory = PathUtils.getDirectory( file, level );
1176             // make all groups have unix style
1177             directory = StringUtils.replace( directory, File.separator, "/" );
1178 
1179             if ( !groups.containsKey( directory ) )
1180             {
1181                 groups.put( directory, new ArrayList<String>() );
1182             }
1183 
1184             List<String> group = groups.get( directory );
1185 
1186             String innerPath = file.substring( directory.length() + 1 );
1187             // make all groups have unix style
1188             innerPath = StringUtils.replace( innerPath, File.separator, "/" );
1189 
1190             group.add( innerPath );
1191         }
1192 
1193         getLogger().debug( "Sorted " + groups.size() + " groups in " + files.size() + " files" );
1194         getLogger().debug( "Sorted Files: " + files );
1195 
1196         return groups;
1197     }
1198 
1199     private FileSet getPackagedFileSet( final boolean filtered, final Set<String> packagedExtensions,
1200                                         final String group, final Set<String> unpackagedExtensions,
1201                                         final List<String> unpackagedFiles, String defaultEncoding )
1202     {
1203         List<String> includes = new ArrayList<>();
1204         List<String> excludes = new ArrayList<>();
1205 
1206         for ( String extension : packagedExtensions )
1207         {
1208             includes.add( "**/*." + extension );
1209 
1210             if ( unpackagedExtensions.contains( extension ) )
1211             {
1212                 excludes.addAll( archetypeFilesResolver.getFilesWithExtension( unpackagedFiles, extension ) );
1213             }
1214         }
1215 
1216         return createFileSet( excludes, true, filtered, group, includes, defaultEncoding );
1217     }
1218 
1219     private List<FileSet> getPackagedFileSets( final boolean filtered, final String group,
1220                                                final List<String> groupFiles, final String packageName,
1221                                                String defaultEncoding )
1222     {
1223         String packageAsDir = StringUtils.replace( packageName, ".", "/" );
1224 
1225         List<FileSet> packagedFileSets = new ArrayList<>();
1226         List<String> packagedFiles = archetypeFilesResolver.getPackagedFiles( groupFiles, packageAsDir );
1227         getLogger().debug( "Found packaged Files:" + packagedFiles );
1228 
1229         List<String> unpackagedFiles = archetypeFilesResolver.getUnpackagedFiles( groupFiles, packageAsDir );
1230         getLogger().debug( "Found unpackaged Files:" + unpackagedFiles );
1231 
1232         Set<String> packagedExtensions = getExtensions( packagedFiles );
1233         getLogger().debug( "Found packaged extensions " + packagedExtensions );
1234 
1235         Set<String> unpackagedExtensions = getExtensions( unpackagedFiles );
1236 
1237         if ( !packagedExtensions.isEmpty() )
1238         {
1239             packagedFileSets.add(
1240                 getPackagedFileSet( filtered, packagedExtensions, group, unpackagedExtensions, unpackagedFiles,
1241                                     defaultEncoding ) );
1242         }
1243 
1244         if ( !unpackagedExtensions.isEmpty() )
1245         {
1246             getLogger().debug( "Found unpackaged extensions " + unpackagedExtensions );
1247 
1248             packagedFileSets.add(
1249                 getUnpackagedFileSet( filtered, unpackagedExtensions, unpackagedFiles, group, packagedExtensions,
1250                                       defaultEncoding ) );
1251         }
1252 
1253         return packagedFileSets;
1254     }
1255 
1256     private void setParentArtifactId( Properties properties, String parentArtifactId )
1257     {
1258         properties.setProperty( Constants.PARENT_ARTIFACT_ID, parentArtifactId );
1259     }
1260 
1261     private void processFileSet( File basedir, File archetypeFilesDirectory, String directory,
1262                                  List<String> fileSetResources, boolean packaged, String packageName,
1263                                  Properties reverseProperties, String defaultEncoding )
1264         throws IOException
1265     {
1266         String packageAsDirectory = StringUtils.replace( packageName, ".", File.separator );
1267 
1268         getLogger().debug( "Package as Directory: Package:" + packageName + "->" + packageAsDirectory );
1269 
1270         for ( String inputFileName : fileSetResources )
1271         {
1272             String initialFilename = packaged
1273                 ? StringUtils.replace( inputFileName, packageAsDirectory + File.separator, "" )
1274                 : inputFileName;
1275 
1276             getLogger().debug( "InputFileName:" + inputFileName );
1277 
1278             File inputFile = new File( basedir, inputFileName );
1279 
1280             FileCharsetDetector detector = new FileCharsetDetector( inputFile );
1281 
1282             String fileEncoding = detector.isFound() ? detector.getCharset() : defaultEncoding;
1283 
1284             String initialcontent = IOUtil.toString( new FileInputStream( inputFile ), fileEncoding );
1285 
1286             for ( Iterator<?> properties = reverseProperties.keySet().iterator(); properties.hasNext(); )
1287             {
1288                 String property = (String) properties.next();
1289 
1290                 if ( initialcontent.indexOf( "${" + property + "}" ) > 0 )
1291                 {
1292                     getLogger().warn(
1293                         "Archetype uses ${" + property + "} for internal processing, but file " + inputFile
1294                             + " contains this property already" );
1295                 }
1296             }
1297 
1298             String content = getReversedContent( initialcontent, reverseProperties );
1299             String outputFilename = getReversedFilename( initialFilename, reverseProperties );
1300 
1301             getLogger().debug( "OutputFileName:" + outputFilename );
1302 
1303             File outputFile = new File( archetypeFilesDirectory, outputFilename );
1304             outputFile.getParentFile().mkdirs();
1305 
1306             if ( !outputFile.exists() && !outputFile.createNewFile() )
1307             {
1308                 getLogger().warn( "Could not create new file \"" + outputFile.getPath()
1309                         + "\" or the file already exists." );
1310             }
1311 
1312             try ( OutputStream os = new FileOutputStream( outputFile ) )
1313             {
1314                 write( content, os, fileEncoding );
1315             }
1316         }
1317     }
1318 
1319     private Properties getReversedProperties( ArchetypeDescriptor archetypeDescriptor, Properties properties )
1320     {
1321         Properties reversedProperties = new Properties();
1322 
1323         reversedProperties.putAll( properties );
1324         reversedProperties.remove( Constants.ARCHETYPE_GROUP_ID );
1325         reversedProperties.remove( Constants.ARCHETYPE_ARTIFACT_ID );
1326         reversedProperties.remove( Constants.ARCHETYPE_VERSION );
1327 
1328         String packageName = properties.getProperty( Constants.PACKAGE );
1329         String packageInPathFormat = getPackageInPathFormat( packageName );
1330         if ( !packageInPathFormat.equals( packageName ) )
1331         {
1332             reversedProperties.setProperty( Constants.PACKAGE_IN_PATH_FORMAT, packageInPathFormat );
1333         }
1334 
1335         // TODO check that reversed properties are all different and no one is a substring of another?
1336         // to avoid wrong variable replacements
1337 
1338         return reversedProperties;
1339     }
1340 
1341     private List<String> resolveFileNames( final Model pom, final File basedir, List<String> excludePatterns )
1342         throws IOException
1343     {
1344         getLogger().debug( "Resolving files for " + pom.getId() + " in " + basedir );
1345 
1346         StringBuilder buff = new StringBuilder( "pom.xml*,archetype.properties*,target/**," );
1347         for ( String module : pom.getModules() )
1348         {
1349             buff.append( ',' ).append( module ).append( "/**" );
1350         }
1351 
1352         for ( String defaultExclude : ListScanner.DEFAULTEXCLUDES )
1353         {
1354             buff.append( ',' ).append( defaultExclude ).append( "/**" );
1355         }
1356 
1357         for ( String excludePattern : excludePatterns )
1358         {
1359             buff.append( ',' ).append( excludePattern );
1360         }
1361 
1362         String excludes = PathUtils.convertPathForOS( buff.toString() );
1363 
1364         List<String> fileNames = FileUtils.getFileNames( basedir, "**,.*,**/.*", excludes, false );
1365 
1366         getLogger().debug( "Resolved " + fileNames.size() + " files" );
1367         getLogger().debug( "Resolved Files:" + fileNames );
1368 
1369         return fileNames;
1370     }
1371 
1372     private List<FileSet> resolveFileSets( String packageName, List<String> fileNames, List<String> languages,
1373                                            List<String> filtereds, String defaultEncoding )
1374     {
1375         List<FileSet> resolvedFileSets = new ArrayList<>();
1376         getLogger().debug(
1377             "Resolving filesets with package=" + packageName + ", languages=" + languages + " and extentions="
1378                 + filtereds );
1379 
1380         List<String> files = new ArrayList<>( fileNames );
1381 
1382         StringBuilder languageIncludes = new StringBuilder();
1383 
1384         for ( String language : languages )
1385         {
1386             languageIncludes.append( ( ( languageIncludes.length() == 0 ) ? "" : "," ) + language + "/**" );
1387         }
1388 
1389         getLogger().debug( "Using languages includes " + languageIncludes );
1390 
1391         StringBuilder filteredIncludes = new StringBuilder();
1392         for ( String filtered : filtereds )
1393         {
1394             filteredIncludes.append(
1395                 ( ( filteredIncludes.length() == 0 ) ? "" : "," ) + "**/" + ( filtered.startsWith( "." ) ? "" : "*." )
1396                     + filtered );
1397         }
1398 
1399         getLogger().debug( "Using filtered includes " + filteredIncludes );
1400 
1401         /* sourcesMainFiles */
1402         List<String> sourcesMainFiles =
1403             archetypeFilesResolver.findSourcesMainFiles( files, languageIncludes.toString() );
1404         if ( !sourcesMainFiles.isEmpty() )
1405         {
1406             files.removeAll( sourcesMainFiles );
1407 
1408             List<String> filteredFiles =
1409                 archetypeFilesResolver.getFilteredFiles( sourcesMainFiles, filteredIncludes.toString() );
1410             sourcesMainFiles.removeAll( filteredFiles );
1411 
1412             List<String> unfilteredFiles = sourcesMainFiles;
1413             if ( !filteredFiles.isEmpty() )
1414             {
1415                 resolvedFileSets.addAll( createFileSets( filteredFiles, 3, true, packageName, true, defaultEncoding ) );
1416             }
1417 
1418             if ( !unfilteredFiles.isEmpty() )
1419             {
1420                 resolvedFileSets.addAll(
1421                     createFileSets( unfilteredFiles, 3, true, packageName, false, defaultEncoding ) );
1422             }
1423         }
1424 
1425         /* resourcesMainFiles */
1426         List<String> resourcesMainFiles =
1427             archetypeFilesResolver.findResourcesMainFiles( files, languageIncludes.toString() );
1428         if ( !resourcesMainFiles.isEmpty() )
1429         {
1430             files.removeAll( resourcesMainFiles );
1431 
1432             List<String> filteredFiles =
1433                 archetypeFilesResolver.getFilteredFiles( resourcesMainFiles, filteredIncludes.toString() );
1434             resourcesMainFiles.removeAll( filteredFiles );
1435 
1436             List<String> unfilteredFiles = resourcesMainFiles;
1437             if ( !filteredFiles.isEmpty() )
1438             {
1439                 resolvedFileSets.addAll(
1440                     createFileSets( filteredFiles, 3, false, packageName, true, defaultEncoding ) );
1441             }
1442             if ( !unfilteredFiles.isEmpty() )
1443             {
1444                 resolvedFileSets.addAll(
1445                     createFileSets( unfilteredFiles, 3, false, packageName, false, defaultEncoding ) );
1446             }
1447         }
1448 
1449         /* sourcesTestFiles */
1450         List<String> sourcesTestFiles =
1451             archetypeFilesResolver.findSourcesTestFiles( files, languageIncludes.toString() );
1452         if ( !sourcesTestFiles.isEmpty() )
1453         {
1454             files.removeAll( sourcesTestFiles );
1455 
1456             List<String> filteredFiles =
1457                 archetypeFilesResolver.getFilteredFiles( sourcesTestFiles, filteredIncludes.toString() );
1458             sourcesTestFiles.removeAll( filteredFiles );
1459 
1460             List<String> unfilteredFiles = sourcesTestFiles;
1461             if ( !filteredFiles.isEmpty() )
1462             {
1463                 resolvedFileSets.addAll( createFileSets( filteredFiles, 3, true, packageName, true, defaultEncoding ) );
1464             }
1465             if ( !unfilteredFiles.isEmpty() )
1466             {
1467                 resolvedFileSets.addAll(
1468                     createFileSets( unfilteredFiles, 3, true, packageName, false, defaultEncoding ) );
1469             }
1470         }
1471 
1472         /* ressourcesTestFiles */
1473         List<String> resourcesTestFiles =
1474             archetypeFilesResolver.findResourcesTestFiles( files, languageIncludes.toString() );
1475         if ( !resourcesTestFiles.isEmpty() )
1476         {
1477             files.removeAll( resourcesTestFiles );
1478 
1479             List<String> filteredFiles =
1480                 archetypeFilesResolver.getFilteredFiles( resourcesTestFiles, filteredIncludes.toString() );
1481             resourcesTestFiles.removeAll( filteredFiles );
1482 
1483             List<String> unfilteredFiles = resourcesTestFiles;
1484             if ( !filteredFiles.isEmpty() )
1485             {
1486                 resolvedFileSets.addAll(
1487                     createFileSets( filteredFiles, 3, false, packageName, true, defaultEncoding ) );
1488             }
1489             if ( !unfilteredFiles.isEmpty() )
1490             {
1491                 resolvedFileSets.addAll(
1492                     createFileSets( unfilteredFiles, 3, false, packageName, false, defaultEncoding ) );
1493             }
1494         }
1495 
1496         /* siteFiles */
1497         List<String> siteFiles = archetypeFilesResolver.findSiteFiles( files, languageIncludes.toString() );
1498         if ( !siteFiles.isEmpty() )
1499         {
1500             files.removeAll( siteFiles );
1501 
1502             List<String> filteredFiles =
1503                 archetypeFilesResolver.getFilteredFiles( siteFiles, filteredIncludes.toString() );
1504             siteFiles.removeAll( filteredFiles );
1505 
1506             List<String> unfilteredFiles = siteFiles;
1507             if ( !filteredFiles.isEmpty() )
1508             {
1509                 resolvedFileSets.addAll(
1510                     createFileSets( filteredFiles, 2, false, packageName, true, defaultEncoding ) );
1511             }
1512             if ( !unfilteredFiles.isEmpty() )
1513             {
1514                 resolvedFileSets.addAll(
1515                     createFileSets( unfilteredFiles, 2, false, packageName, false, defaultEncoding ) );
1516             }
1517         }
1518 
1519         /* thirdLevelSourcesfiles */
1520         List<String> thirdLevelSourcesfiles =
1521             archetypeFilesResolver.findOtherSources( 3, files, languageIncludes.toString() );
1522         if ( !thirdLevelSourcesfiles.isEmpty() )
1523         {
1524             files.removeAll( thirdLevelSourcesfiles );
1525 
1526             List<String> filteredFiles =
1527                 archetypeFilesResolver.getFilteredFiles( thirdLevelSourcesfiles, filteredIncludes.toString() );
1528             thirdLevelSourcesfiles.removeAll( filteredFiles );
1529 
1530             List<String> unfilteredFiles = thirdLevelSourcesfiles;
1531             if ( !filteredFiles.isEmpty() )
1532             {
1533                 resolvedFileSets.addAll( createFileSets( filteredFiles, 3, true, packageName, true, defaultEncoding ) );
1534             }
1535             if ( !unfilteredFiles.isEmpty() )
1536             {
1537                 resolvedFileSets.addAll(
1538                     createFileSets( unfilteredFiles, 3, true, packageName, false, defaultEncoding ) );
1539             }
1540 
1541             /* thirdLevelResourcesfiles */
1542             List<String> thirdLevelResourcesfiles =
1543                 archetypeFilesResolver.findOtherResources( 3, files, thirdLevelSourcesfiles,
1544                                                            languageIncludes.toString() );
1545             if ( !thirdLevelResourcesfiles.isEmpty() )
1546             {
1547                 files.removeAll( thirdLevelResourcesfiles );
1548                 filteredFiles =
1549                     archetypeFilesResolver.getFilteredFiles( thirdLevelResourcesfiles, filteredIncludes.toString() );
1550                 thirdLevelResourcesfiles.removeAll( filteredFiles );
1551                 unfilteredFiles = thirdLevelResourcesfiles;
1552                 if ( !filteredFiles.isEmpty() )
1553                 {
1554                     resolvedFileSets.addAll(
1555                         createFileSets( filteredFiles, 3, false, packageName, true, defaultEncoding ) );
1556                 }
1557                 if ( !unfilteredFiles.isEmpty() )
1558                 {
1559                     resolvedFileSets.addAll(
1560                         createFileSets( unfilteredFiles, 3, false, packageName, false, defaultEncoding ) );
1561                 }
1562             }
1563         } // end if
1564 
1565         /* secondLevelSourcesfiles */
1566         List<String> secondLevelSourcesfiles =
1567             archetypeFilesResolver.findOtherSources( 2, files, languageIncludes.toString() );
1568         if ( !secondLevelSourcesfiles.isEmpty() )
1569         {
1570             files.removeAll( secondLevelSourcesfiles );
1571 
1572             List<String> filteredFiles =
1573                 archetypeFilesResolver.getFilteredFiles( secondLevelSourcesfiles, filteredIncludes.toString() );
1574             secondLevelSourcesfiles.removeAll( filteredFiles );
1575 
1576             List<String> unfilteredFiles = secondLevelSourcesfiles;
1577             if ( !filteredFiles.isEmpty() )
1578             {
1579                 resolvedFileSets.addAll( createFileSets( filteredFiles, 2, true, packageName, true, defaultEncoding ) );
1580             }
1581             if ( !unfilteredFiles.isEmpty() )
1582             {
1583                 resolvedFileSets.addAll(
1584                     createFileSets( unfilteredFiles, 2, true, packageName, false, defaultEncoding ) );
1585             }
1586         }
1587 
1588         /* secondLevelResourcesfiles */
1589         List<String> secondLevelResourcesfiles =
1590             archetypeFilesResolver.findOtherResources( 2, files, languageIncludes.toString() );
1591         if ( !secondLevelResourcesfiles.isEmpty() )
1592         {
1593             files.removeAll( secondLevelResourcesfiles );
1594 
1595             List<String> filteredFiles =
1596                 archetypeFilesResolver.getFilteredFiles( secondLevelResourcesfiles, filteredIncludes.toString() );
1597             secondLevelResourcesfiles.removeAll( filteredFiles );
1598 
1599             List<String> unfilteredFiles = secondLevelResourcesfiles;
1600             if ( !filteredFiles.isEmpty() )
1601             {
1602                 resolvedFileSets.addAll(
1603                     createFileSets( filteredFiles, 2, false, packageName, true, defaultEncoding ) );
1604             }
1605             if ( !unfilteredFiles.isEmpty() )
1606             {
1607                 resolvedFileSets.addAll(
1608                     createFileSets( unfilteredFiles, 2, false, packageName, false, defaultEncoding ) );
1609             }
1610         }
1611 
1612         /* rootResourcesfiles */
1613         List<String> rootResourcesfiles =
1614             archetypeFilesResolver.findOtherResources( 0, files, languageIncludes.toString() );
1615         if ( !rootResourcesfiles.isEmpty() )
1616         {
1617             files.removeAll( rootResourcesfiles );
1618 
1619             List<String> filteredFiles =
1620                 archetypeFilesResolver.getFilteredFiles( rootResourcesfiles, filteredIncludes.toString() );
1621             rootResourcesfiles.removeAll( filteredFiles );
1622 
1623             List<String> unfilteredFiles = rootResourcesfiles;
1624             if ( !filteredFiles.isEmpty() )
1625             {
1626                 resolvedFileSets.addAll(
1627                     createFileSets( filteredFiles, 0, false, packageName, true, defaultEncoding ) );
1628             }
1629             if ( !unfilteredFiles.isEmpty() )
1630             {
1631                 resolvedFileSets.addAll(
1632                     createFileSets( unfilteredFiles, 0, false, packageName, false, defaultEncoding ) );
1633             }
1634         }
1635 
1636         /**/
1637         if ( !files.isEmpty() )
1638         {
1639             getLogger().info( "Ignored files: " + files );
1640         }
1641 
1642         return resolvedFileSets;
1643     }
1644 
1645     private void restoreArtifactId( Properties properties, String artifactId )
1646     {
1647         if ( StringUtils.isEmpty( artifactId ) )
1648         {
1649             properties.remove( Constants.ARTIFACT_ID );
1650         }
1651         else
1652         {
1653             properties.setProperty( Constants.ARTIFACT_ID, artifactId );
1654         }
1655     }
1656 
1657     private void restoreParentArtifactId( Properties properties, String parentArtifactId )
1658     {
1659         if ( StringUtils.isEmpty( parentArtifactId ) )
1660         {
1661             properties.remove( Constants.PARENT_ARTIFACT_ID );
1662         }
1663         else
1664         {
1665             properties.setProperty( Constants.PARENT_ARTIFACT_ID, parentArtifactId );
1666         }
1667     }
1668 
1669     private String getReversedContent( String content, Properties properties )
1670     {
1671         String result =
1672             StringUtils.replace( StringUtils.replace( content, "$", "${symbol_dollar}" ), "\\", "${symbol_escape}" );
1673         result = getReversedPlainContent( result, properties );
1674 
1675         // TODO: Replace velocity to a better engine...
1676         return "#set( $symbol_pound = '#' )\n" + "#set( $symbol_dollar = '$' )\n" + "#set( $symbol_escape = '\\' )\n"
1677             + StringUtils.replace( result, "#", "${symbol_pound}" );
1678     }
1679 
1680     private String getReversedPlainContent( String content, Properties properties )
1681     {
1682         String result = content;
1683 
1684         for ( Iterator<?> propertyIterator = properties.keySet().iterator(); propertyIterator.hasNext(); )
1685         {
1686             String propertyKey = (String) propertyIterator.next();
1687 
1688             result = StringUtils.replace( result, properties.getProperty( propertyKey ), "${" + propertyKey + "}" );
1689         }
1690         return result;
1691     }
1692 
1693     private String getReversedFilename( String filename, Properties properties )
1694     {
1695         String result = filename;
1696 
1697         for ( Iterator<?> propertyIterator = properties.keySet().iterator(); propertyIterator.hasNext(); )
1698         {
1699             String propertyKey = (String) propertyIterator.next();
1700 
1701             result = StringUtils.replace( result, properties.getProperty( propertyKey ), "__" + propertyKey + "__" );
1702         }
1703 
1704         return result;
1705     }
1706 
1707     private String getTemplateOutputDirectory()
1708     {
1709         return Constants.SRC + File.separator + Constants.MAIN + File.separator + Constants.RESOURCES;
1710     }
1711 
1712     private FileSet getUnpackagedFileSet( final boolean filtered, final String group, final List<String> groupFiles,
1713                                           String defaultEncoding )
1714     {
1715         Set<String> extensions = getExtensions( groupFiles );
1716 
1717         List<String> includes = new ArrayList<>();
1718         List<String> excludes = new ArrayList<>();
1719 
1720         for ( String extension : extensions )
1721         {
1722             includes.add( "**/*." + extension );
1723         }
1724 
1725         return createFileSet( excludes, false, filtered, group, includes, defaultEncoding );
1726     }
1727 
1728     private FileSet getUnpackagedFileSet( final boolean filtered, final Set<String> unpackagedExtensions,
1729                                           final List<String> unpackagedFiles, final String group,
1730                                           final Set<String> packagedExtensions, String defaultEncoding )
1731     {
1732         List<String> includes = new ArrayList<>();
1733         List<String> excludes = new ArrayList<>();
1734 
1735         for ( String extension : unpackagedExtensions )
1736         {
1737             if ( packagedExtensions.contains( extension ) )
1738             {
1739                 includes.addAll( archetypeFilesResolver.getFilesWithExtension( unpackagedFiles, extension ) );
1740             }
1741             else
1742             {
1743                 if ( StringUtils.isEmpty( extension ) )
1744                 {
1745                     includes.add( "**/*" );
1746                 }
1747                 else
1748                 {
1749                     includes.add( "**/*." + extension );
1750                 }
1751             }
1752         }
1753 
1754         return createFileSet( excludes, false, filtered, group, includes, defaultEncoding );
1755     }
1756 
1757     private static final String MAVEN_PROPERTIES =
1758         "META-INF/maven/org.apache.maven.archetype/archetype-common/pom.properties";
1759 
1760     public String getArchetypeVersion()
1761     {
1762         // This should actually come from the pom.properties at testing but it's not generated and put into the JAR, it
1763         // happens as part of the JAR plugin which is crap as it makes testing inconsistent.
1764         String version = "version";
1765 
1766         try ( InputStream is = getClass().getClassLoader().getResourceAsStream( MAVEN_PROPERTIES ) )
1767         {
1768             Properties properties = new Properties();
1769 
1770             if ( is != null )
1771             {
1772                 properties.load( is );
1773 
1774                 String property = properties.getProperty( "version" );
1775 
1776                 if ( property != null )
1777                 {
1778                     return property;
1779                 }
1780             }
1781 
1782             return version;
1783         }
1784         catch ( IOException e )
1785         {
1786             return version;
1787         }
1788     }
1789 }