Example usage for org.apache.commons.exec CommandLine addArgument

List of usage examples for org.apache.commons.exec CommandLine addArgument

Introduction

In this page you can find the example usage for org.apache.commons.exec CommandLine addArgument.

Prototype

public CommandLine addArgument(final String argument) 

Source Link

Document

Add a single argument.

Usage

From source file:com.alibaba.jstorm.utils.JStormUtils.java

public static void exec_command(String command) throws ExecuteException, IOException {
    String[] cmdlist = command.split(" ");
    CommandLine cmd = new CommandLine(cmdlist[0]);
    for (int i = 1; i < cmdlist.length; i++) {
        cmd.addArgument(cmdlist[i]);
    }/*from   ww  w .  j ava 2 s  . com*/

    DefaultExecutor exec = new DefaultExecutor();
    exec.execute(cmd);
}

From source file:com.walmart.gatling.commons.ReportExecutor.java

private void runJob(Master.GenerateReport job) {
    TaskEvent taskEvent = job.reportJob.taskEvent;
    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    Map<String, Object> map = new HashMap<>();

    map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName())));
    cmdLine.addArgument("${path}");

    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }//  ww  w.j  a va2 s.c o  m
    String dir = agentConfig.getJob().getLogDirectory() + "reports/" + job.reportJob.trackingId + "/";
    cmdLine.addArgument(dir);

    cmdLine.setSubstitutionMap(map);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(agentConfig.getJob().getExitValues());
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(new File(agentConfig.getJob().getPath()));
    FileOutputStream outFile = null;
    FileOutputStream errorFile = null;
    try {
        List<String> resultFiles = new ArrayList<>(job.results.size());
        //download all files adn
        /*int i=0;
        for (Worker.Result result : job.results) {
        String destFile = dir  + i++ + ".log";
        resultFiles.add(destFile);
        DownloadFile.downloadFile(result.metrics,destFile);
        }*/
        AtomicInteger index = new AtomicInteger();
        job.results.parallelStream().forEach(result -> {
            String destFile = dir + index.incrementAndGet() + ".log";
            resultFiles.add(destFile);
            DownloadFile.downloadFile(result.metrics, destFile);
        });
        String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.reportJob.trackingId);
        String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.reportJob.trackingId);
        //create the std and err files
        outFile = FileUtils.openOutputStream(new File(outPath));
        errorFile = FileUtils.openOutputStream(new File(errPath));

        PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile),
                new ExecLogHandler(errorFile));

        executor.setStreamHandler(psh);
        System.out.println(cmdLine);
        int exitResult = executor.execute(cmdLine);
        ReportResult result;
        if (executor.isFailure(exitResult)) {
            result = new ReportResult(dir, job.reportJob, false);
            log.info("Report Executor Failed, result: " + job.toString());
        } else {
            result = new ReportResult(job.reportJob.getHtml(), job.reportJob, true);
            log.info("Report Executor Completed, result: " + result.toString());
        }
        for (String resultFile : resultFiles) {
            FileUtils.deleteQuietly(new File(resultFile));
        }
        getSender().tell(result, getSelf());

    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }

}

From source file:hr.fer.zemris.vhdllab.service.impl.GhdlSimulator.java

private void prepairSimulationCommandLine(SimulationContext context) {
    String cmd = getProperties().getProperty(PROP_SIMULATION_CMD);
    cmd = cmd.replace("{files}", context.targetFile.getName());

    CommandLine cl = createCommandLine(cmd);
    cl.addArgument("--vcd=simout.vcd");

    Testbench tb = null;/*from ww  w.  j a v a  2 s . co  m*/
    try {
        tb = TestbenchParser.parseXml(context.targetFile.getData());
    } catch (UniformTestbenchParserException e) {
        throw new SimulationException(e);
    }
    long simulationLength = tb.getSimulationLength();
    if (simulationLength <= 0) {
        simulationLength = 100;
    } else {
        simulationLength = simulationLength / TimeScale.getMultiplier(tb.getTimeScale());
        simulationLength = (long) (simulationLength * 1.1);
    }
    cl.addArgument("--stop-time=" + simulationLength + tb.getTimeScale().toString().toLowerCase());

    context.commandLine = cl;
}

From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java

protected boolean compileForEeprom(String executable, File sourceFile, File destinationFile) {
    try {/*  w  w  w .  ja  va 2  s.  c  o  m*/
        List<CLib> libs = new ArrayList<>();
        libs.add(cLibs.get("simpletools"));
        libs.add(cLibs.get("simpletext"));
        libs.add(cLibs.get("simplei2c"));

        File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib");
        Map map = new HashMap();
        map.put("sourceFile", sourceFile);
        map.put("destinationFile", destinationFile);
        CommandLine cmdLine = new CommandLine(executable);
        for (CLib lib : libs) {
            cmdLine.addArgument("-I").addArgument("${libdir" + lib.getName() + "}");
            cmdLine.addArgument("-L").addArgument("${memorymodel" + lib.getName() + "}");
            cmdLine.addArgument("-l" + lib.getName());

            map.put("libdir" + lib.getName(), new File(libDirectory, lib.getLibdir()));
            map.put("memorymodel" + lib.getName(), new File(libDirectory, lib.getMemoryModel().get("cmm")));
        }
        cmdLine.addArgument("-Os");
        cmdLine.addArgument("-mcmm");
        cmdLine.addArgument("-m32bit-doubles");
        cmdLine.addArgument("-std=c99");
        cmdLine.addArgument("-o").addArgument("${destinationFile}");
        cmdLine.addArgument("${sourceFile}");
        cmdLine.addArgument("-lm");
        for (CLib lib : libs) {
            cmdLine.addArgument("-l" + lib.getName());
        }
        cmdLine.setSubstitutionMap(map);
        DefaultExecutor executor = new DefaultExecutor();
        //  executor.setExitValues(new int[]{402, 101});

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        try {
            exitValue = executor.execute(cmdLine);
        } catch (ExecuteException ee) {
            exitValue = ee.getExitValue();
            logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue);
            success = false;
            return false;
        } finally {
            output = outputStream.toString();
        }

        //            System.out.println("output: " + output);
        /*
         Scanner scanner = new Scanner(output);
                
                
         Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?");
         Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$");
         while (scanner.hasNextLine()) {
         String portLine = scanner.nextLine();
         if (chipFoundPattern.matcher(portLine).matches()) {
         Matcher portMatch = pattern.matcher(portLine);
         if (portMatch.find()) {
         //   String port = portMatch.group("comport");
                
         }
         }
         }
         */
        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}

From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java

protected boolean compileForRam(String executable, File sourceFile, File destinationFile) {
    try {//from w  ww.j ava2s .  c  o  m
        List<CLib> libs = new ArrayList<>();
        libs.add(cLibs.get("simpletools"));
        libs.add(cLibs.get("simpletext"));
        libs.add(cLibs.get("simplei2c"));

        File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib");
        Map map = new HashMap();
        map.put("sourceFile", sourceFile);
        map.put("destinationFile", destinationFile);
        CommandLine cmdLine = new CommandLine(executable);
        for (CLib lib : libs) {
            cmdLine.addArgument("-I").addArgument("${libdir" + lib.getName() + "}");
            cmdLine.addArgument("-L").addArgument("${memorymodel" + lib.getName() + "}");
            //                cmdLine.addArgument("-l" + lib.getName());

            map.put("libdir" + lib.getName(), new File(libDirectory, lib.getLibdir()));
            map.put("memorymodel" + lib.getName(), new File(libDirectory, lib.getMemoryModel().get("cmm")));
        }
        cmdLine.addArgument("-Os");
        cmdLine.addArgument("-mcmm");
        cmdLine.addArgument("-m32bit-doubles");
        cmdLine.addArgument("-std=c99");
        cmdLine.addArgument("-o").addArgument("${destinationFile}");
        cmdLine.addArgument("${sourceFile}");
        cmdLine.addArgument("-lm");
        for (CLib lib : libs) {
            cmdLine.addArgument("-l" + lib.getName());
        }

        cmdLine.setSubstitutionMap(map);
        DefaultExecutor executor = new DefaultExecutor();
        //  executor.setExitValues(new int[]{402, 101});

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        try {
            exitValue = executor.execute(cmdLine);
        } catch (ExecuteException ee) {
            exitValue = ee.getExitValue();
            logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue);
            success = false;
            return false;
        } finally {
            output = outputStream.toString();
        }

        //            System.out.println("output: " + output);
        /*
         Scanner scanner = new Scanner(output);
                
                
         Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?");
         Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$");
         while (scanner.hasNextLine()) {
         String portLine = scanner.nextLine();
         if (chipFoundPattern.matcher(portLine).matches()) {
         Matcher portMatch = pattern.matcher(portLine);
         if (portMatch.find()) {
         //   String port = portMatch.group("comport");
                
         }
         }
         }
         */
        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}

From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java

/**
 *
 *
 * @param executable/* w  w  w  . j  a v a  2  s .  c  om*/
 * @param sourceFile
 * @return
 */
protected boolean compile(String executable, File sourceFile) {
    try {
        List<CLib> libs = new ArrayList<>();
        libs.add(cLibs.get("simpletools"));
        libs.add(cLibs.get("simpletext"));
        libs.add(cLibs.get("simplei2c"));

        File temporaryDestinationFile = File.createTempFile("blocklyapp", ".elf");
        File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib");
        Map map = new HashMap();
        map.put("sourceFile", sourceFile);
        map.put("destinationFile", temporaryDestinationFile);

        CommandLine cmdLine = new CommandLine(executable);
        for (CLib lib : libs) {
            cmdLine.addArgument("-I").addArgument("${libdir" + lib.getName() + "}");
            cmdLine.addArgument("-L").addArgument("${memorymodel" + lib.getName() + "}");
            // cmdLine.addArgument("-l" + lib.getName());

            map.put("libdir" + lib.getName(), new File(libDirectory, lib.getLibdir()));
            map.put("memorymodel" + lib.getName(), new File(libDirectory, lib.getMemoryModel().get("cmm")));
        }
        cmdLine.addArgument("-Os");
        cmdLine.addArgument("-mcmm");
        cmdLine.addArgument("-m32bit-doubles");
        cmdLine.addArgument("-fno-exceptions");
        cmdLine.addArgument("-std=c99");
        cmdLine.addArgument("-o").addArgument("${destinationFile}");
        cmdLine.addArgument("${sourceFile}");
        cmdLine.addArgument("-lm");
        for (CLib lib : libs) {
            cmdLine.addArgument("-l" + lib.getName());
        }

        cmdLine.setSubstitutionMap(map);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValues(new int[] { 0, 1 });

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        try {
            System.out.println(cmdLine);
            exitValue = executor.execute(cmdLine);
        } catch (ExecuteException ee) {
            exitValue = ee.getExitValue();
            logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue);
            success = false;
            return false;
        } finally {
            temporaryDestinationFile.delete();
            output = outputStream.toString();
        }

        //            System.out.println("output: " + output);
        /*
         Scanner scanner = new Scanner(output);
                
                
         Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?");
         Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$");
         while (scanner.hasNextLine()) {
         String portLine = scanner.nextLine();
         if (chipFoundPattern.matcher(portLine).matches()) {
         Matcher portMatch = pattern.matcher(portLine);
         if (portMatch.find()) {
         //   String port = portMatch.group("comport");
                
         }
         }
         }
         */
        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}

From source file:com.netflix.genie.core.jobs.workflow.impl.JobKickoffTask.java

/**
 * Create user on the system. Synchronized to prevent multiple threads from trying to create user at the same time.
 *
 * @param user  user id// ww  w  .j  av a2s.  c  o m
 * @param group group id
 * @throws GenieException If there is any problem.
 */
protected synchronized void createUser(final String user, final String group) throws GenieException {

    // First check if user already exists
    final CommandLine idCheckCommandLine = new CommandLine("id").addArgument("-u").addArgument(user);

    try {
        this.executor.execute(idCheckCommandLine);
        log.debug("User already exists");
    } catch (final IOException ioe) {
        log.debug("User does not exist. Creating it now.");

        // Determine if the group is valid by checking that its not null and not same as user.
        final boolean isGroupValid = StringUtils.isNotBlank(group) && !group.equals(user);

        // Create the group for the user if its not the same as the user.
        if (isGroupValid) {
            log.debug("Group and User are different so creating group now.");
            final CommandLine groupCreateCommandLine = new CommandLine("sudo").addArgument("groupadd")
                    .addArgument(group);

            // We create the group and ignore the error as it will fail if group already exists.
            // If the failure is due to some other reason, then user creation will fail and we catch that.
            try {
                log.debug("Running command to create group:  [" + groupCreateCommandLine.toString() + "]");
                this.executor.execute(groupCreateCommandLine);
            } catch (IOException ioexception) {
                log.debug("Group creation threw an error as it might already exist");
            }
        }

        final CommandLine userCreateCommandLine = new CommandLine("sudo").addArgument("useradd")
                .addArgument(user);
        if (isGroupValid) {
            userCreateCommandLine.addArgument("-G").addArgument(group);
        }
        userCreateCommandLine.addArgument("-M");

        try {
            log.debug("Running command to create user: [" + userCreateCommandLine.toString() + "]");
            this.executor.execute(userCreateCommandLine);
        } catch (IOException ioexception) {
            throw new GenieServerException("Could not create user " + user + " with exception " + ioexception);
        }
    }
}

From source file:com.netflix.genie.web.jobs.workflow.impl.JobKickoffTask.java

/**
 * Create user on the system. Synchronized to prevent multiple threads from trying to create user at the same time.
 *
 * @param user  user id//from   w w  w. ja va2  s . c  om
 * @param group group id
 * @throws GenieException If there is any problem.
 */
protected synchronized void createUser(final String user, final String group) throws GenieException {

    // First check if user already exists
    final CommandLine idCheckCommandLine = new CommandLine("id").addArgument("-u").addArgument(user);

    try {
        this.executor.execute(idCheckCommandLine);
        log.debug("User already exists");
    } catch (final IOException ioe) {
        log.debug("User does not exist. Creating it now.");

        // Determine if the group is valid by checking that its not null and not same as user.
        final boolean isGroupValid = StringUtils.isNotBlank(group) && !group.equals(user);

        // Create the group for the user if its not the same as the user.
        if (isGroupValid) {
            log.debug("Group and User are different so creating group now.");
            final CommandLine groupCreateCommandLine = new CommandLine("sudo").addArgument("groupadd")
                    .addArgument(group);

            // We create the group and ignore the error as it will fail if group already exists.
            // If the failure is due to some other reason, then user creation will fail and we catch that.
            try {
                log.debug("Running command to create group:  [{}]", groupCreateCommandLine);
                this.executor.execute(groupCreateCommandLine);
            } catch (IOException ioexception) {
                log.debug("Group creation threw an error as it might already exist", ioexception);
            }
        }

        final CommandLine userCreateCommandLine = new CommandLine("sudo").addArgument("useradd")
                .addArgument(user);
        if (isGroupValid) {
            userCreateCommandLine.addArgument("-G").addArgument(group);
        }
        userCreateCommandLine.addArgument("-M");

        try {
            log.debug("Running command to create user: [{}]", userCreateCommandLine);
            this.executor.execute(userCreateCommandLine);
        } catch (IOException ioexception) {
            throw new GenieServerException("Could not create user " + user, ioexception);
        }
    }
}

From source file:com.sonar.it.jenkins.orchestrator.container.JenkinsWrapper.java

public void start() {
    if (started.getAndSet(true)) {
        throw new IllegalStateException("App server is already started");
    }//from ww  w .  ja  v a2 s.  c  o  m

    LOG.info("Start jenkins on port " + port + " in " + workingDir);
    resultHandler = createResultHandler();
    try {
        FileUtils.forceMkdir(workingDir);
        CommandLine command;
        if (javaHome == null) {
            command = new CommandLine("java");
        } else {
            command = new CommandLine(FileUtils.getFile(javaHome, "bin", "java"));
        }
        command.addArgument("-Xmx512M");
        command.addArgument("-XX:MaxPermSize=128m");
        command.addArgument("-Djava.awt.headless=true");
        command.addArgument("-Djenkins.install.runSetupWizard=false");
        command.addArgument("-DJENKINS_HOME=" + workingDir.getAbsolutePath());
        String jaCoCoArgument = JaCoCoArgumentsBuilder.getJaCoCoArgument(config);
        if (jaCoCoArgument != null) {
            LOG.info("JaCoCo enabled");
            command.addArgument(jaCoCoArgument);
        }

        command.addArgument("-jar");
        command.addArgument("jenkins-war-" + server.getVersion() + ".war");
        command.addArgument("--httpPort=" + port);
        command.addArgument("--ajp13Port=-1");

        executor.setWorkingDirectory(workingDir.getParentFile());
        executor.execute(command, resultHandler);
    } catch (IOException e) {
        throw new IllegalStateException("Can't start jenkins", e);
    }

    waitForJenkinsToStart();
}

From source file:de.simu.decomap.messaging.resultprocessor.impl.helper.RulesExecutor.java

/**
 * Executing a predefined Rule//from  ww  w. j  av a 2 s .c o  m
 * @param ruleType RuleType
 * @param arg args for Rule
 * @return Success
 */
public boolean executePredefinedRule(byte ruleType, String arg) {
    logger.info("[IPTABLES] -> executing predefined command...");

    // use apache's commons-exec for executing command!
    CommandLine cmdLine = new CommandLine(command);

    // get the predefined rule-parameters
    String[] ruleParams = Rules.getPredefindedRuleParameters(ruleType, arg);

    if (ruleParams != null) {

        // add rule-parameters to CommanLine-Object
        for (int i = 0; i < ruleParams.length; i++) {
            cmdLine.addArgument(ruleParams[i]);
        }

        // execute command
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(mTimeout);
        Executor executor = new DefaultExecutor();
        executor.setExitValue(1);
        executor.setWatchdog(watchdog);
        try {
            executor.execute(cmdLine, resultHandler);
        } catch (ExecuteException e) {
            logger.warn("[IPTABLES] -> error while executing predefined command: execute-exception occured!");
            return false;
        } catch (IOException e) {
            logger.warn("[IPTABLES] -> error while executing predefined command: io-exception occured!");
            return false;
        }

        try {
            // some time later the result handler callback was invoked so we
            // can safely request the exit value
            resultHandler.waitFor();
            int exitCode = resultHandler.getExitValue();
            logger.info("[IPTABLES] -> command " + ruleType + " executed, exit-code is: " + exitCode);

            switch (exitCode) {
            case EXIT_CODE_SUCCESS:
                return true;
            case EXIT_CODE_ERROR:
                return false;
            default:
                return false;
            }

        } catch (InterruptedException e) {
            logger.warn(
                    "[IPTABLES] -> error while executing predefined command: interrupted-exception occured!");
            return false;
        }

    } else {
        logger.warn("[IPTABLES] -> error while excuting predefined command: rule-parameters-list is null!");
        return false;
    }
}