Main method which extracts given Maven Archetype in destination directory

@return
973315
public int execute() throws IOException
   {
      outputDir.mkdirs();

      // some archetypes might not use maven or use the maven source layout so lets remove
      // the pom.xml and src folder if its already been pre-created
      // as these will be created if necessary via the archetype jar's contents
      File pom = new File(outputDir, "pom.xml");
      if (pom.isFile() && pom.exists()) {
         pom.delete();
      }
      File src = new File(outputDir, "src");
      if (src.isDirectory() && src.exists()) {
         recursiveDelete(src);
      }

      if (packageName == null || packageName.length() == 0)
      {
         packageName = groupId + "." + artifactId;
      }

      String packageDir = packageName.replace('.', '/');

      info("Creating archetype using Maven groupId: " +
               groupId + ", artifactId: " + artifactId + ", version: " + version
               + " in directory: " + outputDir);

      Map<String, String> replaceProperties = new HashMap<String, String>();

      ZipInputStream zip = null;
      try
      {
         zip = new ZipInputStream(archetypeIn);
         boolean ok = true;
         while (ok)
         {
            ZipEntry entry = zip.getNextEntry();
            if (entry == null)
            {
               ok = false;
            }
            else
            {
               if (!entry.isDirectory())
               {
                  String fullName = entry.getName();
                  if (fullName != null && fullName.startsWith(zipEntryPrefix))
                  {
                     String name = replaceFileProperties(fullName.substring(zipEntryPrefix.length()), replaceProperties);
                     debug("Processing resource: " + name);

                     int idx = name.lastIndexOf('/');
                     Matcher matcher = sourcePathRegexPattern.matcher(name);
                     String dirName;
                     if (packageName.length() > 0 && idx > 0 && matcher.matches())
                     {
                        String prefix = matcher.group(1);
                        dirName = prefix + packageDir + "/" + name.substring(prefix.length());
                     }
                     else if (packageName.length() > 0 && name.startsWith(webInfResources))
                     {
                        dirName = "src/main/webapp/WEB-INF/" + packageDir + "/resources"
                                 + name.substring(webInfResources.length());
                     }
                     else
                     {
                        dirName = name;
                     }

                     // lets replace properties...
                     File file = new File(outputDir, dirName);
                     file.getParentFile().mkdirs();
                     FileOutputStream out = null;
                     try
                     {
                        out = new FileOutputStream(file);
                        boolean isBinary = false;
                        for (String suffix : binarySuffixes)
                        {
                           if (name.endsWith(suffix))
                           {
                              isBinary = true;
                              break;
                           }
                        }
                        if (isBinary)
                        {
                           // binary file? don't transform.
                           Streams.write(zip, out);
                        }
                        else
                        {
                           // text file...
                           ByteArrayOutputStream bos = new ByteArrayOutputStream();
                           Streams.write(zip, bos);
                           String text = new String(bos.toByteArray(), "UTF-8");
                           out.write(transformContents(text, replaceProperties).getBytes());
                        }
                     }
                     finally
                     {
                        if (out != null)
                        {
                           out.close();
                        }
                     }
                  }
                  else if (fullName != null && fullName.equals("META-INF/maven/archetype-metadata.xml"))
                  {
                     // we assume that this resource will be first in Archetype's ZIP
                     // this way we can find out what are the required properties before we will actually use them
                     parseReplaceProperties(zip, replaceProperties);
                     replaceProperties.putAll(overrideProperties);
                  }
               }
               zip.closeEntry();
            }
         }
      }
      catch (Exception e)
      {
         throw new IOException(e.getMessage(), e);
      }
      finally
      {
         if (zip != null)
         {
            zip.close();
         }
      }

      info("Using replace properties: " + replaceProperties);

      // now lets replace all the properties in the pom.xml
      if (!replaceProperties.isEmpty())
      {
         String text;
         try (FileInputStream fis = new FileInputStream(pom))
         {
            text = Streams.toString(fis);
         }
         for (Map.Entry<String, String> e : replaceProperties.entrySet())
         {
            text = replaceVariable(text, e.getKey(), e.getValue());
         }
         try (FileWriter writer = new FileWriter(pom))
         {
            writer.write(text);
            writer.flush();
         }
      }

      // now lets create the default directories
      if (createDefaultDirectories && pom.exists())
      {
         File srcDir = new File(outputDir, "src");
         File mainDir = new File(srcDir, "main");
         File testDir = new File(srcDir, "test");

         String srcDirName = "java";
         // Who needs Scala in 2014?
         // if (new File(mainDir, "scala").exists() || new File(textDir, "scala").exists()) {
         // srcDirName = "scala";
         // }

         for (File dir : new File[] { mainDir, testDir })
         {
            for (String name : new String[] { srcDirName + "/" + packageDir, "resources" })
            {
               new File(dir, name).mkdirs();
            }
         }
      }

      return 0;
   }
894714
private TransformerFactory getTransformerFactory()
        throws MojoFailureException, MojoExecutionException
    {
        if ( transformerFactory == null )
        {
            return TransformerFactory.newInstance();
        }

        try
        {
            return newTransformerFactory( transformerFactory, Thread.currentThread().getContextClassLoader() );
        }
        catch ( NoSuchMethodException exception )
        {
            throw new MojoFailureException( "JDK6 required when using transformerFactory parameter" );
        }
        catch ( IllegalAccessException exception )
        {
            throw new MojoExecutionException( "Cannot instantiate transformer factory", exception );
        }
        catch ( InvocationTargetException exception )
        {
            throw new MojoExecutionException( "Cannot instantiate transformer factory", exception );
        }
    }
91987
private Pom mavenizeModule(MavenizationContext mavCtx, ProjectModel projectModel, Pom containingModule)
    {
        LOG.info("Mavenizing submodule ProjectModel " + projectModel.toPrettyString());
        LOG.info("    Root file: " + projectModel.getRootFileModel().toPrettyString());
        LOG.info("    Containing module: " + containingModule);

        if (projectModel.getRootFileModel().getParseError() != null)
            return null;

        // Known library -> add as a dependency and skip.

        // SHA1 identified archive?
        if (projectModel.getRootFileModel() instanceof IdentifiedArchiveModel)
        {
            final IdentifiedArchiveModel idArch = (IdentifiedArchiveModel)projectModel.getRootFileModel();
            if (idArch == null)
                LOG.warning("Project's IdentifiedArchiveModel getRootFileModel() returned null.");
            else if (idArch.getCoordinate() == null)
                LOG.warning("Project's IdentifiedArchiveModel getRootFileModel().getCoordinate() returned null.");
            else if(containingModule == null)
                LOG.warning("containingModule is null."); // IllegalStateEx?
            else
                containingModule.dependencies.add(new SimpleDependency(Dependency.Role.LIBRARY, MavenCoord.from(idArch.getCoordinate())));

            LOG.info("Known library, skipping recursive mavenization: " + idArch.getCoordinate());
            return null;
        }

        // ArchiveModel's organizations contain a known org, like Apache.
        if (projectModel.getRootFileModel() instanceof ArchiveModel)
        {
            Set<String> skipOrganizations = new HashSet(Arrays.asList("Apache Sun Iona IBM Codehaus Spring Sonatype JBoss Oracle".toLowerCase().split("")));

            final ArchiveModel arch = (ArchiveModel)projectModel.getRootFileModel();
            for (OrganizationModel org : arch.getOrganizationModels())
            {
                if (skipOrganizations.contains(org.getName().toLowerCase()))
                {
                    LOG.info("Library from 3rd party vendor ("+org.getName()+"), skipping recursive mavenization: " + arch.getFilePath());
                    return null;
                }
            }
        }

        // A MavenProject.
        // TODO: This covers both app modules and libraries with pom.xml inside. Need to diferentiate - skip only libraries.
        // TODO: This should disappear after WINDUP-981
        if (false && projectModel instanceof MavenProjectModel)
        {
            final MavenProjectModel mvnProject = (MavenProjectModel)projectModel;
            if (mvnProject.getMavenIdentifier() == null)
                LOG.warning("MavenProject's getMavenIdentifier() returned null.");
            else if(containingModule == null)
                LOG.warning("containingModule is null."); // IllegalStateEx?
            else if (true /* isLibraryAndNotProjectModule() */)
                containingModule.dependencies.add(new SimpleDependency(Dependency.Role.LIBRARY, MavenCoord.fromGAVPC(mvnProject.getMavenIdentifier())));
            return null;
        }

        MavenCoord modulePomCoords = new MavenCoord();
        modulePomCoords.setGroupId(mavCtx.getUnifiedGroupId());
        modulePomCoords.setVersion(mavCtx.getUnifiedVersion());
        final String artifactId = deriveAppropriateArtifactId(projectModel);
        modulePomCoords.setArtifactId(artifactId);
        modulePomCoords.setPackaging(guessPackaging(projectModel));

        Pom modulePom = new Pom(modulePomCoords);
        modulePom.role = Pom.ModuleRole.NORMAL;
        modulePom.parent = mavCtx.getRootPom();
        mavCtx.getRootPom().submodules.put(artifactId, modulePom);
        mavCtx.getKnownSubmodules().add(modulePom);


        // Set up the dependency of the containing module on the contained module. E.g. EAR depends on WAR.
        if(containingModule != null)
            containingModule.dependencies.add(modulePom);

        // Nested archives
        // For now, only count with the modules of this app. There are likely more in the other apps.
        Set<ArchiveModel> nestedModules = new HashSet<>();
        for (FileModel file : projectModel.getFileModelsNoDirectories())
        {
            if(!(file instanceof ArchiveModel)) //  TODO: Query for ArchiveModel directly.
                continue;

            // Known library -> simple dependency.
            if(file instanceof IdentifiedArchiveModel){
                IdentifiedArchiveModel artifact = (IdentifiedArchiveModel) file;
                modulePom.dependencies.add(new SimpleDependency(Dependency.Role.LIBRARY, MavenCoord.from(artifact.getCoordinate())));
            }
            // Unknown archives -> nested modules? -> local dependencies.
            else {
                nestedModules.add((ArchiveModel) file);
            }
        }

        // Nested modules already identified as ProjectModel
        for (ProjectModel subProject : projectModel.getChildProjects())
        {
            Pom subModulePom = mavenizeModule(mavCtx, subProject, modulePom);
            if (subModulePom == null)
                continue;
            modulePom.dependencies.add(subModulePom);
        }

        // Nested module candidates.
        for (ArchiveModel nestedModule : nestedModules)
        {
            // TODO: Is it a submodule or a library? Does it appear in multiple applications?
            //Pom subModulePom = mavenizeModule(mavCtx, nestedModule, containingModule);
            //modulePom.dependencies.add(subModulePom.identification);
        }

        // TODO: MIGR-237 Determine and add the project internal dependencies (on other submodules, cross-app)
        // Queues? JNDI? CDI? REST + WS endpoints?
        // Needs to be done after initial mavenization of all apps to have their G:A:V.

        // TODO: Determine and add compile-time (API) dependencies (like, Java EE API's)
        // One big Java EE API vs. individual?

        // TODO: Remove the deps versions overriding the BOM.
        new FeatureBasedApiDependenciesDeducer(mavCtx).addAppropriateDependencies(projectModel, modulePom);

        return modulePom;
    }
973985
private Store getStore(MavenProject rootModule) throws MojoExecutionException {
        StoreConfiguration configuration = getStoreConfiguration(rootModule);
        List<Class<?>> descriptorTypes;
        try {
            descriptorTypes = pluginRepositoryProvider.getPluginRepository().getModelPluginRepository().getDescriptorTypes();
        } catch (PluginRepositoryException e) {
            throw new MojoExecutionException("Cannot determine model types.", e);
        }
        Object existingStore = cachingStoreProvider.getStore(configuration, descriptorTypes);
        if (!Store.class.isAssignableFrom(existingStore.getClass())) {
            throw new MojoExecutionException(
                    "Cannot re-use store instance from reactor. Either declare the plugin as extension or execute Maven using the property -D"
                            + PROPERTY_STORE_LIFECYCLE + "=" + StoreLifecycle.MODULE + " on the command line.");
        }
        return (Store) existingStore;
    }
697007
String getDocumentationDir() {
        String baseDir = project.getBuild().getDirectory();
        if (baseDir == null || new File(baseDir).exists()) {
            baseDir = project.getBasedir().getAbsolutePath();
            baseDir = baseDir + "/target";
            if (!new File(baseDir).exists()) {
                //maven plugin declared in child module
                baseDir = project.getBasedir().getAbsolutePath();
            }
        }
        if (!baseDir.endsWith("/")) {
            baseDir = baseDir + "/";
        }

        if (outputDir == null) {
            outputDir = "cukedoctor/";
        }

        if (!outputDir.endsWith("/")) {
            outputDir = outputDir + "/";
        }

        return baseDir + outputDir;

    }
1159259
public File getBuildDir() {
        // we use the null check variant so that people can write true unit tests with a mock ItemParent
        // and without a JenkinsRule. Such tests are of limited utility as there is a high risk of hitting
        // some code that needs the singleton, but for persistence migration test cases it makes sense to permit
        Jenkins j = Jenkins.getInstanceOrNull();
        if (j == null) {
            return new File(getRootDir(), "builds");
        }
        return j.getBuildDirFor(this);
    }
531267
@Nullable
  private File findProjectGitDirectory() {
    if (this.mavenProject == null) {
      return null;
    }

    File basedir = mavenProject.getBasedir();
    while (basedir != null) {
      File gitdir = new File(basedir, Constants.DOT_GIT);
      if (gitdir.exists()) {
        if (gitdir.isDirectory()) {
          return gitdir;
        } else if (gitdir.isFile()) {
          return processGitDirFile(gitdir);
        } else {
          return null;
        }
      }
      basedir = basedir.getParentFile();
    }
    return null;
  }
1267279
private static String getVersionFromPom() {

        final String absolutePath = new File(BuildVersion.class.getResource(BuildVersion.class
                .getSimpleName() + ".class").getPath())
                .getParentFile().getParentFile().getParentFile().getParentFile().getParentFile()
                .getParentFile().getParentFile().getAbsolutePath();

        final File file = new File(absolutePath + "/pom.xml");

        try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) {

            final MavenXpp3Reader xpp3Reader = new MavenXpp3Reader();
            Model model = xpp3Reader.read(reader);
            return model.getVersion();

        } catch (NoClassDefFoundError e) {
            // if you want to get the version possibly in development add in to your pom
            // pax-url-aether.jar
            return null;
        } catch (Exception e) {
            return null;
        }
    }
372049
public MavenProject getMavenProject(Artifact artifact) {
		try {
			final MavenSession session = getMavenSession();
			final MavenProject current = session.getCurrentProject();
			final MavenProject prj = getMavenProjectBuilder().buildFromRepository(
					artifact,
					current.getRemoteArtifactRepositories(),
					session.getLocalRepository());
			return prj;
		} catch (ProjectBuildingException e) {
			getLog().warn(e);
		}
		return null;
	}
460080
private static String findJavaVersionString(MavenProject project) {
        while (project != null) {
            String target = project.getProperties().getProperty("maven.compiler.target");
            if (target != null) {
                return target;
            }
            for (org.apache.maven.model.Plugin plugin : CompoundList.of(project.getBuildPlugins(), project.getPluginManagement().getPlugins())) {
                if ("maven-compiler-plugin".equals(plugin.getArtifactId())) {
                    if (plugin.getConfiguration() instanceof Xpp3Dom) {
                        Xpp3Dom node = ((Xpp3Dom) plugin.getConfiguration()).getChild("target");
                        if (node != null) {
                            return node.getValue();
                        }
                    }
                }
            }
            project = project.getParent();
        }
        return null;
    }
1080158
public File[] build() {
        MavenStrategyStage maven = Maven.configureResolver()
                .workOffline(offline)
                .resolve(artifactCoordinates);

        return applyTransitivity(maven).asFile();
    }
275752
public Collection<File> getClasspath( String scope )
        throws MojoExecutionException
    {
        try
        {
            Collection<File> files = classpathBuilder.buildClasspathList( getProject(), scope, getProjectArtifacts(), isGenerator() );

            if ( getLog().isDebugEnabled() )
            {
                getLog().debug( "GWT SDK execution classpath :" );
                for ( File f : files )
                {
                    getLog().debug( "   " + f.getAbsolutePath() );
                }
            }
            return files;
        }
        catch ( ClasspathBuilderException e )
        {
            throw new MojoExecutionException( e.getMessage(), e );
        }
    }
623054
private ClassLoader getClassLoader()
        throws MojoExecutionException
    {
        List<URL> classpathURLs = new ArrayList<URL>();
        this.addRelevantPluginDependenciesToClasspath( classpathURLs );
        this.addRelevantProjectDependenciesToClasspath( classpathURLs );
        this.addAdditionalClasspathElements( classpathURLs );
        
        if (outputDirectory.isDirectory()) {
        	// load compiled classes
        	Collection listFiles = FileUtils.listFiles(outputDirectory, new String[]{"class"}, true);
        	for (Object object : listFiles) {
        		if (object instanceof File) {
        			File f = (File) object;
        			if (f.isFile()) {
        				try {
        					classpathURLs.add(f.toURI().toURL());
        				} catch (Exception e) {
        					// TODO: handle exception
        				}
        			}
        		}
        	}
        }
        
        
        return new URLClassLoader( classpathURLs.toArray( new URL[classpathURLs.size()] ) , getClass().getClassLoader());
    }
1285187
public static String exportTypeSystem() {
      Resource out = new StringResource();
      try {
         exportTypeSystem(out);
         return out.readToString().trim();
      } catch (IOException e) {
         throw Throwables.propagate(e);
      }
   }
1237548
protected List<File> getClassPath() throws MojoExecutionException {
		if (this.bufferedClasspath == null) {
			final Set<String> classPath = new LinkedHashSet<>();
			final MavenProject project = getProject();
			classPath.add(project.getBuild().getSourceDirectory());
			try {
				classPath.addAll(project.getCompileClasspathElements());
			} catch (DependencyResolutionRequiredException e) {
				throw new MojoExecutionException(e.getLocalizedMessage(), e);
			}
			for (final Artifact dep : project.getArtifacts()) {
				classPath.add(dep.getFile().getAbsolutePath());
			}
			classPath.remove(project.getBuild().getOutputDirectory());
			final List<File> files = new ArrayList<>();
			for (final String filename : classPath) {
				final File file = new File(filename);
				if (file.exists()) {
					files.add(file);
				} else {
					getLog().warn(MessageFormat.format(Messages.AbstractSarlBatchCompilerMojo_10, filename));
				}
			}
			this.bufferedClasspath = files;
		}
		return this.bufferedClasspath;
	}
222831
private String getRelativePomPath(MavenModule mavenModule, MavenModuleSetBuild mavenBuild) {
        String relativePath = mavenModule.getRelativePath();
        if (StringUtils.isBlank(relativePath)) {
            return POM_NAME;
        }

        // If this is the root module, return the root pom path.
        if (mavenModule.getModuleName().toString().
                equals(mavenBuild.getProject().getRootModule().getModuleName().toString())) {
            return mavenBuild.getProject().getRootPOM(null);
        }

        // to remove the project folder name if exists
        // keeps only the name of the module
        String modulePath = relativePath.substring(relativePath.indexOf("/") + 1);
        for (String moduleName : mavenModules) {
            if (moduleName.contains(modulePath)) {
                return createPomPath(relativePath, moduleName);
            }
        }

        // In case this module is not in the parent pom
        return relativePath + "/" + POM_NAME;
    }
288328
@Override
  public File getNoArchDirectory(final File baseDir, final String artifactId, final String version)
      throws MojoExecutionException, MojoFailureException {
    return baseDir;
  }