Java Code Examples for org.codehaus.plexus.util.cli.CommandLineUtils#executeCommandLine()

The following examples show how to use org.codehaus.plexus.util.cli.CommandLineUtils#executeCommandLine() . 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: CanteenExecutableIT.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void stdoutWorks() throws Exception {
    File exe = getExecutable(getPlatformClassifier());

    Commandline commandLine = new Commandline();
    commandLine.setExecutable(exe.getCanonicalPath());
    commandLine.addArguments(new String[] {"1"});

    StringWriter stdOut = new StringWriter();
    StringWriter stdErr = new StringWriter();

    int returnCode = CommandLineUtils.executeCommandLine(commandLine, new WriterStreamConsumer(stdOut), new WriterStreamConsumer(stdErr));

    assertThat(returnCode).withFailMessage("Unexpected return code").isEqualTo(0);
    assertThat(stdOut.toString()).isEqualTo("success\n");
    assertThat(stdErr.toString()).isEmpty();
}
 
Example 2
Source File: CanteenExecutableIT.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void stderrWorks() throws Exception {
    File exe = getExecutable(getPlatformClassifier());

    Commandline commandLine = new Commandline();
    commandLine.setExecutable(exe.getCanonicalPath());
    commandLine.addArguments(new String[] {"0"});

    StringWriter stdOut = new StringWriter();
    StringWriter stdErr = new StringWriter();

    int returnCode = CommandLineUtils.executeCommandLine(commandLine, new WriterStreamConsumer(stdOut), new WriterStreamConsumer(stdErr));

    assertThat(returnCode).withFailMessage("Unexpected return code").isEqualTo(42);
    assertThat(stdOut.toString()).isEmpty();
    assertThat(stdErr.toString()).isEqualTo("failure\n");
}
 
Example 3
Source File: CanteenExecutableIT.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void stdinWorks() throws Exception {
    File exe = getExecutable(getPlatformClassifier());

    Commandline commandLine = new Commandline();
    commandLine.setExecutable(exe.getCanonicalPath());

    StringWriter stdOut = new StringWriter();
    StringWriter stdErr = new StringWriter();
    InputStream stdIn = new ByteArrayInputStream("1\n".getBytes(StandardCharsets.US_ASCII));

    int returnCode = CommandLineUtils.executeCommandLine(commandLine, stdIn,  new WriterStreamConsumer(stdOut), new WriterStreamConsumer(stdErr));

    assertThat(returnCode).withFailMessage("Unexpected return code").isEqualTo(0);
    assertThat(stdOut.toString()).endsWith("success\n");
    assertThat(stdErr.toString()).isEmpty();
}
 
Example 4
Source File: AbstractCommunityEnvFactory.java    From maven-native with MIT License 6 votes vote down vote up
protected Map<String, String> executeCommandLine(Commandline command) throws NativeBuildException
{
    EnvStreamConsumer stdout = new EnvStreamConsumer();
    StreamConsumer stderr = new DefaultConsumer();

    try
    {
        CommandLineUtils.executeCommandLine( command, stdout, stderr );
    }
    catch ( CommandLineException e )
    {
        throw new NativeBuildException( "Failed to execute vcvarsall.bat" );
    }

    return stdout.getParsedEnv();
}
 
Example 5
Source File: CommandLineUtil.java    From maven-native with MIT License 6 votes vote down vote up
public static void execute( Commandline cl, Logger logger )
    throws NativeBuildException
{
    int ok;

    try
    {
        DefaultConsumer stdout = new DefaultConsumer();

        DefaultConsumer stderr = stdout;

        logger.info( cl.toString() );

        ok = CommandLineUtils.executeCommandLine( cl, stdout, stderr );
    }
    catch ( CommandLineException ecx )
    {
        throw new NativeBuildException( "Error executing command line", ecx );
    }

    if ( ok != 0 )
    {
        throw new NativeBuildException( "Error executing command line. Exit code:" + ok );
    }
}
 
Example 6
Source File: BuildNumberMojoTest.java    From buildnumber-maven-plugin with MIT License 6 votes vote down vote up
private static boolean isSvn18()
{
    Commandline cl = new Commandline();
    cl.setExecutable( "svn" );
    cl.createArg().setValue( "--version" );

    StringStreamConsumer stdout = new StringStreamConsumer();
    StringStreamConsumer stderr = new StringStreamConsumer();

    try
    {
        CommandLineUtils.executeCommandLine( cl, stdout, stderr );
        Matcher versionMatcher = SVN_VERSION_PATTERN.matcher( stdout.getOutput() );
        return versionMatcher.find() && ( Integer.parseInt( versionMatcher.group( 1 ) ) > 1
            || Integer.parseInt( versionMatcher.group( 2 ) ) >= 8 );
    }
    catch ( CommandLineException e )
    {
    }

    return false;
}
 
Example 7
Source File: DocumentationIntegrationTest.java    From depgraph-maven-plugin with Apache License 2.0 6 votes vote down vote up
private static String getDotExecutable() {
  Commandline cmd = new Commandline();
  String finderExecutable = isWindows() ? "where.exe" : "which";

  cmd.setExecutable(finderExecutable);
  cmd.addArguments(new String[]{"dot"});

  CommandLineUtils.StringStreamConsumer systemOut = new CommandLineUtils.StringStreamConsumer();
  CommandLineUtils.StringStreamConsumer systemErr = new CommandLineUtils.StringStreamConsumer();

  try {
    int exitCode = CommandLineUtils.executeCommandLine(cmd, systemOut, systemErr);
    if (exitCode != 0) {
      return null;
    }
  } catch (CommandLineException e) {
    return null;
  }

  return systemOut.getOutput();
}
 
Example 8
Source File: RegQuery.java    From maven-native with MIT License 5 votes vote down vote up
public static String getValue( String valueType, String folderName, String folderKey )
    throws NativeBuildException
{
    Commandline cl = new Commandline();
    cl.setExecutable( "reg" );
    cl.createArg().setValue( "query" );
    cl.createArg().setValue( folderName );
    cl.createArg().setValue( "/v" );
    cl.createArg().setValue( folderKey );

    CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();
    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();

    try
    {
        int ok = CommandLineUtils.executeCommandLine( cl, stdout, stderr );

        if ( ok != 0 )
        {
            return null;
        }
    }
    catch ( CommandLineException e )
    {
        throw new NativeBuildException( e.getMessage(), e );
    }

    String result = stdout.getOutput();

    int p = result.indexOf( valueType );

    if ( p == -1 )
    {
        return null;
    }

    return result.substring( p + valueType.length() ).trim();
}
 
Example 9
Source File: AbstractCodegenMojo.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Run the JDK version (could be set via the toolchain) and see if we need to configure the JvmArgs
 * accordingly. Once we remove JDK8 support we can just add the additional args by default and remove
 * this method.
 */
private void setJvmForkArgs(String javaExecutablePath) {
    Commandline cmd = new Commandline();
    cmd.getShell().setQuotedArgumentsEnabled(true); // for JVM args
    cmd.setWorkingDirectory(project.getBuild().getDirectory());
    cmd.setExecutable(javaExecutablePath);
    Java9StreamConsumer consumer = new Java9StreamConsumer();
    try {
        cmd.createArg().setValue("-XshowSettings:properties -version");
        CommandLineUtils.executeCommandLine(cmd, null, consumer);
    } catch (Exception e2) {
        e2.printStackTrace();
    }

    if (additionalJvmArgs == null) {
        additionalJvmArgs = "";
    }
    if (consumer.isJava9Plus()) {
        additionalJvmArgs = "--add-exports=jdk.xml.dom/org.w3c.dom.html=ALL-UNNAMED "
                            + "--add-exports=java.xml/com.sun.org.apache.xerces.internal.impl.xs=ALL-UNNAMED "
                            + "--add-opens java.base/java.security=ALL-UNNAMED "
                            + "--add-opens java.base/java.net=ALL-UNNAMED "
                            + "--add-opens java.base/java.lang=ALL-UNNAMED "
                            + "--add-opens java.base/java.util=ALL-UNNAMED "
                            + "--add-opens java.base/java.util.concurrent=ALL-UNNAMED "
                            + additionalJvmArgs;
    }
}
 
Example 10
Source File: MavenCommandLineMojo.java    From dependency-mediator with Apache License 2.0 5 votes vote down vote up
public void copyDependenciesTest(File dependencyFolder) throws MojoFailureException,
        MojoExecutionException {
    getLog().info("Start to copy dependencies");
    Commandline cl = new Commandline();
    cl.setExecutable("mvn");
    cl.createArg().setValue("clean");
    cl.createArg().setValue("dependency:copy-dependencies");
    cl.createArg().setValue("-DoutputDirectory=" + dependencyFolder.getAbsolutePath());
    cl.createArg().setValue("-Dsilent=true");
    String excludedArtifactIds = this.getTestDependencyArtifactIds();
    if (!excludedArtifactIds.isEmpty()) {
        cl.createArg().setValue("-DexcludeArtifactIds=" + excludedArtifactIds);
        getLog().info("====Excluded artifact ids: " + excludedArtifactIds);
    } else {
        getLog().info("====No excluded artifact ids");
    }
    WriterStreamConsumer systemOut = new WriterStreamConsumer(
            new OutputStreamWriter(System.out));
    int result = -1;
    try {
        result = CommandLineUtils.executeCommandLine(cl, systemOut, systemOut);
    } catch (CommandLineException e) {
        String message = "Failed to execute command: " + cl.toString();
        throw new MojoFailureException(message);
    }
    if (result != 0) {
        getLog().error("Failed to copy dependencies");
        System.exit(result);
    }
}
 
Example 11
Source File: Git.java    From opoopress with Apache License 2.0 5 votes vote down vote up
private boolean execute(String command, String... args) throws GitException {
	Commandline cl = new Commandline();
	cl.setExecutable("git");
	cl.createArg().setValue(command);
	cl.setWorkingDirectory(workingDirectory.getAbsolutePath());
	
	//args
	for (int i = 0; i < args.length; i++){
		cl.createArg().setValue(args[i]);
	}
	
	if (log.isInfoEnabled()) {
		log.info("[" + cl.getWorkingDirectory().getAbsolutePath() + "] Executing: " + cl);
	}
	
	int exitCode;
	try {
		exitCode = CommandLineUtils.executeCommandLine(cl, stdout, stderr);
	} catch (CommandLineException e) {
		throw new GitException("Error while executing command.", e);
	}

	if(log.isDebugEnabled()){
		log.debug("Run: " + cl + " / $? = " + exitCode);
	}
	
	return exitCode == 0;
}
 
Example 12
Source File: ArchiveEntryUtils.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void chmod(final File file, final int mode, final Log logger, boolean useJvmChmod) throws ArchiverException {
    if (!Os.isFamily(Os.FAMILY_UNIX)) {
        return;
    }

    final String m = Integer.toOctalString(mode & 0xfff);

    if (useJvmChmod && !jvmFilePermAvailable) {
        logger.info("chmod it's not possible where your current jvm");
        useJvmChmod = false;
    }

    if (useJvmChmod && jvmFilePermAvailable) {
        applyPermissionsWithJvm(file, m, logger);
        return;
    }

    try {
        final Commandline commandline = new Commandline();

        commandline.setWorkingDirectory(file.getParentFile().getAbsolutePath());

        if (logger.isDebugEnabled()) {
            logger.debug(file + ": mode " + Integer.toOctalString(mode) + ", chmod " + m);
        }

        commandline.setExecutable("chmod");

        commandline.createArg().setValue(m);

        final String path = file.getAbsolutePath();

        commandline.createArg().setValue(path);

        final CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();

        final CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();

        final int exitCode = CommandLineUtils.executeCommandLine(commandline, stderr, stdout);

        if (exitCode != 0) {
            logger.warn("-------------------------------");
            logger.warn("Standard error:");
            logger.warn("-------------------------------");
            logger.warn(stderr.getOutput());
            logger.warn("-------------------------------");
            logger.warn("Standard output:");
            logger.warn("-------------------------------");
            logger.warn(stdout.getOutput());
            logger.warn("-------------------------------");

            throw new ArchiverException("chmod exit code was: " + exitCode);
        }
    } catch (final CommandLineException e) {
        throw new ArchiverException("Error while executing chmod.", e);
    }

}
 
Example 13
Source File: CommandExecutor.java    From atlas with Apache License 2.0 4 votes vote down vote up
@Override
public void executeCommand(String executable, List<String> commands, File workingDirectory,
                           boolean failsOnErrorOutput) throws ExecutionException {
    if (commands == null) {
        commands = new ArrayList<String>();
    }
    stdOut = new StreamConsumerImpl(logger, captureStdOut);
    stdErr = new ErrorStreamConsumer(logger, errorListener, captureStdErr);
    commandline = new Commandline();
    if (customShell != null) {
        commandline.setShell(customShell);
    }
    commandline.setExecutable(executable);

    // Add the environment variables as needed
    if (environment != null) {
        for (Map.Entry<String, String> entry : environment.entrySet()) {
            commandline.addEnvironment(entry.getKey(), entry.getValue());
        }
    }

    commandline.addArguments(commands.toArray(new String[commands.size()]));
    if (workingDirectory != null && workingDirectory.exists()) {
        commandline.setWorkingDirectory(workingDirectory.getAbsolutePath());
    }
    try {
        logger.debug("ANDROID-040-000: Executing command: Commandline = " + commandline);
        result = CommandLineUtils.executeCommandLine(commandline, stdOut, stdErr);
        if (logger != null) {
            logger.debug("ANDROID-040-000: Executed command: Commandline = " + commandline + ", Result = "
                    + result);
        } else {
            System.out.println("ANDROID-040-000: Executed command: Commandline = " + commandline
                    + ", Result = " + result);
        }
        if (failsOnErrorOutput && stdErr.hasError() || result != 0) {
            throw new ExecutionException("ANDROID-040-001: Could not execute: Command = "
                    + commandline.toString() + ", Result = " + result);
        }
    } catch (CommandLineException e) {
        throw new ExecutionException("ANDROID-040-002: Could not execute: Command = "
                + commandline.toString() + ", Error message = " + e.getMessage());
    }
    setPid(commandline.getPid());
}
 
Example 14
Source File: AbstractMSVCEnvFactory.java    From maven-native with MIT License 4 votes vote down vote up
protected Map<String, String> createEnvs( String commonToolEnvKey, String platform )
    throws NativeBuildException
{

    File tmpEnvExecFile = null;
    try
    {
        File vsCommonToolDir = this.getCommonToolDirectory( commonToolEnvKey );

        File vsInstallDir = this.getVisualStudioInstallDirectory( vsCommonToolDir );

        if ( !vsInstallDir.isDirectory() )
        {
            throw new NativeBuildException( vsInstallDir.getPath() + " is not a directory." );
        }

        tmpEnvExecFile = this.createEnvWrapperFile( vsInstallDir, platform );

        Commandline cl = new Commandline();
        cl.setExecutable( tmpEnvExecFile.getAbsolutePath() );

        EnvStreamConsumer stdout = new EnvStreamConsumer();
        StreamConsumer stderr = new DefaultConsumer();

        CommandLineUtils.executeCommandLine( cl, stdout, stderr );

        return stdout.getParsedEnv();
    }
    catch ( Exception e )
    {
        throw new NativeBuildException( "Unable to retrieve env", e );
    }
    finally
    {
        if ( tmpEnvExecFile != null )
        {
            tmpEnvExecFile.delete();
        }
    }

}
 
Example 15
Source File: AbstractGraphMojo.java    From depgraph-maven-plugin with Apache License 2.0 4 votes vote down vote up
private void createDotGraphImage(Path graphFilePath) throws IOException {
  String graphFileName = createDotImageFileName(graphFilePath);
  Path graphFile = graphFilePath.resolveSibling(graphFileName);

  String dotExecutable = determineDotExecutable();
  String[] arguments = new String[]{
      "-T", this.imageFormat,
      "-o", graphFile.toAbsolutePath().toString(),
      graphFilePath.toAbsolutePath().toString()};

  Commandline cmd = new Commandline();
  cmd.setExecutable(dotExecutable);
  cmd.addArguments(arguments);

  getLog().info("Running Graphviz: " + dotExecutable + " " + Joiner.on(" ").join(arguments));

  StringStreamConsumer systemOut = new StringStreamConsumer();
  StringStreamConsumer systemErr = new StringStreamConsumer();
  int exitCode;

  try {
    exitCode = CommandLineUtils.executeCommandLine(cmd, systemOut, systemErr);
  } catch (CommandLineException e) {
    throw new IOException("Unable to execute Graphviz", e);
  }

  Splitter lineSplitter = Splitter.on(LINE_SEPARATOR_PATTERN).omitEmptyStrings().trimResults();
  Iterable<String> output = Iterables.concat(
      lineSplitter.split(systemOut.getOutput()),
      lineSplitter.split(systemErr.getOutput()));

  for (String line : output) {
    getLog().info("  dot> " + line);
  }

  if (exitCode != 0) {
    throw new IOException("Graphviz terminated abnormally. Exit code: " + exitCode);
  }

  getLog().info("Graph image created on " + graphFile.toAbsolutePath());
}
 
Example 16
Source File: AbstractGitFlowMojo.java    From gitflow-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Executes command line.
 * 
 * @param cmd
 *            Command line.
 * @param failOnError
 *            Whether to throw exception on NOT success exit code.
 * @param argStr
 *            Command line arguments as a string.
 * @param args
 *            Command line arguments.
 * @return {@link CommandResult} instance holding command exit code, output
 *         and error if any.
 * @throws CommandLineException
 * @throws MojoFailureException
 *             If <code>failOnError</code> is <code>true</code> and command
 *             exit code is NOT equals to 0.
 */
private CommandResult executeCommand(final Commandline cmd,
        final boolean failOnError, final String argStr,
        final String... args) throws CommandLineException,
        MojoFailureException {
    // initialize executables
    initExecutables();

    if (getLog().isDebugEnabled()) {
        getLog().debug(
                cmd.getExecutable() + " " + StringUtils.join(args, " ")
                        + (argStr == null ? "" : " " + argStr));
    }

    cmd.clearArgs();
    cmd.addArguments(args);

    if (StringUtils.isNotBlank(argStr)) {
        cmd.createArg().setLine(argStr);
    }

    final StringBufferStreamConsumer out = new StringBufferStreamConsumer(
            verbose);

    final CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer();

    // execute
    final int exitCode = CommandLineUtils.executeCommandLine(cmd, out, err);

    String errorStr = err.getOutput();
    String outStr = out.getOutput();

    if (failOnError && exitCode != SUCCESS_EXIT_CODE) {
        // not all commands print errors to error stream
        if (StringUtils.isBlank(errorStr) && StringUtils.isNotBlank(outStr)) {
            errorStr = outStr;
        }

        throw new MojoFailureException(errorStr);
    }

    return new CommandResult(exitCode, outStr, errorStr);
}