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.netflix.genie.core.jobs.workflow.impl.JobKickoffTask.java

private void makeDirGroupWritable(final String dir) throws GenieServerException {
    log.debug("Adding write permissions for the directory " + dir + " for the group.");
    final CommandLine commandLIne = new CommandLine("sudo").addArgument("chmod").addArgument("g+w")
            .addArgument(dir);//from   w  ww  . j  a  va 2s.c om

    try {
        this.executor.execute(commandLIne);
    } catch (IOException ioe) {
        throw new GenieServerException("Could not make the job working logs directory group writable.");
    }
}

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

private void makeDirGroupWritable(final String dir) throws GenieServerException {
    log.debug("Adding write permissions for the directory {} for the group.", dir);
    final CommandLine commandLIne = new CommandLine("sudo").addArgument("chmod").addArgument("g+w")
            .addArgument(dir);/*from   w w w .  j  a  va 2 s  .com*/

    try {
        this.executor.execute(commandLIne);
    } catch (IOException ioe) {
        throw new GenieServerException("Could not make the job working logs directory group writable.", ioe);
    }
}

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

public ExecuteWatchdog adbAsync(final List<Object> arguments, long timeoutMillis) throws IOException {
    CommandLine cmdLine = new CommandLine(ADB);
    if (!this.serial.isEmpty()) {
        cmdLine.addArgument("-s");
        cmdLine.addArgument(serial);/*w  w  w.j  a va  2 s.  c  o m*/
    }
    arguments.forEach((arg) -> {
        cmdLine.addArgument(arg + "");
    });
    LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " "));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis);
    Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new ESH());
    executor.execute(cmdLine, new DefaultExecuteResultHandler());

    return watchdog;
}

From source file:io.selendroid.standalone.builder.SelendroidServerBuilder.java

File createAndAddCustomizedAndroidManifestToSelendroidServer()
        throws IOException, ShellCommandException, AndroidSdkException {
    String targetPackageName = applicationUnderTest.getBasePackage();

    File tmpDir = Files.createTempDir();
    if (deleteTmpFiles()) {
        tmpDir.deleteOnExit();/*from w  ww .  ja  v a  2s . co m*/
    }

    File customizedManifest = new File(tmpDir, "AndroidManifest.xml");
    if (deleteTmpFiles()) {
        customizedManifest.deleteOnExit();
    }
    log.info("Adding target package '" + targetPackageName + "' to " + customizedManifest.getAbsolutePath());

    // add target package
    InputStream inputStream = getResourceAsStream(selendroidApplicationXmlTemplate);
    if (inputStream == null) {
        throw new SelendroidException("AndroidApplication.xml template file was not found.");
    }
    String content = IOUtils.toString(inputStream, Charset.defaultCharset().displayName());

    // find the first occurance of "package" and appending the targetpackagename to begining
    int i = content.toLowerCase().indexOf("package");
    int cnt = 0;
    for (; i < content.length(); i++) {
        if (content.charAt(i) == '\"') {
            cnt++;
        }
        if (cnt == 2) {
            break;
        }
    }
    content = content.substring(0, i) + "." + targetPackageName + content.substring(i);
    log.info("Final Manifest File:\n" + content);
    content = content.replaceAll(SELENDROID_TEST_APP_PACKAGE, targetPackageName);
    // Seems like this needs to be done
    if (content.contains(ICON)) {
        content = content.replaceAll(ICON, "");
    }

    OutputStream outputStream = new FileOutputStream(customizedManifest);
    IOUtils.write(content, outputStream, Charset.defaultCharset().displayName());
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(outputStream);

    // adding the xml to an empty apk
    CommandLine createManifestApk = new CommandLine(AndroidSdk.aapt());

    File manifestApkFile = File.createTempFile("manifest", ".apk");
    if (deleteTmpFiles()) {
        manifestApkFile.deleteOnExit();
    }

    createManifestApk.addArgument("package", false);
    createManifestApk.addArgument("-M", false);
    createManifestApk.addArgument(customizedManifest.getAbsolutePath(), false);
    createManifestApk.addArgument("-I", false);
    createManifestApk.addArgument(AndroidSdk.androidJar(), false);
    createManifestApk.addArgument("-F", false);
    createManifestApk.addArgument(manifestApkFile.getAbsolutePath(), false);
    createManifestApk.addArgument("-f", false);
    log.info(ShellCommand.exec(createManifestApk, 20000L));

    ZipFile manifestApk = new ZipFile(manifestApkFile);
    ZipArchiveEntry binaryManifestXml = manifestApk.getEntry("AndroidManifest.xml");

    File finalSelendroidServerFile = File.createTempFile("selendroid-server", ".apk");
    if (deleteTmpFiles()) {
        finalSelendroidServerFile.deleteOnExit();
    }

    ZipArchiveOutputStream finalSelendroidServer = new ZipArchiveOutputStream(finalSelendroidServerFile);
    finalSelendroidServer.putArchiveEntry(binaryManifestXml);
    IOUtils.copy(manifestApk.getInputStream(binaryManifestXml), finalSelendroidServer);

    ZipFile selendroidPrebuildApk = new ZipFile(selendroidServer.getAbsolutePath());
    Enumeration<ZipArchiveEntry> entries = selendroidPrebuildApk.getEntries();
    for (; entries.hasMoreElements();) {
        ZipArchiveEntry dd = entries.nextElement();
        finalSelendroidServer.putArchiveEntry(dd);

        IOUtils.copy(selendroidPrebuildApk.getInputStream(dd), finalSelendroidServer);
    }

    finalSelendroidServer.closeArchiveEntry();
    finalSelendroidServer.close();
    manifestApk.close();
    log.info("file: " + finalSelendroidServerFile.getAbsolutePath());
    return finalSelendroidServerFile;
}

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//from  w  w w  . j  av a2  s . 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/*  www .j  ava  2  s .  co 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);
                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.tupilabs.pbs.PBS.java

/**
 * PBS qdel command.//  w ww  .  j av  a  2 s  .co m
 * <p>
 * Equivalent to qdel [param]
 *
 * @param jobId job id
 */
public static void qdel(String jobId) {
    final CommandLine cmdLine = new CommandLine(COMMAND_QDEL);
    cmdLine.addArgument(jobId);

    final OutputStream out = new ByteArrayOutputStream();
    final OutputStream err = new ByteArrayOutputStream();

    DefaultExecuteResultHandler resultHandler;
    try {
        resultHandler = execute(cmdLine, null, out, err);
        resultHandler.waitFor(DEFAULT_TIMEOUT);
    } catch (ExecuteException e) {
        throw new PBSException("Failed to execute qdel command: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PBSException("Failed to execute qdel command: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new PBSException("Failed to execute qdel command: " + e.getMessage(), e);
    }

    final int exitValue = resultHandler.getExitValue();
    LOGGER.info("qdel exit value: " + exitValue);

    if (exitValue != 0)
        throw new PBSException("Failed to delete job " + jobId + ". Error output: " + err.toString());
}

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

protected boolean compileForEeprom(String executable, File sourceFile, File destinationFile) {
    try {//w  w w  .j  a  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:io.selendroid.android.impl.DefaultAndroidEmulator.java

@Override
public void start(Locale locale, int emulatorPort, Map<String, Object> options) throws AndroidDeviceException {
    if (isEmulatorStarted()) {
        throw new SelendroidException("Error - Android emulator is already started " + this);
    }/*from  ww w. ja  va  2  s. c om*/
    Long timeout = null;
    String emulatorOptions = null;
    String display = null;
    if (options != null) {
        if (options.containsKey(TIMEOUT_OPTION)) {
            timeout = (Long) options.get(TIMEOUT_OPTION);
        }
        if (options.containsKey(DISPLAY_OPTION)) {
            display = (String) options.get(DISPLAY_OPTION);
        }
        if (options.containsKey(EMULATOR_OPTIONS)) {
            emulatorOptions = (String) options.get(EMULATOR_OPTIONS);
        }
    }

    if (display != null) {
        log.info("Using display " + display + " for running the emulator");
    }
    if (timeout == null) {
        timeout = 120000L;
    }
    log.info("Using timeout of '" + timeout / 1000 + "' seconds to start the emulator.");
    this.locale = locale;

    CommandLine cmd = new CommandLine(AndroidSdk.emulator());

    cmd.addArgument("-no-snapshot-save", false);
    cmd.addArgument("-avd", false);
    cmd.addArgument(avdName, false);
    cmd.addArgument("-port", false);
    cmd.addArgument(String.valueOf(emulatorPort), false);
    if (locale != null) {
        cmd.addArgument("-prop", false);
        cmd.addArgument("persist.sys.language=" + locale.getLanguage(), false);
        cmd.addArgument("-prop", false);
        cmd.addArgument("persist.sys.country=" + locale.getCountry(), false);
    }
    if (emulatorOptions != null && emulatorOptions.isEmpty() == false) {
        cmd.addArgument(emulatorOptions, false);
    }

    long start = System.currentTimeMillis();
    long timemoutEnd = start + timeout;
    try {
        ShellCommand.execAsync(display, cmd);
    } catch (ShellCommandException e) {
        throw new SelendroidException("unable to start the emulator: " + this);
    }
    setSerial(emulatorPort);
    Boolean adbKillServerAttempted = false;
    while (isDeviceReady() == false) {

        if (!adbKillServerAttempted && System.currentTimeMillis() - start > 10000) {
            CommandLine adbDevicesCmd = new CommandLine(AndroidSdk.adb());
            adbDevicesCmd.addArgument("devices", false);

            String devices = "";
            try {
                devices = ShellCommand.exec(adbDevicesCmd, 20000);
            } catch (ShellCommandException e) {
                // pass
            }
            if (!devices.contains(String.valueOf(emulatorPort))) {
                CommandLine resetAdb = new CommandLine(AndroidSdk.adb());
                resetAdb.addArgument("kill-server", false);

                try {
                    ShellCommand.exec(resetAdb, 20000);
                } catch (ShellCommandException e) {
                    throw new SelendroidException("unable to kill the adb server");
                }
            }
            adbKillServerAttempted = true;
        }
        if (timemoutEnd >= System.currentTimeMillis()) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
        } else {
            throw new AndroidDeviceException("The emulator with avd '" + getAvdName()
                    + "' was not started after " + (System.currentTimeMillis() - start) / 1000 + " seconds.");
        }
    }

    log.info("Emulator start took: " + (System.currentTimeMillis() - start) / 1000 + " seconds");
    log.info("Please have in mind, starting an emulator takes usually about 45 seconds.");
    unlockEmulatorScreen();

    waitForLauncherToComplete();

    // we observed that emulators can sometimes not be 'fully loaded'
    // if we click on the All Apps button and wait for it to load it is more likely to be in a
    // usable state.
    allAppsGridView();

    waitForLauncherToComplete();
    setWasStartedBySelendroid(true);
}

From source file:com.sohu.dc.jobkeeper.ActiveMasterManager.java

private void startPrepare() {
    String shellPath = ActiveMasterManager.class.getClassLoader().getResource("").getPath().replace("classes/",
            "");/*from  w w w  . jav a 2 s  .  c  o  m*/
    DefaultExecutor executor = new DefaultExecutor();
    CommandLine cmd = new CommandLine(shellPath + "prepare.sh");
    try {
        executor.execute(cmd);
    } catch (ExecuteException e) {
        LOG.debug("prepare.sh exec faild \n" + e);
    } catch (IOException e) {
        LOG.debug("prepare.sh exec faild \n" + e);
    }

}