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

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

Introduction

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

Prototype

public int execute(final CommandLine command) throws ExecuteException, IOException 

Source Link

Usage

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

protected boolean loadIntoRam(String executable, File ramFile, String comPort) {
    try {/*from w  w  w  . ja v a 2s. c  o m*/
        Map map = new HashMap();
        map.put("ramFile", ramFile);

        CommandLine cmdLine = new CommandLine(executable);
        cmdLine.addArgument("-r");
        if (comPort != null) {
            cmdLine.addArgument("-p").addArgument(comPort);
        }
        cmdLine.addArgument("${ramFile}");

        cmdLine.setSubstitutionMap(map);
        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);
            success = false;
            return false;
        } finally {
            output = outputStream.toString();
        }

        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}

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

protected List<String> getPorts(String executable) {
    List<String> ports = new ArrayList<>();
    try {//from  w w  w .j ava 2 s .  c o  m
        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:eu.creatingfuture.propeller.blocklyprop.propeller.PropellerLoad.java

protected boolean loadIntoEeprom(String executable, File eepromFile, String comPort) {
    try {/*from  ww w.ja v a2s. c  o  m*/
        Map map = new HashMap();
        map.put("eepromFile", eepromFile);

        CommandLine cmdLine = new CommandLine(executable);
        cmdLine.addArgument("-r");
        cmdLine.addArgument("-e");
        if (comPort != null) {
            cmdLine.addArgument("-p").addArgument(comPort);
        }
        cmdLine.addArgument("${eepromFile}");

        cmdLine.setSubstitutionMap(map);
        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);
            success = false;
            return false;
        } finally {
            output = outputStream.toString();
        }

        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}

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 w w .ja  va  2 s .c o m
        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:eu.crisis_economics.abm.dashboard.cluster.script.BashScheduler.java

/** {@inheritDoc} 
 * @throws SchedulerException /*from  w  w w  .  j ava 2  s .com*/
 */
@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:com.walmart.gatling.commons.ScriptExecutor.java

private void runCancelJob(Master.Job message) {
    if (getAbortStatus(message.abortUrl, message.trackingId)) {
        CommandLine cmdLine = new CommandLine("/bin/bash");
        cmdLine.addArgument(agentConfig.getJob().getJobArtifact("cancel"));
        cmdLine.addArgument(message.jobId);
        DefaultExecutor killExecutor = new DefaultExecutor();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        killExecutor.setWatchdog(watchdog);
        try {/*from   w  ww .  j  a  v a 2  s.c  o m*/
            log.info("Cancel command: {}", cmdLine);
            killExecutor.execute(cmdLine);
        } catch (IOException e) {
            log.error(e, "Error cancelling job");
        }
    }
}

From source file:cat.ogasoft.protocolizer.processor.CompilerPhase.java

public static void processCompiler(RoundEnvironment roundEnv) throws CompilerException {
    try {//from www  . ja v  a  2s. c o m
        String protocPath = "src" + File.separatorChar + "cat" + File.separatorChar + "ogasoft"
                + File.separatorChar + "protocolizer" + File.separatorChar + "protoc";

        DefaultExecutor de = new DefaultExecutor();
        for (Element element : roundEnv.getElementsAnnotatedWith(ProtoFileV2.Compiler.class)) {
            ProtoFileV2.Compiler compiler = element.getAnnotation(ProtoFileV2.Compiler.class);
            if (compiler.compile()) {
                String base = protocPath.replace('.', File.separatorChar);
                File dst = new File(base);
                if (!dst.exists() && !dst.mkdirs()) {
                    throw new Exception("Cann not be created directory " + dst.getAbsolutePath());
                }
                File rootDirectori = new File(base);
                //Compile all the files in compiler.protoFilePaths()
                FileFilter filter = new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        return pathname.getName().toLowerCase().endsWith(".proto");
                    }
                };
                for (File protoc : rootDirectori.listFiles(filter)) {
                    String target = base + File.separatorChar + protoc.getName();
                    LOG.info("\tCompiling " + target + "...");
                    CommandLine cmd = CommandLine.parse(compiler.command() + " --proto_path=" + protocPath + " "
                            + compiler.language().option + "=src " + target);
                    int result = de.execute(cmd);
                    if (result != 0) {
                        throw new CompilerException("HO ho... somthing went wrong, code: " + result);
                    }
                    LOG.info("\t" + target + " compiled");
                }
            }
        }
    } catch (Exception e) {
        //Any exception is a CompilerException.
        throw new CompilerException(e.getMessage());
    }
}

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

public List<String> getPorts() {
    List<String> ports = new ArrayList<>();
    try {//from www. j  a v a  2s.c  om
        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 {/*from  w w w .j av a2s  .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:edu.stolaf.cs.wmrserver.testjob.TestJobTask.java

public TestJobResult call() throws IOException {
    // Create the result object
    TestJobResult result = new TestJobResult();

    // Map/* w  w  w.  j ava  2  s  .co  m*/

    CappedInputStream mapInput = null;
    try {
        // List the input files and open a stream
        FileSystem fs = _inputPath.getFileSystem(_conf);
        FileStatus[] files = JobServiceHandler.listInputFiles(fs, _inputPath);
        AggregateInputStream aggregateInput = new AggregateInputStream(fs, files);
        mapInput = new CappedInputStream(aggregateInput, _inputCap);

        // Run the mapper
        result.setMapResult(runTransform(_id, _mapperFile, _packageDir, mapInput));
    } finally {
        IOUtils.closeQuietly(mapInput);
    }

    // Return if mapper failed or did not produce output
    if (result.getMapResult().getExitCode() != 0 || result.getMapResult().getOutputFile() == null)
        return result;

    // Sort
    // While this seems (and is) inefficient for computers, this is
    //actually probably the shortest way to write this code since
    // vanilla Java does not provide an equivalent of sort -n.
    // If you want to write it in Java, use java.util.TreeSet.

    File intermediateFile = null;
    FileOutputStream intermediateOutput = null;
    try {
        // Create and open temporary file for sorted intermediate output
        intermediateFile = File.createTempFile("job-" + Long.toString(_id), "-intermediate", _tempDir);
        intermediateOutput = new FileOutputStream(intermediateFile);

        // Run the sort

        CommandLine sortCommand = new CommandLine("sort");
        //sortCommand.addArgument("--field-separator=\t");
        if (_numericSort)
            sortCommand.addArgument("-n");
        sortCommand.addArgument(result.getMapResult().getOutputFile().getCanonicalPath(), false);
        DefaultExecutor exec = new DefaultExecutor();
        ExecuteWatchdog dog = new ExecuteWatchdog(EXECUTABLE_TIMEOUT);
        PumpStreamHandler pump = new PumpStreamHandler(intermediateOutput);
        exec.setWatchdog(dog);
        exec.setStreamHandler(pump);

        try {
            exec.execute(sortCommand);
        } catch (ExecuteException ex) {
            throw new IOException("Sort process failed while running test jobs", ex);
        }
    } finally {
        IOUtils.closeQuietly(intermediateOutput);
    }

    // Reduce

    FileInputStream reduceInput = null;
    try {
        // Open the intermediate file for reading
        reduceInput = new FileInputStream(intermediateFile);

        // Run the reducer
        result.setReduceResult(runTransform(_id, _reducerFile, _packageDir, reduceInput));
    } finally {
        IOUtils.closeQuietly(reduceInput);

        // Delete intermediate file
        intermediateFile.delete();
    }

    return result;
}