Java Code Examples for org.codehaus.plexus.util.cli.Commandline#addArguments()

The following examples show how to use org.codehaus.plexus.util.cli.Commandline#addArguments() . 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: 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 4
Source File: PhantomJsProcessBuilder.java    From phantomjs-maven-plugin with MIT License 6 votes vote down vote up
private Commandline getCommandLine() throws ExecutionException {
  Commandline commandline = new Commandline(this.phantomJsBinary);

  if (configFile != null && configFile.exists()) {
    commandline.createArg().setValue("--config=" + configFile.getAbsolutePath());
  } else {
    commandline.addArguments(this.getCommandLineOptions(commandLineOptions));
  }
  if (script != null) {
    commandline.createArg().setValue(script);
  }
  if (arguments != null) {
    commandline.addArguments(arguments.toArray(new String[arguments.size()]));
  }
  if (workingDirectory != null) {
    commandline.setWorkingDirectory(workingDirectory);
  }

  return commandline;
}
 
Example 5
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 6
Source File: JavahExecutable.java    From maven-native with MIT License 4 votes vote down vote up
protected Commandline createJavahCommand( JavahConfiguration config )
    throws NativeBuildException
{
    this.validateConfiguration( config );

    Commandline cl = new Commandline();

    if ( config.getWorkingDirectory() != null )
    {
        cl.setWorkingDirectory( config.getWorkingDirectory().getPath() );
    }

    cl.setExecutable( this.getJavaHExecutable( config ) );

    if ( config.getFileName() != null && config.getFileName().length() > 0 )
    {
        File outputFile = new File( config.getOutputDirectory(), config.getFileName() );
        cl.createArg().setValue( "-o" );
        cl.createArg().setFile( outputFile );
    }
    else
    {
        if ( config.getOutputDirectory() != null )
        {
            cl.createArg().setValue( "-d" );
            cl.createArg().setFile( config.getOutputDirectory() );
        }
    }

    String[] classPaths = config.getClassPaths();

    StringBuffer classPathBuffer = new StringBuffer();

    for ( int i = 0; i < classPaths.length; ++i )
    {
        classPathBuffer.append( classPaths[i] );
        if ( i != classPaths.length - 1 )
        {
            classPathBuffer.append( File.pathSeparatorChar );
        }
    }

    if ( config.getUseEnvClasspath() )
    {
        cl.addEnvironment( "CLASSPATH", classPathBuffer.toString() );
    }
    else
    {
        cl.createArg().setValue( "-classpath" );

        cl.createArg().setValue( classPathBuffer.toString() );
    }

    if ( config.getVerbose() )
    {
        cl.createArg().setValue( "-verbose" );
    }

    cl.addArguments( config.getClassNames() );

    return cl;
}
 
Example 7
Source File: MSVCMessageCompiler.java    From maven-native with MIT License 4 votes vote down vote up
protected Commandline getCommandLine( MessageCompilerConfiguration config, File source )
    throws NativeBuildException
{

    Commandline cl = new Commandline();

    EnvUtil.setupCommandlineEnv( cl, config.getEnvFactory() );

    if ( config.getWorkingDirectory() != null )
    {
        cl.setWorkingDirectory( config.getWorkingDirectory().getPath() );
    }

    if ( config.getExecutable() == null || config.getExecutable().trim().length() == 0 )
    {
        config.setExecutable( "mc.exe" );
    }
    cl.setExecutable( config.getExecutable().trim() );

    cl.addArguments( config.getOptions() );

    if ( config.getOutputDirectory() != null && config.getOutputDirectory().getPath().trim().length() != 0 )
    {
        cl.createArg().setValue( "-r" );
        cl.createArg().setValue( config.getOutputDirectory().getPath() );

        cl.createArg().setValue( "-h" );
        cl.createArg().setValue( config.getOutputDirectory().getPath() );

    }

    if ( config.getDebugOutputDirectory() != null
            && config.getDebugOutputDirectory().getPath().trim().length() != 0 )
    {
        cl.createArg().setValue( "-x" );
        cl.createArg().setValue( config.getDebugOutputDirectory().getPath() );
    }

    cl.createArg().setValue( source.getPath() );

    return cl;
}
 
Example 8
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 9
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);
}