Search in sources :

Example 6 with InvocationResult

use of org.apache.maven.shared.invoker.InvocationResult in project repairnator by Spirals-Team.

the class RunnableMavenInvoker method run.

@Override
public void run() {
    InvocationRequest request = new DefaultInvocationRequest();
    request.setPomFile(new File(this.mavenHelper.getPomFile()));
    request.setGoals(Arrays.asList(this.mavenHelper.getGoal()));
    request.setProperties(this.mavenHelper.getProperties());
    Invoker invoker = new DefaultInvoker();
    if (this.mavenHelper.getErrorHandler() != null) {
        invoker.setErrorHandler(this.mavenHelper.getErrorHandler());
    }
    invoker.setOutputHandler(this.mavenHelper.getOutputHandler());
    try {
        InvocationResult result = invoker.execute(request);
        this.exitCode = result.getExitCode();
    } catch (MavenInvocationException e) {
        this.logger.error("Error while executing goal :" + this.mavenHelper.getGoal() + " on the following pom file: " + this.mavenHelper.getPomFile() + ". Properties: " + this.mavenHelper.getProperties());
        this.logger.debug(e.getMessage());
        this.mavenHelper.getInspector().getJobStatus().addStepError(this.mavenHelper.getName(), e.getMessage());
        this.exitCode = MavenHelper.MAVEN_ERROR;
    }
}
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) InvocationResult(org.apache.maven.shared.invoker.InvocationResult)

Example 7 with InvocationResult

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

the class AbstractInvokerMojo method runBuild.

/**
 * Runs the specified project.
 *
 * @param basedir The base directory of the project, must not be <code>null</code>.
 * @param pomFile The (already interpolated) POM file, may be <code>null</code> for a POM-less Maven invocation.
 * @param settingsFile The (already interpolated) user settings file for the build, may be <code>null</code>. Will
 *            be merged with the settings file of the invoking Maven process.
 * @param invokerProperties The properties to use.
 * @return <code>true</code> if the project was launched or <code>false</code> if the selector script indicated that
 *         the project should be skipped.
 * @throws org.apache.maven.plugin.MojoExecutionException If the project could not be launched.
 * @throws org.apache.maven.shared.scriptinterpreter.RunFailureException If either a hook script or the build itself
 *             failed.
 */
private boolean runBuild(File basedir, File pomFile, File settingsFile, File actualJavaHome, InvokerProperties invokerProperties) throws MojoExecutionException, RunFailureException {
    if (getLog().isDebugEnabled() && !invokerProperties.getProperties().isEmpty()) {
        Properties props = invokerProperties.getProperties();
        getLog().debug("Using invoker properties:");
        for (String key : new TreeSet<String>(props.stringPropertyNames())) {
            String value = props.getProperty(key);
            getLog().debug("  " + key + " = " + value);
        }
    }
    List<String> goals = getGoals(basedir);
    List<String> profiles = getProfiles(basedir);
    Map<String, Object> context = new LinkedHashMap<String, Object>();
    FileLogger logger = setupBuildLogFile(basedir);
    boolean selectorResult = true;
    try {
        try {
            scriptRunner.run("selector script", basedir, selectorScript, context, logger, BuildJob.Result.SKIPPED, false);
        } catch (RunErrorException e) {
            selectorResult = false;
            throw e;
        } catch (RunFailureException e) {
            selectorResult = false;
            return false;
        }
        scriptRunner.run("pre-build script", basedir, preBuildHookScript, context, logger, BuildJob.Result.FAILURE_PRE_HOOK, false);
        final InvocationRequest request = new DefaultInvocationRequest();
        request.setLocalRepositoryDirectory(localRepositoryPath);
        request.setBatchMode(true);
        request.setShowErrors(showErrors);
        request.setDebug(debug);
        request.setShowVersion(showVersion);
        setupLoggerForBuildJob(logger, request);
        if (mavenHome != null) {
            invoker.setMavenHome(mavenHome);
            // FIXME: Should we really take care of M2_HOME?
            request.addShellEnvironment("M2_HOME", mavenHome.getAbsolutePath());
        }
        if (mavenExecutable != null) {
            invoker.setMavenExecutable(new File(mavenExecutable));
        }
        if (actualJavaHome != null) {
            request.setJavaHome(actualJavaHome);
        }
        if (environmentVariables != null) {
            for (Map.Entry<String, String> variable : environmentVariables.entrySet()) {
                request.addShellEnvironment(variable.getKey(), variable.getValue());
            }
        }
        for (int invocationIndex = 1; ; invocationIndex++) {
            if (invocationIndex > 1 && !invokerProperties.isInvocationDefined(invocationIndex)) {
                break;
            }
            request.setBaseDirectory(basedir);
            request.setPomFile(pomFile);
            request.setGoals(goals);
            request.setProfiles(profiles);
            request.setMavenOpts(mavenOpts);
            request.setOffline(false);
            String customSettingsFile = invokerProperties.getSettingsFile(invocationIndex);
            if (customSettingsFile != null) {
                File interpolateSettingsFile = interpolateSettings(new File(customSettingsFile));
                File mergeSettingsFile = mergeSettings(interpolateSettingsFile);
                request.setUserSettingsFile(mergeSettingsFile);
            } else {
                request.setUserSettingsFile(settingsFile);
            }
            Properties systemProperties = getSystemProperties(basedir, invokerProperties.getSystemPropertiesFile(invocationIndex));
            request.setProperties(systemProperties);
            invokerProperties.configureInvocation(request, invocationIndex);
            if (getLog().isDebugEnabled()) {
                try {
                    getLog().debug("Using MAVEN_OPTS: " + request.getMavenOpts());
                    getLog().debug("Executing: " + new MavenCommandLineBuilder().build(request));
                } catch (CommandLineConfigurationException e) {
                    getLog().debug("Failed to display command line: " + e.getMessage());
                }
            }
            InvocationResult result;
            try {
                result = invoker.execute(request);
            } catch (final MavenInvocationException e) {
                getLog().debug("Error invoking Maven: " + e.getMessage(), e);
                throw new RunFailureException("Maven invocation failed. " + e.getMessage(), BuildJob.Result.FAILURE_BUILD);
            }
            verify(result, invocationIndex, invokerProperties, logger);
        }
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        if (selectorResult) {
            runPostBuildHook(basedir, context, logger);
        }
        if (logger != null) {
            logger.close();
        }
    }
    return true;
}
Also used : RunErrorException(org.apache.maven.shared.scriptinterpreter.RunErrorException) 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) IOException(java.io.IOException) Properties(java.util.Properties) InvocationResult(org.apache.maven.shared.invoker.InvocationResult) LinkedHashMap(java.util.LinkedHashMap) RunFailureException(org.apache.maven.shared.scriptinterpreter.RunFailureException) TreeSet(java.util.TreeSet) DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) MavenCommandLineBuilder(org.apache.maven.shared.invoker.MavenCommandLineBuilder) CommandLineConfigurationException(org.apache.maven.shared.invoker.CommandLineConfigurationException) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 8 with InvocationResult

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

the class JavadocUtil method invokeMaven.

/**
 * Invoke Maven for the given project file with a list of goals and properties, the output will be in the
 * invokerlog file.
 * <br/>
 * <b>Note</b>: the Maven Home should be defined in the <code>maven.home</code> Java system property or defined in
 * <code>M2_HOME</code> system env variables.
 *
 * @param log a logger could be null.
 * @param localRepositoryDir the localRepository not null.
 * @param projectFile a not null project file.
 * @param goals a not null goals list.
 * @param properties the properties for the goals, could be null.
 * @param invokerLog the log file where the invoker will be written, if null using <code>System.out</code>.
 * @throws MavenInvocationException if any
 * @since 2.6
 */
protected static void invokeMaven(Log log, File localRepositoryDir, File projectFile, List<String> goals, Properties properties, File invokerLog) throws MavenInvocationException {
    if (projectFile == null) {
        throw new IllegalArgumentException("projectFile should be not null.");
    }
    if (!projectFile.isFile()) {
        throw new IllegalArgumentException(projectFile.getAbsolutePath() + " is not a file.");
    }
    if (goals == null || goals.size() == 0) {
        throw new IllegalArgumentException("goals should be not empty.");
    }
    if (localRepositoryDir == null || !localRepositoryDir.isDirectory()) {
        throw new IllegalArgumentException("localRepositoryDir '" + localRepositoryDir + "' should be a directory.");
    }
    String mavenHome = getMavenHome(log);
    if (StringUtils.isEmpty(mavenHome)) {
        String msg = "Could NOT invoke Maven because no Maven Home is defined. You need to have set the M2_HOME " + "system env variable or a maven.home Java system properties.";
        if (log != null) {
            log.error(msg);
        } else {
            System.err.println(msg);
        }
        return;
    }
    Invoker invoker = new DefaultInvoker();
    invoker.setMavenHome(new File(mavenHome));
    invoker.setLocalRepositoryDirectory(localRepositoryDir);
    InvocationRequest request = new DefaultInvocationRequest();
    request.setBaseDirectory(projectFile.getParentFile());
    request.setPomFile(projectFile);
    if (log != null) {
        request.setDebug(log.isDebugEnabled());
    } else {
        request.setDebug(true);
    }
    request.setGoals(goals);
    if (properties != null) {
        request.setProperties(properties);
    }
    File javaHome = getJavaHome(log);
    if (javaHome != null) {
        request.setJavaHome(javaHome);
    }
    if (log != null && log.isDebugEnabled()) {
        log.debug("Invoking Maven for the goals: " + goals + " with " + (properties == null ? "no properties" : "properties=" + properties));
    }
    InvocationResult result = invoke(log, invoker, request, invokerLog, goals, properties, null);
    if (result.getExitCode() != 0) {
        String invokerLogContent = readFile(invokerLog, "UTF-8");
        // see DefaultMaven
        if (invokerLogContent != null && (!invokerLogContent.contains("Scanning for projects...") || invokerLogContent.contains(OutOfMemoryError.class.getName()))) {
            if (log != null) {
                log.error("Error occurred during initialization of VM, trying to use an empty MAVEN_OPTS...");
                if (log.isDebugEnabled()) {
                    log.debug("Reinvoking Maven for the goals: " + goals + " with an empty MAVEN_OPTS...");
                }
            }
            result = invoke(log, invoker, request, invokerLog, goals, properties, "");
        }
    }
    if (result.getExitCode() != 0) {
        String invokerLogContent = readFile(invokerLog, "UTF-8");
        // see DefaultMaven
        if (invokerLogContent != null && (!invokerLogContent.contains("Scanning for projects...") || invokerLogContent.contains(OutOfMemoryError.class.getName()))) {
            throw new MavenInvocationException(ERROR_INIT_VM);
        }
        throw new MavenInvocationException("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) File(java.io.File) InvocationResult(org.apache.maven.shared.invoker.InvocationResult)

Example 9 with InvocationResult

use of org.apache.maven.shared.invoker.InvocationResult in project spring-boot by spring-projects.

the class MavenBuild method execute.

private void execute(ProjectCallback callback, int expectedExitCode) {
    Invoker invoker = new DefaultInvoker();
    invoker.setMavenHome(this.home);
    InvocationRequest request = new DefaultInvocationRequest();
    try {
        Path destination = this.temp.toPath();
        Path source = this.projectDir.toPath();
        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Files.createDirectories(destination.resolve(source.relativize(dir)));
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toFile().getName().equals("pom.xml")) {
                    String pomXml = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
                    for (Entry<String, String> replacement : MavenBuild.this.pomReplacements.entrySet()) {
                        pomXml = pomXml.replace("@" + replacement.getKey() + "@", replacement.getValue());
                    }
                    Files.write(destination.resolve(source.relativize(file)), pomXml.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW);
                } else {
                    Files.copy(file, destination.resolve(source.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
                }
                return FileVisitResult.CONTINUE;
            }
        });
        String settingsXml = new String(Files.readAllBytes(Paths.get("src", "intTest", "projects", "settings.xml")), StandardCharsets.UTF_8).replace("@localCentralUrl@", new File("build/int-test-maven-repository").toURI().toURL().toString()).replace("@localRepositoryPath@", new File("build/local-maven-repository").getAbsolutePath());
        Files.write(destination.resolve("settings.xml"), settingsXml.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW);
        request.setBaseDirectory(this.temp);
        request.setJavaHome(new File(System.getProperty("java.home")));
        request.setProperties(this.properties);
        request.setGoals(this.goals.isEmpty() ? Collections.singletonList("package") : this.goals);
        request.setUserSettingsFile(new File(this.temp, "settings.xml"));
        request.setUpdateSnapshots(true);
        request.setBatchMode(true);
        // request.setMavenOpts("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=8000");
        File target = new File(this.temp, "target");
        target.mkdirs();
        if (this.preparation != null) {
            this.preparation.doWith(this.temp);
        }
        File buildLogFile = new File(target, "build.log");
        try (PrintWriter buildLog = new PrintWriter(new FileWriter(buildLogFile))) {
            request.setOutputHandler((line) -> {
                buildLog.println(line);
                buildLog.flush();
            });
            try {
                InvocationResult result = invoker.execute(request);
                assertThat(result.getExitCode()).as(contentOf(buildLogFile)).isEqualTo(expectedExitCode);
            } catch (MavenInvocationException ex) {
                throw new RuntimeException(ex);
            }
        }
        callback.doWith(this.temp);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
Also used : Path(java.nio.file.Path) DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) InvocationRequest(org.apache.maven.shared.invoker.InvocationRequest) FileWriter(java.io.FileWriter) MavenInvocationException(org.apache.maven.shared.invoker.MavenInvocationException) DefaultInvoker(org.apache.maven.shared.invoker.DefaultInvoker) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) InvocationResult(org.apache.maven.shared.invoker.InvocationResult) MavenInvocationException(org.apache.maven.shared.invoker.MavenInvocationException) IOException(java.io.IOException) Entry(java.util.Map.Entry) Invoker(org.apache.maven.shared.invoker.Invoker) DefaultInvoker(org.apache.maven.shared.invoker.DefaultInvoker) DefaultInvocationRequest(org.apache.maven.shared.invoker.DefaultInvocationRequest) File(java.io.File) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) PrintWriter(java.io.PrintWriter)

Example 10 with InvocationResult

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

the class JavadocUtil method invokeMaven.

/**
     * Invoke Maven for the given project file with a list of goals and properties, the output will be in the
     * invokerlog file.
     * <br/>
     * <b>Note</b>: the Maven Home should be defined in the <code>maven.home</code> Java system property or defined in
     * <code>M2_HOME</code> system env variables.
     *
     * @param log a logger could be null.
     * @param localRepositoryDir the localRepository not null.
     * @param projectFile a not null project file.
     * @param goals a not null goals list.
     * @param properties the properties for the goals, could be null.
     * @param invokerLog the log file where the invoker will be written, if null using <code>System.out</code>.
     * @throws MavenInvocationException if any
     * @since 2.6
     */
protected static void invokeMaven(Log log, File localRepositoryDir, File projectFile, List<String> goals, Properties properties, File invokerLog) throws MavenInvocationException {
    if (projectFile == null) {
        throw new IllegalArgumentException("projectFile should be not null.");
    }
    if (!projectFile.isFile()) {
        throw new IllegalArgumentException(projectFile.getAbsolutePath() + " is not a file.");
    }
    if (goals == null || goals.size() == 0) {
        throw new IllegalArgumentException("goals should be not empty.");
    }
    if (localRepositoryDir == null || !localRepositoryDir.isDirectory()) {
        throw new IllegalArgumentException("localRepositoryDir '" + localRepositoryDir + "' should be a directory.");
    }
    String mavenHome = getMavenHome(log);
    if (StringUtils.isEmpty(mavenHome)) {
        String msg = "Could NOT invoke Maven because no Maven Home is defined. You need to have set the M2_HOME " + "system env variable or a maven.home Java system properties.";
        if (log != null) {
            log.error(msg);
        } else {
            System.err.println(msg);
        }
        return;
    }
    Invoker invoker = new DefaultInvoker();
    invoker.setMavenHome(new File(mavenHome));
    invoker.setLocalRepositoryDirectory(localRepositoryDir);
    InvocationRequest request = new DefaultInvocationRequest();
    request.setBaseDirectory(projectFile.getParentFile());
    request.setPomFile(projectFile);
    if (log != null) {
        request.setDebug(log.isDebugEnabled());
    } else {
        request.setDebug(true);
    }
    request.setGoals(goals);
    if (properties != null) {
        request.setProperties(properties);
    }
    File javaHome = getJavaHome(log);
    if (javaHome != null) {
        request.setJavaHome(javaHome);
    }
    if (log != null && log.isDebugEnabled()) {
        log.debug("Invoking Maven for the goals: " + goals + " with " + (properties == null ? "no properties" : "properties=" + properties));
    }
    InvocationResult result = invoke(log, invoker, request, invokerLog, goals, properties, null);
    if (result.getExitCode() != 0) {
        String invokerLogContent = readFile(invokerLog, "UTF-8");
        // see DefaultMaven
        if (invokerLogContent != null && (!invokerLogContent.contains("Scanning for projects...") || invokerLogContent.contains(OutOfMemoryError.class.getName()))) {
            if (log != null) {
                log.error("Error occurred during initialization of VM, trying to use an empty MAVEN_OPTS...");
                if (log.isDebugEnabled()) {
                    log.debug("Reinvoking Maven for the goals: " + goals + " with an empty MAVEN_OPTS...");
                }
            }
            result = invoke(log, invoker, request, invokerLog, goals, properties, "");
        }
    }
    if (result.getExitCode() != 0) {
        String invokerLogContent = readFile(invokerLog, "UTF-8");
        // see DefaultMaven
        if (invokerLogContent != null && (!invokerLogContent.contains("Scanning for projects...") || invokerLogContent.contains(OutOfMemoryError.class.getName()))) {
            throw new MavenInvocationException(ERROR_INIT_VM);
        }
        throw new MavenInvocationException("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) File(java.io.File) InvocationResult(org.apache.maven.shared.invoker.InvocationResult)

Aggregations

InvocationResult (org.apache.maven.shared.invoker.InvocationResult)16 DefaultInvocationRequest (org.apache.maven.shared.invoker.DefaultInvocationRequest)15 InvocationRequest (org.apache.maven.shared.invoker.InvocationRequest)15 File (java.io.File)14 MavenInvocationException (org.apache.maven.shared.invoker.MavenInvocationException)13 DefaultInvoker (org.apache.maven.shared.invoker.DefaultInvoker)11 Invoker (org.apache.maven.shared.invoker.Invoker)10 IOException (java.io.IOException)5 Properties (java.util.Properties)3 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)3 FileNotFoundException (java.io.FileNotFoundException)2 LinkedHashMap (java.util.LinkedHashMap)2 RunFailureException (org.apache.maven.shared.scriptinterpreter.RunFailureException)2 FileWriter (java.io.FileWriter)1 PrintStream (java.io.PrintStream)1 PrintWriter (java.io.PrintWriter)1 Reader (java.io.Reader)1 Writer (java.io.Writer)1 FileVisitResult (java.nio.file.FileVisitResult)1 Path (java.nio.file.Path)1