Example usage for java.lang Process waitFor

List of usage examples for java.lang Process waitFor

Introduction

In this page you can find the example usage for java.lang Process waitFor.

Prototype

public abstract int waitFor() throws InterruptedException;

Source Link

Document

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Usage

From source file:edu.wisc.doit.tcrypt.TokenEncryptDecryptIT.java

@Test
public void testJavaEncOpenSSLDec() throws Exception {
    //Encrypt with Java
    final String expected = "foobar";
    final String encrypted = this.tokenEncrypter.encrypt(expected);

    //Decrypt with OpenSSL
    final File decryptFileScript = setupTempFile("decryptToken.sh");
    decryptFileScript.setExecutable(true);

    final File privateKey = setupTempFile("my.wisc.edu-private.pem");

    final ProcessBuilder pb = new ProcessBuilder(decryptFileScript.getAbsolutePath(),
            privateKey.getAbsolutePath(), encrypted);

    final Process p = pb.start();
    final int ret = p.waitFor();
    if (ret != 0) {
        final String pOut = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pOut);
        final String pErr = IOUtils.toString(p.getErrorStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pErr);
    }/*from w w  w  . j  av a2s  .  c o m*/
    assertEquals(0, ret);

    final String actual = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();

    //Verify
    assertEquals(expected, actual);
}

From source file:com.ikon.servlet.TextToSpeechServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String cmd = "espeak -v mb-es1 -f input.txt | mbrola -e /usr/share/mbrola/voices/es1 - -.wav "
            + "| oggenc -Q - -o output.ogg";
    String text = WebUtils.getString(request, "text");
    String docPath = WebUtils.getString(request, "docPath");
    response.setContentType("audio/ogg");
    FileInputStream fis = null;//w  w w  . j ava 2  s.  co  m
    OutputStream os = null;

    try {
        if (!text.equals("")) {
            FileUtils.writeStringToFile(new File("input.txt"), text);
        } else if (!docPath.equals("")) {
            InputStream is = OKMDocument.getInstance().getContent(null, docPath, false);
            Document doc = OKMDocument.getInstance().getProperties(null, docPath);
            DocConverter.getInstance().doc2txt(is, doc.getMimeType(), new File("input.txt"));
        }

        // Convert to voice
        ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", cmd);
        Process process = pb.start();
        process.waitFor();
        String info = IOUtils.toString(process.getInputStream());
        process.destroy();

        if (process.exitValue() == 1) {
            log.warn(info);
        }

        // Send to client
        os = response.getOutputStream();
        fis = new FileInputStream("output.ogg");
        IOUtils.copy(fis, os);
        os.flush();
    } catch (InterruptedException e) {
        log.warn(e.getMessage(), e);
    } catch (IOException e) {
        log.warn(e.getMessage(), e);
    } catch (PathNotFoundException e) {
        log.warn(e.getMessage(), e);
    } catch (AccessDeniedException e) {
        log.warn(e.getMessage(), e);
    } catch (RepositoryException e) {
        log.warn(e.getMessage(), e);
    } catch (DatabaseException e) {
        log.warn(e.getMessage(), e);
    } catch (ConversionException e) {
        log.warn(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(os);
    }
}

From source file:com.ms.commons.standalone.pojo.StandaloneJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    JobDataMap dataMap = context.getMergedJobDataMap();
    String baseStandalonePath = dataMap.getString("baseStandalonePath");
    CronJob cronJob = (CronJob) dataMap.get("cronJob");
    try {//w  ww.ja va2s  . com
        modifyDataSourceProperties(cronJob.getFullClassName(), cronJob.getIdentity(), baseStandalonePath);
    } catch (Exception e1) {
        logger.warn("?job?msun.datasource.properties??"
                + cronJob.getIdentity() + "", e1);
    }

    String cmd = String.format("/bin/bash %s/bin/jobRunner.sh start %s", baseStandalonePath,
            cronJob.getFullClassName());
    Runtime runtime = Runtime.getRuntime();
    Process process = null;
    try {
        process = runtime.exec(cmd);
        process.waitFor();
    } catch (Exception e) {
        logger.error("runtime.exec cmd: " + cmd + " failed");
        throw new JobExecutionException(e);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:com.kurento.kmf.repository.test.OneRecordingServerTest.java

protected void uploadFileWithCURL(String uploadURL, File fileToUpload)
        throws FileNotFoundException, IOException {

    log.info("Start uploading file with curl");
    long startTime = System.currentTimeMillis();

    ProcessBuilder builder = new ProcessBuilder("curl", "-i", "-F",
            "filedata=@" + fileToUpload.getAbsolutePath(), uploadURL);
    builder.redirectOutput();//  w  ww . ja v a  2  s  .  c  o m
    Process process = builder.start();
    try {
        process.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    long duration = System.currentTimeMillis() - startTime;
    log.info("Finished uploading content in " + (((double) duration) / 1000) + " seconds.");
}

From source file:com.uber.hoodie.cli.commands.RecordsCommand.java

@CliCommand(value = "records deduplicate", help = "De-duplicate a partition path contains duplicates & produce repaired files to replace with")
public String deduplicate(@CliOption(key = {
        "duplicatedPartitionPath" }, help = "Partition Path containing the duplicates") final String duplicatedPartitionPath,
        @CliOption(key = {/*from ww w  .j  av  a 2  s .c  o  m*/
                "repairedOutputPath" }, help = "Location to place the repaired files") final String repairedOutputPath,
        @CliOption(key = {
                "sparkProperties" }, help = "Spark Properites File Path") final String sparkPropertiesPath)
        throws Exception {
    SparkLauncher sparkLauncher = SparkUtil.initLauncher(sparkPropertiesPath);
    sparkLauncher.addAppArgs(SparkMain.SparkCommand.DEDUPLICATE.toString(), duplicatedPartitionPath,
            repairedOutputPath, HoodieCLI.tableMetadata.getBasePath());
    Process process = sparkLauncher.launch();
    InputStreamConsumer.captureOutput(process);
    int exitCode = process.waitFor();

    if (exitCode != 0) {
        return "Deduplicated files placed in:  " + repairedOutputPath;
    }
    return "Deduplication failed ";
}

From source file:com.anosym.webcmd.web.SSHTerminalController.java

@SuppressWarnings({ "UseSpecificCatch", "BroadCatchBlock", "TooBroadCatch" })
public void handleCommand() {
    try {/*from w  w w .  ja  va2s  . com*/
        String command = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
                .get("ssh-terminal-command");
        String cmd[] = command.trim().split(" ");
        System.out.println("Command: " + Arrays.toString(cmd));
        Process p = Runtime.getRuntime().exec(cmd);
        p.waitFor();
        InputStream inn = p.getInputStream();
        int count = inn.available();
        byte[] buffer = new byte[count];
        //wait for the input to be available.
        inn.read(buffer);
        //            String result = new String(buffer);
        //            SSHTerminalResponse response = new SSHTerminalResponse(result, SSHTerminalResponse.TerminalResponseType.COMPLETE);
        //            RequestContext rc = RequestContext.getCurrentInstance();
        //            rc.addCallbackParam("response", response);
        //            System.out.println("Response: " + result);
    } catch (Exception ex) {
        //            Logger.getLogger(SSHTerminalController.class.getName()).log(Level.SEVERE, null, ex);
        //            String result = ExceptionUtils.getFullStackTrace(ex);
        //            SSHTerminalResponse response = new SSHTerminalResponse(result, SSHTerminalResponse.TerminalResponseType.COMPLETE);
        //            RequestContext rc = RequestContext.getCurrentInstance();
        //            rc.addCallbackParam("response", response);
    }

}

From source file:com.roche.iceboar.downloader.JREDownloader.java

private boolean canUseUnzippedJre() {
    String path = settings.getUnzippedJrePathFromCache();
    if (StringUtils.isBlank(path)) {
        return false;
    }//  w w  w . j  ava  2  s . c o m
    ExecutableCommand cmd = executableCommandFactory.createJavaGetVersionNumberCommand(path);
    int exitValue = -1;
    try {
        Process exec = cmd.exec();
        exitValue = exec.waitFor();
        System.out.println("Check Java version from cache, exit Value: " + exitValue);
    } catch (Exception e) {
        System.out.println("Can't use unzipped JRE. Exception message: " + e.getMessage());
    }
    return exitValue == 0;
}

From source file:edu.northwestern.bioinformatics.studycalendar.utility.osgimosis.BidirectionalObjectStoreTest.java

private Process performMemoryTest(String refType) throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder("java", "-Xmx16M", "-cp", "target/classes:target/test/classes",
            MemTest.class.getName(), refType);
    builder.redirectErrorStream(true);//from  w ww  . ja  v a2  s  .com
    builder.directory(detectBaseDirectory());
    Process p = builder.start();
    p.waitFor();
    IOUtils.copy(p.getInputStream(), System.out);
    return p;
}

From source file:ch.unibas.fittingwizard.infrastructure.base.PythonScriptRunner.java

private int run(File scriptName) {
    logger.info("Running python script\n" + pb.command() + "\nin directory:\n" + pb.directory()
            + "\nwith environment:\n" + pb.environment());

    int exitCode = 0;
    try {/*w ww. ja va 2 s .c  om*/
        Process p = pb.start();
        exitCode = p.waitFor();
    } catch (Exception e) {
        throw new RuntimeException(String.format("Python script [%s] failed.", scriptName.getName()), e);
    }
    logger.info("Python return value: " + exitCode);
    if (exitCode != 0) {
        throw new ScriptExecutionException(
                String.format("Python script [%s] did not exit correctly. Exit code: %s", scriptName.getName(),
                        String.valueOf(exitCode)));
    }

    return exitCode;
}

From source file:azkaban.metric.GangliaMetricEmitter.java

/**
 * Report metric by executing command line interface of gmetrics
 * {@inheritDoc}//  w w w  .jav a2 s .  co  m
 * @see azkaban.metric.IMetricEmitter#reportMetric(azkaban.metric.IMetric)
 */
@Override
public void reportMetric(final IMetric<?> metric) throws MetricException {
    String gangliaCommand = buildCommand(metric);

    if (gangliaCommand != null) {
        // executes shell command to report metric to ganglia dashboard
        try {
            Process emission = Runtime.getRuntime().exec(gangliaCommand);
            int exitCode;
            exitCode = emission.waitFor();
            if (exitCode != 0) {
                throw new MetricException("Failed to report metric using gmetric");
            }
        } catch (Exception e) {
            throw new MetricException("Failed to report metric using gmetric");
        }
    } else {
        throw new MetricException("Failed to build ganglia Command");
    }
}