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:hoot.services.command.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()) {

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

        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(stdout, stderr);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(executeStreamHandler);

        int exitValue;
        try {
            exitValue = executor.execute(cmdLine);
        } catch (Exception e) {
            exitValue = -1;
            logger.warn("Error executing: {}", cmdLine, e);
        }

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

        this.stdout = stdout.toString();

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

        return commandResult;
    }
}

From source file:eu.crisis_economics.abm.dashboard.cluster.script.BashScheduler.java

private void makeScriptsExecutable() {
    File scriptsDirectory = new File(scriptsDir + File.separator + schedulerType);
    String[] scripts = scriptsDirectory.list(new PatternFilenameFilter(".*\\.sh"));

    CommandLine commandLine = new CommandLine("chmod");
    commandLine.addArgument("755");
    for (String script : scripts) {
        commandLine.addArgument(scriptsDir + File.separator + schedulerType + File.separator + script, false);
    }/*from   w  w  w . j av a 2 s  .  co  m*/

    DefaultExecutor executor = new DefaultExecutor();

    try {
        executor.execute(commandLine);
    } catch (ExecuteException e) {
        // ignore this; there will be an exception later, if this scheduler is used
    } catch (IOException e) {
        // ignore this; there will be an exception later, if this scheduler is used
    }
}

From source file:io.selendroid.android.impl.DefaultHardwareDeviceTests.java

private String listInstalledPackages() throws Exception {
    CommandLine command = new CommandLine(AndroidSdk.adb().getAbsolutePath());
    command.addArgument("-s", false);
    command.addArgument(serial, false);/*w w w  . ja v a 2s .  co  m*/
    command.addArgument("shell", false);
    command.addArgument("pm", false);
    command.addArgument("list", false);
    command.addArgument("packages", false);
    return ShellCommand.exec(command);
}

From source file:io.selendroid.android.impl.DefaultAndroidApp.java

@Override
public void deleteFileFromWithinApk(String file) throws ShellCommandException, AndroidSdkException {
    CommandLine line = new CommandLine(AndroidSdk.aapt());
    line.addArgument("remove", false);
    line.addArgument(apkFile.getAbsolutePath(), false);
    line.addArgument(file, false);// w w  w . j  av  a  2  s.  c o m

    ShellCommand.exec(line, 20000);
}

From source file:net.robyf.dbpatcher.util.MySqlUtil.java

/**
 * Restores a MySQL database from a file.
 * /*w  ww.j  a  v a2s .c  o  m*/
 * @param databaseName The name of the database
 * @param fileName Backup file
 * @param username Username of the database user
 * @param password Password of the database user
 */
public static void restore(final String databaseName, final String fileName, final String username,
        final String password) {
    LogFactory.getLog().log("Restoring from " + fileName + " into " + databaseName);

    CommandLine command = new CommandLine("mysql");
    addCredentials(command, username, password);
    command.addArgument(databaseName);

    try (FileInputStream input = new FileInputStream(fileName)) {
        executeWithInput(command, input);
    } catch (IOException ioe) {
        throw new UtilException("Error restoring a database", ioe);
    }
}

From source file:at.treedb.util.Execute.java

public static ExecResult execute(String command, String[] param, Map<String, File> map) {
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = null;/*from w  ww  .  j av  a2  s  .  c om*/
    int exitValue = 0;
    try {
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        cmdLine = new CommandLine(command);
        if (param != null) {
            for (String s : param) {
                s = s.trim();
                if (s.isEmpty()) {
                    continue;
                }
                cmdLine.addArgument(s);
            }
        }
        cmdLine.setSubstitutionMap(map);
        executor.setStreamHandler(streamHandler);
        exitValue = executor.execute(cmdLine);

        return new ExecResult(exitValue, outputStream.toString(), null);
    } catch (Exception e) {
        return new ExecResult(-1, outputStream.toString(), e);
    }

}

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

/**
 * Ctor/*from www . java 2  s  . c  o  m*/
 *
 * @param workingDirectory working directory for execution
 * @param async            whether to wait for command to return
 * @param subsMap          variables substitution
 * @param vars             variables where to save optional expression evaluation
 * @param testEnv          test environment
 * @param command          command line to execute
 * @throws java.io.IOException if an exception occurred
 */
public CukeCommandExecutor(String command, String workingDirectory, boolean async, Map<String, String> subsMap,
        Map<String, Object> vars, Map<String, String> testEnv) throws IOException {

    this.substitutionMap = subsMap;
    this.testEnvironment = testEnv;
    this.variables = vars;
    // Must get the existing environment so it inherits but overrides
    Map<String, String> env = new HashMap<String, String>(System.getenv());
    if (null != testEnvironment) {
        env.putAll(testEnvironment);
    }
    env.put("user.home", System.getProperty("user.home"));

    ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
    setWatchdog(watchdog);
    String[] args = command.split("\\s+");
    commandLine = new CommandLine(args[0]);
    if (args.length > 0) {
        for (int i = 1; i < args.length; i++) {
            commandLine.addArgument(args[i]);
        }
    }
    commandLine.setSubstitutionMap(substitutionMap);

    this.environment = env;
    this.command = command;
    this.async = async;
    setWorkingDirectory(new File(workingDirectory));
    String logFileName = command.replaceAll("[:\\.\\-\\s\\/\\\\]", "_");
    if (logFileName.length() > 128) {
        logFileName = logFileName.substring(0, 100);
    }
    this.logFile = new File(getWorkingDirectory(),
            "cuke_logs" + File.separator + +System.currentTimeMillis() + "-" + logFileName + ".log");

    FileUtils.forceMkdir(logFile.getParentFile());

    OutputStream outputStream = new FileOutputStream(logFile);
    this.teeOutputStream = new TeeOutputStream(outputStream, System.out); // also redirected to stdout
    ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    this.setStreamHandler(streamHandler);
}

From source file:com.netflix.genie.web.services.impl.LocalJobKillServiceImplUnitTests.java

/**
 * Setup for the tests./*  www  . j av a 2s  . c o  m*/
 *
 * @throws IOException if the job directory cannot be created
 */
@Before
public void setup() throws IOException {
    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
    final File tempDirectory = Files.createTempDir();
    this.genieWorkingDir = new FileSystemResource(tempDirectory);
    Files.createParentDirs(new File(tempDirectory.getPath() + "/" + ID + "/genie/x"));
    this.jobSearchService = Mockito.mock(JobSearchService.class);
    this.executor = Mockito.mock(Executor.class);
    this.genieEventBus = Mockito.mock(GenieEventBus.class);
    this.service = new LocalJobKillServiceImpl(HOSTNAME, this.jobSearchService, this.executor, false,
            this.genieEventBus, this.genieWorkingDir, GenieObjectMapper.getMapper());

    this.killCommand = new CommandLine("kill");
    this.killCommand.addArguments(Integer.toString(PID));
}

From source file:hu.bme.mit.trainbenchmark.benchmark.fourstore.driver.UnixUtils.java

public static void exec(final String command, final Map<String, String> environmentVariables,
        final OutputStream outputStream) throws IOException, ExecuteException {
    final Map<?, ?> executionEnvironment = EnvironmentUtils.getProcEnvironment();
    for (final Entry<String, String> environmentVariable : environmentVariables.entrySet()) {
        final String keyAndValue = environmentVariable.getKey() + "=" + environmentVariable.getValue();
        EnvironmentUtils.addVariableToEnvironment(executionEnvironment, keyAndValue);
    }/*www. ja  va  2s .  c o m*/

    final PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);

    final CommandLine commandLine = new CommandLine("/bin/bash");
    commandLine.addArguments(new String[] { "-c", command }, false);

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(streamHandler);
    executor.execute(commandLine, executionEnvironment);
}

From source file:com.vmware.bdd.usermgmt.job.CfgUserMgmtOnMgmtVMExecutor.java

private void enableSudo(String adminGroupName) {
    CommandLine cmdLine = new CommandLine(sudoCmd).addArgument(UserMgmtConstants.ENABLE_SUDO_SCRIPT)
            .addArgument(adminGroupName);
    execCommand(cmdLine);/*www . j  a  va  2s . c o m*/
}