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.jivesoftware.os.jive.utils.shell.utils.Invoke.java

public static int invoke(File home, String[] command, final InputStream writeToProcess,
        final ConcurrentLinkedQueue<String> response) throws Exception {
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);/* ww  w.j  av  a  2 s  .  c  o  m*/
    if (home != null) {
        executor.setWorkingDirectory(home);
    }

    //give all the processes 120s to return that they started successfully
    ExecuteWatchdog watchdog = new ExecuteWatchdog(120000);
    executor.setWatchdog(watchdog);

    LogOutputStream outputStream = new LogOutputStream(20000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    LogOutputStream errorStream = new LogOutputStream(40000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, errorStream, writeToProcess);
    executor.setStreamHandler(pumpStreamHandler);
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine commandLine = new CommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i]);
    }
    try {
        //executor.execute(commandLine, handler);
        return executor.execute(commandLine);
        //handler.waitFor(20000);
    } catch (Exception x) {
        x.printStackTrace();
        return 1;
    }
}

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

@Test
public void testLegacyCsvFormat() throws Exception {
    SprayToThor sprayToThor = new SprayToThor();
    sprayToThor.setFormat(SprayToThor.FORMAT.CSV);
    CommandLine cmdLine = new CommandLine("/bin/dfuplus");
    sprayToThor.addFormatArguments(cmdLine);
    assertEquals(2, cmdLine.getArguments().length);
    assertEquals("format=csv", cmdLine.getArguments()[0]);
    assertEquals("maxrecordsize=8192", cmdLine.getArguments()[1]);
}

From source file:com.comcast.tvx.haproxy.HAProxyServiceController.java

@Override
public int reload() {
    if (!new File("/etc/init.d/haproxy").exists()) {
        logger.info("HaProxy is not installed");
        throw new IllegalArgumentException("HaProxy is not installed");
    }/*  w  ww  . ja  v a  2s  .c om*/

    CommandLine cmdLine = new CommandLine("sudo");
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    cmdLine.addArgument("service");
    cmdLine.addArgument("haproxy");
    cmdLine.addArgument("reload");

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(psh);

    int exitValue;
    try {
        exitValue = executor.execute(cmdLine);
    } catch (ExecuteException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    logger.info("output from running process: " + stdout.toString());
    logger.info("Exit value was: " + exitValue);
    return exitValue;

}

From source file:eu.creatingfuture.propeller.blocklyprop.propellent.Propellent.java

public List<String> getPorts() {
    List<String> ports = new ArrayList<>();
    try {/*w w  w.  j  ava  2s  . c o  m*/
        CommandLine cmdLine = new CommandLine("propellent/Propellent.exe");
        cmdLine.addArgument("/id");
        cmdLine.addArgument("/gui").addArgument("OFF");
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValues(new int[] { 451, 301 });

        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);
            return ports;
        }

        output = outputStream.toString();

        // 301 = None found
        // 451 = Chip found
        if (exitValue == 301) {
            return ports;
        }

        //            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");
                    ports.add(port);
                }
            }
        }

        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        return ports;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        return null;
    }
}

From source file:eu.creatingfuture.propeller.webLoader.propellent.Propellent.java

public List<String> getPorts() {
    List<String> ports = new ArrayList<String>();
    try {// w  w  w  . j a  v  a  2 s  .c  o m
        CommandLine cmdLine = new CommandLine("propellent/Propellent.exe");
        cmdLine.addArgument("/id");
        cmdLine.addArgument("/gui").addArgument("OFF");
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValues(new int[] { 451, 301 });

        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);
            return ports;
        }

        output = outputStream.toString();

        // 301 = None found
        // 451 = Chip found
        if (exitValue == 301) {
            return ports;
        }

        //            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");
                    ports.add(port);
                }
            }
        }

        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        return ports;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        return null;
    }
}

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

public static void ensureDeployApp(String url, String name, String location) throws Exception {
    Executor exec = new DefaultExecutor();
    CommandLine cl = new CommandLine(getScriptsDir() + File.separator + REDEPLOY_WLS_APP_SCRIPT);
    if (getArchetypeSettings() != null && getArchetypeSettings().length() != 0) {
        cl.addArgument(getArchetypeSettings());
    }//from w ww . jav a2  s . c om
    cl.addArgument(url);
    cl.addArgument(name);
    cl.addArgument(location);
    cl.setSubstitutionMap(getSubstitutionMap());
    int exitValue = exec.execute(cl);
    String msg = String.format("Server running at %s failed to deploy app %s at %s", url, name,
            expandVariables(location));
    ensureBuildSuccessful("redeploy.log");
    Assert.assertEquals(msg, 0, exitValue);
}

From source file:com.creactiviti.piper.plugin.ffmpeg.Mediainfo.java

@Override
public Map<String, Object> handle(Task aTask) throws Exception {
    CommandLine cmd = new CommandLine("mediainfo");
    cmd.addArgument(aTask.getRequiredString("input"));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        exec.execute(cmd);//from ww w .j a va  2s .co m
        return parse(FileUtils.readFileToString(tempFile));
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {
        FileUtils.deleteQuietly(tempFile);
    }
}

From source file:eu.learnpad.verification.plugin.pn.modelcheckers.LOLA.java

public static String sync_getVerificationOutput(String lolaBinPath, String modelToVerify,
        String propertyToVerify, boolean useCoverabilitySearch, final int timeoutInSeconds) throws Exception {

    int cores = Runtime.getRuntime().availableProcessors();
    String filePath = System.getProperty("java.io.tmpdir") + "/" + java.util.UUID.randomUUID() + ".lola";
    IOUtils.writeFile(modelToVerify.getBytes(), filePath, false);
    //IOUtils.writeFile(propertyToVerify.getBytes(), filePath+".ctl", false);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = new CommandLine(lolaBinPath);

    cmdLine.addArgument("--nolog");

    //cmdLine.addArgument("--formula="+filePath+".ctl", false);
    cmdLine.addArgument("--formula=" + propertyToVerify, false);
    cmdLine.addArgument("--threads=" + cores);
    if (useCoverabilitySearch)
        cmdLine.addArgument("--search=cover");
    cmdLine.addArgument("-p");
    //cmdLine.addArgument("--path=\""+filePath+".out\"", false);
    //cmdLine.addArgument("--state=\""+filePath+".out\"", false);
    cmdLine.addArgument(filePath, false);

    DefaultExecutor exec = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(1000 * timeoutInSeconds);

    exec.setWatchdog(watchdog);//from   w  w w  .  j  a v a 2 s  . co  m
    exec.setStreamHandler(streamHandler);
    exec.setExitValues(new int[] { 0, 1, 2, 139, 35584 });
    int exitVal = exec.execute(cmdLine);

    String output = outputStream.toString();

    if (watchdog.killedProcess())
        throw new Exception("ERROR: Timeout occurred. LOLA has reached the execution time limit of "
                + timeoutInSeconds + " seconds, so it has been aborted.\nPartial Output:\n" + output);

    if (exitVal != 0 || output.equals("") || output.contains("aborting [#"))
        throw new Exception("ERROR: LOLA internal error\nExit code:" + exitVal + "\nExec: " + cmdLine.toString()
                + "\nOutput:\n" + output);
    new File(filePath).delete();
    return output;
}

From source file:de.pawlidi.openaletheia.utils.exec.ProcessExecutor.java

/**
 * Execute given system command with arguments.
 * //from w w w.  j  av a  2 s  .  c om
 * @param command
 *            to execute
 * @param args
 *            as command arguments
 * @return command output as String, null otherwise
 */
public static String executeCommand(final String command, String... args) {
    if (StringUtils.isNotEmpty(command)) {

        // create string output for executor
        ProcessStringOutput processOutput = new ProcessStringOutput(PROCESS_OUTPUT_LEVEL);
        // create external process
        Executor executor = createExecutor(processOutput);

        // create command line without any arguments
        final CommandLine commandLine = new CommandLine(command);

        if (ArrayUtils.isNotEmpty(args)) {
            // add command arguments
            commandLine.addArguments(args);
        }
        int exitValue = -1;

        try {
            // execute command
            exitValue = executor.execute(commandLine);
        } catch (IOException e) {
            // ignore exception
        }

        if (!executor.isFailure(exitValue)) {
            return processOutput.getOutput();
        }
    }
    return null;
}

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

private String extractApkDetails(String regex) throws ShellCommandException, AndroidSdkException {
    CommandLine line = new CommandLine(AndroidSdk.aapt());

    line.addArgument("dump", false);
    line.addArgument("badging", false);
    line.addArgument(apkFile.getAbsolutePath(), false);
    String output = ShellCommand.exec(line, 20000);

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(output);
    if (matcher.find()) {
        return matcher.group(1);
    }/* w w  w .  j a  v a2 s  .  c  om*/

    return null;
}