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

The following examples show how to use org.apache.maven.shared.invoker.InvocationOutputHandler. 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: ListExtensionsIT.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private List<String> listExtensions()
        throws MavenInvocationException, IOException {
    InvocationRequest request = new DefaultInvocationRequest();
    request.setBatchMode(true);
    request.setGoals(Collections.singletonList(
            getPluginGroupId() + ":" + getPluginArtifactId() + ":" + getPluginVersion() + ":list-extensions"));
    getEnv().forEach(request::addShellEnvironment);

    File outputLog = new File(testDir, "output.log");
    InvocationOutputHandler outputHandler = new PrintStreamHandler(
            new PrintStream(new TeeOutputStream(System.out, Files.newOutputStream(outputLog.toPath())), true, "UTF-8"),
            true);
    invoker.setOutputHandler(outputHandler);

    File invokerLog = new File(testDir, "invoker.log");
    PrintStreamLogger logger = new PrintStreamLogger(new PrintStream(new FileOutputStream(invokerLog), false, "UTF-8"),
            InvokerLogger.DEBUG);
    invoker.setLogger(logger);

    invoker.execute(request);
    return Files.readAllLines(outputLog.toPath());
}
 
Example #2
Source File: TestPackager.java    From justtestlah with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a test package for AWS Devicefarm.
 *
 * @param logger {@link InvokerLogger} logger to be used for the Maven build output
 * @param clean true, if the target directory should be cleaned (forcing recompilation)
 * @return {@link File} of the ZIP package to be used by AWS Devicefarm
 * @throws MavenInvocationException error during Maven build
 */
protected File packageProjectForDeviceFarm(InvocationOutputHandler logger, boolean clean)
    throws MavenInvocationException {
  InvocationRequest request = new DefaultInvocationRequest();
  request.setPomFile(
      new File(properties.getProperty("aws.demo.path") + File.separator + "pom.xml"));
  request.setProfiles(List.of("aws"));
  if (clean) {
    request.setGoals(List.of("clean", "package"));
  } else {
    request.setGoals(List.of("package"));
  }
  request.setUpdateSnapshots(true);
  new DefaultInvoker().setOutputHandler(logger).execute(request);
  return new File(
      properties.getProperty("aws.demo.path")
          + File.separator
          + "target"
          + File.separator
          + properties.getProperty("aws.testpackage.name")
          + ".zip");
}
 
Example #3
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 #4
Source File: AppEstate.java    From app-runner with MIT License 5 votes vote down vote up
public void update(String name, InvocationOutputHandler outputHandler) throws Exception {
    for (AppDescription manager : managers) {
        if (manager.name().equalsIgnoreCase(name)) {
            manager.update(runnerProvider, outputHandler);
            return;
        }
    }

    throw new AppNotFoundException("No app found with name '" + name + "'. Valid names: " + allAppNames());
}
 
Example #5
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 #6
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 #7
Source File: MavenHelper.java    From repairnator with MIT License 4 votes vote down vote up
public InvocationOutputHandler getErrorHandler() {
    return errorHandler;
}
 
Example #8
Source File: MavenHelper.java    From repairnator with MIT License 4 votes vote down vote up
public InvocationOutputHandler getOutputHandler() {
    return outputHandler;
}
 
Example #9
Source File: MavenHelper.java    From repairnator with MIT License 4 votes vote down vote up
public void setErrorHandler(InvocationOutputHandler errorHandler) {
    this.errorHandler = errorHandler;
}
 
Example #10
Source File: MavenHelper.java    From repairnator with MIT License 4 votes vote down vote up
public void setOutputHandler(InvocationOutputHandler outputHandler) {
    this.outputHandler = outputHandler;
}
 
Example #11
Source File: AppManager.java    From app-runner with MIT License 4 votes vote down vote up
public synchronized void update(AppRunnerFactoryProvider runnerProvider, InvocationOutputHandler outputHandler) throws Exception {
    clearLogs();
    markBuildAsFetching();

    LineConsumer buildLogHandler = line -> {
        try {
            outputHandler.consumeLine(line);
        } catch (IOException ignored) {
        }
        latestBuildLog += line + LINE_SEPARATOR;
    };

    // Well this is complicated.
    // Basically, we want the build log to contain a bit of the startup, and then detach itself.
    AtomicReference<LineConsumer> buildLogHandle = new AtomicReference<>(buildLogHandler);
    LineConsumer consoleLogHandler = line -> {
        LineConsumer another = buildLogHandle.get();
        if (another != null) {
            another.consumeLine(StringUtils.stripEnd(line, "\r\n"));
        }
        synchronized (consoleLog) {
            consoleLog.add(line);
        }
    };


    buildLogHandler.consumeLine("Fetching latest changes from git...");
    File instanceDir = fetchChangesAndCreateInstanceDir();
    buildLogHandler.consumeLine("Created new instance in " + fullPath(instanceDir));

    AppRunner oldRunner = currentRunner;
    AppRunnerFactory appRunnerFactory = runnerProvider.runnerFor(name(), instanceDir);
    String runnerId = appRunnerFactory.id();
    markBuildAsStarting(runnerId);
    currentRunner = appRunnerFactory.appRunner(instanceDir);
    log.info("Using " + appRunnerFactory.id() + " for " + name);
    int port = getAFreePort();

    Map<String, String> envVarsForApp = createAppEnvVars(port, name, dataDir, tempDir);

    try (Waiter startupWaiter = Waiter.waitForApp(name, port)) {
        currentRunner.start(buildLogHandler, consoleLogHandler, envVarsForApp, startupWaiter);
    } catch (Exception e) {
        recordBuildFailure("Crashed during startup", runnerId);
        throw e;
    }
    recordBuildSuccess(runnerId);
    buildLogHandle.set(null);

    for (AppChangeListener listener : listeners) {
        listener.onAppStarted(name, new URL("http://localhost:" + port + "/" + name));
    }
    if (oldRunner != null) {
        buildLogHandler.consumeLine("Shutting down previous version");
        log.info("Shutting down previous version of " + name);
        oldRunner.shutdown();
        buildLogHandler.consumeLine("Deployment complete.");
        File oldInstanceDir = oldRunner.getInstanceDir();
        quietlyDeleteTheOldInstanceDirInTheBackground(oldInstanceDir);
    }
}
 
Example #12
Source File: MockAppDescription.java    From app-runner with MIT License 4 votes vote down vote up
public void update(AppRunnerFactoryProvider runnerProvider, InvocationOutputHandler outputHandler) throws Exception {
    ++updateCount;
}
 
Example #13
Source File: AppDescription.java    From app-runner with MIT License votes vote down vote up
void update(AppRunnerFactoryProvider runnerProvider, InvocationOutputHandler outputHandler) throws Exception;