org.apache.maven.shared.invoker.InvocationResult Java Examples

The following examples show how to use org.apache.maven.shared.invoker.InvocationResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExecuteUtil.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public static void executeMaven(File projectDirectory, CommandInvocation invocation, String buildTarget) {
    String mvnPath = findExecutable("mvn");
    System.setProperty("maven.home", mvnPath);

    InvocationRequest request = new DefaultInvocationRequest();
    request.setPomFile(new File(projectDirectory.getAbsolutePath() + File.separatorChar + "pom.xml"));
    request.setGoals(Collections.singletonList(buildTarget));

    Invoker invoker = new DefaultInvoker();

    InvocationResult result = null;
    try {
        result = invoker.execute(request);
    } catch (MavenInvocationException e) {
        invocation.println("Failed during invocation: " + e.getMessage());
    }

    if (result.getExitCode() != 0) {
        invocation.println("Build failed.");
    }
}
 
Example #2
Source File: AbstractSundrioMojo.java    From sundrio with Apache License 2.0 6 votes vote down vote up
void backGroundBuild(MavenProject project) throws MojoExecutionException {
    MavenExecutionRequest executionRequest = session.getRequest();

    InvocationRequest request = new DefaultInvocationRequest();
    request.setBaseDirectory(project.getBasedir());
    request.setPomFile(project.getFile());
    request.setGoals(executionRequest.getGoals());
    request.setRecursive(false);
    request.setInteractive(false);

    request.setProfiles(executionRequest.getActiveProfiles());
    request.setProperties(executionRequest.getUserProperties());
    Invoker invoker = new DefaultInvoker();
    try {
        InvocationResult result = invoker.execute(request);
        if (result.getExitCode() != 0) {
            throw new IllegalStateException("Error invoking Maven goals:[" + StringUtils.join(executionRequest.getGoals(), ", ") + "]", result.getExecutionException());
        }
    } catch (MavenInvocationException e) {
        throw new IllegalStateException("Error invoking Maven goals:[" + StringUtils.join(executionRequest.getGoals(), ", ") + "]", e);
    }
}
 
Example #3
Source File: BuildProject.java    From unleash-maven-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void execute(ExecutionContext context) throws MojoExecutionException, MojoFailureException {
  this.log.info("Starting release build.");

  try {
    InvocationRequest request = setupInvocationRequest();
    Invoker invoker = setupInvoker();

    InvocationResult result = invoker.execute(request);
    if (result.getExitCode() != 0) {
      CommandLineException executionException = result.getExecutionException();
      if (executionException != null) {
        throw new MojoFailureException("Error during project build: " + executionException.getMessage(),
            executionException);
      } else {
        throw new MojoFailureException("Error during project build: " + result.getExitCode());
      }
    }
  } catch (MavenInvocationException e) {
    throw new MojoFailureException(e.getMessage(), e);
  }
}
 
Example #4
Source File: NativeBuildMojo.java    From client-maven-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void execute() throws MojoExecutionException {
    getLog().debug("Start building");

    // prepare the execution:
    final InvocationRequest invocationRequest = new DefaultInvocationRequest();
    invocationRequest.setProfiles(project.getActiveProfiles().stream()
            .map(Profile::getId)
            .collect(Collectors.toList()));
    invocationRequest.setPomFile(new File(pom));

    invocationRequest.setGoals(Arrays.asList("client:compile", "client:link"));

    final Invoker invoker = new DefaultInvoker();
    // execute:
    try {
        final InvocationResult invocationResult = invoker.execute(invocationRequest);
        if (invocationResult.getExitCode() != 0) {
            throw new MojoExecutionException("Error, client:build failed", invocationResult.getExecutionException());
        }
    } catch (MavenInvocationException e) {
        e.printStackTrace();
        throw new MojoExecutionException("Error", e);
    }

}
 
Example #5
Source File: ProjectGenerator.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
protected void runMavenGoals(File outputDir, String... goals) throws MavenInvocationException {
    List<String> goalList = Arrays.asList(goals);
    LOG.info("Invoking maven with goals: " + goalList + " in folder: " + outputDir);
    File pomFile = new File(outputDir, "pom.xml");

    InvocationRequest request = new DefaultInvocationRequest();
    request.setLocalRepositoryDirectory(localMavenRepo);
    request.setInteractive(false);
    request.setPomFile(pomFile);
    request.setGoals(goalList);

    // lets use a dummy service name to avoid it being too long
    request.setMavenOpts("-Dfabric8.service.name=dummy-name");

    Invoker invoker = new DefaultInvoker();
    InvocationResult result = invoker.execute(request);
    int exitCode = result.getExitCode();
    LOG.info("maven result " + exitCode + " exception: " + result.getExecutionException());
    if (exitCode != 0) {
        LOG.error("Failed to invoke maven goals: " + goalList + " in folder: " + outputDir + ". Exit Code: " + exitCode);
        failedFolders.add(outputDir);
    }
}
 
Example #6
Source File: ProjectGenerator.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
public File getArtifactJar(String groupId, String artifactId, String version) {
    Properties properties = new Properties();
    properties.put("groupId", groupId);
    properties.put("artifactId", artifactId);
    properties.put("version", version);

    InvocationRequest request = new DefaultInvocationRequest();
    request.setLocalRepositoryDirectory(localMavenRepo);
    request.setInteractive(false);
    List<String> goalList = Arrays.asList("org.apache.maven.plugins:maven-dependency-plugin:2.10:get");
    request.setGoals(goalList);
    request.setProperties(properties);

    try {
        Invoker invoker = new DefaultInvoker();
        InvocationResult result = invoker.execute(request);
        int exitCode = result.getExitCode();
        LOG.info("maven result " + exitCode + " exception: " + result.getExecutionException());
        assertEquals("Failed to invoke maven goals: " + goalList + " with properties: " + properties + ". Exit Code: ", 0, exitCode);
    } catch (MavenInvocationException e) {
        fail("Failed to invoke maven goals: " + goalList + " with properties: " + properties + ". Exception " + e, e);
    }
    String path = groupId.replace('.', '/') + "/" + artifactId + "/" + version + "/" + artifactId + "-" + version + ".jar";
    return new File(localMavenRepo, path);
}
 
Example #7
Source File: MavenDependencyResolver.java    From carnotzet with Apache License 2.0 6 votes vote down vote up
private void executeMavenBuild(List<String> goals, InvocationOutputHandler outputHandler) {
	log.debug("Invoking maven with goals {}", goals);
	InvocationRequest request = new DefaultInvocationRequest();
	request.setBatchMode(true);
	request.setGoals(goals);
	// reset MAVEN_DEBUG_OPTS to allow debugging without blocking the invoker calls
	request.addShellEnvironment("MAVEN_DEBUG_OPTS", "");
	InvocationOutputHandler outHandler = outputHandler;
	if (outHandler == null) {
		outHandler = log::debug;
	}
	request.setOutputHandler(outHandler);
	try {
		InvocationResult result = maven.execute(request);
		if (result.getExitCode() != 0) {
			throw new MavenInvocationException("Maven process exited with non-zero code [" + result.getExitCode() + "]. "
					+ "Retry with debug log level enabled to see the maven invocation logs");
		}
	}
	catch (MavenInvocationException e) {
		throw new CarnotzetDefinitionException("Error invoking mvn " + goals, e);
	}
}
 
Example #8
Source File: CreateProjectMojoIT.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private InvocationResult setup(Properties params)
        throws MavenInvocationException, FileNotFoundException, UnsupportedEncodingException {

    params.setProperty("platformGroupId", ToolsConstants.IO_QUARKUS);
    params.setProperty("platformArtifactId", "quarkus-bom");
    params.setProperty("platformVersion", getPluginVersion());

    InvocationRequest request = new DefaultInvocationRequest();
    request.setBatchMode(true);
    request.setGoals(Collections.singletonList(
            getPluginGroupId() + ":" + getPluginArtifactId() + ":" + getPluginVersion() + ":create"));
    request.setDebug(false);
    request.setShowErrors(false);
    request.setProperties(params);
    getEnv().forEach(request::addShellEnvironment);
    File log = new File(testDir, "build-create-" + testDir.getName() + ".log");
    PrintStreamLogger logger = new PrintStreamLogger(new PrintStream(new FileOutputStream(log), false, "UTF-8"),
            InvokerLogger.DEBUG);
    invoker.setLogger(logger);
    return invoker.execute(request);
}
 
Example #9
Source File: CreateProjectMojoIT.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testProjectGenerationWithInvalidPackage() throws Exception {
    testDir = initEmptyProject("projects/project-generation-invalid-package");
    assertThat(testDir).isDirectory();
    invoker = initInvoker(testDir);

    Properties properties = new Properties();
    properties.put("projectGroupId", "org.acme");
    properties.put("projectArtifactId", "acme");
    properties.put("className", "org.acme.invalid-package-name.MyResource");

    InvocationResult result = setup(properties);

    assertThat(result.getExitCode()).isNotZero();
    assertThat(new File(testDir, "src/main/java/org/acme")).doesNotExist();
}
 
Example #10
Source File: MavenJarResolver.java    From beakerx with Apache License 2.0 6 votes vote down vote up
private AddMvnCommandResult retrieveDeps(String dependencies, Message parent, String pomAsString) {
  File finalPom = null;
  try {
    finalPom = saveToFile(commandParams.getPathToNotebookJars(), pomAsString);
    InvocationRequest request = createInvocationRequest(finalPom);
    MvnDownloadLoggerWidget progress = new MvnDownloadLoggerWidget(parent);
    this.logs = manageOutput(this.logs, parent);
    MavenInvocationSilentOutputHandler outputHandler = new MavenInvocationSilentOutputHandler(progress, this.logs);
    Invoker invoker = getInvoker(outputHandler);
    progress.display();
    InvocationResult invocationResult = invoker.execute(request);
    progress.close();
    this.logs.stop();
    return getResult(invocationResult, dependencies);
  } catch (Exception e) {
    return AddMvnCommandResult.error(e.getMessage());
  } finally {
    deletePomFolder(finalPom);
  }
}
 
Example #11
Source File: WADFlow.java    From wad with MIT License 6 votes vote down vote up
void build() {
    long start = System.currentTimeMillis();
    try {
        System.out.printf("[%s%s%s]", TerminalColors.TIME.value(), currentFormattedTime(), TerminalColors.RESET.value());
        InvocationResult result = this.builder.build();
        if (result.getExitCode() == 0) {
            System.out.printf("[%d]", successCounter.incrementAndGet());
            System.out.print("\uD83D\uDC4D");
            long buildTime = (System.currentTimeMillis() - start);
            buildTimes.add(buildTime);
            System.out.println(" built in " + buildTime + " ms");
            if (buildTimes.size() % 10 == 0) {
                this.printStatistics();
            }
        } else {
            System.out.printf("[%d] ", buildErrorCounter.incrementAndGet());
            System.out.println("\uD83D\uDC4E ");
        }
    } catch (MavenInvocationException ex) {
        System.err.println(ex.getClass().getName() + " " + ex.getMessage());
    }
}
 
Example #12
Source File: RunnableMavenInvoker.java    From repairnator with MIT License 5 votes vote down vote up
@Override
public void run() {
    InvocationRequest request = new DefaultInvocationRequest();
    request.setPomFile(new File(this.mavenHelper.getPomFile()));
    request.setGoals(Arrays.asList(this.mavenHelper.getGoal()));
    Properties props = this.mavenHelper.getProperties();
    if (System.getenv("M2_HOME") == null) {
        // sensible value
        // https://stackoverflow.com/questions/14793015/programmatically-launch-m2e-maven-command
        String mavenHome = RepairnatorConfig.getInstance().getMavenHome();
        System.out.println("M2_HOME not found, using provided input value instead - " + mavenHome);
        System.setProperty("maven.home", mavenHome);
    } else if ( System.getProperty("maven.home") == null ) {
        System.setProperty("maven.home", System.getenv("M2_HOME"));
    }
    request.setProperties(props);
    request.setBatchMode(true);
    request.setShowErrors(true);

    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.error(e.getMessage());
        this.mavenHelper.getInspector().getJobStatus().addStepError(this.mavenHelper.getName(), e.getMessage());
        this.exitCode = MavenHelper.MAVEN_ERROR;
    }
}
 
Example #13
Source File: ArchetypeTest.java    From ipaas-quickstarts with Apache License 2.0 5 votes vote down vote up
protected static int invokeMaven(String[] args, String outDir, File logFile) {
    List<String> goals = Arrays.asList(args);
    String commandLine = Strings.join(goals, " ");

    InvocationResult result = null;
    try {
        File dir = new File(outDir);

        InvocationRequest request = new DefaultInvocationRequest();
        request.setGoals(goals);

        InvocationOutputHandler outputHandler = new SystemOutAndFileHandler(logFile);
        outputHandler.consumeLine("");
        outputHandler.consumeLine("");
        outputHandler.consumeLine(dir.getName() + " : starting: mvn " + commandLine);
        outputHandler.consumeLine("");
        request.setOutputHandler(outputHandler);
        request.setErrorHandler(outputHandler);

        DefaultInvoker invoker = new DefaultInvoker();
        request.setPomFile(new File(dir, "pom.xml"));
        result = invoker.execute(request);
        CommandLineException executionException = result.getExecutionException();
        if (executionException != null) {
            LOG.error("Failed to invoke maven with: mvn " + commandLine + ". " + executionException, executionException);
        }
    } catch (Exception e) {
        LOG.error("Failed to invoke maven with: mvn " + commandLine + ". " + e, e);
    }
    return result == null ? 1 : result.getExitCode();
}
 
Example #14
Source File: InvokerMojo.java    From iterator-maven-plugin with Apache License 2.0 5 votes vote down vote up
private InvocationResult mavenCall( ItemWithProperties item )
    throws MavenInvocationException
{
    InvocationRequest request = createAndConfigureAnInvocationRequest( item );

    OutputConsumer output = new OutputConsumer( getLog() );
    request.setOutputHandler( output );

    invoker.setWorkingDirectory( getWorkingDirectoryAfterPlaceHolderIsReplaced( item ) );

    return invoker.execute( request );
}
 
Example #15
Source File: MavenJarResolver.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private AddMvnCommandResult getResult(InvocationResult invocationResult, String dependencies) {
  if (invocationResult.getExitCode() != 0) {
    if (invocationResult.getExecutionException() != null) {
      return AddMvnCommandResult.error(invocationResult.getExecutionException().getMessage());
    }
    StringBuilder errorMsgBuilder = new StringBuilder("Could not resolve dependencies for:");
    errorMsgBuilder
            .append("\n")
            .append(dependencies);
    return AddMvnCommandResult.error(errorMsgBuilder.toString());
  }

  return AddMvnCommandResult.success(transformFromMavenRepoToKernelRepo(mavenBuildClasspath(), jarsFromRepo()));
}
 
Example #16
Source File: MavenExecutorImpl.java    From developer-studio with Apache License 2.0 5 votes vote down vote up
public boolean executeMavenGoal(File projectPath, List<String> goals,
		boolean isOffline) {
	InvocationRequest request = new DefaultInvocationRequest();

	if (!projectPath.exists()) {
		projectPath.mkdirs();
	}

	request.setPomFile(new File(projectPath, POM_XML));

	if (goals == null) {
		goals = getDefaultMavenGoals();
	}
	request.setGoals(goals);
	Invoker invoker = new DefaultInvoker();
	request.setOffline(isOffline);

	try {
		InvocationResult result = invoker.execute(request);
		if (result.getExecutionException() == null) {
			if (result.getExitCode() != 0) {
				request.setOffline(!isOffline);
				result = invoker.execute(request);
				if (result.getExitCode() == 0) {
					return true;
				} else {
					final String errorMessage = "No maven Project found at "
							+ projectPath;
					log.error(errorMessage);
					throw new MavenInvocationException(errorMessage);
				}
			}
			return true;
		}
	} catch (MavenInvocationException e) {
		log.error("Maven invocation failed", e);
	}
	return false;
}
 
Example #17
Source File: LibertySettingsDirectoryTest.java    From ci.maven with Apache License 2.0 5 votes vote down vote up
@Test
public void testLibertyConfigDirInvalidDir() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    File pomFilePath = new File("../pom.xml");
    Document pomFile = builder.parse(pomFilePath);
    pomFile.getDocumentElement().normalize();

    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    String pomVersion = xpath.evaluate("/project/build/plugins/plugin[artifactId='liberty-maven-plugin']/version", pomFile);

    Properties props = new Properties();
    props.put("pluginVersion", pomVersion);

    InvocationRequest request = new DefaultInvocationRequest()
    .setPomFile( new File("../src/test/resources/invalidDirPom.xml"))
    .setGoals( Collections.singletonList("package"))
    .setProperties(props);

    InvocationOutputHandler outputHandler = new InvocationOutputHandler(){
        @Override
        public void consumeLine(String line) throws IOException {
            if (line.contains("<libertySettingsFolder> must be a directory")) {
                throw new IOException("Caught expected MojoExecutionException - " + line);
            }
        }
    };

    Invoker invoker = new DefaultInvoker();
    invoker.setOutputHandler(outputHandler);

    InvocationResult result = invoker.execute( request );

    assertTrue("Exited successfully, expected non-zero exit code.", result.getExitCode() != 0);
    assertNotNull("Expected MojoExecutionException to be thrown.", result.getExecutionException());
}
 
Example #18
Source File: CreateProjectMojoIT.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testProjectGenerationFromScratchWithMissingExtensionShouldFail() throws Exception {
    testDir = initEmptyProject("projects/project-generation-with-missing-extension");
    assertThat(testDir).isDirectory();
    invoker = initInvoker(testDir);

    Properties properties = new Properties();
    properties.put("projectGroupId", "org.acme");
    properties.put("projectArtifactId", "acme");
    properties.put("className", "org.acme.MyResource");
    properties.put("extensions", "resteasy,smallrye-metrics,missing");
    InvocationResult result = setup(properties);

    assertThat(result.getExitCode()).isZero();
}
 
Example #19
Source File: CreateProjectMojoIT.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testProjectGenerationWithExistingPomShouldFail() throws Exception {
    testDir = initProject("projects/simple-pom-it", "projects/project-generation-from-empty-pom");
    assertThat(testDir).isDirectory();
    invoker = initInvoker(testDir);
    InvocationResult result = setup(new Properties());

    assertThat(result.getExitCode()).isOne();
}
 
Example #20
Source File: EndpointsGetClientLib.java    From appengine-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
  getLog().info("");
  getLog().info("Google App Engine Java SDK - Generate endpoints get client lib");

  List<String> classNames = getAPIServicesClasses();
  if (classNames.isEmpty()) {
    getLog().info("No Endpoints classes detected.");
    return;
  }

  try {
    executeEndpointsCommand("get-client-lib", new String[0],
            classNames.toArray(new String[classNames.size()]));
    File webInf = new File(outputDirectory + "/WEB-INF");
    if (webInf.exists() && webInf.isDirectory()) {
      File[] files = webInf.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
          return name.endsWith("-java.zip");
        }
      });
      File mavenProjectsDir = new File(clientLibsDirectory);
      mavenProjectsDir.mkdirs();
      for (File source : files) {
        File pomFile = unjarMavenProject(source, mavenProjectsDir);
        if (pomFile != null) {
          getLog().info("BUILDING Endpoints Client Library from: " + pomFile);
          InvocationRequest request = new DefaultInvocationRequest();
          request.setPomFile(pomFile);
          request.setGoals(Collections.singletonList("install"));
          Invoker invoker = new DefaultInvoker();
          InvocationResult result = invoker.execute(request);
          if (result.getExitCode() != 0) {
            throw new IllegalStateException("Build failed.");
          }
          getLog().info("Endpoint get client lib generation and compilation done.");

        }
      }
    }
  } catch (MojoExecutionException e) {
    getLog().error(e);
    throw new MojoExecutionException(
            "Error while generating Google App Engine endpoint get client lib", e);
  } catch (MavenInvocationException ex) {
    Logger.getLogger(EndpointsGetClientLib.class.getName()).log(Level.SEVERE, null, ex);
  }
}
 
Example #21
Source File: ReleaseInvoker.java    From multi-module-maven-release-plugin with MIT License 4 votes vote down vote up
public final void runMavenBuild(final Reactor reactor) throws MojoExecutionException {
    request.setBatchMode(true);
	request.setShowErrors(true);
	request.setDebug(log.isDebugEnabled());


	final List<String> goals = getGoals();
       if (arguments != null) {
           goals.add(arguments);
       }
	if (skipTests) {
		goals.add(SKIP_TESTS);
	}
	request.setGoals(getGoals());

	final List<String> profiles = profilesToActivate();
	request.setProfiles(profiles);

	request.setAlsoMake(true);
	final List<String> changedModules = new ArrayList<String>();
	final List<String> modulesToRelease = getModulesToRelease();
	for (final ReleasableModule releasableModule : reactor.getModulesInBuildOrder()) {
		final String modulePath = releasableModule.getRelativePathToModule();
		final boolean userExplicitlyWantsThisToBeReleased = modulesToRelease.contains(modulePath);
		final boolean userImplicitlyWantsThisToBeReleased = modulesToRelease.isEmpty();
		if (userExplicitlyWantsThisToBeReleased
				|| (userImplicitlyWantsThisToBeReleased && releasableModule.willBeReleased())) {
			changedModules.add(modulePath);
		}
	}
	request.setProjects(changedModules);

	final String profilesInfo = profiles.isEmpty() ? "no profiles activated" : "profiles " + profiles;

	log.info(format("About to run mvn %s with %s", goals, profilesInfo));

	try {
		final InvocationResult result = invoker.execute(request);
		if (result.getExitCode() != 0) {
			throw new MojoExecutionException("Maven execution returned code " + result.getExitCode());
		}
	} catch (final MavenInvocationException e) {
		throw new MojoExecutionException("Failed to build artifact", e);
	}
}
 
Example #22
Source File: EndpointsGetClientLib.java    From gcloud-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
  getLog().info("");
  getLog().info("Google App Engine Java SDK - Generate endpoints get client lib");

  List<String> classNames = getAPIServicesClasses();
  if (classNames.isEmpty()) {
    getLog().info("No Endpoints classes detected.");
    return;
  }

  try {
    executeEndpointsCommand("get-client-lib", new String[0],
        classNames.toArray(new String[classNames.size()]));
    File webInf = new File(output_directory + "/WEB-INF");
    if (webInf.exists() && webInf.isDirectory()) {
      File[] files = webInf.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
          return name.endsWith("-java.zip");
        }
      });
      File mavenProjectsDir = new File(client_libs_directory);
      mavenProjectsDir.mkdirs();
      for (File source : files) {
        File pomFile = unjarMavenProject(source, mavenProjectsDir);
        if (pomFile != null) {
          getLog().info("BUILDING Endpoints Client Library from: " + pomFile);
          InvocationRequest request = new DefaultInvocationRequest();
          request.setPomFile(pomFile);
          request.setGoals(Collections.singletonList("install"));
          Invoker invoker = new DefaultInvoker();
          InvocationResult result = invoker.execute(request);
          if (result.getExitCode() != 0) {
            throw new IllegalStateException("Build failed.");
          }
          getLog().info("Endpoint get client lib generation and compilation done.");

        }
      }
    }
  } catch (MojoExecutionException e) {
    getLog().error(e);
    throw new MojoExecutionException(
        "Error while generating Google App Engine endpoint get client lib", e);
  } catch (MavenInvocationException ex) {
    Logger.getLogger(EndpointsGetClientLib.class.getName()).log(Level.SEVERE, null, ex);
  }
}
 
Example #23
Source File: RunningInvoker.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public InvocationResult execute(InvocationRequest request) throws MavenInvocationException {
    return super.execute(request);
}
 
Example #24
Source File: InvokerMojo.java    From iterator-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Possibly to multithreading..
 * 
 * @throws MojoFailureException in case of failure.
 */
// private int numberOfThreads;

public void execute()
    throws MojoExecutionException, MojoFailureException
{
    if ( isSkip() )
    {
        getLog().info( "Skip by user request." );
        return;
    }

    if ( isNoneSet() )
    {
        throw new MojoExecutionException( "You have to use at least one. " + "Either items, "
            + "itemsWithProperties, content or folder element!" );
    }

    if ( isMoreThanOneSet() )
    {
        throw new MojoExecutionException( "You can use only one element. "
            + "Either items, itemsWithProperties, content or folder element but not more than one of them." );
    }

    File localRepository = new File( getMavenSession().getSettings().getLocalRepository() );

    invoker.setLocalRepositoryDirectory( localRepository );
    // invoker.setOutputHandler(outputHandler);
    // TODO: Check how it looks if we will use the invokerLogger?
    // invoker.setLogger();

    // getLog().info("local repository: " + localRepository);
    // // getLog().isDebugEnabled()
    // getLog().info("Invoker:" + invoker);

    List<Exception> exceptions = new ArrayList<>();

    for ( ItemWithProperties item : getItemsConverted() )
    {
        try
        {
            createLogOutput( item );
            InvocationResult result = mavenCall( item );

            if ( result.getExitCode() == 0 )
            {
                getLog().info( "------ Maven call was Ok." );
                continue;
            }

            getLog().error( "------ Maven call was NOT Ok. for iteration " + item.getName() + " ( return code: " + result.getExitCode() + " )" );
            if ( result.getExecutionException() != null )
            {
                getLog().error( result.getExecutionException().getMessage(),
                                result.getExecutionException().getCause() );
            }

            String failureMessage =
                "Maven call failed with return code " + result.getExitCode() + " for iteration: " + item.getName();

            if ( isFailAtEnd() )
            {
                exceptions.add( new RuntimeException( failureMessage ) );
            }
            else
            {
                throw new MojoFailureException( failureMessage );
            }

        }
        catch ( MavenInvocationException e )
        {
            // This will stop any iteration.
            getLog().error( "------ ***** Command line options are wrong:", e );
            throw new MojoExecutionException( "Command line options are wrong:", e );
        }
    }

    if ( !exceptions.isEmpty() )
    {
        for ( Exception exception : exceptions )
        {
            getLog().error( exception );
        }
        throw new MojoExecutionException( "Failures during iterations." );
    }
}
 
Example #25
Source File: Builder.java    From wad with MIT License 4 votes vote down vote up
public InvocationResult build() throws MavenInvocationException {
    return this.invoker.execute(request);
}
 
Example #26
Source File: IntegrationTestMojo.java    From helidon-build-tools with Apache License 2.0 4 votes vote down vote up
private void invokePostArchetypeGenerationGoals(List<String> goals, File basedir)
        throws IOException, MojoExecutionException {

    FileLogger logger = setupLogger(basedir);

    if (!goals.isEmpty()) {
        getLog().info("Invoking post-archetype-generation goals: " + goals);
        InvocationRequest request = new DefaultInvocationRequest()
                .setBaseDirectory(basedir)
                .setGoals(goals)
                .setBatchMode(true)
                .setShowErrors(true)
                .setDebug(debug)
                .setShowVersion(showVersion);

        if (logger != null) {
            request.setErrorHandler(logger);
            request.setOutputHandler(logger);
        }

        if (!properties.isEmpty()) {
            Properties props = new Properties();
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                if (entry.getValue() != null) {
                    props.setProperty(entry.getKey(), entry.getValue());
                }
            }
            request.setProperties(props);
        }

        try {
            InvocationResult result = invoker.execute(request);
            getLog().info("Post-archetype-generation invoker exit code: " + result.getExitCode());
            if (result.getExitCode() != 0) {
                throw new MojoExecutionException("Execution failure: exit code = " + result.getExitCode(),
                        result.getExecutionException());
            }
        } catch (MavenInvocationException ex) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        }
    } else {
        getLog().info("No post-archetype-generation goals to invoke.");
    }
}