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

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

Introduction

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

Prototype

public DefaultExecutor() 

Source Link

Document

Default constructor creating a default PumpStreamHandler and sets the working directory of the subprocess to the current working directory.

Usage

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

public List<String> getPorts() {
    List<String> ports = new ArrayList<String>();
    try {//  ww w . ja v  a 2s.  com
        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.blackducksoftware.tools.scmconnector.core.CommandLineExecutor.java

@Override
public int executeCommand(Logger log, CommandLine command, File targetDir, String promptResponse)
        throws Exception {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);/*from   ww w.  j a va  2  s.  c  om*/

    PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHangler(log, Level.INFO));
    executor.setStreamHandler(psh);

    providePromptResponse(psh, promptResponse);

    executor.setWorkingDirectory(targetDir);

    // This log msg would reveal password
    // log.info("Command: " + command.toString() + " executed in: "
    // + targetDir.toString());

    int exitStatus = 1;
    try {
        exitStatus = executor.execute(command, EnvironmentUtils.getProcEnvironment());
    } catch (Exception e) {
        log.error("Failure executing Command: " + e.getMessage());
    }
    return exitStatus;
}

From source file:io.selendroid.io.ShellCommand.java

public static void execAsync(String display, CommandLine commandline) throws ShellCommandException {
    log.info("executing async command: " + commandline);
    DefaultExecutor exec = new DefaultExecutor();

    ExecuteResultHandler handler = new DefaultExecuteResultHandler();
    PumpStreamHandler streamHandler = new PumpStreamHandler(new PritingLogOutputStream());
    exec.setStreamHandler(streamHandler);
    try {//from   w  w w . j  a  v  a2  s  .  c om
        if (display == null || display.isEmpty()) {
            exec.execute(commandline, handler);
        } else {
            Map env = EnvironmentUtils.getProcEnvironment();
            EnvironmentUtils.addVariableToEnvironment(env, "DISPLAY=:" + display);

            exec.execute(commandline, env, handler);
        }
    } catch (Exception e) {
        throw new ShellCommandException("An error occured while executing shell command: " + commandline, e);
    }
}

From source file:com.github.nbyl.xfdcontrol.plugins.notification.blink1.Blink1ToolCommand.java

public void run() throws IOException {
    LOGGER.debug("Running command: {}", this.commandLine.toString());

    DefaultExecutor executor = new DefaultExecutor();
    executor.execute(this.commandLine);
}

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

@Override
public Object handle(Task aTask) throws Exception {
    List<String> options = aTask.getList("options", String.class);
    CommandLine cmd = new CommandLine("ffmpeg");
    options.forEach(o -> cmd.addArgument(o));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        int exitValue = exec.execute(cmd);
        return exitValue != 0 ? FileUtils.readFileToString(tempFile) : cmd.toString();
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {//w  w  w .ja v  a2s .  c  o  m
        FileUtils.deleteQuietly(tempFile);
    }
}

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");
    }//from w w w .j a v  a2s .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:com.rest4j.generator.JavaGeneratorTest.java

@Test
public void testJavaClient() throws Exception {
    gen.setStylesheet("com/rest4j/client/java.xslt");
    new File("target/java").mkdir();
    gen.setApiXmlUrl(getClass().getResource("doc-generator-graph.xml"));
    gen.setOutputDir("target/java");
    gen.addParam(new TemplateParam("common-params", "access-token"));
    gen.addParam(new TemplateParam("additional-client-code", "// ADDITIONAL CODE"));
    gen.generate();//from   ww  w. j a va 2s  . c o  m

    // let's try compiling the damn thing
    CommandLine cmdLine = CommandLine.parse("mvn package");
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File("target/java"));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    int exitValue = executor.execute(cmdLine);
    assertFalse(executor.isFailure(exitValue));

    // check doc comments in the file A.java
    String a = IOUtils.toString(new File("target/java/src/main/java/api/model/A.java").toURI());
    assertTrue(a, a.contains("Some additional client info"));
    assertFalse(a, a.contains("Some additional python client info"));

    // check existence of Parameter Object class
    a = IOUtils.toString(new File("target/java/src/main/java/api/model/PatchBRequest.java").toURI());
    assertTrue(a, a.contains("class PatchBRequest"));

    // check some file paths
    assertTrue(new File("target/java/src/main/java/api/util/JsonUtil.java").canRead());
    assertTrue(new File("target/java/src/main/java/api/Request.java").canRead());

    String client = IOUtils.toString(new File("target/java/src/main/java/api/Client.java").toURI());
    assertTrue(client.contains("ADDITIONAL CODE"));
}

From source file:com.rest4j.generator.PHPGeneratorTest.java

@Test
public void testPHPClient() throws Exception {
    gen.setStylesheet("com/rest4j/client/php.xslt");
    new File("target/php").mkdir();
    gen.setApiXmlUrl(getClass().getResource("doc-generator-graph.xml"));
    gen.setOutputDir("target/php");
    gen.addParam(new TemplateParam("common-params", "access-token"));
    gen.addParam(new TemplateParam("prefix", "Test"));
    gen.addParam(new TemplateParam("additional-client-code", "// ADDITIONAL CODE"));
    gen.generate();/*from  w  w w .j  a v  a 2  s.co m*/

    // check the syntax
    CommandLine cmdLine = CommandLine.parse("php apiclient.php");
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File("target/php"));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    int exitValue = executor.execute(cmdLine);
    assertFalse(executor.isFailure(exitValue));

    // check existence of Parameter Object class
    String client = IOUtils.toString(new File("target/php/apiclient.php").toURI());
    assertTrue(client, client.contains("class TestPatchBRequest"));

    assertTrue(client.contains("ADDITIONAL CODE"));
}

From source file:com.jaeksoft.searchlib.util.ExecuteUtils.java

final public static int command(File workingDirectory, String cmd, String classpath, boolean setJavaTempDir,
        OutputStream outputStream, OutputStream errorStream, Long timeOut, String... arguments)
        throws ExecuteException, IOException {
    Map<String, String> envMap = null;
    if (classpath != null) {
        envMap = new HashMap<String, String>();
        envMap.put("CLASSPATH", classpath);
    }//from w w  w .ja v a2  s  .c  o  m
    CommandLine commandLine = new CommandLine(cmd);
    if (setJavaTempDir)
        if (!StringUtils.isEmpty(SystemUtils.JAVA_IO_TMPDIR))
            commandLine.addArgument(StringUtils.fastConcat("-Djava.io.tmpdir=", SystemUtils.JAVA_IO_TMPDIR),
                    false);
    if (arguments != null)
        for (String argument : arguments)
            commandLine.addArgument(argument);
    DefaultExecutor executor = new DefaultExecutor();
    if (workingDirectory != null)
        executor.setWorkingDirectory(workingDirectory);
    if (outputStream != null) {
        PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, errorStream);
        executor.setStreamHandler(pumpStreamHandler);
    }
    if (timeOut != null) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut);
        executor.setWatchdog(watchdog);
    }
    return envMap != null ? executor.execute(commandLine, envMap) : executor.execute(commandLine);
}

From source file:com.github.rwhogg.git_vcr.review.ProcessBasedReviewTool.java

/**
 * Runs the command string specified by commandLine, then returns the output.
 * Note that any command-line arguments from the configuration are automatically added.
 * @param commands The rest of the command line, excluding any arguments
 * @return The output of the command/*www.j  a v a2s .  co m*/
 */
protected List<String> runProcess(String commands) throws ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    executor.setExitValues(null);
    String arguments = configuration.getString("args", "");
    executor.execute(CommandLine.parse(getExecutableName() + " " + arguments + " " + commands));
    return Arrays.asList(outputStream.toString("UTF-8").split("\n"));
}