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:io.hops.hopsworks.api.zeppelin.util.ZeppelinResource.java

private boolean isProccessAlive(String pid) {
    String[] command = { "kill", "-0", pid };
    ProcessBuilder pb = new ProcessBuilder(command);
    if (pid == null) {
        return false;
    }/*from   w ww  .j  av  a2 s  .com*/

    //TODO: We should clear the environment variables before launching the 
    // redirect stdout and stderr for child process to the zeppelin/project/logs file.
    int exitValue;
    try {
        Process p = pb.start();
        p.waitFor();
        exitValue = p.exitValue();
    } catch (IOException | InterruptedException ex) {

        logger.log(Level.WARNING, "Problem testing Zeppelin Interpreter: {0}", ex.toString());
        //if the pid file exists but we can not test if it is alive then
        //we answer true, b/c pid files are deleted when a process is killed.
        return true;
    }
    return exitValue == 0;
}

From source file:net.landora.video.mplayer.MPlayerParser.java

private MPlayerInfoParse mplayerIdentify(File f, Integer videoId, Integer audioId, Integer subtitleId)
        throws IOException, InterruptedException {
    //mplayer -frames 0 -msglevel identify=9 "$1" -vo null -ao null 2>/dev/null | grep "^ID"
    List<String> cmd = new ArrayList<String>();
    cmd.add(ProgramsAddon.getInstance().getConfiguredPath(CommonPrograms.MPLAYER));
    cmd.add("-frames");
    cmd.add("0");
    cmd.add("-msglevel");
    cmd.add("identify=9");
    cmd.add("-vo");
    cmd.add("null");
    cmd.add("-ao");
    cmd.add("null");

    if (videoId != null) {
        cmd.add("-vid");
        cmd.add(videoId.toString());/*from w w  w .  j  a  v a  2  s.  c  o  m*/
    }

    if (audioId != null) {
        cmd.add("-aid");
        cmd.add(audioId.toString());
    }

    if (subtitleId != null) {
        cmd.add("-sid");
        cmd.add(subtitleId.toString());
    }

    cmd.add(f.getAbsolutePath());

    ProcessBuilder process = new ProcessBuilder(cmd);
    process.redirectErrorStream(true);
    Process p = process.start();

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

    Matcher infoMatcher = dataPattern.matcher(buffer.toString());
    MPlayerInfoParse result = new MPlayerInfoParse();
    while (infoMatcher.find()) {
        result.add(infoMatcher.group(1), infoMatcher.group(2));
    }

    return result;
}

From source file:org.openlmis.fulfillment.ExportSchemaFlywayCallback.java

@Override
public void afterMigrate(Connection connection) {
    XLOGGER.entry(connection);/*  w w w. ja  v  a2  s.c om*/

    XLOGGER.info("After migrations, exporting db schema");

    int exitCode = 0;
    try {
        schemaName = Optional.ofNullable(schemaName).orElse("fulfillment");

        Process proc = Runtime.getRuntime().exec("/app/export_schema.sh " + schemaName);

        StreamGobbler streamGobbler = new StreamGobbler(proc.getInputStream(), XLOGGER::info);
        Executors.newSingleThreadExecutor().submit(streamGobbler);

        exitCode = proc.waitFor();
    } catch (Exception ex) {
        XLOGGER.warn("Exporting db schema failed with message: " + ex);
    }

    XLOGGER.exit(exitCode);
}

From source file:com.atlassian.launchpad.jira.gerrittabpanel.GerritTabPanel.java

@Override
public List<IssueAction> getActions(Issue issue, User remoteUser) {
    List<IssueAction> messages = new ArrayList<IssueAction>();
    System.err.println(USER);/*from  w w  w .  j  a va 2 s  .  c  om*/
    //read and validate the Gerrit commit hash
    CustomField gerritLinkFieldContent = ComponentAccessor.getCustomFieldManager()
            .getCustomFieldObjectByName(GERRIT_ID_FIELD_NAME);
    if (gerritLinkFieldContent == null) {
        messages.add(new GenericMessageAction("\"" + GERRIT_ID_FIELD_NAME
                + "\" custom field not available. Cannot process Gerrit Review comments"));
        return messages;
    }

    Object gitHashFieldObj = issue.getCustomFieldValue(gerritLinkFieldContent);
    if (gitHashFieldObj == null) {
        messages.add(new GenericMessageAction("\"" + GERRIT_ID_FIELD_NAME
                + "\" not provided. Please provide Gerrit ID to see review comments for this issue."));
        return messages;
    }

    String gitHash = gitHashFieldObj.toString().trim();
    if (gitHash.length() == 0) {
        messages.add(new GenericMessageAction(
                "To view related Gerrit review comments for this issue please provide the Git Commit Hash"));
        return messages;
    }

    else if (!isValidGitHash(gitHash)) {
        messages.add(new GenericMessageAction("Gerrit Commit ID not properly formatted"));
        return messages;
    }

    //frame command to access SSH API
    String sshCom = "ssh -i /home/jira/.ssh/id_rsa -p " + PORT + " " + USER + "@" + HOST
            + " gerrit query --format=json --current-patch-set --comments change:" + gitHash;

    try {
        Process p = Runtime.getRuntime().exec(sshCom);
        p.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = reader.readLine();
        if (line != null) {
            JSONTokener tokener = new JSONTokener(line);
            JSONObject finalResult = new JSONObject(tokener);
            if (!finalResult.has(KEY_COMMENTS)) {
                messages.add(new GenericMessageAction("No comments available for this Gerrit review."));
                return messages;
            }

            JSONArray commentsJson = finalResult.getJSONArray(KEY_COMMENTS);
            for (int k = 0; k < commentsJson.length(); k++) {
                JSONObject commentJson = commentsJson.getJSONObject(k);
                GerritCommentAction commentAction = createCommentActionFromJSON(commentJson);
                messages.add(commentAction);
            }

            String status = finalResult.getString("status");
            messages.add(new GenericMessageAction("<h2>Gerrit Status: " + status + "</h2>"));

            //reverse message order to display most recent first
            Collections.reverse(messages);
        }

    } catch (JSONException e) {
        // JSON returned from SSH API did not contain proper keys
        e.printStackTrace();
    } catch (InterruptedException e) {
        // Exception in attempting to execute the ssh command
        e.printStackTrace();
    } catch (IOException e) {
        // Exception in reading from the input stream
        e.printStackTrace();
    }

    return messages;
}

From source file:com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlistParser.java

public void convert(File projectFile, File destinationProjectFile) throws IOException {
    if (!SystemUtils.IS_OS_MAC_OSX) {
        throw new UnsupportedOperationException(
                "The pbxproj file conversion can only be performed on a Mac OS X "
                        + "operating system as the Mac OS X specific tool 'plutil' gets called.");
    }/*from w ww  . j a va2  s .  co m*/
    Process exec = Runtime.getRuntime().exec(new String[] { "plutil", "-convert", "xml1", "-o",
            destinationProjectFile.getAbsolutePath(), projectFile.getAbsolutePath() });
    try {
        exec.waitFor();
    } catch (InterruptedException e) {
    }

    if (exec.exitValue() != 0) {
        throw new RuntimeException("Could not convert file (Exit Code: " + exec.exitValue() + ")");
    }
}

From source file:org.ednovo.gooru.application.converter.GooruImageUtil.java

public void scaleImageUsingImageMagick(String srcFilePath, int width, int height, String destFilePath)
        throws Exception {
    try {//from   w  w  w .j  a va2 s .c  om
        String resizeCommand = new String(
                "/usr/bin/gm@convert@" + srcFilePath + "@-resize@" + width + X + height + "@" + destFilePath);
        String cmdArgs[] = resizeCommand.split("@");
        Process thumsProcess = Runtime.getRuntime().exec(cmdArgs);
        thumsProcess.waitFor();

        String line;
        StringBuffer sb = new StringBuffer();

        BufferedReader in = new BufferedReader(new InputStreamReader(thumsProcess.getInputStream()));
        while ((line = in.readLine()) != null) {
            sb.append(line).append("\n");
        }
        in.close();

        logger.info("output : {} -  Status : {} - Command : " + StringUtils.join(cmdArgs, " "), sb.toString(),
                thumsProcess.exitValue() + "");

    } catch (Exception e) {
        logger.error("something went wrong while converting image", e);
    }

}

From source file:com.bekwam.resignator.SettingsController.java

private boolean validateJDKHome(String jdkHome) {

    Preconditions.checkNotNull(jdkHome);

    Map<Path, Integer> cmdsAndResults = new LinkedHashMap<>();
    cmdsAndResults.put(Paths.get(jdkHome, "bin", "keytool"), 0);
    cmdsAndResults.put(Paths.get(jdkHome, "bin", "jarsigner"), 0);
    cmdsAndResults.put(Paths.get(jdkHome, "bin", "jar"), 1);

    try {// w w  w  .  j a va 2 s . c  o m
        piSettings.setVisible(true);
        piSettings.setProgress(0.0d);

        for (Path cmd : cmdsAndResults.keySet()) {

            if (logger.isDebugEnabled()) {
                logger.debug("[VAL JDKHOME] cmd={}", cmd.toString());
            }

            Process p = Runtime.getRuntime().exec(new String[] { cmd.toString() });

            int exitValue = p.waitFor();

            if (logger.isDebugEnabled()) {
                logger.debug("[VAL JDKHOME] retval={}", exitValue);
            }

            if (exitValue != cmdsAndResults.get(cmd)) { // lookup expected return code
                return false;
            }

            piSettings.setProgress(piSettings.getProgress() + 1 / cmdsAndResults.size());
        }
    } catch (IOException | InterruptedException exc) {
        logger.error("error running '{" + jdkHome + "}'", exc);
        return false;
    } finally {
        piSettings.setVisible(false);
        piSettings.setProgress(0.0d);
    }

    return true;
}

From source file:dpfmanager.shell.modules.periodic.core.ControllerWindows.java

@Override
public boolean savePeriodicalCheck(PeriodicCheck check) {
    try {/*from ww  w.jav  a 2 s .c om*/
        createIfNotExistsVBS();
        String params = buildCommandArguments(check);
        String exe = asString(getVBSPath());
        String dpfCommand = "wscript.exe " + exe + " " + params;
        String command = "";
        Periodicity periodicity = check.getPeriodicity();
        switch (periodicity.getMode()) {
        case DAILY:
            command = "schtasks /create /tn \"" + check.getUuid() + "\" /tr \"" + dpfCommand
                    + "\" /sc daily /st " + periodicity.getTimeString();
            break;
        case WEEKLY:
            command = "schtasks /create /tn \"" + check.getUuid() + "\" /tr \"" + dpfCommand
                    + "\" /sc weekly /d " + parseDaysOfWeek(periodicity.getDaysOfWeek()) + " /st "
                    + periodicity.getTimeString();
            break;
        case MONTHLY:
            command = "schtasks /create /tn \"" + check.getUuid() + "\" /tr \"" + dpfCommand
                    + "\" /sc monthly /d " + periodicity.getDayOfMonth() + " /st "
                    + periodicity.getTimeString();
            break;
        }

        // Run command
        Process proc = Runtime.getRuntime().exec(command);
        proc.waitFor();
        return (proc.exitValue() == 0);
    } catch (Exception e) {
        return false;
    }
}

From source file:com.epam.controllers.pages.graphviz.GraphViz.java

/**
 * It will call the external dot program, and return the image in
 * binary format./*from w  ww  . ja  va2s  .  c o  m*/
 * @param dot Source of the graph (in dot language).
 * @param type Type of the output image to be produced, e.g.: gif, dot, fig, pdf, ps, svg, png.
 * @return The image of the graph in .gif format.
 */
private byte[] get_img_stream(File dot, String type) {
    File img;
    byte[] img_stream = null;

    try {
        img = File.createTempFile("graph_", "." + type, new File(GraphViz.TEMP_DIR));
        Runtime rt = Runtime.getRuntime();

        // patch by Mike Chenault
        String[] args = { DOT, "-T" + type, dot.getAbsolutePath(), "-o", img.getAbsolutePath() };
        Process p = rt.exec(args);

        p.waitFor();

        FileInputStream in = new FileInputStream(img.getAbsolutePath());
        img_stream = new byte[in.available()];
        in.read(img_stream);
        // Close it if we need to
        if (in != null)
            in.close();

        if (img.delete() == false)
            log.warn("Warning: " + img.getAbsolutePath() + " could not be deleted!");
    } catch (java.io.IOException ioe) {
        log.warn("Error:    in I/O processing of tempfile in dir " + GraphViz.TEMP_DIR + "\n");
        log.warn("       or in calling external command");
        log.error("stacktrace", ioe);
    } catch (java.lang.InterruptedException ie) {
        log.error("Error: the execution of the external program was interrupted", ie);
    }

    return img_stream;
}

From source file:com.thoughtworks.go.agent.AgentProcessParentImplTest.java

@Test
public void shouldLogInterruptOnAgentProcess() throws InterruptedException {
    final List<String> cmd = new ArrayList<>();
    try (LogFixture logFixture = logFixtureFor(AgentProcessParentImpl.class, Level.DEBUG)) {
        Process subProcess = mockProcess();
        when(subProcess.waitFor()).thenThrow(new InterruptedException("bang bang!"));
        AgentProcessParentImpl bootstrapper = createBootstrapper(cmd, subProcess);
        int returnCode = bootstrapper.run("bootstrapper_version", "bar", getURLGenerator(), new HashMap<>(),
                context());//from   ww  w. j a v a2  s. co m
        assertThat(returnCode, is(0));
        assertThat(logFixture.contains(Level.ERROR,
                "Agent was interrupted. Terminating agent and respawning. java.lang.InterruptedException: bang bang!"),
                is(true));
        verify(subProcess).destroy();
    }
}