Search in sources :

Example 6 with MavenInvocationException

use of org.apache.maven.shared.invoker.MavenInvocationException 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 MavenInvocationException

use of org.apache.maven.shared.invoker.MavenInvocationException 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 MavenInvocationException

use of org.apache.maven.shared.invoker.MavenInvocationException 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 MavenInvocationException

use of org.apache.maven.shared.invoker.MavenInvocationException 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 MavenInvocationException

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

the class AbstractJavadocMojo method getModulesLinks.

/**
     * Using Maven, a Javadoc link is given by <code>${project.url}/apidocs</code>.
     *
     * @return the detected Javadoc links using the Maven conventions for all modules defined in the current project
     *         or an empty list.
     * @throws MavenReportException if any
     * @see #detectOfflineLinks
     * @see #reactorProjects
     * @since 2.6
     */
private List<OfflineLink> getModulesLinks() throws MavenReportException {
    if (!detectOfflineLinks || isAggregator() || reactorProjects == null) {
        return Collections.emptyList();
    }
    getLog().debug("Trying to add links for modules...");
    Set<String> dependencyArtifactIds = new HashSet<String>();
    final Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();
    for (Artifact artifact : dependencyArtifacts) {
        dependencyArtifactIds.add(artifact.getId());
    }
    List<OfflineLink> modulesLinks = new ArrayList<OfflineLink>();
    String javadocDirRelative = PathUtils.toRelative(project.getBasedir(), getOutputDirectory());
    for (MavenProject p : reactorProjects) {
        if (!dependencyArtifactIds.contains(p.getArtifact().getId()) || (p.getUrl() == null)) {
            continue;
        }
        File location = new File(p.getBasedir(), javadocDirRelative);
        if (!location.exists()) {
            if (getLog().isDebugEnabled()) {
                getLog().debug("Javadoc directory not found: " + location);
            }
            String javadocGoal = getFullJavadocGoal();
            getLog().info("The goal '" + javadocGoal + "' has not been previously called for the module: '" + p.getId() + "'. Trying to invoke it...");
            File invokerDir = new File(project.getBuild().getDirectory(), "invoker");
            invokerDir.mkdirs();
            File invokerLogFile = FileUtils.createTempFile("maven-javadoc-plugin", ".txt", invokerDir);
            try {
                JavadocUtil.invokeMaven(getLog(), new File(localRepository.getBasedir()), p.getFile(), Collections.singletonList(javadocGoal), null, invokerLogFile);
            } catch (MavenInvocationException e) {
                logError("MavenInvocationException: " + e.getMessage(), e);
                String invokerLogContent = JavadocUtil.readFile(invokerLogFile, null);
                //   the JVM won't start (opposite of what it was).
                if (invokerLogContent != null && invokerLogContent.contains(JavadocUtil.ERROR_INIT_VM)) {
                    throw new MavenReportException(e.getMessage(), e);
                }
            } finally {
                // just create the directory to prevent repeated invocations..
                if (!location.exists()) {
                    getLog().warn("Creating fake javadoc directory to prevent repeated invocations: " + location);
                    location.mkdirs();
                }
            }
        }
        if (location.exists()) {
            String url = getJavadocLink(p);
            OfflineLink ol = new OfflineLink();
            ol.setUrl(url);
            ol.setLocation(location.getAbsolutePath());
            if (getLog().isDebugEnabled()) {
                getLog().debug("Added Javadoc offline link: " + url + " for the module: " + p.getId());
            }
            modulesLinks.add(ol);
        }
    }
    return modulesLinks;
}
Also used : MavenProject(org.apache.maven.project.MavenProject) MavenInvocationException(org.apache.maven.shared.invoker.MavenInvocationException) ArrayList(java.util.ArrayList) OfflineLink(org.apache.maven.plugin.javadoc.options.OfflineLink) File(java.io.File) JavadocPathArtifact(org.apache.maven.plugin.javadoc.options.JavadocPathArtifact) Artifact(org.apache.maven.artifact.Artifact) DocletArtifact(org.apache.maven.plugin.javadoc.options.DocletArtifact) BootclasspathArtifact(org.apache.maven.plugin.javadoc.options.BootclasspathArtifact) ResourcesArtifact(org.apache.maven.plugin.javadoc.options.ResourcesArtifact) TagletArtifact(org.apache.maven.plugin.javadoc.options.TagletArtifact) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) MavenReportException(org.apache.maven.reporting.MavenReportException)

Aggregations

MavenInvocationException (org.apache.maven.shared.invoker.MavenInvocationException)18 File (java.io.File)16 DefaultInvocationRequest (org.apache.maven.shared.invoker.DefaultInvocationRequest)15 InvocationRequest (org.apache.maven.shared.invoker.InvocationRequest)15 InvocationResult (org.apache.maven.shared.invoker.InvocationResult)13 DefaultInvoker (org.apache.maven.shared.invoker.DefaultInvoker)11 Invoker (org.apache.maven.shared.invoker.Invoker)11 Properties (java.util.Properties)5 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 Artifact (org.apache.maven.artifact.Artifact)3 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)3 HashSet (java.util.HashSet)2 LinkedHashMap (java.util.LinkedHashMap)2 LinkedHashSet (java.util.LinkedHashSet)2 MavenProject (org.apache.maven.project.MavenProject)2 MavenReportException (org.apache.maven.reporting.MavenReportException)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