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

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

Introduction

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

Prototype

public void setStreamHandler(final ExecuteStreamHandler streamHandler) 

Source Link

Usage

From source file:eu.creatingfuture.propeller.webLoader.propeller.PropellerLoad.java

protected List<String> getPorts(String executable) {
    List<String> ports = new ArrayList<String>();
    try {/*from  w ww .  j  a v  a 2  s. c  om*/
        CommandLine cmdLine = new CommandLine(executable);
        cmdLine.addArgument("-P");
        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;
        } finally {
            output = outputStream.toString();
        }

        /*
         if (exitValue == 301) {
         return ports;
         }
         */
        //            System.out.println("output: " + output);
        Scanner scanner = new Scanner(output);

        while (scanner.hasNextLine()) {
            ports.add(scanner.nextLine());
        }

        return ports;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        return null;
    }
}

From source file:modules.GeneralNativeCommandModule.java

protected KeyValueResult extractNative(String command, String options, Path path)
        throws NativeExecutionException {
    if (command == null || command.equals("")) {
        System.err.println("command null at GeneralNativeCommandModule.extractNative()");
        return null;
    }//  w w w  .  ja  va  2s .  c  o  m
    CommandLine commandLine = new CommandLine(command);

    if (options != null && !options.equals("")) {
        String[] args = options.split(" ");
        commandLine.addArguments(args);
    }

    if (path != null) {
        commandLine.addArgument(path.toAbsolutePath().toString(), false);
    }
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig();
    executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout));
    if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) {
        executor.setWorkingDirectory(getConfig().workingDirectory);
    }
    try {
        // System.out.println(commandLine);
        executor.execute(commandLine);
    } catch (ExecuteException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        n.exitCode = xs.getExitValue();
        throw n;
    } catch (IOException xs) {
        // System.out.println(commandLine);
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        throw n;
    }
    KeyValueResult t = new KeyValueResult("GeneralNativeCommandResults");
    t.add("fullOutput", outputStream.toString().trim());
    return t;
}

From source file:modules.NativeProcessIterativeDaemonModule.java

protected String extractNative(String command, String options, Path path) throws NativeExecutionException {
    if (command == null || command.equals("")) {
        System.err.println("command null at GeneralNativeCommandModule.extractNative()");
        return null;
    }/*from   w  w w  .  j  a  v a2s.c o m*/
    CommandLine commandLine = new CommandLine(command);

    if (options != null && !options.equals("")) {
        String[] args = options.split(" ");
        commandLine.addArguments(args);
    }

    if (path != null) {
        commandLine.addArgument(path.toAbsolutePath().toString(), false);
    }
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig();
    executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout));
    if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) {
        executor.setWorkingDirectory(getConfig().workingDirectory);
    }
    try {

        // System.out.println("Now execute " + commandLine);
        executor.execute(commandLine);
    } catch (ExecuteException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        n.exitCode = xs.getExitValue();
        throw n;
    } catch (IOException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        throw n;
    }
    return outputStream.toString().trim();
}

From source file:com.alibaba.jstorm.yarn.utils.JStormUtils.java

/**
 * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler If it is frontend, ByteArrayOutputStream.toString get the result
 * <p/>// www  .j  av  a 2s . c  om
 * This function don't care whether the command is successfully or not
 *
 * @param command
 * @param environment
 * @param workDir
 * @param resultHandler
 * @return
 * @throws IOException
 */
@Deprecated
public static ByteArrayOutputStream launchProcess(String command, final Map environment, final String workDir,
        ExecuteResultHandler resultHandler) throws IOException {

    String[] cmdlist = command.split(" ");

    CommandLine cmd = new CommandLine(cmdlist[0]);
    for (String cmdItem : cmdlist) {
        if (StringUtils.isBlank(cmdItem) == false) {
            cmd.addArgument(cmdItem);
        }
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);
    if (StringUtils.isBlank(workDir) == false) {
        executor.setWorkingDirectory(new File(workDir));
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PumpStreamHandler streamHandler = new PumpStreamHandler(out, out);
    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    try {
        if (resultHandler == null) {
            executor.execute(cmd, environment);
        } else {
            executor.execute(cmd, environment, resultHandler);
        }
    } catch (ExecuteException e) {

        // @@@@
        // failed to run command
    }

    return out;

}

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

public List<String> getPorts() {
    List<String> ports = new ArrayList<>();
    try {/*from   w w w . ja v a2s . 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  .  ja v a2 s  .  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:io.selendroid.android.impl.AbstractDevice.java

private void startLogging() {
    logoutput = new ByteArrayOutputStream();
    DefaultExecutor exec = new DefaultExecutor();
    exec.setStreamHandler(new PumpStreamHandler(logoutput));
    CommandLine command = adbCommand("logcat", "ResourceType:S", "dalvikvm:S", "Trace:S", "SurfaceFlinger:S",
            "StrictMode:S", "ExchangeService:S", "SVGAndroid:S", "skia:S", "LoaderManager:S",
            "ActivityThread:S", "-v", "time");
    log.info("starting logcat:");
    log.fine(command.toString());/* w w  w . ja v a  2 s .  c o  m*/
    try {
        exec.execute(command, new DefaultExecuteResultHandler());
        logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        exec.setWatchdog(logcatWatchdog);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

public boolean compile(File file) {
    try {/*from w w  w. j a  va  2 s .com*/
        Map map = new HashMap();
        map.put("file", file);

        CommandLine cmdLine = new CommandLine("propellent/Propellent.exe");
        cmdLine.addArgument("/compile");
        cmdLine.addArgument("/gui").addArgument("OFF");
        cmdLine.addArgument("${file}");
        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);
            return false;
        }

        output = outputStream.toString();

        // 101 = Compile error
        // 402 = Compile succesfull
        if (exitValue == 101) {
            return false;
        }

        //            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);
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        return false;
    }
}

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

/** {@inheritDoc} 
 * @throws SchedulerException /* w ww  .ja v  a 2s  .c om*/
 */
@Override
public String runParameterSweep(final Model paramSweepConfig, final String timeLimit, final File workDir)
        throws SchedulerException {

    File file = null;
    try {
        //         file = File.createTempFile("paramsweep-", ".xml");
        file = new File(workDir, "paramsweep-config.xml");
        Marshaller marshaller = JAXBContext.newInstance(Model.class).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(paramSweepConfig, file);
        //      } catch (IOException e) {
        //         throw new SchedulerException("Could not create temporary parameter-sweep configuration xml.", e);
    } catch (JAXBException e) {
        throw new SchedulerException(
                "Could not write temporary parameter-sweep configuration xml: " + file.toString(), e);
    }
    CommandLine cmd = new CommandLine(cmdFile);
    Map<String, Object> substitutions = new HashMap<String, Object>();
    substitutions.put(CMD_SUBSTITUTION_NAME_FILE, file);
    cmd.setSubstitutionMap(substitutions);

    if (timeLimit != null && !timeLimit.isEmpty()) {
        cmd.addArgument("-t", false);
        cmd.addArgument(timeLimit, false);
    }

    // add server port argument
    cmd.addArgument("-p", false);
    cmd.addArgument(String.valueOf(serverPort), false);

    cmd.addArgument("${" + CMD_SUBSTITUTION_NAME_FILE + "}", false);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(workDir);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(byteArrayOutputStream);

    executor.setStreamHandler(streamHandler);

    try {
        executor.execute(cmd);
    } catch (ExecuteException e) {
        throw new SchedulerException(
                paramSweepCmd + " exited with " + e.getExitValue() + ". Output:\n" + byteArrayOutputStream, e);
    } catch (IOException e) {
        throw new SchedulerException(
                "Execution of " + paramSweepCmd + " failed. Output:\n" + byteArrayOutputStream, e);
    }

    // the standard output of the script is the job id
    final String jobId = byteArrayOutputStream.toString();

    return jobId;
}

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

/**
 * Executes the ffmpeg process with the previous given arguments.
 * //from w w w.  jav  a2  s . c  om
 * @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();
}