Example usage for org.apache.commons.exec DefaultExecutor DefaultExecutor

List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor

Introduction

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

Prototype

public DefaultExecutor() 

Source Link

Document

Default constructor creating a default PumpStreamHandler and sets the working directory of the subprocess to the current working directory.

Usage

From source file:com.github.shyiko.hmp.StopMojo.java

private void kill(int pid) throws IOException {
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new ExecutionStreamHandler(quiet));
    executor.execute(CommandLine.parse("kill -15 " + pid));
}

From source file:com.magnet.tools.tests.WebLogicStepDefs.java

public static void ensureStartServer(String location, String httpPingUrl) throws Exception {
    Executor exec = new DefaultExecutor();
    CommandLine cl = new CommandLine(getScriptsDir() + File.separator + START_WLS_SERVER_SCRIPT);
    if (getArchetypeSettings() != null && getArchetypeSettings().length() != 0) {
        cl.addArgument("--s");
        cl.addArgument(getArchetypeSettings());
    }/*from   w  w  w  .j  a  v a 2  s  . com*/
    cl.addArgument(String.format("-DdomainHome=%s", location));
    cl.addArgument(String.format("-DhttpPingUrl=%s", httpPingUrl));
    cl.setSubstitutionMap(getSubstitutionMap());
    int exitValue = exec.execute(cl);
    ensureBuildSuccessful("start-server.log");
    String msg = String.format("server failed to start at %s", expandVariables(location));
    Assert.assertEquals(msg, 0, exitValue);
}

From source file:com.netflix.genie.GenieCoreTestApplication.java

/**
 * Get an {@link Executor} to use for executing processes from tasks.
 *
 * @return The executor to use//from  www  . ja va 2s  .  com
 */
@Bean
public Executor processExecutor() {
    final Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(null, null));
    return executor;
}

From source file:com.meltmedia.cadmium.blackbox.test.CliCommitCloneTest.java

/**
 * <p>Runs the Cadmium CLI command commit from Apache Commons Exec library. Then uses {@link CadmiumAssertions#assertContentDeployed(String, java.io.File, String)} to assert that the content deployed properly.</p>
 * <p>To override the site url, pass <code>-Dcom.meltmedia.cadmium.test.site.url=[URL]</code> to the jvm that this test case will be running in. The site url defaults to <code>http://localhost</code> if not set.</p>
 * @throws IOException See {@link DefaultExecutor#execute(CommandLine)} for more information.
 * @throws ExecuteException See {@link DefaultExecutor#execute(CommandLine)} for more information.
 * @throws InterruptedException /* ww  w. j  a v a2s  . c  o m*/
 * 
 * @see <a href="http://commons.apache.org/exec">Apache Commons Exec</a>
 */
@Test
public void testCommit() throws ExecuteException, IOException {
    String deployUrl = System.getProperty("com.meltmedia.cadmium.test.site.url", DEPLOY_URL);
    CommandLine commitCmd = CommandLine
            .parse("cadmium commit -m \"Testing commit command\" " + TEST_CONTENT_LOCATION + " " + deployUrl);

    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValue(0);
    ExecuteWatchdog watchDog = new ExecuteWatchdog(60000);
    exec.setWatchdog(watchDog);

    int exitValue = exec.execute(commitCmd);

    assertEquals("Commit command returned with an error status.", exitValue, 0);

    assertContentDeployed("Failed to commit content to remote site.", new File(TEST_CONTENT_LOCATION),
            DEPLOY_URL);
}

From source file:com.tascape.qa.th.android.comm.Adb.java

public static void reset() throws IOException {
    CommandLine cmdLine = new CommandLine(ADB);
    cmdLine.addArgument("kill-server");
    LOG.debug("{}", cmdLine.toString());
    Executor executor = new DefaultExecutor();
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }//from ww  w. j  a  v a 2 s . co m
    cmdLine = new CommandLine(ADB);
    cmdLine.addArgument("devices");
    LOG.debug("{}", cmdLine.toString());
    executor = new DefaultExecutor();
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }
}

From source file:hoot.services.nativeinterfaces.CommandRunnerImpl.java

@Override
public CommandResult exec(String[] command) throws IOException {
    logger.debug("Executing the following command: {}", Arrays.toString(command));

    try (OutputStream stdout = new ByteArrayOutputStream(); OutputStream stderr = new ByteArrayOutputStream()) {

        this.stdout = stdout;
        this.stderr = stderr;

        CommandLine cmdLine = new CommandLine(command[0]);
        for (int i = 1; i < command.length; i++) {
            cmdLine.addArgument(command[i], false);
        }/*from w ww  . jav a 2 s.c o  m*/

        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(stdout, stderr);
        DefaultExecutor executor = new DefaultExecutor();
        this.watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        executor.setWatchdog(this.watchDog);
        executor.setStreamHandler(executeStreamHandler);

        int exitValue;
        try {
            exitValue = executor.execute(cmdLine);

            if (executor.isFailure(exitValue) && this.watchDog.killedProcess()) {
                // it was killed on purpose by the watchdog
                logger.info("Process for '{}' command was killed!", cmdLine);
            }
        } catch (Exception e) {
            exitValue = -1;
            logger.warn("Error executing: {}", cmdLine, e);
        }

        CommandResult commandResult = new CommandResult(cmdLine.toString(), exitValue, stdout.toString(),
                stderr.toString());

        logger.debug("Finished executing: {}", commandResult);

        return commandResult;
    }
}

From source file:com.demandware.vulnapp.challenge.impl.CommandInjectionChallenge.java

private String getCommandOutput(String command) {
    String output = null;//from  w  w  w  .  jav a  2  s .  c o m
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        CommandLine cmd = new CommandLine("/bin/bash");
        String[] args = new String[] { "-c", command };
        cmd.addArguments(args, false);
        PumpStreamHandler psh = new PumpStreamHandler(outputStream);

        DefaultExecutor exec = new DefaultExecutor();
        exec.setStreamHandler(psh);
        exec.execute(cmd);
        output = outputStream.toString();
    } catch (ExecuteException e) {
        e.printStackTrace();
        output = "Could not execute command";
    } catch (IOException e) {
        e.printStackTrace();
    }
    return output;
}

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());
    }//from  w  w w .j av a2 s  .  com
    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:com.wipro.ats.bdre.tdimport.QueuedFileUploader.java

private static void importFile(FileCopyInfo fileCopying) throws IOException {
    try {/*from w  w  w .j  a v  a  2 s  .c om*/
        String sCommandString;
        String subProcessId = fileCopying.getSubProcessId();
        GetProcess getProcess = new GetProcess();
        String params[] = { "-p", subProcessId };
        ProcessInfo processInfo = getProcess.getParentInfoFromSubProcess(params);
        String monDirName = new GetProperties().getProperties(subProcessId, "td-load")
                .getProperty("monitored-dir-name");
        String targetDirPath = "tdload/" + processInfo.getBusDomainId() + "/" + processInfo.getProcessTypeId()
                + "/" + processInfo.getProcessId();
        String absoluteFilePath = "tdload/" + processInfo.getBusDomainId() + "/"
                + processInfo.getProcessTypeId() + "/" + processInfo.getProcessId() + "/"
                + fileCopying.getFileName();
        String command = "sh " + MDConfig.getProperty("execute.script-path") + "/file-loader-remote.sh" + " "
                + absoluteFilePath + " " + fileCopying.getTdDB() + " " + fileCopying.getTdTable() + " "
                + fileCopying.getTdUserName() + " " + fileCopying.getTdPassword() + " "
                + fileCopying.getTdTpdid() + " " + fileCopying.getTdDelimiter() + " " + targetDirPath + " "
                + monDirName + " " + fileCopying.getFileName();
        sCommandString = command;
        CommandLine oCmdLine = CommandLine.parse(sCommandString);
        LOGGER.debug("executing command :" + command);
        DefaultExecutor oDefaultExecutor = new DefaultExecutor();
        //oDefaultExecutor.setExitValue(0);
        oDefaultExecutor.execute(oCmdLine);

    } catch (Exception e) {
        FileMonitor.addToQueue(fileCopying.getFileName(), fileCopying);
        LOGGER.error("Error in importing file into TD. Requeuing file " + fileCopying.getFileName(), e);
        throw new IOException(e);
    }
}

From source file:com.github.genium_framework.appium.support.command.CommandManager.java

/**
 * Execute a command on the operating system using Apache Commons Exec. This
 * function runs asynchronously and dumps both stderr and stdout streams to
 * a temp file.//from  w  w w  . j a v a  2s.co m
 *
 * @param commandLine The command to be executed.
 * @param outputStreamHandler An output stream to dump the process stderr
 * and stdout to it.
 */
public static void executeCommandUsingApacheExec(CommandLine commandLine, OutputStream outputStreamHandler) {
    try {
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamHandler);

        Executor process = new DefaultExecutor();
        process.setExitValue(0);
        process.setStreamHandler(streamHandler);
        process.execute(commandLine, resultHandler);
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "An exception was thrown.", ex);
    }
}