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:be.tarsos.transcoder.ffmpeg.FFMPEGExecutor.java

public AudioInputStream pipe(Attributes attributes) throws EncoderException {
    String pipeEnvironment;//  w w w  .jav a2s  . c o  m
    String pipeArgument;
    File pipeLogFile;
    int pipeBuffer;

    if (System.getProperty("os.name").indexOf("indows") > 0) {
        pipeEnvironment = "cmd.exe";
        pipeArgument = "/C";
    } else {
        pipeEnvironment = "/bin/bash";
        pipeArgument = "-c";
    }
    pipeLogFile = new File("decoder_log.txt");
    //buffer 1/4 second of audio.
    pipeBuffer = attributes.getSamplingRate() / 4;

    AudioFormat audioFormat = Encoder.getTargetAudioFormat(attributes);

    String command = toString();

    ProcessBuilder pb = new ProcessBuilder(pipeEnvironment, pipeArgument, command);

    pb.redirectError(Redirect.appendTo(pipeLogFile));

    LOG.fine("Starting piped decoding process");
    final Process process;
    try {
        process = pb.start();
    } catch (IOException e1) {
        throw new EncoderException("Problem starting piped sub process: " + e1.getMessage());
    }

    InputStream stdOut = new BufferedInputStream(process.getInputStream(), pipeBuffer);

    //read and ignore the 46 byte wav header, only pipe the pcm samples to the audioinputstream
    byte[] header = new byte[46];
    double sleepSeconds = 0;
    double timeoutLimit = 20; //seconds

    try {
        while (stdOut.available() < header.length) {
            try {
                Thread.sleep(100);
                sleepSeconds += 0.1;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (sleepSeconds > timeoutLimit) {
                throw new Error("Could not read from pipe within " + timeoutLimit + " seconds: timeout!");
            }
        }
        int bytesRead = stdOut.read(header);
        if (bytesRead != header.length) {
            throw new EncoderException(
                    "Could not read complete WAV-header from pipe. This could result in mis-aligned frames!");
        }
    } catch (IOException e1) {
        throw new EncoderException("Problem reading from piped sub process: " + e1.getMessage());
    }

    final AudioInputStream audioStream = new AudioInputStream(stdOut, audioFormat, AudioSystem.NOT_SPECIFIED);

    //This thread waits for the end of the subprocess.
    new Thread(new Runnable() {
        public void run() {
            try {
                process.waitFor();
                LOG.fine("Finished piped decoding process");
            } catch (InterruptedException e) {
                LOG.severe("Interrupted while waiting for sub process exit.");
                e.printStackTrace();
            }
        }
    }, "Decoding Pipe Reader").start();
    return audioStream;
}

From source file:edu.clemson.cs.nestbed.server.management.instrumentation.ProgramCompileManagerImpl.java

private File getMessageFile(File dir, String messageType) throws IOException {
    log.info("getMessageFile():  directory = " + dir.getAbsolutePath() + ", messageType = " + messageType);

    ProcessBuilder processBuilder = new ProcessBuilder(GET_FILE, dir.getAbsolutePath(), messageType);
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();

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

    String line = in.readLine();/*  w  ww  . j a v a  2s.  co m*/
    in.close();

    return (line != null) ? new File(line) : null;
}

From source file:edu.clemson.cs.nestbed.server.management.instrumentation.ProgramCompileManagerImpl.java

private List<String> getMessageList(File dir, String tosPlatform) throws IOException {
    log.info("getMessageList(): directory = " + dir.getAbsolutePath() + ", tosPlatform = " + tosPlatform);
    List<String> messageList = new ArrayList<String>();
    ProcessBuilder processBuilder = new ProcessBuilder(GET_TYPES, dir.getAbsolutePath(), tosPlatform);
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();

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

    String line;//from   w  ww . ja  v a 2 s .  c  om
    while ((line = in.readLine()) != null) {
        messageList.add(line);
    }
    in.close();

    return messageList;
}

From source file:net.landora.video.mkv.MKVParser.java

public Video handleFile(File f) {

    try {//from  ww w . j  a  v  a 2 s  .  co  m
        ProcessBuilder process = new ProcessBuilder(
                ProgramsAddon.getInstance().getConfiguredPath(CommonPrograms.MKVINFO), f.getAbsolutePath());
        process.redirectErrorStream(true);
        Process p = process.start();

        StringWriter buffer = new StringWriter();
        IOUtils.copy(p.getInputStream(), buffer);
        p.waitFor();

        String reply = buffer.toString();
        buffer = null;

        if (reply.contains("No segment/level 0 element found.")) {
            return null;
        }

        Matcher mkvInfoMatcher = dataPattern.matcher(reply);

        file = new MKVFile();
        file.setFile(f);
        state = MKVParserState.Other;

        while (mkvInfoMatcher.find()) {
            depth = mkvInfoMatcher.group(1).length();
            field = mkvInfoMatcher.group(2);
            value = mkvInfoMatcher.group(3);

            switch (state) {
            case Segment_Header:
                handleSegmentHeader();
                break;
            case UnknownTrack:
                handleUnknownTrack();
                break;
            case VideoTrack:
                handleVideo();

                break;
            case AudioTrack:
                handleAudo();

                break;
            case SubtitleTrack:
                handleGeneralStreamFields();

                break;
            case Attachment:
                handleAttachment();
                break;

            case Chapter:
                handleChapter();
                break;

            case Other:
            default:
                handleStateless();
            }
        }
        return file;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.serena.rlc.provider.filesystem.client.FilesystemClient.java

public void localExec(String execScript, String execDir, String execParams, boolean ignoreErrors)
        throws FilesystemClientException {
    Path script = Paths.get(execDir + File.separatorChar + execScript);

    try {/*  ww  w .  ja va  2s. c  o m*/
        if (!Files.exists(script)) {
            if (ignoreErrors) {
                logger.debug("Execution script " + script.toString() + " does not exist, ignoring...");
            } else {
                throw new FilesystemClientException(
                        "Execution script " + script.toString() + " does not exist");
            }
        } else {
            ProcessBuilder pb = new ProcessBuilder(script.toString());
            pb.directory(new File(script.getParent().toString()));
            System.out.println(pb.directory().toString());
            logger.debug("Executing script " + execScript + " in directory " + execDir + " with parameters: "
                    + execParams);
            Process p = pb.start(); // Start the process.
            p.waitFor(); // Wait for the process to finish.
            logger.debug("Executed script " + execScript + " successfully.");
        }
    } catch (Exception e) {
        logger.debug(e.getLocalizedMessage());
        throw new FilesystemClientException(e.getLocalizedMessage());
    }

}

From source file:com.microsoft.tfs.client.common.ui.protocolhandler.ProtocolHandlerWindowsRegistrationCommand.java

private String getCurrentProtocolHandlerRegistryValue() {
    BufferedReader stdout = null;
    String line;/*from  w w  w  .j  ava  2 s .c  o m*/

    try {
        final ProcessBuilder pb = new ProcessBuilder("reg", //$NON-NLS-1$
                "query", //$NON-NLS-1$
                PROTOCOL_HANDLER_REGISTRY_PATH, "/ve"); //$NON-NLS-1$
        pb.redirectErrorStream(true);

        final Process cmd = pb.start();
        int rc = cmd.waitFor();

        if (rc == 0) {
            stdout = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
            while ((line = stdout.readLine()) != null) {
                int idx = 0;
                /* @formatter:off
                 * the output contains at most one line like 
                 * 
                 *    (Default)    REG_EXPAND_SZ    "%USERPROFILE%\.vsts\latestIDE.cmd" "%1"
                 * 
                 * @formatter:on
                 */
                if ((idx = line.indexOf(PROTOCOL_HANDLER_REG_VALUE_TYPE)) < 0) {
                    continue;
                }

                return line.substring(idx + PROTOCOL_HANDLER_REG_VALUE_TYPE.length()).trim();
            }
        }
    } catch (final InterruptedException e) {
        log.warn("Protocol handler registration has been cancelled."); //$NON-NLS-1$
    } catch (final Exception e) {
        log.error("Error accessing Windows registry:", e); //$NON-NLS-1$
    } finally {
        tryClose(stdout);
    }

    return null;
}

From source file:de.tudarmstadt.ukp.csniper.webapp.search.cqp.CqpQuery.java

private Process getCQPProcess() throws DataAccessResourceFailureException {
    try {/*from w  w w .  j av a  2 s .com*/
        List<String> cmd = new ArrayList<String>();

        cmd.add(engine.getCqpExecutable().getAbsolutePath());
        cmd.add("-r");
        cmd.add(engine.getRegistryPath().getAbsolutePath());
        // run cqp as child process (-c)
        cmd.add("-c");

        if (log.isTraceEnabled()) {
            log.trace("Invoking [" + StringUtils.join(cmd, " ") + "]");
        }

        final ProcessBuilder pb = new ProcessBuilder(cmd);
        return pb.start();
    } catch (IOException e1) {
        throw new DataAccessResourceFailureException("Unable to start CQP process", e1);
    }
}

From source file:edu.uci.ics.asterix.event.management.EventExecutor.java

public void executeEvent(Node node, String script, List<String> args, boolean isDaemon, Cluster cluster,
        Pattern pattern, IOutputHandler outputHandler, AsterixEventServiceClient client) throws IOException {
    List<String> pargs = new ArrayList<String>();
    pargs.add("/bin/bash");
    pargs.add(client.getEventsHomeDir() + File.separator + AsterixEventServiceUtil.EVENT_DIR + File.separator
            + EXECUTE_SCRIPT);/*  ww  w .ja  va  2 s. c  o  m*/
    StringBuffer envBuffer = new StringBuffer(IP_LOCATION + "=" + node.getClusterIp() + " ");
    boolean isMasterNode = node.getId().equals(cluster.getMasterNode().getId());

    if (!node.getId().equals(EventDriver.CLIENT_NODE_ID) && cluster.getEnv() != null) {
        for (Property p : cluster.getEnv().getProperty()) {
            if (p.getKey().equals("JAVA_HOME")) {
                String val = node.getJavaHome() == null ? p.getValue() : node.getJavaHome();
                envBuffer.append(p.getKey() + "=" + val + " ");
            } else if (p.getKey().equals(EventUtil.NC_JAVA_OPTS)) {
                if (!isMasterNode) {
                    StringBuilder builder = new StringBuilder();
                    builder.append("\"");
                    String javaOpts = p.getValue();
                    if (javaOpts != null) {
                        builder.append(javaOpts);
                    }
                    if (node.getDebugPort() != null) {
                        int debugPort = node.getDebugPort().intValue();
                        if (!javaOpts.contains("-Xdebug")) {
                            builder.append(
                                    (" " + "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address="
                                            + debugPort));
                        }
                    }
                    builder.append("\"");
                    envBuffer.append("JAVA_OPTS" + "=" + builder + " ");
                }
            } else if (p.getKey().equals(EventUtil.CC_JAVA_OPTS)) {
                if (isMasterNode) {
                    StringBuilder builder = new StringBuilder();
                    builder.append("\"");
                    String javaOpts = p.getValue();
                    if (javaOpts != null) {
                        builder.append(javaOpts);
                    }
                    if (node.getDebugPort() != null) {
                        int debugPort = node.getDebugPort().intValue();
                        if (!javaOpts.contains("-Xdebug")) {
                            builder.append(
                                    (" " + "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address="
                                            + debugPort));
                        }
                    }
                    builder.append("\"");
                    envBuffer.append("JAVA_OPTS" + "=" + builder + " ");
                }
            } else if (p.getKey().equals("LOG_DIR")) {
                String val = node.getLogDir() == null ? p.getValue() : node.getLogDir();
                envBuffer.append(p.getKey() + "=" + val + " ");
            } else {
                envBuffer.append(p.getKey() + "=" + p.getValue() + " ");
            }

        }
        pargs.add(cluster.getUsername() == null ? System.getProperty("user.name") : cluster.getUsername());
    }

    StringBuffer argBuffer = new StringBuffer();
    if (args != null && args.size() > 0) {
        for (String arg : args) {
            argBuffer.append(arg + " ");
        }
    }

    ProcessBuilder pb = new ProcessBuilder(pargs);
    pb.environment().put(IP_LOCATION, node.getClusterIp());
    pb.environment().put(CLUSTER_ENV, envBuffer.toString());
    pb.environment().put(SCRIPT, script);
    pb.environment().put(ARGS, argBuffer.toString());
    pb.environment().put(DAEMON, isDaemon ? "true" : "false");

    Process p = pb.start();
    if (!isDaemon) {
        BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
        StringWriter writer = new StringWriter();
        IOUtils.copy(bis, writer, "UTF-8");
        String result = writer.getBuffer().toString();
        OutputAnalysis analysis = outputHandler.reportEventOutput(pattern.getEvent(), result);
        if (!analysis.isExpected()) {
            throw new IOException(analysis.getErrorMessage() + result);
        }
    }
}

From source file:archive_v1.Retrieve.java

public void execRetrieve(String filename) {
    String execRetrieveCommand = null;

    execRetrieveCommand = "tar xvf /dev/st0 -C /u01/restore archive/" + filename;

    Process proc = null;/* w  ww . j a  v  a  2  s .  c o  m*/
    String output = null;
    try {

        ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", execRetrieveCommand);
        builder.redirectErrorStream(true);
        proc = builder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        output = reader.readLine();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:ml.shifu.shifu.core.alg.TensorflowTrainer.java

public void train() throws IOException {
    List<String> commands = buildCommands();
    ProcessBuilder pb = new ProcessBuilder(commands);

    pb.directory(new File("./"));
    pb.redirectErrorStream(true);//w  w w .  j a  v a2 s . co  m
    LOGGER.info("Start trainning sub process. Commands {}", commands.toString());
    Process process = pb.start();
    StreamCollector sc = new StreamCollector(process.getInputStream());
    sc.start();

    try {
        process.waitFor();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        if (sc != null) {
            sc.close();
        }
    }
}