org.codehaus.plexus.util.cli.CommandLineUtils Java Examples

The following examples show how to use org.codehaus.plexus.util.cli.CommandLineUtils. 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: 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 #3
Source File: AbstractExecMojo.java    From exec-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the argument string given by the user. Strings are recognized as everything between STRING_WRAPPER.
 * PARAMETER_DELIMITER is ignored inside a string. STRING_WRAPPER and PARAMETER_DELIMITER can be escaped using
 * ESCAPE_CHAR.
 *
 * @return Array of String representing the arguments
 * @throws MojoExecutionException for wrong formatted arguments
 */
protected String[] parseCommandlineArgs()
    throws MojoExecutionException
{
    if ( commandlineArgs == null )
    {
        return null;
    }
    else
    {
        try
        {
            return CommandLineUtils.translateCommandline( commandlineArgs );
        }
        catch ( Exception e )
        {
            throw new MojoExecutionException( e.getMessage() );
        }
    }
}
 
Example #4
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 #5
Source File: AbstractGitflowBranchMojo.java    From gitflow-helper-maven-plugin with Apache License 2.0 6 votes vote down vote up
public void execute() throws MojoExecutionException, MojoFailureException {
    // Weather we resolve a single branch name or not, it won't hurt to run it through property replacement.
    try {
        systemEnvVars = CommandLineUtils.getSystemEnvVars();
    } catch (IOException ioe) {
        throw new MojoExecutionException("Unable to read System Envirionment Variables: ", ioe);
    }

    // Validate the match type.
    checkReleaseBranchMatchTypeParam();

    ScmUtils scmUtils = new ScmUtils(systemEnvVars, scmManager, project, getLog(), masterBranchPattern, supportBranchPattern, releaseBranchPattern, hotfixBranchPattern, developmentBranchPattern);
    GitBranchInfo branchInfo = scmUtils.resolveBranchInfo(gitBranchExpression);

    getLog().debug("Building for: " + branchInfo);
    execute(branchInfo);
}
 
Example #6
Source File: RunMojo.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (optionalRunExtraArgs == null) {
        optionalRunExtraArgs = new ArrayList<>();
    }

    String runArgsProp = System.getProperty("vertx.runArgs");

    if (StringUtils.isNotEmpty(runArgsProp)) {
        getLog().debug("Got command line arguments from property :" + runArgsProp);
        try {
            String[] argValues = CommandLineUtils.translateCommandline(runArgsProp);
            optionalRunExtraArgs.addAll(Arrays.asList(argValues));
        } catch (Exception e) {
            throw new MojoFailureException("Unable to parse system property vertx.runArgs", e);
        }
    } else if (runArgs != null && !runArgs.isEmpty()) {
        optionalRunExtraArgs.addAll(runArgs);
    }

    super.execute();
}
 
Example #7
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 #8
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 #9
Source File: EmbedderFactory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static Map<String, String> getCustomGlobalUserProperties() {
    //maybe set org.eclipse.aether.ConfigurationProperties.USER_AGENT with netbeans specific value.
    Map<String, String> toRet = new HashMap<String, String>();
    String options = getPreferences().get(PROP_DEFAULT_OPTIONS, "");
    try {
        
        String[] cmdlines = CommandLineUtils.translateCommandline(options);
        if (cmdlines != null) {
            for (String cmd : cmdlines) {
                if (cmd != null && cmd.startsWith("-D")) {
                    cmd = cmd.substring("-D".length());
                    int ind = cmd.indexOf('=');
                    if (ind > -1) {
                        String key = cmd.substring(0, ind);
                        String val = cmd.substring(ind + 1);
                        toRet.put(key, val);
                    }
                }
            }
        }
        return toRet;
    } catch (Exception ex) {
        LOG.log(Level.FINE, "cannot parse " + options, ex);
        return Collections.emptyMap();
    }
}
 
Example #10
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 #11
Source File: MavenSettings.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean hasOption(String longName, String shortName) {
    String defOpts = getDefaultOptions();
    if (defOpts != null) {
        try {
            String[] strs = CommandLineUtils.translateCommandline(defOpts);
            for (String s : strs) {
                s = s.trim();
                if (s.startsWith(shortName) || s.startsWith(longName)) {
                    return true;
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(MavenSettings.class.getName()).log(Level.FINE, "Error parsing global options:{0}", defOpts);
            //will check for contains of -X be enough?
            return defOpts.contains(longName) || defOpts.contains(shortName);
        }
    }
    return false;
}
 
Example #12
Source File: AbstractExecMojo.java    From jprotobuf with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the argument string given by the user. Strings are recognized as everything between STRING_WRAPPER.
 * PARAMETER_DELIMITER is ignored inside a string. STRING_WRAPPER and PARAMETER_DELIMITER can be escaped using
 * ESCAPE_CHAR.
 *
 * @return Array of String representing the arguments
 * @throws MojoExecutionException for wrong formatted arguments
 */
protected String[] parseCommandlineArgs()
    throws MojoExecutionException
{
    if ( commandlineArgs == null )
    {
        return null;
    }
    else
    {
        try
        {
            return CommandLineUtils.translateCommandline( commandlineArgs );
        }
        catch ( Exception e )
        {
            throw new MojoExecutionException( e.getMessage() );
        }
    }
}
 
Example #13
Source File: RunMojo.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (optionalRunExtraArgs == null) {
        optionalRunExtraArgs = new ArrayList<>();
    }

    String runArgsProp = System.getProperty("vertx.runArgs");

    if (StringUtils.isNotEmpty(runArgsProp)) {
        getLog().debug("Got command line arguments from property :" + runArgsProp);
        try {
            String[] argValues = CommandLineUtils.translateCommandline(runArgsProp);
            optionalRunExtraArgs.addAll(Arrays.asList(argValues));
        } catch (Exception e) {
            throw new MojoFailureException("Unable to parse system property vertx.runArgs", e);
        }
    } else if (runArgs != null && !runArgs.isEmpty()) {
        optionalRunExtraArgs.addAll(runArgs);
    }

    super.execute();
}
 
Example #14
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 #15
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 #16
Source File: ScmUtils.java    From gitflow-helper-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static void execGitCmd(ScmLogger logger, StreamConsumer consumer, Commandline cl) throws ScmException {
    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();

    int exitCode = GitCommandLineUtils.execute(cl, consumer, stderr, logger);

    if (exitCode != 0)
    {
        throw new ScmException("Git command failed: " + stderr.getOutput());
    }
}
 
Example #17
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 #18
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 #19
Source File: ExecMojo.java    From exec-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void handleSystemPropertyArguments( String argsProp, List<String> commandArguments )
    throws MojoExecutionException
{
    getLog().debug( "got arguments from system properties: " + argsProp );

    try
    {
        String[] args = CommandLineUtils.translateCommandline( argsProp );
        commandArguments.addAll( Arrays.asList( args ) );
    }
    catch ( Exception e )
    {
        throw new MojoExecutionException( "Couldn't parse systemproperty 'exec.args'" );
    }
}
 
Example #20
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 #21
Source File: PhantomJsProcessBuilder.java    From phantomjs-maven-plugin with MIT License 5 votes vote down vote up
@VisibleForTesting
String[] getCommandLineOptions(String commandLineOptions) throws ExecutionException {
  try {
    return CommandLineUtils.translateCommandline(commandLineOptions);
  } catch (Exception e) {
    throw new ExecutionException(UNABLE_TO_BUILD_CMD_LINE_OPTIONS, e);
  }
}
 
Example #22
Source File: CosChecker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static List<String> extractDebugJVMOptions(String argLine) throws Exception {
    String[] split = CommandLineUtils.translateCommandline(argLine);
    List<String> toRet = new ArrayList<String>();
    for (String arg : split) {
        if ("-Xdebug".equals(arg)) { //NOI18N
            continue;
        }
        if ("-Djava.compiler=none".equals(arg)) { //NOI18N
            continue;
        }
        if ("-Xnoagent".equals(arg)) { //NOI18N
            continue;
        }
        if (arg.startsWith("-Xrunjdwp")) { //NOI18N
            continue;
        }
        if (arg.equals("-agentlib:jdwp")) { //NOI18N
            continue;
        }
        if (arg.startsWith("-agentlib:jdwp=")) { //NOI18N
            continue;
        }
        if (arg.trim().length() == 0) {
            continue;
        }
        toRet.add(arg);
    }
    return toRet;
}
 
Example #23
Source File: Args.java    From amazon-neptune-tools with Apache License 2.0 5 votes vote down vote up
public Args(String cmd) {
    String[] values;
    try {
        values = CommandLineUtils.translateCommandline(cmd);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    args.addAll(Arrays.asList(values));
}
 
Example #24
Source File: JavaFXBaseMojo.java    From javafx-maven-plugin with Apache License 2.0 5 votes vote down vote up
Map<String, String> handleSystemEnvVariables() {
    Map<String, String> enviro = new HashMap<>();
    try {
        Properties systemEnvVars = CommandLineUtils.getSystemEnvVars();
        for (Map.Entry<?, ?> entry : systemEnvVars.entrySet()) {
            enviro.put((String) entry.getKey(), (String) entry.getValue());
        }
    } catch (IOException x) {
        getLog().error("Could not assign default system environment variables.", x);
    }

    return enviro;
}
 
Example #25
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);
}
 
Example #26
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 #27
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 #28
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 #29
Source File: ExecMojo.java    From exec-maven-plugin with Apache License 2.0 4 votes vote down vote up
private Map<String, String> handleSystemEnvVariables()
    throws MojoExecutionException
{

    Map<String, String> enviro = new HashMap<String, String>();
    try
    {
        Properties systemEnvVars = CommandLineUtils.getSystemEnvVars();
        for ( Map.Entry<?, ?> entry : systemEnvVars.entrySet() )
        {
            enviro.put( (String) entry.getKey(), (String) entry.getValue() );
        }
    }
    catch ( IOException x )
    {
        getLog().error( "Could not assign default system enviroment variables.", x );
    }

    if ( environmentVariables != null )
    {
        enviro.putAll( environmentVariables );
    }

    if ( this.environmentScript != null )
    {
        getLog().info( "Pick up external environment script: " + this.environmentScript );
        Map<String, String> envVarsFromScript = this.createEnvs( this.environmentScript );
        if ( envVarsFromScript != null )
        {
            enviro.putAll( envVarsFromScript );
        }
    }

    if ( this.getLog().isDebugEnabled() )
    {
        Set<String> keys = new TreeSet<String>();
        keys.addAll( enviro.keySet() );
        for ( String key : keys )
        {
            this.getLog().debug( "env: " + key + "=" + enviro.get( key ) );
        }
    }

    return enviro;
}
 
Example #30
Source File: StepBeanDefinitionRegistrar.java    From spring-cloud-dataflow with Apache License 2.0 4 votes vote down vote up
private String getCommandLineArgsForTask(String arguments, String taskName, Map<String, Integer> taskSuffixMap, String ctrName ) {
	String result = "";
	if(!StringUtils.hasText(arguments)) {
		return arguments;
	}
	if(arguments.startsWith("\"") && arguments.endsWith("\"")) {
		arguments = arguments.substring(1, arguments.length() - 1);
	}
	arguments = arguments.replace('\n', ' ').replace('\t', ' ');
	this.firstAdd = true;
	try {
		String[] args = CommandLineUtils.translateCommandline(arguments);
		String taskNamePrefix = taskName + ".";
		String taskNameNonIdentify = "--" + taskNamePrefix;
		for(String commandLineArg : Arrays.asList(args)) {
			String userPrefix = getPrefix(commandLineArg);
			String commandLineArgPrefix = ctrName + "-" + userPrefix;
			String commandLineArgToken = commandLineArgPrefix + ".";
			if(commandLineArgToken.equals(taskNameNonIdentify) || commandLineArgToken.equals(taskNamePrefix)) {
				result = addBlankToCommandLineArgs(result);
				if(commandLineArg.startsWith(userPrefix)) {
					result = result.concat(commandLineArg.substring(userPrefix.length() + 1));
				}
				else {
					result = result + "--" + commandLineArg.substring(userPrefix.length() + 3);
				}
				continue;
			}
			if(!taskSuffixMap.containsKey(commandLineArgPrefix)) {
				result = addBlankToCommandLineArgs(result);
				if(commandLineArg.contains(" ")) {
					commandLineArg = commandLineArg.substring(0, commandLineArg.indexOf("=")) +
							"=\"" + commandLineArg.substring(commandLineArg.indexOf("=") + 1 )+ "\"";
				}
				result = result.concat(commandLineArg);
			}
		}
	}
	catch (Exception e) {
		throw new IllegalArgumentException("Unable to extract command line args for task " + taskName, e);
	}

	return result;
}