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

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

Introduction

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

Prototype

public CommandLine(final CommandLine other) 

Source Link

Document

Copy constructor.

Usage

From source file:com.abiquo.nodecollector.service.impl.StonithServiceImpl.java

protected CommandLine buildCommand(final String ip, final Integer port, final String user,
        final String password) {
    CommandLine command = new CommandLine("ipmitool");
    command.addArgument("-H").addArgument(ip, true);
    command.addArgument("-U").addArgument(user, true);
    command.addArgument("-P").addArgument(password, true);
    command.addArgument("chassis", true);

    if (port != null) {
        command.addArgument("-p").addArgument(port.toString(), true);
    }/*from  ww  w  .  ja  v a 2s.com*/

    return command;
}

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 www  .  jav  a  2 s  .  com*/
    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: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());
    }/* w w w  . j  a v a2 s  . co m*/
    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:io.gatling.mojo.GatlingJavaMainCallerByFork.java

@Override
public boolean run(boolean displayCmd, boolean throwFailure) throws Exception {
    List<String> cmd = buildCommand();
    displayCmd(displayCmd, cmd);//www.jav a 2  s . co  m
    Executor exec = new DefaultExecutor();

    // err and out are redirected to out
    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in));

    exec.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine cl = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        cl.addArgument(cmd.get(i), false);
    }
    try {
        int exitValue = exec.execute(cl);
        if (exitValue != 0) {
            if (throwFailure) {
                throw new MojoFailureException("command line returned non-zero value:" + exitValue);
            }
            return false;
        }
        return true;
    } catch (ExecuteException exc) {
        if (throwFailure) {
            throw exc;
        }
        return false;
    }
}

From source file:edu.emory.cci.aiw.neo4jetl.Neo4jHome.java

private void controlServer(String command) throws IOException, InterruptedException, CommandFailedException {
    LOGGER.debug("Executing neo4j command {}...", command);
    CommandLine serverControlCommand = new CommandLine(new File(this.home, SERVER_CONTROL_COMMAND));
    serverControlCommand.addArgument("${command}");
    Map<String, String> map = new HashMap<>();
    map.put("command", command);
    serverControlCommand.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);//from   w w  w.j  av  a2  s.com
    executor.setWatchdog(watchdog);
    executor.execute(serverControlCommand, resultHandler);
    LOGGER.debug("Neo4j command {} is completed, checking exit value...", command);
    resultHandler.waitFor();
    int exitValue = resultHandler.getExitValue();
    if (exitValue != 0) {
        ExecuteException exception = resultHandler.getException();
        throw new CommandFailedException(exitValue, "Neo4j command '" + command + "' failed", exception);
    }
    LOGGER.debug("Neo4j command {} was successful", command);
}

From source file:de.esukom.decoit.ifmapclient.iptables.RulesExecutor.java

public boolean executePredefinedRule(byte ruleType, String[] arg) {
    IfMapClient.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]);
        }/*from w w w.j a  v a2  s.  co m*/

        // 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) {
            IfMapClient.LOGGER.warning(
                    "[IPTABLES] -> error while executing predefined command: execute-exception occured!");
            return false;
        } catch (IOException e) {
            IfMapClient.LOGGER
                    .warning("[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();
            IfMapClient.LOGGER.warning("[IPTABLES] -> command 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) {
            IfMapClient.LOGGER.warning(
                    "[IPTABLES] -> error while executing predefined command: interrupted-exception occured!");
            return false;
        }

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

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.AmazonHtmlToMobiConverter.java

@Override
public File convertToMobi(File htmlFile) {
    logger.debug("Enter convertToMobi()...");

    if (htmlFile == null) {
        logger.error("Document is null, aborting...");
        System.exit(1);//from ww w.  j  ava  2 s  .  co m
    }

    CommandLine cmdLine;
    if (execPath != null) {
        // Run the configured kindlegen executable
        logger.info("Kindlegen will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Kindlegen will be run within the PATH variable.");
        cmdLine = new CommandLine(command);
    }

    // Run configuration
    cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString());
    cmdLine.addArgument("-c0");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter stdoutWriter = new StringWriter();
    StringWriter stderrWriter = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(stdoutWriter, Charset.forName("UTF-8"));
    WriterOutputStream writerErrorStream = new WriterOutputStream(stderrWriter, Charset.forName("UTF-8"));

    ExecuteStreamHandler kindlegenStreamHandler = new PumpStreamHandler(writerOutputStream, writerErrorStream);
    executor.setStreamHandler(kindlegenStreamHandler);

    logger.debug("Launching kindlegen:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("Kindlegen failed to execute:");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("Kindlegen execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();
            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"kindlegen\"")) {
                logger.error("Kindlegen could not be run! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("Kindlegen's execution got interrupted: ");
        logger.error(e.getMessage(), e);
    }

    try {
        String stderrOutput = stderrWriter.getBuffer().toString();
        stderrWriter.close();
        if (stderrOutput.isEmpty() == false) {
            logger.error("Kindlegen logged some errors:");
            logger.error(stderrOutput);
        }
    } catch (IOException e) {
        logger.error("Error closing kindlegen's stderr buffer");
        logger.error(e.getMessage(), e);
    }

    String output = "";
    try {
        output += stdoutWriter.getBuffer().toString();
        stdoutWriter.close();

    } catch (IOException e) {
        logger.error("Error closing kindlegen's stdout buffer:");
        logger.error(e.getMessage(), e);
    }

    logger.debug("Kindlegen output: \n" + output);

    String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString();
    logger.debug("Moving Kindlegen output file: " + mobiFilename);

    Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename);
    return tempMobiFilepath.toFile();
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.CalibreHtmlToMobiConverter.java

@Override
public File convertToMobi(File htmlFile) {
    logger.debug("Enter convertToMobi()...");

    if (htmlFile == null) {
        logger.error("Document is null, aborting...");
        System.exit(1);// w  w w .  ja  v  a2  s  .  c om
    }

    CommandLine cmdLine;
    if (execPath != null) {
        // Run the configured calibre ebook-convert executable
        logger.info("Calibre ebook-convert will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Calibre ebook-convert will be run within the PATH variable.");
        cmdLine = new CommandLine(command);
    }

    // cli command: ebook-convert input_file.html output_file.mobi --mobi-file-type=new

    // Run configuration
    cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString());

    String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString();
    Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename);

    logger.debug("Mobi output file: " + tempMobiFilepath.toAbsolutePath().toString());
    cmdLine.addArgument(tempMobiFilepath.toAbsolutePath().toString());

    // Output will be in format "KF8" only, old format does not allow external CSS files
    cmdLine.addArgument("--mobi-file-type=new");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter writer = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8"));

    ExecuteStreamHandler calibreStreamHandler = new PumpStreamHandler(writerOutputStream, System.err);
    executor.setStreamHandler(calibreStreamHandler);

    logger.debug("Launching calibres ebook-convert:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("calibres ebook-convert failed to execute:");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("calibre ebook-converts execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();
            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"ebook-convert\"")) {
                logger.error("calibres ebook-convert could not be run! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("calibre ebook-converts execution got interrupted: ");
        logger.error(e.getMessage(), e);
    }

    String output = "";
    try {
        output += writer.getBuffer().toString();
        writer.close();

    } catch (IOException e) {
        logger.error("Error reading calibre ebook-converts output from buffer:");
        logger.error(e.getMessage(), e);

    }

    logger.debug("Calibre ebook-convert output: \n" + output);

    return tempMobiFilepath.toFile();
}

From source file:com.netflix.spinnaker.halyard.core.job.v1.JobExecutorLocal.java

@Override
public String startJob(JobRequest jobRequest, Map<String, String> env, InputStream stdIn,
        ByteArrayOutputStream stdOut, ByteArrayOutputStream stdErr) {
    List<String> tokenizedCommand = jobRequest.getTokenizedCommand();
    if (tokenizedCommand == null || tokenizedCommand.isEmpty()) {
        throw new IllegalArgumentException("JobRequest must include a tokenized command to run");
    }//from  w  ww.  j a v a 2  s.  c  o  m

    final long timeoutMillis = jobRequest.getTimeoutMillis() == null ? ExecuteWatchdog.INFINITE_TIMEOUT
            : jobRequest.getTimeoutMillis();

    String jobId = UUID.randomUUID().toString();

    pendingJobSet.add(jobId);

    log.info("Scheduling job " + jobRequest.getTokenizedCommand() + " with id " + jobId);

    scheduler.createWorker().schedule(new Action0() {
        @Override
        public void call() {
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdOut, stdErr, stdIn);
            CommandLine commandLine;

            log.info("Executing " + jobId + "with tokenized command: " + tokenizedCommand);

            // Grab the first element as the command.
            commandLine = new CommandLine(jobRequest.getTokenizedCommand().get(0));

            // Treat the rest as arguments.
            String[] arguments = Arrays.copyOfRange(tokenizedCommand.toArray(new String[0]), 1,
                    tokenizedCommand.size());

            commandLine.addArguments(arguments, false);

            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis) {
                @Override
                public void timeoutOccured(Watchdog w) {
                    // If a watchdog is passed in, this was an actual time-out. Otherwise, it is likely
                    // the result of calling watchdog.destroyProcess().
                    if (w != null) {
                        log.warn("Job " + jobId + " timed-out after " + timeoutMillis + "ms.");

                        cancelJob(jobId);
                    }

                    super.timeoutOccured(w);
                }
            };

            Executor executor = new DefaultExecutor();
            executor.setStreamHandler(pumpStreamHandler);
            executor.setWatchdog(watchdog);
            try {
                executor.execute(commandLine, env, resultHandler);
            } catch (IOException e) {
                throw new RuntimeException("Execution of " + jobId + " failed ", e);
            }

            // Give the job some time to spin up.
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignored) {
            }

            jobIdToHandlerMap.put(jobId, new ExecutionHandler().setResultHandler(resultHandler)
                    .setWatchdog(watchdog).setStdOut(stdOut).setStdErr(stdErr));

            if (pendingJobSet.contains(jobId)) {
                pendingJobSet.remove(jobId);
            } else {
                // If the job was removed from the set of pending jobs by someone else, its deletion was requested
                jobIdToHandlerMap.remove(jobId);
                watchdog.destroyProcess();
            }
        }
    });

    return jobId;
}

From source file:name.martingeisse.webide.features.verilog.simulator.VerilogSimulatorMenuDelegate.java

@Override
public void invoke(final Object context, final List<ResourceHandle> anchor, final Object parameter) {

    // check anchor
    logger.trace("VerilogSimulatorMenuDelegate invoked...");
    if (anchor.isEmpty()) {
        logger.trace("empty anchor (no file selected for simulation)");
        return;//from  www  .j  a v  a  2 s  . c  om
    }
    final ResourceHandle inputFile = anchor.get(0);

    // make sure the anchor element is a file
    if (!inputFile.isFile()) {
        logger.trace("selected anchor is not a file");
        return;
    }
    logger.trace("selected file for simulation: " + inputFile.getPath());

    // catch exceptions to cleanly de-allocate the temporary folder
    TemporaryFolder temporaryFolder = null;
    try {

        // allocate a temporary folder for the output files
        temporaryFolder = new TemporaryFolder();
        logger.trace("allocation temporary folder: " + temporaryFolder.getInstanceFolder());

        // build the command line
        final CommandLine commandLine = new CommandLine(Configuration.getBashPath());
        commandLine.addArgument("--login");
        commandLine.addArgument("-c");
        commandLine.addArgument("vvp " + Configuration.getStdinPath(), false);
        logger.trace("command line: " + commandLine);

        // build I/O streams
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(inputFile.readBinaryFile(true));
        final ByteArrayOutputStream outputStream = null;
        final OutputStream errorStream = System.err;
        final ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream,
                inputStream);

        // run Icarus
        final Executor executor = new DefaultExecutor();
        executor.setStreamHandler(streamHandler);
        executor.setWorkingDirectory(temporaryFolder.getInstanceFolder());
        executor.execute(commandLine);
        logger.trace("VVP finished");

        // create the output files
        final ResourceHandle outputFolder = inputFile.getParent();
        logger.trace("creating output files in folder: " + outputFolder);
        for (final File temporaryFile : temporaryFolder.getInstanceFolder().listFiles()) {
            if (temporaryFile.isFile()) {
                final ResourceHandle outputFile = outputFolder.getChild(temporaryFile.getName());
                logger.trace("creating output file " + outputFile + " from " + temporaryFile);
                outputFile.writeFile(temporaryFile, true, true);
                logger.trace("output file created");
            } else {
                logger.trace("skipping (not a file): " + temporaryFile);
            }
        }
        logger.trace("output files created");

    } catch (final IOException e) {
        logger.error("exception during VVP simulation", e);
        return;
    } finally {
        if (temporaryFolder != null) {
            temporaryFolder.dispose();
        }
    }

}