Build the customized Share webapp (i.e. the share.war)
that should be deployed by Tomcat by applying all AMPs and JARs from
the {@code <shareModules> } configuration.

@throws MojoExecutionException when any problem appears building the share war
543353
protected void buildShareWar() throws MojoExecutionException {
        buildCustomWarInDir(SHARE_WAR_PREFIX_NAME, shareModules,
                alfrescoGroupId, alfrescoShareWarArtifactId, alfrescoShareVersion);

        copyShareLog4jConfig();
        copyShareConfigCustom();
        copyHotswapAgentProperties(SHARE_WAR_PREFIX_NAME);


        String shareWarArtifactId = packageAndInstallCustomWar(SHARE_WAR_PREFIX_NAME);

        // Set up the custom share war to be run by Tomcat plugin
        runnerAlfrescoGroupId = "${project.groupId}";
        runnerAlfrescoShareWarArtifactId = shareWarArtifactId;
        runnerAlfrescoShareVersion = "${project.version}";
    }
1213340
protected static void throwMojoExecutionException(Object mojo, String message, Exception cause) throws Exception {
        Class<?> clz = mojo.getClass().getClassLoader().loadClass(MavenNames.MOJO_EXECUTION_EXCEPTION_BIN);
        Constructor<?> con = clz.getConstructor(String.class, Exception.class);
        Exception ex = (Exception) con.newInstance(message, cause);
        throw ex;
    }
546526
public void execute() throws MojoExecutionException, MojoFailureException {
		try {
			createBundles();
		} catch (Exception ex) {
			Logger logger = Logger.getLogger(JawrMojo.class.getName());
			if(ex instanceof ServletException){
				logger.log(Level.SEVERE, null, ((ServletException)ex).getRootCause());
			}else{
				logger.log(Level.SEVERE, null, ex);
			}
			throw new MojoFailureException("JAWR Maven plugin failed: " + ex.getLocalizedMessage());
		}
	}
815400
private void createCodeFormatter() throws MojoExecutionException {
        Map<String, String> javaFormattingOptions = getFormattingOptions(this.configFile);
        if (javaFormattingOptions != null) {
            this.javaFormatter.init(javaFormattingOptions, this);
        }
        Map<String, String> jsFormattingOptions = getFormattingOptions(this.configJsFile);
        if (jsFormattingOptions != null) {
            this.jsFormatter.init(jsFormattingOptions, this);
        }
        if (configHtmlFile != null) {
            this.htmlFormatter.init(getOptionsFromPropertiesFile(configHtmlFile), this);
        }
        if (configXmlFile != null) {
            Map<String, String> xmlFormattingOptions = getOptionsFromPropertiesFile(configXmlFile);
            xmlFormattingOptions.put("lineending", this.lineEnding.getChars());
            this.xmlFormatter.init(xmlFormattingOptions, this);
        }
        if (configJsonFile != null) {
            Map<String, String> jsonFormattingOptions = getOptionsFromPropertiesFile(configJsonFile);
            jsonFormattingOptions.put("lineending", this.lineEnding.getChars());
            this.jsonFormatter.init(jsonFormattingOptions, this);
        }
        if (configCssFile != null) {
            this.cssFormatter.init(getOptionsFromPropertiesFile(configCssFile), this);
        }
        // stop the process if not config files where found
        if (javaFormattingOptions == null && jsFormattingOptions == null && configHtmlFile == null
                && configXmlFile == null && configCssFile == null) {
            throw new MojoExecutionException(
                    "You must provide a Java, Javascript, HTML, XML, JSON, or CSS configuration file.");
        }
    }
434143
private URL[] generateClassPathUrls() throws MojoExecutionException {
        List<URL> urls = new ArrayList<URL>();
        URL url;
        try {
            for (Object element : getCompileClasspath()) {
                String path = (String) element;
                if (path.endsWith(".jar")) {
                    url = new URL("jar:" + new File(path).toURI().toString() + "!/");
                } else {
                    url = new File(path).toURI().toURL();
                }
                urls.add(url);
            }
        } catch (MalformedURLException e) {
            throw new MojoExecutionException("Could not set up classpath", e);
        }
        return urls.toArray(new URL[urls.size()]);
    }
1007740
@Override
  public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
      return;
    }

    PackageDownloader downloader = new PackageDownloader(getPackageManagerProperties(), getLoggerWrapper());

    File outputFileObject = downloader.downloadFile(getPackageFile(), this.outputFile);
    if (this.unpack) {
      unpackFile(outputFileObject);
    }
  }
167461
protected void extendRealmClasspath()
            throws MojoExecutionException {
        List<URL> urls = new ArrayList<>();

        for (String fileName : compileClasspathElements) {
            File pathElem = new File(fileName);
            try {
                URL url = pathElem.toURI().toURL();
                urls.add(url);
                getLog().debug("Added classpathElement URL " + url);
            } catch (MalformedURLException e) {
                throw new MojoExecutionException("Error in adding the classpath " + pathElem, e);
            }
        }

        ClassLoader jpaRealm =
                new URLClassLoader(urls.toArray(new URL[urls.size()]), getClass().getClassLoader());

        // set the new ClassLoader as default for this Thread
        // will be reverted in the caller method.
        Thread.currentThread().setContextClassLoader(jpaRealm);
    }
749978
public void execute() throws MojoExecutionException {
        
        if (skip) {
            getLog().info("Skipping ceylon:sdk-check");
            return;
        }
        
        if (System.getProperty(CEYLON_REPO) != null) {
            getLog().debug("System property ceylon.repo found: " + System.getProperty(CEYLON_REPO));  
            sysRepo = new File(System.getProperty(CEYLON_REPO));
        } else {
            getLog().debug("System property ceylon.repo not found");
        }
        
        if (sysRepo == null && System.getenv("CEYLON_HOME") != null) {
            getLog().debug("Environment variable CEYLON_HOME found : " + System.getenv("CEYLON_HOME"));            
            sysRepo = new File(System.getenv("CEYLON_HOME"), "repo");
        } else {
            getLog().debug("Environment variable CEYLON_HOME not found");
        }
        
        if (sysRepo == null) {
            String dotCeylon = System.getProperty("user.home") 
                   + File.separator + ".ceylon";
            
            File hDir = findSdkHome(dotCeylon);
            
            if (hDir != null) {
                File r = new File(hDir, "repo");
                if (r != null && r.isDirectory()) {
                    sysRepo = r;
                }
            }
        }
        
        if (sysRepo == null) {
            throw new MojoExecutionException("Ceylon system repo (ceylon.repo or CEYLON_HOME) not set,"
                + " or repo not found in them, or in {user.home}/.ceylon/ceylon-1.x.x/repo. "
                + "Please use goal ceylon:sdk-download");
        } else if (!sysRepo.isDirectory()) {
            throw new MojoExecutionException("Ceylon system repo found but does not exist or is not a directory");
        } else {
            System.setProperty(CEYLON_REPO, sysRepo.getAbsolutePath());
            getLog().info("Ceylon system repo set to " + System.getProperty(CEYLON_REPO));
        }  
    }
202659
@SuppressWarnings("unchecked")
    public void execute() throws MojoExecutionException {

        if (isSkip()) {
            if (getLog().isInfoEnabled()) {
                getLog().info("Skipping execution because of 'skip' option");
            }
            return;
        }

        ArtifactHandler artifactHandler = project.getArtifact().getArtifactHandler();
        if (!forceAjcCompile && !"java".equalsIgnoreCase(artifactHandler.getLanguage())) {
            getLog().warn("Not executing aspectJ compiler as the project is not a Java classpath-capable package");
            return;
        }

        // MASPECT-110:
        //
        // Only add the aspectSourcePathDir and testAspectSourcePathDir to their respective
        // compileSourceRoots if they actually exist and are directories... to avoid crashing
        // downstream plugins requiring/assuming that all entries within the compileSourceRoots
        // and testCompileSourceRoots are directories.
        //
        final File aspectSourcePathDir = FileUtils.resolveFile(basedir, aspectDirectory);
        final File testAspectSourcePathDir = FileUtils.resolveFile(basedir, testAspectDirectory);

        final String aspectSourcePath = aspectSourcePathDir.getAbsolutePath();
        final String testAspectSourcePath = testAspectSourcePathDir.getAbsolutePath();

        if (aspectSourcePathDir.exists() && aspectSourcePathDir.isDirectory()
                && !project.getCompileSourceRoots().contains(aspectSourcePath)) {
            getLog().debug("Adding existing aspectSourcePathDir [" + aspectSourcePath + "] to compileSourceRoots.");
            project.getCompileSourceRoots().add(aspectSourcePath);
        } else {
            getLog().debug("Not adding non-existent or already added aspectSourcePathDir [" + aspectSourcePath
                    + "] to compileSourceRoots.");
        }

        if (testAspectSourcePathDir.exists() && testAspectSourcePathDir.isDirectory()
                && !project.getTestCompileSourceRoots().contains(testAspectSourcePath)) {
            getLog().debug(
                    "Adding existing testAspectSourcePathDir [" + testAspectSourcePath + "] to testCompileSourceRoots.");
            project.getTestCompileSourceRoots().add(testAspectSourcePath);
        } else {
            getLog().debug("Not adding non-existent or already added testAspectSourcePathDir [" + testAspectSourcePath
                    + "] to testCompileSourceRoots.");
        }

        assembleArguments();

        if (!forceAjcCompile && !hasSourcesToCompile()) {
            getLog().warn("No sources found skipping aspectJ compile");
            return;
        }

        if (!forceAjcCompile && !isBuildNeeded()) {
            getLog().info("No modifications found skipping aspectJ compile");
            return;
        }

        if (getLog().isDebugEnabled()) {
            StringBuilder command = new StringBuilder("Running : ajc");

            for (String arg : ajcOptions) {
                command.append(' ').append(arg);
            }
            getLog().debug(command);
        }
        try {
            getLog().debug(
                    "Compiling and weaving " + resolvedIncludes.size() + " sources to " + getOutputDirectory());
            AjcHelper.writeBuildConfigToFile(ajcOptions, argumentFileName, getOutputDirectory());
            getLog().debug(
                    "Arguments file written : " + new File(getOutputDirectory(), argumentFileName).getAbsolutePath());
        } catch (IOException e) {
            throw new MojoExecutionException("Could not write arguments file to the target area", e);
        }

        final Main ajcMain = new Main();
        MavenMessageHandler mavenMessageHandler = new MavenMessageHandler(getLog());
        ajcMain.setHolder(mavenMessageHandler);

        synchronized (BIG_ASPECTJ_LOCK) {
            ajcMain.runMain(ajcOptions.toArray(new String[ajcOptions.size()]), false);
        }

        IMessage[] errors = mavenMessageHandler.getMessages(IMessage.ERROR, true);
        if (!proceedOnError && errors.length > 0) {
            throw CompilationFailedException.create(errors);
        }
    }
385480
public void run() throws MojoExecutionException {
    try {
      runMojo
          .getAppEngineFactory()
          .devServerRunSync()
          .run(configBuilder.buildRunConfiguration(processServices(), processProjectId()));
    } catch (AppEngineException ex) {
      throw new MojoExecutionException("Failed to run devappserver", ex);
    }
  }
342628
protected Xpp3Dom createSREConfiguration() throws MojoExecutionException, MojoFailureException {
		final Xpp3Dom xmlConfiguration = new Xpp3Dom("configuration"); //$NON-NLS-1$
		final Xpp3Dom xmlArchive = new Xpp3Dom("archive"); //$NON-NLS-1$
		xmlConfiguration.addChild(xmlArchive);

		final String mainClass = getMainClass();
		if (mainClass.isEmpty()) {
			throw new MojoFailureException("the main class of the SRE is missed"); //$NON-NLS-1$
		}
		final Xpp3Dom xmlManifest = new Xpp3Dom("manifest"); //$NON-NLS-1$
		xmlArchive.addChild(xmlManifest);
		final Xpp3Dom xmlManifestMainClass = new Xpp3Dom("mainClass"); //$NON-NLS-1$
		xmlManifestMainClass.setValue(mainClass);
		xmlManifest.addChild(xmlManifestMainClass);

		final Xpp3Dom xmlSections = new Xpp3Dom("manifestSections"); //$NON-NLS-1$
		xmlArchive.addChild(xmlSections);
		final Xpp3Dom xmlSection = new Xpp3Dom("manifestSection"); //$NON-NLS-1$
		xmlSections.addChild(xmlSection);
		final Xpp3Dom xmlSectionName = new Xpp3Dom("name"); //$NON-NLS-1$
		xmlSectionName.setValue(SREConstants.MANIFEST_SECTION_SRE);
		xmlSection.addChild(xmlSectionName);
		final Xpp3Dom xmlManifestEntries = new Xpp3Dom("manifestEntries"); //$NON-NLS-1$
		xmlSection.addChild(xmlManifestEntries);

		ManifestUpdater updater = getManifestUpdater();
		if (updater == null) {
			updater = new ManifestUpdater() {

				@Override
				public void addSREAttribute(String name, String value) {
					assert name != null && !name.isEmpty();
					if (value != null && !value.isEmpty()) {
						getLog().debug("Adding to SRE manifest: " + name + " = " + value);  //$NON-NLS-1$//$NON-NLS-2$
						final Xpp3Dom xmlManifestEntry = new Xpp3Dom(name);
						xmlManifestEntry.setValue(value);
						xmlManifestEntries.addChild(xmlManifestEntry);
					}
				}

				@Override
				public void addMainAttribute(String name, String value) {
					//
				}

			};
		}

		buildManifest(updater, mainClass);

		return xmlConfiguration;
	}
204630
protected void logConfiguration() throws MojoExecutionException {
		super.logConfiguration();

		getLog().info("target:" + target);
		getLog().info("roundtripTestClassName:" + roundtripTestClassName);
		getLog().info("resourceIncludes:" + resourceIncludes);
		getLog().info("variant:" + variant);
		getLog().info("persistenceUnitName:" + persistenceUnitName);
		getLog().info("persistenceXml:" + persistenceXml);
		getLog().info("generateHashCode:" + generateHashCode);
		getLog().info("generateEquals:" + generateEquals);
		getLog().info("generateTransientId:" + generateTransientId);
		getLog().info("result:" + result);
		getLog().info("preArgs:" + Arrays.toString(preArgs));
		getLog().info("postArgs:" + Arrays.toString(postArgs));
		try {
			getLog().info(
					"XJC loaded from:"
							+ Options.class.getResource("Options.class")
									.toURI().toURL().toExternalForm());
		} catch (IOException ignored) {
		} catch (URISyntaxException ignored) {
		}

	}
822319
protected void setupForExpandedWar() {

    webapp.setServerClasses(getServerClasses());
    webapp.setDescriptor(webapp + "/WEB-INF/web.xml");
    webapp.setResourceBase(resourceBase);
    webapp.setParentLoaderPriority(false);
  }
350398
protected void startTomcat(boolean fork) throws MojoExecutionException {
        getLog().info("Starting Tomcat, fork = " + fork);

        List<Dependency> tomcatPluginDependencies = new ArrayList<Dependency>();
        ArrayList webapps2Deploy = new ArrayList<Element>();

        // Add the basic Tomcat dependencies
        tomcatPluginDependencies.add(
                // Packaging goes faster with this lib
                dependency("org.codehaus.plexus", "plexus-archiver", "2.3"));

        tomcatPluginDependencies.add(
                // The following dependency is needed, otherwise you get
                //  Caused by: java.lang.NoSuchMethodError:
                //      javax.servlet.ServletContext.getSessionCookieConfig()Ljavax/servlet/SessionCookieConfig
                // This method is in Servlet API 3.0
                dependency("javax.servlet", "javax.servlet-api", "3.0.1"));

        // Do we have any extra Tomcat Plugin dependencies to include?
        if (tomcatDependencies != null && tomcatDependencies.size() > 0) {
            for (TomcatDependency tomcatDep : tomcatDependencies) {
                tomcatPluginDependencies.add(
                        dependency(tomcatDep.getGroupId(), tomcatDep.getArtifactId(), tomcatDep.getVersion()));
            }
        }

        tomcatPluginDependencies.add(
                // Bring in the MySQL JDBC Driver
                dependency("mysql", "mysql-connector-java", "5.1.32"));

        tomcatPluginDependencies.add(
                // Bring in the PostgreSQL JDBC Driver
                dependency("org.postgresql", "postgresql", "9.4-1201-jdbc41"));


        if (enablePlatform) {
            webapps2Deploy.add(createWebAppElement(
                    runnerAlfrescoGroupId, runnerAlfrescoPlatformWarArtifactId, runnerAlfrescoPlatformVersion,
                    "/alfresco", null));
        }

        if (enableShare) {
            webapps2Deploy.add(createWebAppElement(
                    runnerAlfrescoGroupId, runnerAlfrescoShareWarArtifactId, runnerAlfrescoShareVersion,
                    shareContextPath, null));
        }

        if (enableApiExplorer) {
            webapps2Deploy.add(createWebAppElement(
                    alfrescoGroupId, alfrescoApiExplorerArtifactId, alfrescoApiExplorerVersion,
                    "/api-explorer", null));
        }


        if (tomcatCustomWebapps != null && !tomcatCustomWebapps.isEmpty()) {
            // We got extra custom webapps to deploy
            for (TomcatWebapp customWebapp: tomcatCustomWebapps) {
                webapps2Deploy.add(createWebAppElement(
                        customWebapp.getGroupId(), customWebapp.getArtifactId(), customWebapp.getVersion(),
                        customWebapp.getContextPath(), customWebapp.getContextFile()));
            }
        }

        // This might be ugly, the MojoExecuter will only accept Element[] and we need this list to be dynamic
        // to avoid NPEs. If there's a better way to do this, then feel free to change it!
        Element[] webapps = new Element[webapps2Deploy.size()];
        webapps2Deploy.toArray(webapps);

        // Set up the system properties that should be set for Tomcat
        ArrayList systemProps = new ArrayList<Element>();

        // Add custom system properties defined in plugin config
        if (tomcatSystemProperties != null && !tomcatSystemProperties.isEmpty()) {
            for (Map.Entry<String, String> sysProp : tomcatSystemProperties.entrySet()) {
                systemProps.add(element(name(sysProp.getKey()), sysProp.getValue()));
            }
        }
        // This might be ugly, the MojoExecuter will only accept Element[] and we need this list to be dynamic
        // to avoid NPEs. If there's a better way to do this, then feel free to change it!
        Element[] systemPropArray = new Element[systemProps.size()];
        systemProps.toArray(systemPropArray);

        executeMojo(
                plugin(
                        groupId("org.apache.tomcat.maven"),
                        artifactId("tomcat7-maven-plugin"),
                        version(MAVEN_TOMCAT7_PLUGIN_VERSION),
                        tomcatPluginDependencies
                ),
                goal("run"),
                configuration(
                        element(name("fork"), fork ? "true" : "false"),

                        /*
                         * Path
                         * In case there is a src/main/webapp in AIO it's nice to serve it up
                         */
                        element(name( "path"), "/"),

                        /*
                         * Port
                         */
                        element(name( "port" ), getPort()),

                        /*
                         * SDK Projects doesn't have packaging set to 'war', they are JARs or POMs,
                         * this setting ignores that fact.
                         */
                        element(name("ignorePackaging"), "true"),

                        /*
                         * Make sure Catalina classes are picked up when we got virtual webapp contexts with classpaths.
                         *
                         * If true a new classLoader separated from maven core will be created to start.
                         * This does not work to run with, getting :
                         *      NoSuchMethodError: javax.servlet.ServletContext.getSessionCookieConfig
                         *      (which lives in Servlet API 3)
                         *
                         */
                        element(name("useSeparateTomcatClassLoader"), "true"),

                        /*
                         * Bring in stuff in the test classpath, such as the alfresco-global.properties
                         * that should be used
                         */
                        element(name("useTestClasspath"), "true"),


                        element(name("systemProperties"), systemPropArray),

                        /*  Should this class loader delegate to the parent class loader before searching its
                            own repositories (i.e. the usual Java2 delegation model).
                            Prevent parent classloader delegation, each webapp loads.
                            If set to true then you will get a truckload of Solr logging as
                            the alf_data_dev/solr4/config/log4j-solr.properties file is not picked up.
                            This also fixes issues with the Google Guava Library, which this tomcat plugin uses
                            version 10.0.1 of but Solr uses 14.0.1 */
                        element(name("delegate"), "false"),

                        /*
                         * Encode url in UTF-8 for proper character handling -->
                         */
                        element(name("uriEncoding"), "UTF-8"),

                        /*
                         * Bring in the webapps that should be deployed and run
                         */
                        element(name("webapps"), webapps)

                ),
                execEnv
        );
    }
487516
public void deployAll() throws MojoExecutionException {
    stager.stage();
    ImmutableList.Builder<Path> computedDeployables = ImmutableList.builder();

    // Look for app.yaml
    Path appYaml = deployMojo.getStagingDirectory().resolve("app.yaml");
    if (!Files.exists(appYaml)) {
      throw new MojoExecutionException("Failed to deploy all: could not find app.yaml.");
    }
    deployMojo.getLog().info("deployAll: Preparing to deploy app.yaml");
    computedDeployables.add(appYaml);

    // Look for config yamls
    String[] configYamls = {"cron.yaml", "dispatch.yaml", "dos.yaml", "index.yaml", "queue.yaml"};
    for (String yamlName : configYamls) {
      Path yaml = appengineDirectory.resolve(yamlName);
      if (Files.exists(yaml)) {
        deployMojo.getLog().info("deployAll: Preparing to deploy " + yamlName);
        computedDeployables.add(yaml);
      }
    }

    DeployConfiguration config =
        configBuilder.buildDeployConfiguration(computedDeployables.build());

    try {
      deployMojo.getAppEngineFactory().deployment().deploy(config);
    } catch (AppEngineException ex) {
      throw new MojoExecutionException("Failed to deploy", ex);
    }
  }
323395
private void setRepositoryMapFile() throws MojoExecutionException {
        if (this.customRepositoryMap != null && !this.customRepositoryMap.isEmpty()) {
            File repositoryMap = getRepositoryMapFile(this.customRepositoryMap);
            if (repositoryMap.exists()) {
                checkRepositoryMapIsValid(repositoryMap);
                try {
                    this.xmlRepositoryMap = repositoryMap.toURI().toURL().openStream();
                } catch (IOException ioe) {
                    throw new MojoExecutionException(ioe.getLocalizedMessage());
                }
            } else {
                throw new MojoExecutionException("Repository map '" + repositoryMap.getAbsolutePath() + "' does not exist");
            }
        }

        if (this.xmlRepositoryMap == null) {
            this.xmlRepositoryMap = this.getClass().getResourceAsStream("/RepositoryMap.xml");
        }
    }
219700
@Override
	protected void setup() throws MojoExecutionException {
		if (verbose) {
			getLog().info("Rox configuration is generated");
		}
		
		// Check if the ROX configuration is available
		if (roxActive && roxConfig != null) {
			// Check the ROX configuration file
			if (!roxConfig.exists() || !roxConfig.isFile() || !roxConfig.getAbsolutePath().endsWith(".yml")) {
				getLog().warn("The " + ROX_PROPERTIES_FILENAME + " configuration seems not to be a valid file or path is incorrect. Rox will be disabled.");
				roxActive = false;
			}
			else {
				try {
					// Prepare the resource to copy
					Resource r = new Resource();
					r.setFiltering(true);
					r.setDirectory(roxConfig.getParent());
					r.setIncludes(Arrays.asList(new String[] {roxConfig.getName()}));

					// Configure the resource filtering
					MavenResourcesExecution mre = new MavenResourcesExecution(
						Arrays.asList(new Resource[] {r}), getWorkingDirectory(), project, encoding, null, null, session
					);
					
					// Filter the resources
					mavenResourcesFiltering.filterResources(mre);
				}
				catch (MavenFilteringException mfe) {
					getLog().warn("Unable to filter the " + ROX_PROPERTIES_FILENAME + " file. Rox will be disabled.", mfe);
					roxActive = false;
				}
			}
		}
		else {
			getLog().info("No rox configuration to use");
			roxActive = false;
		}		
	}