Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

In this page you can find the example usage for java.lang ProcessBuilder start.

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:de.tudarmstadt.ukp.dkpro.spelling.experiments.hoo2012.io.HOO2012Evaluator.java

private void runProcess(String command) throws Exception {
    ProcessBuilder mProBuilder;
    Process mProcess;//from  w w  w . j a  v  a  2s.com
    BufferedReader mResultReader;

    System.out.println(command);

    mProBuilder = new ProcessBuilder("/bin/sh", "-c", command);
    mProcess = mProBuilder.start();
    mResultReader = new BufferedReader(new InputStreamReader(mProcess.getInputStream()));

    while (!mResultReader.ready()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    while (mResultReader.ready()) {
        String line = mResultReader.readLine();
        if (line == null)
            throw new IOException("Unexpected end of OutputStream.");

        System.out.println(line);
    }
}

From source file:com.reelfx.model.ScreenRecorder.java

public void run() {
    try {/*www . jav a  2  s .  c o  m*/
        if (Applet.IS_MAC) {
            List<String> macArgs = new ArrayList<String>();
            macArgs.add(MAC_EXEC.getAbsolutePath());
            macArgs.add(OUTPUT_FILE.getAbsolutePath());

            ProcessBuilder pb = new ProcessBuilder(macArgs);
            recordingProcess = pb.start();
            fireProcessUpdate(RECORDING_STARTED);

            errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "mac E");
            inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "mac O");

            logger.info("Starting listener threads...");
            errorGobbler.start();
            inputGobbler.start();

            recordingProcess.waitFor();
            fireProcessUpdate(RECORDING_COMPLETE);
        }

        else if (Applet.IS_LINUX) {
            // can have problem with file permissions when methods are invoked via Javascript even if applet is signed, 
            // thus some code needs to wrapped in a privledged block
            AccessController.doPrivileged(new PrivilegedAction<Object>() {

                @Override
                public Object run() {

                    try {
                        int width = Applet.CAPTURE_VIEWPORT.width;
                        if (width % 2 != 0)
                            width--;
                        int height = Applet.CAPTURE_VIEWPORT.height;
                        if (height % 2 != 0)
                            height--;

                        List<String> ffmpegArgs = new ArrayList<String>();
                        //ffmpegArgs.add("/usr/bin/ffmpeg");
                        ffmpegArgs.add(Applet.BIN_FOLDER.getAbsoluteFile() + File.separator + "ffmpeg");
                        // screen capture settings
                        ffmpegArgs.addAll(
                                parseParameters("-y -f x11grab -s " + width + "x" + height + " -r 20 -i :0.0+"
                                        + Applet.CAPTURE_VIEWPORT.x + "," + Applet.CAPTURE_VIEWPORT.y));
                        // microphone settings (good resource: http://www.oreilly.de/catalog/multilinux/excerpt/ch14-05.htm)
                        /* 04/29/2010 - ffmpeg gets much better framerate when not recording microphone (let Java do this)
                         * if(audioSource != null) { 
                           String driver = audioIndex > 0 ? "/dev/dsp"+audioIndex : "/dev/dsp";
                           ffmpegArgs.addAll(parseParameters("-f oss -ac 1 -ar "+AudioRecorder.FREQ+" -i "+driver));
                        }*/
                        // output file settings
                        ffmpegArgs.addAll(parseParameters("-vcodec mpeg4 -r 20 -b 5000k")); // -s "+Math.round(width*SCALE)+"x"+Math.round(height*SCALE))
                        ffmpegArgs.add(OUTPUT_FILE.getAbsolutePath());

                        logger.info("Executing this command: " + prettyCommand(ffmpegArgs));

                        ProcessBuilder pb = new ProcessBuilder(ffmpegArgs);
                        recordingProcess = pb.start();
                        // fireProcessUpdate(RECORDING_STARTED); // moved to action listener method

                        errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "ffmpeg E");
                        inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "ffmpeg O");

                        logger.info("Starting listener threads...");
                        errorGobbler.start();
                        errorGobbler.addActionListener("Stream mapping:", self);
                        inputGobbler.start();

                        recordingProcess.waitFor();

                        fireProcessUpdate(RECORDING_COMPLETE);

                    } catch (Exception e) {
                        logger.error("Error running Linux screen recorder!", e);
                    }
                    return null;
                }
            });
        }

        else if (Applet.IS_WINDOWS) {
            // can have problem with file permissions when methods are invoked via Javascript even if applet is signed, 
            // thus some code needs to wrapped in a privileged block
            AccessController.doPrivileged(new PrivilegedAction<Object>() {

                @Override
                public Object run() {

                    try {
                        List<String> ffmpegArgs = new ArrayList<String>();
                        ffmpegArgs.add(FFMPEG_EXEC.getAbsolutePath());
                        // for full screen, use simply "cursor:desktop"
                        int width = Applet.CAPTURE_VIEWPORT.width % 2 == 0 ? Applet.CAPTURE_VIEWPORT.width
                                : Applet.CAPTURE_VIEWPORT.width - 1;
                        int height = Applet.CAPTURE_VIEWPORT.height % 2 == 0 ? Applet.CAPTURE_VIEWPORT.height
                                : Applet.CAPTURE_VIEWPORT.height - 1;
                        String viewport = ":offset=" + Applet.CAPTURE_VIEWPORT.x + ","
                                + Applet.CAPTURE_VIEWPORT.y;
                        viewport += ":size=" + width + "," + height;
                        ffmpegArgs.addAll(parseParameters("-y -f gdigrab -r 20 -i cursor:desktop" + viewport
                                + " -vcodec mpeg4 -b 5000k " + OUTPUT_FILE));

                        logger.info("Executing this command: " + prettyCommand(ffmpegArgs));
                        ProcessBuilder pb = new ProcessBuilder(ffmpegArgs);
                        recordingProcess = pb.start();
                        //fireProcessUpdate(RECORDING_STARTED); // moved to action listener method

                        // ffmpeg doesn't get the microphone on Windows, but this allows it to record a better frame rate anyway

                        errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "ffmpeg E");
                        inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "ffmpeg O");

                        logger.info("Starting listener threads...");
                        errorGobbler.start();
                        errorGobbler.addActionListener("Stream mapping:", self);
                        inputGobbler.start();

                        recordingProcess.waitFor();

                        fireProcessUpdate(RECORDING_COMPLETE);

                    } catch (Exception e) {
                        logger.error("Error while running Windows screen recorder!", e);
                    }
                    return null;
                }
            });

        }

    } catch (Exception ie) {
        logger.error("Exception while running ScreenRecorder!", ie);
    }
}

From source file:com.kdmanalytics.toif.adaptor.FindbugsAdaptor.java

/**
 * method used to aid the testing of the getGeneratorVersion method. We need some indirection so
 * that this class can be partially mocked.
 * /*w  w  w .ja v a  2s.  c o  m*/
 * @param process
 * @return
 * @throws IOException
 */
protected InputStream startProcess(ProcessBuilder process) throws IOException {
    Process findbugsInstance = process.start();
    InputStream in = findbugsInstance.getInputStream();
    return in;
}

From source file:org.jellycastle.maven.Maven.java

/**
 * Run new Maven os process with given arguments and commands.
 *//*from   w  w  w. j ava2  s. c  o  m*/
public void execute() {
    Process process = null;
    BufferedReader br = null;
    try {
        ProcessBuilder processBuilder = getProcessBuilder();
        processBuilder.redirectErrorStream(true);
        log.info("Starting process: " + processBuilder.command());

        process = processBuilder.start();

        // Read output
        br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        process.waitFor();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        close(br);
        destroyProcess(process);
    }
}

From source file:com.gordoni.opal.ScenarioSet.java

public void subprocess(String cmd, String prefix, String... args) throws IOException, InterruptedException {
    String real_cwd = System.getProperty("user.dir");
    List<String> arguments = new ArrayList<String>(Arrays.asList(args));
    arguments.add(0, real_cwd + "/" + cmd);
    ProcessBuilder pb = new ProcessBuilder(arguments);
    Map<String, String> env = pb.environment();
    env.put("OPAL_FILE_PREFIX", cwd + "/" + prefix);
    pb.redirectError(Redirect.INHERIT);// www  .  ja  v a  2  s  .c om
    Process p = pb.start();

    InputStream stdout = p.getInputStream();
    byte buf[] = new byte[8192];
    while (stdout.read(buf) != -1) {
    }
    p.waitFor();
    assert (p.exitValue() == 0);
}

From source file:com.netflix.dynomitemanager.defaultimpl.FloridaProcessManager.java

public void start() throws IOException {
    logger.info(String.format("Starting dynomite server"));

    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);/*w  ww . j  av a  2 s  .c  om*/
        command.add("-n");
        command.add("-E");
    }
    command.addAll(getStartCommand());

    ProcessBuilder startDynomite = new ProcessBuilder(command);
    Map<String, String> env = startDynomite.environment();
    setEnv(env);

    startDynomite.directory(new File("/"));
    startDynomite.redirectErrorStream(true);
    Process starter = startDynomite.start();

    try {
        sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
        int code = starter.exitValue();
        if (code == 0) {
            logger.info("Dynomite server has been started");
            instanceState.setStorageProxyAlive(true);
        } else {
            logger.error("Unable to start Dynomite server. Error code: {}", code);
        }

        logProcessOutput(starter);
    } catch (Exception e) {
        logger.warn("Starting Dynomite has an error", e);
    }
}

From source file:com.photon.phresco.framework.impl.ProjectRuntimeManagerImpl.java

private BufferedReader executeJenkinsProcess(List<String> commands) throws PhrescoException {
    ProcessBuilder processBuilder = new ProcessBuilder(commands);
    processBuilder.directory(new File("C:\\download\\workspace\\tools\\jenkins"));
    try {/*  ww w  .  j  av a 2s.  co  m*/
        Process process = processBuilder.start();
        return new BufferedReader(new InputStreamReader(process.getInputStream()));
    } catch (IOException e) {
        throw new PhrescoException(e);
    }
}

From source file:es.amplia.research.maven.protodocbook.cmd.Factory.java

public void executeAll() throws IOException, InterruptedException {

    File target = new File("target");
    target.mkdir();// ww w .  java2 s.c  o  m

    ProcessBuilder pb = new ProcessBuilder("/usr/bin/make", "clean");
    Map<String, String> env = pb.environment();
    pb.directory(new File(homeDir, "linux"));
    File logFile = new File("log");
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    Process p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/bin/make");
    pb.directory(new File(homeDir, "linux"));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/local/bin/protoc", "-I/usr/include", "--proto_path=src/main/protobuf",
            "src/main/protobuf/sample.proto",
            "--plugin=" + this.homeDir.getAbsolutePath() + "/linux/protoc-gen-docbook", "--docbook_out=target");
    pb.directory(new File("."));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/bin/fop", "-xml", "target/docbook_out.xml", "-xsl",
            "/usr/share/xml/docbook/stylesheet/docbook-xsl/fo/docbook.xsl", "-pdf", "target/docbook_out.pdf",
            "-param", "page.orientation", "landscape", "-param", "paper.type", "USletter");
    pb.directory(new File("."));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = br.readLine()) != null) {
        if (this.log.isInfoEnabled())
            this.log.info(line);
    }
}

From source file:com.liferay.petra.doulos.processor.BaseShellDoulosRequestProcessor.java

protected void execute(ShellStatus shellStatus) throws Exception {
    shellStatus.status = "executing";

    List<String> shellCommandsList = getShellCommands(shellStatus);

    shellCommandsList.add(0, "/bin/bash");
    shellCommandsList.add(1, "-x");
    shellCommandsList.add(2, "-c");

    String[] shellCommands = shellCommandsList.toArray(new String[shellCommandsList.size()]);

    shellStatus.shellCommands = StringUtils.join(shellCommands, "\n");

    ProcessBuilder processBuilder = new ProcessBuilder(shellCommands);

    processBuilder.redirectErrorStream(true);

    Process process = processBuilder.start();

    StringBuilder sb = new StringBuilder();

    String line = null;//from   w ww  . j  ava 2s.c o  m

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

    while ((line = bufferedReader.readLine()) != null) {
        sb.append(line);
        sb.append("\n");
    }

    bufferedReader.close();

    try {
        if (_log.isDebugEnabled()) {
            _log.debug("Wait for process to finish");
        }

        process.waitFor();

        shellStatus.exitValue = String.valueOf(process.exitValue());
        shellStatus.output = sb.toString();
        shellStatus.status = "finished";
    } catch (Exception e) {
        Writer writer = new StringWriter();

        PrintWriter printWriter = new PrintWriter(writer);

        e.printStackTrace(printWriter);

        shellStatus.exception = writer.toString();

        shellStatus.status = "exception";
    }
}

From source file:com.lithium.flow.vault.AgentVault.java

private void startAgent(@Nonnull String password) {
    try {//from ww  w.j  a  va2s. co m
        int port = findFreePort();
        String agentPassword = Vaults.securePassword();

        Map<String, String> map = new HashMap<>();
        Store agentStore = new MemoryStore(map);
        Vault agentVault = new SecureVault(Configs.empty(), agentStore);
        agentVault.setup(agentPassword);
        agentVault.putValue("password", password);

        ProcessBuilder builder = new ProcessBuilder();
        builder.command(System.getProperty("java.home") + "/bin/java", "-Dagent.port=" + port,
                AgentServer.class.getName());
        builder.environment().put("CLASSPATH", System.getProperty("java.class.path"));
        Process process = builder.start();

        OutputStream out = process.getOutputStream();
        mapper.writeValue(out, map);
        out.close();

        store.putValue("vault.agent.port", String.valueOf(port));
        store.putValue("vault.agent.password", agentPassword);
    } catch (IOException e) {
        throw new VaultException("failed to start agent", e);
    }
}