Search in sources :

Example 26 with InvocationRequest

use of org.apache.maven.shared.invoker.InvocationRequest in project maven-plugins by apache.

the class SiteInvoker method invoke.

/**
 * @param projectFile not null, should be in the ${project.basedir}
 * @param invokerLog not null
 * @param mavenHome not null
 * @param goals the list of goals
 * @param properties the properties for the invoker
 */
private void invoke(File projectFile, File invokerLog, String mavenHome, List goals, List activeProfiles, Properties properties) {
    Invoker invoker = new DefaultInvoker();
    invoker.setMavenHome(new File(mavenHome));
    File localRepoDir = new File(localRepository.getBasedir());
    invoker.setLocalRepositoryDirectory(localRepoDir);
    InvocationRequest request = new DefaultInvocationRequest();
    request.setLocalRepositoryDirectory(localRepoDir);
    // request.setUserSettingsFile( settingsFile );
    request.setBatchMode(true);
    request.setShowErrors(getLog().isErrorEnabled());
    request.setDebug(getLog().isDebugEnabled());
    // request.setShowVersion( false );
    request.setBaseDirectory(projectFile.getParentFile());
    request.setPomFile(projectFile);
    request.setGoals(goals);
    request.setProperties(properties);
    request.setProfiles(activeProfiles);
    File javaHome = getJavaHome();
    if (javaHome != null) {
        request.setJavaHome(javaHome);
    }
    InvocationResult invocationResult;
    try {
        if (getLog().isDebugEnabled()) {
            getLog().debug("Invoking Maven for the goals: " + goals + " with properties=" + properties);
        }
        invocationResult = invoke(invoker, request, invokerLog, goals, properties, null);
    } catch (MavenInvocationException e) {
        getLog().error("Error when invoking Maven, consult the invoker log.");
        getLog().debug(e);
        return;
    }
    String invokerLogContent = null;
    Reader reader = null;
    try {
        reader = ReaderFactory.newReader(invokerLog, "UTF-8");
        invokerLogContent = IOUtil.toString(reader);
        reader.close();
        reader = null;
    } catch (IOException e) {
        getLog().error("IOException: " + e.getMessage());
        getLog().debug(e);
    } finally {
        IOUtil.close(reader);
    }
    if (invokerLogContent != null && invokerLogContent.contains("Error occurred during initialization of VM")) {
        getLog().info("Error occurred during initialization of VM, try to use an empty MAVEN_OPTS.");
        if (getLog().isDebugEnabled()) {
            getLog().debug("Reinvoking Maven for the goals: " + goals + " with an empty MAVEN_OPTS");
        }
        try {
            invocationResult = invoke(invoker, request, invokerLog, goals, properties, "");
        } catch (MavenInvocationException e) {
            getLog().error("Error when reinvoking Maven, consult the invoker log.");
            getLog().debug(e);
            return;
        }
    }
    if (invocationResult.getExitCode() != 0) {
        if (getLog().isErrorEnabled()) {
            getLog().error("Error when invoking Maven, consult the invoker log file: " + invokerLog.getAbsolutePath());
        }
    }
}
Also used : Invoker(org.apache.maven.shared.invoker.Invoker) DefaultInvoker(org.apache.maven.shared.invoker.DefaultInvoker) DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) InvocationRequest(org.apache.maven.shared.invoker.InvocationRequest) MavenInvocationException(org.apache.maven.shared.invoker.MavenInvocationException) DefaultInvoker(org.apache.maven.shared.invoker.DefaultInvoker) DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) Reader(java.io.Reader) IOException(java.io.IOException) File(java.io.File) InvocationResult(org.apache.maven.shared.invoker.InvocationResult)

Example 27 with InvocationRequest

use of org.apache.maven.shared.invoker.InvocationRequest in project maven-archetype by apache.

the class CreateProjectFromArchetypeMojo method invokePostArchetypeGenerationGoals.

private void invokePostArchetypeGenerationGoals(String goals, String artifactId) throws MojoExecutionException, MojoFailureException {
    getLog().info("Invoking post-archetype-generation goals: " + goals);
    File projectBasedir = new File(basedir, artifactId);
    if (projectBasedir.exists()) {
        InvocationRequest request = new DefaultInvocationRequest().setBaseDirectory(projectBasedir).setGoals(Arrays.asList(StringUtils.split(goals, ",")));
        try {
            InvocationResult result = invoker.execute(request);
            if (result.getExitCode() != 0) {
                throw new MojoExecutionException("Failed to invoke goals", result.getExecutionException());
            }
        } catch (MavenInvocationException e) {
            throw new MojoExecutionException("Cannot run additions goals.", e);
        }
    } else {
        getLog().info("Post-archetype-generation goals aborted: unavailable basedir " + projectBasedir);
    }
}
Also used : DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) InvocationRequest(org.apache.maven.shared.invoker.InvocationRequest) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MavenInvocationException(org.apache.maven.shared.invoker.MavenInvocationException) DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) File(java.io.File) InvocationResult(org.apache.maven.shared.invoker.InvocationResult)

Example 28 with InvocationRequest

use of org.apache.maven.shared.invoker.InvocationRequest in project maven-archetype by apache.

the class IntegrationTestMojo method invokePostArchetypeGenerationGoals.

private void invokePostArchetypeGenerationGoals(String goals, File basedir, File goalFile) throws IntegrationTestFailure, IOException, MojoExecutionException {
    FileLogger logger = setupLogger(basedir);
    if (!StringUtils.isBlank(goals)) {
        getLog().info("Invoking post-archetype-generation goals: " + goals);
        if (!localRepositoryPath.exists()) {
            localRepositoryPath.mkdirs();
        }
        // @formatter:off
        InvocationRequest request = new DefaultInvocationRequest().setBaseDirectory(basedir).setGoals(Arrays.asList(StringUtils.split(goals, ","))).setLocalRepositoryDirectory(localRepositoryPath).setInteractive(false).setShowErrors(true);
        // @formatter:on
        request.setDebug(debug);
        request.setShowVersion(showVersion);
        if (logger != null) {
            request.setErrorHandler(logger);
            request.setOutputHandler(logger);
        }
        File interpolatedSettingsFile = null;
        if (settingsFile != null) {
            File interpolatedSettingsDirectory = new File(project.getBuild().getOutputDirectory(), "archetype-it");
            if (interpolatedSettingsDirectory.exists()) {
                FileUtils.deleteDirectory(interpolatedSettingsDirectory);
            }
            interpolatedSettingsDirectory.mkdir();
            interpolatedSettingsFile = new File(interpolatedSettingsDirectory, "interpolated-" + settingsFile.getName());
            buildInterpolatedFile(settingsFile, interpolatedSettingsFile);
            request.setUserSettingsFile(interpolatedSettingsFile);
        }
        try {
            InvocationResult result = invoker.execute(request);
            getLog().info("Post-archetype-generation invoker exit code: " + result.getExitCode());
            if (result.getExitCode() != 0) {
                throw new IntegrationTestFailure("Execution failure: exit code = " + result.getExitCode(), result.getExecutionException());
            }
        } catch (MavenInvocationException e) {
            throw new IntegrationTestFailure("Cannot run additions goals.", e);
        }
    } else {
        getLog().info("No post-archetype-generation goals to invoke.");
    }
    // verify result
    ScriptRunner scriptRunner = new ScriptRunner(getLog());
    scriptRunner.setScriptEncoding(encoding);
    Map<String, Object> context = new LinkedHashMap<String, Object>();
    context.put("projectDir", basedir);
    try {
        scriptRunner.run("post-build script", goalFile.getParentFile(), postBuildHookScript, context, logger, "failure post script", true);
    } catch (RunFailureException e) {
        throw new IntegrationTestFailure("post build script failure failure: " + e.getMessage(), e);
    }
}
Also used : DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) InvocationRequest(org.apache.maven.shared.invoker.InvocationRequest) MavenInvocationException(org.apache.maven.shared.invoker.MavenInvocationException) ScriptRunner(org.apache.maven.shared.scriptinterpreter.ScriptRunner) InvocationResult(org.apache.maven.shared.invoker.InvocationResult) LinkedHashMap(java.util.LinkedHashMap) RunFailureException(org.apache.maven.shared.scriptinterpreter.RunFailureException) DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) File(java.io.File)

Example 29 with InvocationRequest

use of org.apache.maven.shared.invoker.InvocationRequest in project maven-archetype by apache.

the class FilesetArchetypeCreator method createArchetype.

public void createArchetype(ArchetypeCreationRequest request, ArchetypeCreationResult result) {
    MavenProject project = request.getProject();
    List<String> languages = request.getLanguages();
    List<String> filtereds = request.getFiltereds();
    String defaultEncoding = request.getDefaultEncoding();
    boolean preserveCData = request.isPreserveCData();
    boolean keepParent = request.isKeepParent();
    boolean partialArchetype = request.isPartialArchetype();
    File outputDirectory = request.getOutputDirectory();
    File basedir = project.getBasedir();
    Properties properties = new Properties();
    Properties configurationProperties = new Properties();
    if (request.getProperties() != null) {
        properties.putAll(request.getProperties());
        configurationProperties.putAll(request.getProperties());
    }
    extractPropertiesFromProject(project, properties, configurationProperties, request.getPackageName());
    if (outputDirectory == null) {
        getLogger().debug("No output directory defined, using default: " + DEFAULT_OUTPUT_DIRECTORY);
        outputDirectory = FileUtils.resolveFile(basedir, DEFAULT_OUTPUT_DIRECTORY);
    }
    outputDirectory.mkdirs();
    getLogger().debug("Creating archetype in " + outputDirectory);
    try {
        File archetypePomFile = createArchetypeProjectPom(project, request.getProjectBuildingRequest(), configurationProperties, outputDirectory);
        File archetypeResourcesDirectory = new File(outputDirectory, getTemplateOutputDirectory());
        File archetypeFilesDirectory = new File(archetypeResourcesDirectory, Constants.ARCHETYPE_RESOURCES);
        getLogger().debug("Archetype's files output directory " + archetypeFilesDirectory);
        File archetypeDescriptorFile = new File(archetypeResourcesDirectory, Constants.ARCHETYPE_DESCRIPTOR);
        archetypeDescriptorFile.getParentFile().mkdirs();
        File archetypePostGenerationScript = new File(archetypeResourcesDirectory, Constants.ARCHETYPE_POST_GENERATION_SCRIPT);
        archetypePostGenerationScript.getParentFile().mkdirs();
        if (request.getProject().getBuild() != null && CollectionUtils.isNotEmpty(request.getProject().getBuild().getResources())) {
            for (Resource resource : request.getProject().getBuild().getResources()) {
                File inputFile = new File(resource.getDirectory() + File.separator + Constants.ARCHETYPE_POST_GENERATION_SCRIPT);
                if (inputFile.exists()) {
                    FileUtils.copyFile(inputFile, archetypePostGenerationScript);
                }
            }
        }
        getLogger().debug("Starting archetype's descriptor " + project.getArtifactId());
        ArchetypeDescriptor archetypeDescriptor = new ArchetypeDescriptor();
        archetypeDescriptor.setName(project.getArtifactId());
        archetypeDescriptor.setPartial(partialArchetype);
        addRequiredProperties(archetypeDescriptor, properties);
        // TODO ensure reverseProperties contains NO dotted properties
        Properties reverseProperties = getReversedProperties(archetypeDescriptor, properties);
        // reverseProperties.remove( Constants.GROUP_ID );
        // TODO ensure pomReversedProperties contains NO dotted properties
        Properties pomReversedProperties = getReversedProperties(archetypeDescriptor, properties);
        // pomReversedProperties.remove( Constants.PACKAGE );
        String packageName = configurationProperties.getProperty(Constants.PACKAGE);
        Model pom = pomManager.readPom(FileUtils.resolveFile(basedir, Constants.ARCHETYPE_POM));
        List<String> excludePatterns = configurationProperties.getProperty(Constants.EXCLUDE_PATTERNS) != null ? Arrays.asList(StringUtils.split(configurationProperties.getProperty(Constants.EXCLUDE_PATTERNS), ",")) : Collections.<String>emptyList();
        List<String> fileNames = resolveFileNames(pom, basedir, excludePatterns);
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Scanned for files " + fileNames.size());
            for (String name : fileNames) {
                getLogger().debug("- " + name);
            }
        }
        List<FileSet> filesets = resolveFileSets(packageName, fileNames, languages, filtereds, defaultEncoding);
        getLogger().debug("Resolved filesets for " + archetypeDescriptor.getName());
        archetypeDescriptor.setFileSets(filesets);
        createArchetypeFiles(reverseProperties, filesets, packageName, basedir, archetypeFilesDirectory, defaultEncoding, excludePatterns);
        getLogger().debug("Created files for " + archetypeDescriptor.getName());
        setParentArtifactId(reverseProperties, configurationProperties.getProperty(Constants.ARTIFACT_ID));
        for (String moduleId : pom.getModules()) {
            String rootArtifactId = configurationProperties.getProperty(Constants.ARTIFACT_ID);
            String moduleIdDirectory = moduleId;
            if (moduleId.indexOf(rootArtifactId) >= 0) {
                moduleIdDirectory = StringUtils.replace(moduleId, rootArtifactId, "__rootArtifactId__");
            }
            getLogger().debug("Creating module " + moduleId);
            ModuleDescriptor moduleDescriptor = createModule(reverseProperties, rootArtifactId, moduleId, packageName, FileUtils.resolveFile(basedir, moduleId), new File(archetypeFilesDirectory, moduleIdDirectory), languages, filtereds, defaultEncoding, preserveCData, keepParent);
            archetypeDescriptor.addModule(moduleDescriptor);
            getLogger().debug("Added module " + moduleDescriptor.getName() + " in " + archetypeDescriptor.getName());
        }
        restoreParentArtifactId(reverseProperties, null);
        restoreArtifactId(reverseProperties, configurationProperties.getProperty(Constants.ARTIFACT_ID));
        createPoms(pom, configurationProperties.getProperty(Constants.ARTIFACT_ID), configurationProperties.getProperty(Constants.ARTIFACT_ID), archetypeFilesDirectory, basedir, pomReversedProperties, preserveCData, keepParent);
        getLogger().debug("Created Archetype " + archetypeDescriptor.getName() + " template pom(s)");
        Writer out = null;
        try {
            out = WriterFactory.newXmlWriter(archetypeDescriptorFile);
            ArchetypeDescriptorXpp3Writer writer = new ArchetypeDescriptorXpp3Writer();
            writer.write(out, archetypeDescriptor);
            getLogger().debug("Archetype " + archetypeDescriptor.getName() + " descriptor written");
        } finally {
            IOUtil.close(out);
        }
        createArchetypeBasicIt(archetypeDescriptor, outputDirectory);
        // Copy archetype integration tests.
        File archetypeIntegrationTestInputFolder = new File(basedir, Constants.SRC + File.separator + "it" + File.separator + "projects");
        File archetypeIntegrationTestOutputFolder = new File(outputDirectory, Constants.SRC + File.separator + Constants.TEST + File.separator + Constants.RESOURCES + File.separator + "projects");
        if (archetypeIntegrationTestInputFolder.exists()) {
            getLogger().info("Copying: " + archetypeIntegrationTestInputFolder.getAbsolutePath() + " into " + archetypeIntegrationTestOutputFolder.getAbsolutePath());
            FileUtils.copyDirectoryStructure(archetypeIntegrationTestInputFolder, archetypeIntegrationTestOutputFolder);
        }
        InvocationRequest internalRequest = new DefaultInvocationRequest();
        internalRequest.setPomFile(archetypePomFile);
        internalRequest.setGoals(Collections.singletonList(request.getPostPhase()));
        if (request.getLocalRepository() != null) {
            internalRequest.setLocalRepositoryDirectory(new File(request.getLocalRepository().getBasedir()));
        }
        InvocationResult invokerResult = invoker.execute(internalRequest);
        if (invokerResult.getExitCode() != 0) {
            if (invokerResult.getExecutionException() != null) {
                throw invokerResult.getExecutionException();
            } else {
                throw new Exception("Invoker process ended with result different than 0!");
            }
        }
    } catch (Exception e) {
        result.setCause(e);
    }
}
Also used : FileSet(org.apache.maven.archetype.metadata.FileSet) DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) InvocationRequest(org.apache.maven.shared.invoker.InvocationRequest) Resource(org.apache.maven.model.Resource) Properties(java.util.Properties) ArchetypeDescriptor(org.apache.maven.archetype.metadata.ArchetypeDescriptor) InvocationResult(org.apache.maven.shared.invoker.InvocationResult) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException) FileNotFoundException(java.io.FileNotFoundException) TemplateCreationException(org.apache.maven.archetype.exception.TemplateCreationException) IOException(java.io.IOException) ArchetypeDescriptorXpp3Writer(org.apache.maven.archetype.metadata.io.xpp3.ArchetypeDescriptorXpp3Writer) ModuleDescriptor(org.apache.maven.archetype.metadata.ModuleDescriptor) MavenProject(org.apache.maven.project.MavenProject) Model(org.apache.maven.model.Model) DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) File(java.io.File) ArchetypeDescriptorXpp3Writer(org.apache.maven.archetype.metadata.io.xpp3.ArchetypeDescriptorXpp3Writer) Writer(java.io.Writer)

Example 30 with InvocationRequest

use of org.apache.maven.shared.invoker.InvocationRequest in project dspot by STAMP-project.

the class CloverExecutor method runGoals.

private int runGoals(String pathToRootOfProject, String... goals) {
    InvocationRequest request = new DefaultInvocationRequest();
    request.setGoals(Arrays.asList(goals));
    request.setPomFile(new File(pathToRootOfProject + FILE_SEPARATOR + POM_FILE));
    request.setJavaHome(new File(System.getProperty("java.home")));
    Properties properties = new Properties();
    properties.setProperty("enforcer.skip", "true");
    properties.setProperty("checkstyle.skip", "true");
    properties.setProperty("cobertura.skip", "true");
    properties.setProperty("skipITs", "true");
    properties.setProperty("rat.skip", "true");
    properties.setProperty("license.skip", "true");
    properties.setProperty("findbugs.skip", "true");
    properties.setProperty("gpg.skip", "true");
    properties.setProperty("jacoco.skip", "true");
    properties.setProperty("animal.sniffer.skip", "true");
    properties.setProperty("proguard.skip", "true");
    request.setProperties(properties);
    Invoker invoker = new DefaultInvoker();
    invoker.setMavenHome(new File(mavenHome));
    invoker.setOutputHandler(System.out::println);
    invoker.setErrorHandler(System.err::println);
    try {
        return invoker.execute(request).getExitCode();
    } catch (MavenInvocationException e) {
        throw new RuntimeException(e);
    }
}
Also used : DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) InvocationRequest(org.apache.maven.shared.invoker.InvocationRequest) Invoker(org.apache.maven.shared.invoker.Invoker) DefaultInvoker(org.apache.maven.shared.invoker.DefaultInvoker) MavenInvocationException(org.apache.maven.shared.invoker.MavenInvocationException) DefaultInvoker(org.apache.maven.shared.invoker.DefaultInvoker) DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) File(java.io.File)

Aggregations

DefaultInvocationRequest (org.apache.maven.shared.invoker.DefaultInvocationRequest)31 InvocationRequest (org.apache.maven.shared.invoker.InvocationRequest)31 File (java.io.File)19 MavenInvocationException (org.apache.maven.shared.invoker.MavenInvocationException)17 Properties (java.util.Properties)15 InvocationResult (org.apache.maven.shared.invoker.InvocationResult)15 DefaultInvoker (org.apache.maven.shared.invoker.DefaultInvoker)14 Invoker (org.apache.maven.shared.invoker.Invoker)13 InvokerProperties (org.apache.maven.plugins.invoker.InvokerProperties)7 IOException (java.io.IOException)5 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)3 ArrayList (java.util.ArrayList)2 LinkedHashMap (java.util.LinkedHashMap)2 CommandLineConfigurationException (org.apache.maven.shared.invoker.CommandLineConfigurationException)2 MavenCommandLineBuilder (org.apache.maven.shared.invoker.MavenCommandLineBuilder)2 RunFailureException (org.apache.maven.shared.scriptinterpreter.RunFailureException)2 FileNotFoundException (java.io.FileNotFoundException)1 FileWriter (java.io.FileWriter)1 PrintWriter (java.io.PrintWriter)1 Reader (java.io.Reader)1