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

The following examples show how to use org.codehaus.plexus.util.cli.Commandline#setExecutable() . 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: 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 2
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 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 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 4
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 5
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 6
Source File: CreateApplicationBundleMojo.java    From appbundle-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void createApplicationsSymlink() throws MojoExecutionException, CommandLineException {
    Commandline symlink = new Commandline();
    symlink.setExecutable("ln");
    symlink.createArgument().setValue("-s");
    symlink.createArgument().setValue("/Applications");
    symlink.createArgument().setValue(buildDirectory.getAbsolutePath());
    try {
        symlink.execute().waitFor();
    } catch (InterruptedException ex) {
        throw new MojoExecutionException("Error preparing bundle disk image while creating symlink" + diskImageFile, ex);
    }
}
 
Example 7
Source File: DefaultRanlib.java    From maven-native with MIT License 5 votes vote down vote up
public void run( File file )
    throws NativeBuildException
{
    Commandline cl = new Commandline();

    cl.setExecutable( "ranlib" );

    cl.createArg().setValue( file.getAbsolutePath() );

    CommandLineUtil.execute( cl, this.getLogger() );
}
 
Example 8
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 9
Source File: MSVCManifest.java    From maven-native with MIT License 5 votes vote down vote up
public void run( ManifestConfiguration config )
    throws NativeBuildException
{
    Commandline cl = new Commandline();

    cl.setExecutable( "mt.exe" );
    cl.setWorkingDirectory( config.getWorkingDirectory().getPath() );

    cl.createArg().setValue( "-manifest" );

    int manifestType = 0;

    if ( "EXE".equalsIgnoreCase( FileUtils.getExtension( config.getInputFile().getPath() ) ) )
    {
        manifestType = 1;
    }
    else if ( "DLL".equalsIgnoreCase( FileUtils.getExtension( config.getInputFile().getPath() ) ) )
    {
        manifestType = 2;
    }

    if ( manifestType == 0 )
    {
        throw new NativeBuildException( "Unknown manifest input file type: " + config.getInputFile() );
    }

    cl.createArg().setFile( config.getManifestFile() );
    cl.createArg().setValue( "-outputresource:" + config.getInputFile() + ";" + manifestType );

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

    CommandLineUtil.execute( cl, this.getLogger() );
}
 
Example 10
Source File: CreateApplicationBundleMojo.java    From appbundle-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void removeApplicationsSymlink() throws MojoExecutionException, CommandLineException {
    Commandline remSymlink = new Commandline();
    String symlink = buildDirectory.getAbsolutePath() + "/Applications";
    if (!new File(symlink).exists()) {
        return;
    }
    remSymlink.setExecutable("rm");
    remSymlink.createArgument().setValue(symlink);
    try {
        remSymlink.execute().waitFor();
    } catch (InterruptedException ex) {
        throw new MojoExecutionException("Error cleaning up (while removing " + symlink +
                " symlink.) Please check permissions for that symlink" + diskImageFile, ex);
    }
}
 
Example 11
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 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: 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 14
Source File: ArchiveLinker.java    From maven-native with MIT License 4 votes vote down vote up
@Override
protected Commandline createLinkerCommandLine( List<File> objectFiles, LinkerConfiguration config )
{
    Commandline cl = new Commandline();

    cl.setWorkingDirectory( config.getWorkingDirectory().getPath() );

    String executable = EXECUTABLE;

    if ( !StringUtils.isBlank( config.getExecutable() ) )
    {
        executable = config.getExecutable();
    }

    cl.setExecutable( executable );

    for ( int i = 0; i < config.getStartOptions().length; ++i )
    {
        cl.createArg().setValue( config.getStartOptions()[i] );
    }

    // the next 2 are for completeness, the start options should be good enough
    for ( int i = 0; i < config.getMiddleOptions().length; ++i )
    {
        cl.createArg().setValue( config.getMiddleOptions()[i] );
    }

    for ( int i = 0; i < config.getEndOptions().length; ++i )
    {
        cl.createArg().setValue( config.getEndOptions()[i] );
    }

    cl.createArg().setFile( config.getOutputFile() );

    for ( int i = 0; i < objectFiles.size(); ++i )
    {
        File objFile = objectFiles.get( i );

        cl.createArg().setValue( objFile.getPath() );
    }

    return cl;

}
 
Example 15
Source File: JavaProcessExecutor.java    From vertx-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public Commandline buildCommandLine() throws Exception {
    Commandline cli = new Commandline();

    //Disable explicit quoting of arguments
    cli.getShell().setQuotedArgumentsEnabled(false);

    cli.setExecutable(javaPath.toString());

    cli.setWorkingDirectory(workingDirectory);

    addClasspath(this.argsList);

    argsLine(cli);

    return cli;
}
 
Example 16
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 17
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 18
Source File: JavaProcessExecutor.java    From vertx-maven-plugin with Apache License 2.0 4 votes vote down vote up
private Commandline buildCommandLine() throws Exception {
    Commandline cli = new Commandline();

    //Disable explicit quoting of arguments
    cli.getShell().setQuotedArgumentsEnabled(false);

    cli.setExecutable(java.getAbsolutePath());

    environment.forEach(cli::addEnvironment);

    cli.setWorkingDirectory(workingDirectory);

    addClasspath(this.argsList);

    argsLine(cli);

    return cli;
}
 
Example 19
Source File: AbstractCCompiler.java    From maven-native with MIT License 3 votes vote down vote up
/**
 * Setup Compiler Command line
 */
protected Commandline getCommandLine( File srcFile, File destFile, CompilerConfiguration config )
    throws NativeBuildException
{

    if ( config.getExecutable() == null )
    {
        config.setExecutable( "gcc" );
    }

    Commandline cl = new Commandline();

    cl.setExecutable( config.getExecutable() );

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

    this.setStartOptions( cl, config );

    this.setIncludePaths( cl, config.getIncludePaths() );

    this.setIncludePaths( cl, config.getSystemIncludePaths() );

    this.setMiddleOptions( cl, config );

    this.setOutputArgs( cl, destFile );

    this.setSourceArgs( cl, srcFile );

    this.setEndOptions( cl, config );

    return cl;
}
 
Example 20
Source File: AbstractGccCompiler.java    From maven-native with MIT License 3 votes vote down vote up
/**
 * Setup Compiler Command line
 */
protected Commandline getCommandLine( File srcFile, File destFile, CompilerConfiguration config )
    throws NativeBuildException
{

    if ( config.getExecutable() == null )
    {
        config.setExecutable( "gcc" );
    }

    Commandline cl = new Commandline();

    cl.setExecutable( config.getExecutable() );

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

    this.setStartOptions( cl, config );

    this.setIncludePaths( cl, config.getIncludePaths() );

    this.setIncludePaths( cl, config.getSystemIncludePaths() );

    this.setMiddleOptions( cl, config );

    this.setOutputArgs( cl, destFile );

    this.setSourceArgs( cl, srcFile );

    this.setEndOptions( cl, config );

    return cl;
}