Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

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

Prototype

List command

To view the source code for java.lang ProcessBuilder command.

Click Source Link

Usage

From source file:com.heliosdecompiler.helios.controller.ProcessController.java

public Process launchProcess(ProcessBuilder launch) throws IOException {
    Process process = launch.start();
    try {// www.j  av  a2  s . c  o  m
        lock.lock();
        processes.add(process);
    } finally {
        lock.unlock();
    }
    backgroundTaskHelper.submit(new BackgroundTask(
            Message.TASK_LAUNCH_PROCESS.format(launch.command().stream().collect(Collectors.joining(" "))),
            true, () -> {
                try {
                    process.waitFor();
                    if (!process.isAlive()) {
                        processes.remove(process);
                    }
                } catch (InterruptedException ignored) {
                }
            }, () -> {
                process.destroyForcibly();
                try {
                    lock.lock();
                    processes.remove(process);
                } finally {
                    lock.unlock();
                }
            }));
    return process;
}

From source file:de.tudarmstadt.ukp.dkpro.core.RSTAnnotator.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    // perform sanity check
    if (sanityCheckOnInit) {
        File rstParserSrcDir = new File(rstParserSrcDirPath);

        // create process
        ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

        // working dir must be set to the src dir of RST parser
        processBuilder.directory(rstParserSrcDir);

        // run the command
        processBuilder.command("python", new File(rstParserSrcDir, "sanity_check.py").getAbsolutePath());

        try {/* w  w  w  .  jav  a  2 s  .  com*/
            Process process = processBuilder.start();

            // and wait
            int returnValue = process.waitFor();

            if (returnValue != 0) {
                throw new RuntimeException("Process exited with code " + returnValue);
            }

        } catch (IOException | InterruptedException e) {
            throw new ResourceInitializationException(e);
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.rftagger.RfTagger.java

private void ensureTaggerRunning() throws AnalysisEngineProcessException {
    if (process == null) {
        try {/*from  ww w  .j  av  a2  s.c  o m*/
            PlatformDetector pd = new PlatformDetector();
            String platform = pd.getPlatformId();
            getLogger().info("Load binary for platform: [" + platform + "]");

            File executableFile = runtimeProvider.getFile("rft-annotate");

            List<String> cmd = new ArrayList<>();
            cmd.add(executableFile.getAbsolutePath());
            cmd.add("-q"); // quiet mode
            cmd.add(modelProvider.getResource().getAbsolutePath());
            ProcessBuilder pb = new ProcessBuilder();
            pb.redirectError(Redirect.INHERIT);
            pb.command(cmd);
            process = pb.start();

            writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), getEncoding()));
            reader = new BufferedReader(new InputStreamReader(process.getInputStream(), getEncoding()));
        } catch (Exception e) {
            throw new AnalysisEngineProcessException(e);
        }
    }
}

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

/**
 * Run new Maven os process with given arguments and commands.
 *//*  w  ww  . j a  v  a 2 s .  c om*/
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:eu.abc4trust.cryptoEngine.uprove.util.UProveLauncher.java

public void start(int port, String name) {
    this.startCalled = true;
    // System.out.println("UProveLauncher.start - instance : " + this +
    // " - port : " + launchName + " :" + launchPort + " - is stopped == " +
    // stopped + " - uproveProcess " + this.uproveProcess );
    ProcessBuilder processBuilder;
    if (this.isWindows()) {
        processBuilder = new ProcessBuilder(this.WINDOWS_COMMAND);
    } else {/*  w ww  . jav a2 s .  c  o  m*/
        processBuilder = new ProcessBuilder(this.NON_WINDOWS_COMMAND);
    }
    processBuilder.command().add("" + port);
    //Map<String, String> env = processBuilder.environment();
    //env.clear();

    processBuilder.directory(this.workingDirectory);
    try {
        this.uproveProcess = processBuilder.start();
        // System.out.println(this.uproveProcess.exitValue());
        InputStream is = this.uproveProcess.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        String terminationString = "Press Enter to exit";
        boolean done = false;
        while (!done) {
            line = br.readLine();
            if (line != null) {
                System.out.println(line);
                done = line.endsWith(terminationString);
            } else {
                System.out.println("UProveLauncher - we get null on stdout from process - process has died..");
                break;
            }
        }
        this.debugOutputCollector = new DebugOutputCollector(this.uproveProcess, name);
        this.debugOutput = new Thread(this.debugOutputCollector, "DebugCollector");
        if (done)
            this.debugOutput.start();
        // System.out.println("process started");
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:functionaltests.scilab.AbstractScilabTest.java

protected void runCommand(String testName, int nb_iter) throws Exception {

    ProcessBuilder pb = initCommand(testName, nb_iter);
    System.out.println("Running command : " + pb.command());

    File okFile = new File(sci_tb_home + fs + "ok.tst");
    File koFile = new File(sci_tb_home + fs + "ko.tst");
    File reFile = new File(sci_tb_home + fs + "re.tst");

    if (okFile.exists()) {
        okFile.delete();// w w  w .  j a  v  a2s.  com
    }

    if (koFile.exists()) {
        koFile.delete();
    }
    if (reFile.exists()) {
        reFile.delete();
    }

    Process p = pb.start();

    IOTools.LoggingThread lt1 = new IOTools.LoggingThread(p.getInputStream(), "[" + testName + "]", System.out);
    Thread t1 = new Thread(lt1, testName);
    t1.setDaemon(true);
    t1.start();

    p.waitFor();
    if (reFile.exists()) {
        // we restart in case of JIMS loading bug
        runCommand(testName, nb_iter);
        return;
    }

    assertTrue(testName + " passed", okFile.exists());

    if (testLeak == 1) {
        File outFile = new File(test_home + fs + "JIMS.out");
        JIMSLogsParser parser = new JIMSLogsParser(leakFile, outFile);
        assertTrue("No leak found in " + outFile + " and " + leakFile, parser.testok());
    }
}

From source file:com.photon.phresco.plugins.xcode.AppDeploy.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {/* w w w .java  2s  .  c o m*/
        if (!deviceDeploy && !SdkVerifier.isAvailable(simVersion)) {
            throw new MojoExecutionException("Selected version " + simVersion + " is not available!");
        }
    } catch (IOException e2) {
        throw new MojoExecutionException("SDK verification failed!");
    } catch (InterruptedException e2) {
        throw new MojoExecutionException("SDK verification interrupted!");
    }
    //get the correct simhome if xCode 4.3 is installed simhome is in /Application/Xcode.app/Contents
    //Fix for artf462004
    File simHomeFile = new File(simHome);
    if (!simHomeFile.exists()) {
        simHome = "/Applications/Xcode.app/Contents" + simHome;
    }

    getLog().info("Simulator home" + simHome);

    if (!deviceDeploy) {
        //copy the files into simulation directory
        String home = System.getProperty("user.home");
        getLog().info("Application.path = " + appPath);
        appName = getAppFileName(appPath);
        getLog().info("Application name = " + appName);
        String deployHome = "";
        if (StringUtils.isNotBlank(appDeployHome)) {
            deployHome = appDeployHome;
        } else {
            deployHome = home + "/Library/Application Support/iPhone Simulator/" + simVersion + "/Applications";
        }
        simHomeAppLocation = new File(
                deployHome + File.separator + project.getName() + File.separator + appName);
        if (!simHomeAppLocation.exists()) {
            getLog().info("directory created");
            simHomeAppLocation.mkdirs();
        }
        getLog().info("Desired location " + simHomeAppLocation.getAbsolutePath());
        try {
            String alignedPath = alignedPath(appPath);
            getLog().info("path to copy source :" + alignedPath);
            XcodeUtil.copyFolder(new File(alignedPath), simHomeAppLocation);
            getLog().info("copy the application " + appPath + " to " + simHomeAppLocation);
        } catch (IOException e1) {
            getLog().error("couldn't copy the application " + appPath + " to " + simHomeAppLocation);
        }
    }
    Runnable runnable = new Runnable() {
        public void run() {

            ProcessBuilder pb;
            if (deviceDeploy) {
                pb = new ProcessBuilder("transporter_chief.rb");
                pb.command().add(appPath);
            } else {
                pb = new ProcessBuilder(simHome);
                // Include errors in output
                pb.redirectErrorStream(true);

                pb.command().add(action);
                pb.command()
                        .add(simHomeAppLocation + File.separator + appName.substring(0, appName.indexOf('.')));
            }
            //               pb.command().add(appName);
            getLog().info("List of commands" + pb.command());
            Process child;
            try {
                //               if(ProcessHelper.isProcessRunning()) {
                //                  ProcessHelper.killSimulatorProcess();
                //               }
                child = pb.start();
                // Consume subprocess output and write to stdout for debugging
                InputStream is = new BufferedInputStream(child.getInputStream());
                int singleByte = 0;
                while ((singleByte = is.read()) != -1) {
                    System.out.write(singleByte);
                }
            } catch (IOException e) {
                getLog().error("error occured in launching simulator ");
                getLog().error(e);
            }
        }
    };

    Thread t = new Thread(runnable, "iPhoneSimulator");
    t.start();
    try {
        t.join(5000);
    } catch (InterruptedException e1) {
        //Intentionally left blank.
    }

}

From source file:org.dcm4che3.conf.core.storage.SingleJsonFileConfigurationStorage.java

private void commitToGitIfConfigured(String path) {
    if (makeGitCommitOnPersist) {

        try {//from   ww  w. j a v  a2  s  .c o  m
            ProcessBuilder processBuilder = new ProcessBuilder();

            processBuilder.redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.INHERIT)
                    .directory(Paths.get(fileName).getParent().toFile());

            processBuilder.command("git", "init").start().waitFor();

            processBuilder.command("git", "add", "-A").start().waitFor();

            // add stacktrace to commitMsg
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            new RuntimeException().printStackTrace(ps);
            String niceStackTrace = baos.toString();
            niceStackTrace = niceStackTrace.replace("\"", "\\\"");
            String[] lines = niceStackTrace.split("\n");
            // remove the exception line itself
            niceStackTrace = String.join("\n", Arrays.copyOfRange(lines, 1, lines.length));

            String commitMsg = "\"Changed path " + path + "\n" + niceStackTrace + "\"";

            processBuilder.command("git", "commit", "-m", commitMsg).start().waitFor();

        } catch (Exception e) {
            throw new ConfigurationException("Cannot commit to git repo", e);
        }
    }
}

From source file:org.wandora.application.tools.extractors.ocr.OCRExtractor.java

private boolean processFile(File f, TopicMap tm, Topic documentTopic) throws TopicMapException {
    boolean success = false;
    this.dateFormatter = new SimpleDateFormat();
    String text = "";
    File tmp = new File(TEMP_PATH + ".txt");

    /*/*from   www. ja  v a2  s.  com*/
     * Build the command to be executed in the form 
     *  <path/to/tesseract> <path/to/input> <path/to/output> -l <lang>
     * where the output file is temporary and is disposed of 
     * once it's contents are read.
     */

    ArrayList<String> cmd = new ArrayList<String>();
    String pathToTes = System.getenv("TESSERACT_PATH") + "tesseract";
    String lang = System.getenv("TESSERACT_LANG");
    cmd.add(pathToTes);
    cmd.add(f.getAbsolutePath());
    cmd.add(TEMP_PATH);
    if (lang != null) {
        cmd.add("-l");
        cmd.add(lang);
    }

    ProcessBuilder pb = new ProcessBuilder();
    pb.command(cmd);

    try {
        Process p = pb.start();
        StreamGobbler gobbler = new StreamGobbler(p.getInputStream());
        StreamGobbler errorGobbler = new StreamGobbler((p.getErrorStream()));
        gobbler.start();
        errorGobbler.start();
        int w = p.waitFor();
        if (w == 0 && p.exitValue() == 0) { // Exited alright
            FileInputStream is = new FileInputStream(TEMP_PATH + ".txt");
            try {
                text = IOUtils.toString(is);
            } finally {
                is.close();
            }
        } else { // Something got messed up
            String error = errorGobbler.getMessage();
            if (error.length() == 0) {
                error = gobbler.getMessage();
            }
            System.out.println(error);
            throw new RuntimeException(error);
        }

        String extracted = dateFormatter.format(new Date());
        Long size = f.length();

        if (lang == null)
            lang = "eng";

        Topic langTopic = getOrCreateLangTopic(tm, lang);
        Topic documentType = createDocumentTypeTopic(tm);
        Topic contentType = getContentType(tm);
        Topic timeExtractedType = getTimeExtractedType(tm);
        Topic fileSizeType = getSizeType(tm);

        documentTopic.addType(documentType);

        documentTopic.setData(contentType, langTopic, text);
        documentTopic.setData(timeExtractedType, langTopic, extracted);
        documentTopic.setData(fileSizeType, langTopic, "" + size);

        success = true;

    } catch (RuntimeException rte) {
        log("The OCR runtime failed for " + f.getPath());
        log(rte.getMessage());
    } catch (TopicMapException tme) { // Adding the topic failed
        log("Failed to add the file topic with the path " + f.getPath());
    } catch (IOException ioe) { // A file operation failed
        log(ioe.getMessage());
    } catch (InterruptedException ie) {
        log("The OCR process failed for the file " + f.getPath());
    } finally { // Cleanup
        tmp.delete();
    }

    return success;
}

From source file:com.github.ffremont.microservices.springboot.node.tasks.StartTask.java

/**
 * Syntaxe : java [-options] class [args...] (pour l'excution d'une classe)
 * ou java [-options] -jar jarfile [args...] (pour l'excution d'un fichier
 * JAR/* w ww . j a  v a2s. com*/
 *
 * @param task
 * @throws
 * com.github.ffremont.microservices.springboot.node.exceptions.FailStartedException
 * @throws
 * com.github.ffremont.microservices.springboot.node.exceptions.FileMsNotFoundException
 */
@Override
public void run(MicroServiceTask task) throws FailStartedException, FileMsNotFoundException {
    LOG.info("Dmarrage du micro service {}", task.getMs().getName());

    Path jar = helper.targetJarOf(task.getMs());
    Path workingDir = helper.targetDirOf(task.getMs());

    if (!Files.exists(jar)
            || !Files.exists(Paths.get(workingDir.toString(), InstallTask.CHECKSUM_FILE_NAME + ".txt"))) {
        throw new FileMsNotFoundException("Jar inexistant ou invalide");
    }

    String javaEx = this.javaExec.isEmpty() ? System.getProperty("java.home") + "/bin/java" : this.javaExec;

    ProcessBuilder ps = new ProcessBuilder(javaEx, "-jar", helper.targetJarOf(task.getMs()).toString(), "&");
    ps.directory(workingDir.toFile());

    try {
        Path consoleLog = Paths.get(workingDir.toString(), "console.log");
        ps.redirectOutput(consoleLog.toFile());
        ps.redirectError(consoleLog.toFile());

        LOG.info("Run de {}", ps.command().toString());
        ps.start();
    } catch (IOException ex) {
        throw new FailStartedException("Impossible de dmarrer le programme java : " + task.getMs().getId(),
                ex);
    }

    LOG.info("Micro service {} dmarr", task.getMs().getName());
}