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.services.impl.LocalJobKillServiceImplUnitTests.java

/**
 * Setup for the tests./*from  w w  w.  j  ava2s . c  om*/
 */
@Before
public void setup() {
    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
    this.jobSearchService = Mockito.mock(JobSearchService.class);
    this.executor = Mockito.mock(Executor.class);
    this.eventPublisher = Mockito.mock(ApplicationEventPublisher.class);
    this.service = new LocalJobKillServiceImpl(HOSTNAME, this.jobSearchService, this.executor, false,
            this.eventPublisher);

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

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

/**
 *
 *
 * @param executable/* w w w. j a  v  a2s  . 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:io.selendroid.android.impl.DefaultAndroidEmulator.java

public static List<AndroidEmulator> listAvailableAvds() throws AndroidDeviceException {
    List<AndroidEmulator> avds = Lists.newArrayList();

    CommandLine cmd = new CommandLine(AndroidSdk.android());
    cmd.addArgument("list", false);
    cmd.addArgument("avds", false);

    String output = null;/*w  w  w  . jav a 2  s  .  c  o  m*/
    try {
        output = ShellCommand.exec(cmd, 20000);
    } catch (ShellCommandException e) {
        throw new AndroidDeviceException(e);
    }
    Map<String, Integer> startedDevices = mapDeviceNamesToSerial();

    String[] avdsOutput = StringUtils.splitByWholeSeparator(output, "---------");
    if (avdsOutput != null && avdsOutput.length > 0) {
        for (int i = 0; i < avdsOutput.length; i++) {
            if (avdsOutput[i].contains("Name:") == false) {
                continue;
            }
            String element = avdsOutput[i];
            String avdName = extractValue("Name: (.*?)$", element);
            String abi = extractValue("ABI: (.*?)$", element);
            String screenSize = extractValue("Skin: (.*?)$", element);
            String target = extractValue("\\(API level (.*?)\\)", element);
            File avdFilePath = new File(extractValue("Path: (.*?)$", element));
            DefaultAndroidEmulator emulator = new DefaultAndroidEmulator(avdName, abi, screenSize, target,
                    avdFilePath);
            if (startedDevices.containsKey(avdName)) {
                emulator.setSerial(startedDevices.get(avdName));
            }
            avds.add(emulator);
        }
    }
    return avds;
}

From source file:com.github.badamowicz.maven.ojdeploy.plugin.executor.OjdeployExecutorTest.java

@BeforeClass
public void beforeClass() {

    prepareDefaultMojo();/*from   ww w.  ja  va2s .c o m*/

    cmdLine = new CommandLine("gedoens.sh");

    executorSimple = new OjdeployExecutor();
    executorSimple.setDryRun(DRY_RUN);
    executorSimple.setCmdLine(cmdLine);

    executorCmdLineTest = new OjdeployExecutor();
}

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

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

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

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

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

    scheduler.createWorker().schedule(new Action0() {
        @Override
        public void call() {
            ByteArrayOutputStream stdOut = new ByteArrayOutputStream();
            ByteArrayOutputStream stdErr = new ByteArrayOutputStream();
            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 e) {
            }

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

    return jobId;
}

From source file:io.selendroid.builder.SelendroidServerBuilderTest.java

@Test
public void testShouldBeAbleToCreateCustomizedAndroidApplicationXML() throws Exception {
    SelendroidServerBuilder builder = getDefaultBuilder();
    builder.init(new DefaultAndroidApp(new File(APK_FILE)));
    builder.cleanUpPrebuildServer();//  w ww  .  j  a v  a2s . c o  m
    File file = builder.createAndAddCustomizedAndroidManifestToSelendroidServer();
    ZipFile zipFile = new ZipFile(file);
    ZipArchiveEntry entry = zipFile.getEntry("AndroidManifest.xml");
    Assert.assertEquals(entry.getName(), "AndroidManifest.xml");
    Assert.assertTrue("Expecting non empty AndroidManifest.xml file", entry.getSize() > 700);

    // Verify that apk is not yet signed
    CommandLine cmd = new CommandLine(AndroidSdk.aapt());
    cmd.addArgument("list", false);
    cmd.addArgument(builder.getSelendroidServer().getAbsolutePath(), false);

    String output = ShellCommand.exec(cmd);

    assertResultDoesNotContainFile(output, "META-INF/CERT.RSA");
    assertResultDoesNotContainFile(output, "META-INF/CERT.SF");
}

From source file:be.tarsos.transcoder.ffmpeg.FFMPEGExecutor.java

/**
 * Executes the ffmpeg process with the previous given arguments.
 * /*from   w  ww.  jav a  2s. c  o m*/
 * @return The standard output of the child process.
 * 
 * @throws IOException
 *             If the process call fails.
 */
public String execute() throws IOException {
    CommandLine cmdLine = new CommandLine(ffmpegExecutablePath);

    int fileNumber = 0;
    Map<String, File> map = new HashMap<String, File>();
    for (int i = 0; i < args.size(); i++) {
        final String arg = args.get(i);
        final Boolean isFile = argIsFile.get(i);
        if (isFile) {
            String key = "file" + fileNumber;
            map.put(key, new File(arg));
            cmdLine.addArgument("'${" + key + "}'", false);
            fileNumber++;
        } else {
            cmdLine.addArgument(arg);
        }
    }
    cmdLine.setSubstitutionMap(map);
    LOG.fine("Execute: " + cmdLine);
    DefaultExecutor executor = new DefaultExecutor();
    //5minutes wait
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000 * 5);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(out));
    int[] exitValues = { 0, 1 };
    executor.setExitValues(exitValues);
    executor.execute(cmdLine);
    return out.toString();
}

From source file:com.adaptris.hpcc.SprayToThorTest.java

/**
 * Technically this won't work with dfuplus as it doesn't set <code>recordsize</code>.
 * @throws Exception/*from w w  w. jav  a 2s  .  c o m*/
 */
@Test
public void testLegacyFixedFormatMaxRecordSize() throws Exception {
    SprayToThor sprayToThor = new SprayToThor();
    sprayToThor.setFormat(SprayToThor.FORMAT.FIXED);
    sprayToThor.setMaxRecordSize(214);
    CommandLine cmdLine = new CommandLine("/bin/dfuplus");
    sprayToThor.addFormatArguments(cmdLine);
    assertEquals(2, cmdLine.getArguments().length);
    assertEquals("format=fixed", cmdLine.getArguments()[0]);
    assertEquals("maxrecordsize=214", cmdLine.getArguments()[1]);
}

From source file:com.dubture.composer.core.launch.DefaultExecutableLauncher.java

protected void doLaunch(String scriptPath, String[] arguments, final ILaunchResponseHandler handler,
        boolean async) throws IOException, InterruptedException, CoreException {

    String phpExe = null;//  w ww. j  a  v  a  2s  . co m

    try {
        Logger.debug("Getting default executable");
        phpExe = LaunchUtil.getPHPExecutable();
    } catch (ExecutableNotFoundException e) {
        showWarning();
        e.printStackTrace();
        Logger.logException(e);
        return;
    }

    Logger.debug("Launching workspace php executable: " + phpExe + " using target " + scriptPath);
    CommandLine cmd = new CommandLine(phpExe);
    cmd.addArgument(scriptPath);
    for (int i = 0; i < arguments.length; i++) {
        cmd.addArgument(arguments[i], false);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler() {
        @Override
        public void onProcessComplete(int exitValue) {
            super.onProcessComplete(exitValue);
            if (handler != null && outputStream != null) {
                handler.handle(outputStream.toString());
            }
        }

        @Override
        public void onProcessFailed(ExecuteException e) {
            super.onProcessFailed(e);

            if (handler != null && errStream != null) {
                handler.handleError(errStream.toString());
            }
        }
    };

    //        System.out.println("Command: " + cmd.toString());

    executor.setWorkingDirectory(new File(new Path(scriptPath).removeLastSegments(1).toOSString()));
    executor.execute(cmd, resultHandler);

    if (async == false) {
        resultHandler.waitFor();
    }
}

From source file:io.gatling.mojo.Fork.java

public void run() throws Exception {

    if (propagateSystemProperties) {
        for (Entry<Object, Object> systemProp : System.getProperties().entrySet()) {
            String name = systemProp.getKey().toString();
            String value = systemProp.getValue().toString();
            if (isPropagatableProperty(name)) {
                String escapedValue = StringUtils.escape(value);
                String safeValue = escapedValue.contains(" ") ? '"' + escapedValue + '"' : escapedValue;
                this.jvmArgs.add("-D" + name + "=" + safeValue);
            }// w ww.jav a  2s . c  om
        }
    }

    this.jvmArgs.add("-jar");
    this.jvmArgs
            .add(MojoUtils.createBooterJar(classpath, MainWithArgsInFile.class.getName()).getCanonicalPath());

    List<String> command = buildCommand();

    Executor exec = new DefaultExecutor();
    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in));
    exec.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine cl = new CommandLine(javaExecutable);
    for (String arg : command) {
        cl.addArgument(arg, false);
    }

    int exitValue = exec.execute(cl);
    if (exitValue != 0) {
        throw new MojoFailureException("command line returned non-zero value:" + exitValue);
    }
}