Example usage for java.lang Process exitValue

List of usage examples for java.lang Process exitValue

Introduction

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

Prototype

public abstract int exitValue();

Source Link

Document

Returns the exit value for the process.

Usage

From source file:edu.clemson.cs.nestbed.server.management.deployment.ProgramDeploymentManagerImpl.java

public List<String> installTraceReceiver(List<MoteTestbedAssignment> interestingMotes) throws RemoteException {
    List<String> success = new ArrayList<String>();

    for (MoteTestbedAssignment mta : interestingMotes) {
        Mote mote = MoteManagerImpl.getInstance().getMote(mta.getMoteID());
        int address = mta.getMoteAddress();
        String moteSerialID = mote.getMoteSerialID();
        String tosPlatform = "telosb"; // Should really look this up
        String commPort = "/dev/motes/" + moteSerialID;

        try {/*  w ww .ja va2s  .c  o m*/

            ProcessBuilder processBuilder;

            log.info("Installing:  " + INSTALL + " " + TRACE_RECORDER_DIR + " " + tosPlatform + " " + address
                    + " " + commPort);

            processBuilder = new ProcessBuilder(INSTALL, TRACE_RECORDER_DIR, tosPlatform,
                    Integer.toString(address), commPort);
            processBuilder.redirectErrorStream(true);

            Process process = processBuilder.start();
            process.waitFor();

            int exitValue = process.exitValue();

            if (exitValue != 0) {
                log.error(moteSerialID + " -- Install failed with exit code: " + exitValue);
            }
            success.add(Integer.toString(address));

        } catch (Exception ex) {
            log.error("installTraceReceiver failed for mote: " + address, ex);
        }
    }

    return success;
}

From source file:com.yahoo.rdl.maven.ProcessRunner.java

public String run(List<String> command, ProcessBuilder processBuilder) throws IOException {
    Process process = processBuilder.start();
    try (StreamConsumer stdout = new StreamConsumer(process.getInputStream()).start()) {
        try (StreamConsumer stderr = new StreamConsumer(process.getErrorStream()).start()) {
            if (!process.waitFor(10, TimeUnit.SECONDS)) {
                throw new IOException("Process took longer than 10 seconds to execute: " + command);
            }//from w  ww  .  j av  a  2s  .c  o m
            if (process.exitValue() != 0) {
                String s = stderr.getContents();
                throw new IOException("command '" + StringUtils.join(command, " ") + "' produced error: " + s);
            }
        }
        return stdout.getContents();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.mskcc.cbio.importer.fetcher.internal.FirehoseFetcherImpl.java

/**
 * Method determines date of latest broad run.  runType
 * argument is one of "analyses" or "stddata".
 *
 * @param runType String//w w  w  .j  a va 2  s .  c  o m
 * @return Date
 * @throws Exception
 */
private Date getLatestBroadRun(String runType) throws Exception {

    // steup a default date for comparision
    Date latestRun = BROAD_DATE_FORMAT.parse("1918_05_11");

    Process process = Runtime.getRuntime().exec(getFirehoseGetScript() + " -r");
    process.waitFor();
    if (process.exitValue() != 0) {
        return latestRun;
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String lineOfOutput;
    while ((lineOfOutput = reader.readLine()) != null) {
        if (lineOfOutput.startsWith(runType)) {
            Matcher lineMatcher = FIREHOSE_GET_RUNS_LINE_REGEX.matcher(lineOfOutput);
            if (lineMatcher.find()) {
                // column is runtype__yyyy_mm_dd
                Matcher columnMatcher = FIREHOSE_GET_RUNS_COL_REGEX.matcher(lineMatcher.group(1));
                // parse date out of column and compare to the current latestRun
                if (columnMatcher.find()) {
                    Date thisRunDate = BROAD_DATE_FORMAT.parse(columnMatcher.group(2));
                    if (thisRunDate.after(latestRun)) {
                        latestRun = thisRunDate;
                    }
                }
            }
        }
    }

    // outta here
    return latestRun;
}

From source file:ape.NetworkDisconnectCommand.java

/**
 * This method actually executes the command that would disconnect the network
 *///from   w w  w  .java  2s.  c om
private boolean executecommand(double time) throws IOException {
    String cmd = "ifdown eth0 && sleep " + time + " && /etc/init.d/network restart";
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process p = null;

    try {
        p = pb.start();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    try {
        if (p.waitFor() != 0) {
            System.out.println(
                    "ERROR: Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");
            Main.logger
                    .info("ERROR: Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");

            ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "/etc/init.d/network restart");
            Process ptmp = tmp2.start();
            try {
                if (ptmp.waitFor() == 0)
                    System.out.println("Connection resumed");
                else {
                    System.out.println("Connection resume failed");
                    return false;
                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
                System.err.println("Catches an exception when trying to recover the network");
                return false;
            }

            return false;
        }
    } catch (InterruptedException e) {
        System.err.println("Executing Command catches an Interrupt, resume connection");
        ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "/etc/init.d/network restart");
        Process ptmp = tmp2.start();
        try {
            if (ptmp.waitFor() == 0)
                System.out.println("Connection Resumed");
            else {
                System.out.println("Connection Resumed Failed");
                return false;
            }
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            System.err.println("Catches an exception when trying to recover the network");
            return false;

        }
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.salsaw.msalsa.clustal.ClustalOmegaManager.java

@Override
public void callClustal(String clustalPath, ClustalFileMapper clustalFileMapper)
        throws IOException, InterruptedException, SALSAException {
    // Get program path to execute
    List<String> clustalProcessCommands = new ArrayList<String>();
    clustalProcessCommands.add(clustalPath);

    // Create the name of output files
    String inputFileName = FilenameUtils.getBaseName(clustalFileMapper.getInputFilePath());
    String inputFileFolderPath = FilenameUtils.getFullPath(clustalFileMapper.getInputFilePath());
    Path alignmentFilePath = Paths.get(inputFileFolderPath, inputFileName + "-aln.fasta");
    Path guideTreeFilePath = Paths.get(inputFileFolderPath, inputFileName + "-tree.dnd");

    // Set inside file mapper
    clustalFileMapper.setAlignmentFilePath(alignmentFilePath.toString());
    clustalFileMapper.setGuideTreeFilePath(guideTreeFilePath.toString());
    setClustalFileMapper(clustalFileMapper);

    // Create clustal omega data
    generateClustalArguments(clustalProcessCommands);

    // http://www.rgagnon.com/javadetails/java-0014.html
    ProcessBuilder builder = new ProcessBuilder(clustalProcessCommands);
    builder.redirectErrorStream(true);/*w w w.  j a v  a 2 s. co m*/
    System.out.println(builder.command());
    final Process process = builder.start();
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    process.waitFor();

    if (process.exitValue() != 0) {
        throw new SALSAException("Failed clustal omega call");
    }
}

From source file:de.smartics.maven.plugin.buildmetadata.scm.maven.ScmAccessInfo.java

/**
 * Fetches the version from the remote Git repository. The implementation uses
 * the Git Command Line Utils./*from  ww  w  .j a  va2s. c  o m*/
 *
 * @param repository the reference to the repository (currently not used).
 * @param remoteVersion the version to fetch.
 * @return the revision information.
 * @throws ScmException on any problem accessing the remote repository.
 */
public Revision fetchRemoteGitVersion(final ScmRepository repository, final ScmVersion remoteVersion)
        throws ScmException {
    try {
        final Commandline cl = GitCommandLineUtils.getBaseGitCommandLine(rootDirectory, "log");
        cl.createArg().setLine("-n 1");
        cl.createArg().setLine("--pretty=format:\"%H %ct\"");
        cl.createArg().setLine(remoteVersion.getName());
        final Process process = cl.execute();
        try {
            process.waitFor();
            final int exitValue = process.exitValue();
            if (exitValue != 0) {
                throw new ScmException("Cannot fetch remote version from repository (" + exitValue + "): "
                        + IOUtils.toString(process.getErrorStream()));
            }
            final String result = IOUtils.toString(process.getInputStream());
            final Revision revision = createRevision(result);
            return revision;
        } finally {
            process.destroy();
        }
    } catch (final Exception e) {
        throw new ScmException("Cannot fetch remote version from repository.", e);
    }
}

From source file:net.solarnetwork.node.control.ping.HttpRequesterJob.java

private void handleOSCommand(String command) {
    if (command == null) {
        return;/*from  ww  w  .  jav a2  s . c  o  m*/
    }
    ProcessBuilder pb = new ProcessBuilder(command.split("\\s+"));
    try {
        Process pr = pb.start();
        logInputStream(pr.getInputStream(), false);
        logInputStream(pr.getErrorStream(), true);
        pr.waitFor();
        if (pr.exitValue() == 0) {
            log.debug("Command [{}] executed", command);
            handleCommandSleep();
        } else {
            log.error("Error executing [{}], exit status: {}", command, pr.exitValue());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.moe.cli.executor.AbstractLinkExecutor.java

@Override
public void execute() throws IOException, URISyntaxException, InterruptedException, CheckArchitectureException,
        UnsupportedTypeException {//from   w  w w  . ja  v  a2s  .  c om

    //collect all header files
    List<String> headerList = new ArrayList<String>();
    if (headers != null) {
        for (String header : headers) {
            if (header != null && !header.isEmpty()) {
                File tmp = new File(header);
                if (tmp.isDirectory()) {
                    Collection<File> files = FileUtils.listFiles(tmp, new String[] { "h" }, true);
                    for (File file : files)
                        headerList.add(file.getAbsolutePath());
                } else {
                    headerList.add(header);
                }
            }
        }
    }

    List<String> frameworkList = new ArrayList<String>();
    Set<String> frameworksSearchPaths = new HashSet<String>();
    if (frameworks != null) {

        for (String framework : frameworks) {
            frameworkList.add(framework);
            File frFile = new File(framework);
            frameworksSearchPaths.add(frFile.getParent());
        }

    }

    // Initialize native libraries
    NatJGenNativeLoader.initNatives();

    // Read arguments
    MOEJavaProject project = new MOEJavaProject("", "/");

    boolean generated = true;
    File tmpDir = NatJFileUtils.getNewTempDirectory();
    if (javaSource == null) {

        //generate bindings for all frameworks
        String natJGenBody = NatjGenFrameworkConfig.generate(packageName, frameworksSearchPaths,
                tmpDir.getPath(), headerList);

        //generate bindings
        generated = generate(project, natJGenBody);
    } else {

        Set<URI> links = new HashSet<URI>();
        for (String jsource : javaSource) {
            links.add(new URI(jsource));
        }
        GrabUtils.downloadToFolder(links, tmpDir);
    }

    if (generated) {
        //try to compile generated jars
        File destinationJavacDir = new File(tmpDir, "result");
        destinationJavacDir.mkdir();

        String indePath = System.getenv("MOE_HOME");
        if (indePath != null && !indePath.isEmpty()) {
            String coreJar = indePath + File.separator + "sdk" + File.separator + "moe-core.jar";
            String iosJar = indePath + File.separator + "sdk" + File.separator + "moe-ios.jar";

            String compileList = createCompileFileList(tmpDir, javaSource != null ? null : packageName);

            String classPathArg = String.format("%s:%s", coreJar, iosJar);
            ProcessBuilder processBuilder = new ProcessBuilder("javac", "@" + compileList, "-cp", classPathArg,
                    "-d", destinationJavacDir.getPath());
            Process process = processBuilder.start();
            process.waitFor();

            if (process.exitValue() == 0 || headerList.size() == 0) {
                //try to create lib subdirectory
                File libTemp = new File(destinationJavacDir, "lib");
                if (!(libTemp.mkdir())) {
                    throw new IOException("Could not create temp directory: " + libTemp.getAbsolutePath());
                }

                //try to create bundle subdirectory
                File bundleTemp = new File(destinationJavacDir, "bundle");
                if (!(bundleTemp.mkdir())) {
                    throw new IOException("Could not create temp directory: " + bundleTemp.getAbsolutePath());
                }

                copyLibrary(libTemp, frameworkList);

                if (bundle != null) {
                    copyBundle(bundleTemp, bundle);
                }

                Map<String, String> flags = getManifestProperties(frameworkList);

                //create manifest file
                Manifest manifest = new Manifest();
                manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

                //Logic from CocoaPods; for more information visit https://github.com/CocoaPods/CocoaPods/issues/3537
                String moe_type = flags.get(MOE_TYPE);
                if (moe_type != null && moe_type.contains("static")) {
                    if (ldFlags != null && !ldFlags.isEmpty()) {
                        if (ldFlags.endsWith(";"))
                            ldFlags += "-ObjC;";
                        else
                            ldFlags += ";-ObjC;";
                    } else {
                        ldFlags = "-ObjC;";
                    }
                }

                if (ldFlags != null && !ldFlags.isEmpty()) {
                    flags.put("MOE_CUSTOM_LINKER_FLAGS", ldFlags);
                }

                for (Map.Entry<String, String> entry : flags.entrySet()) {
                    manifest.getMainAttributes().put(new Attributes.Name(entry.getKey()), entry.getValue());
                }

                //try to create manifest subdirectory
                File manifestTemp = new File(destinationJavacDir, "META-INF");
                if (!(manifestTemp.mkdir())) {
                    throw new IOException("Could not create temp directory: " + bundleTemp.getAbsolutePath());
                }

                String manifestFileName = "MANIFEST.MF";
                File manifestFile = new File(manifestTemp, manifestFileName);
                FileOutputStream manOut = new FileOutputStream(manifestFile);
                manifest.write(manOut);
                manOut.close();

                //try to pack custom content into jar
                File jarFile = new File(outFile);

                FileOutputStream jarFos = null;
                JarArchiveOutputStream target = null;
                try {
                    jarFos = new FileOutputStream(jarFile);
                    target = new JarArchiveOutputStream(jarFos);

                    for (File file : destinationJavacDir.listFiles()) {
                        ArchiveUtils.addFileToJar(destinationJavacDir, file, target);
                    }
                    target.close();

                } finally {
                    if (jarFos != null) {
                        jarFos.close();
                    }

                    if (target != null) {
                        target.close();
                    }
                }
            } else {
                throw new IOException("An error occured during process of bindings compilation");
            }
        } else {
            throw new IOException("Could not find system variable - MOE_HOME");
        }
    } else {
        throw new IOException("An error occured during process of bindings generation");
    }

}

From source file:org.hyperic.util.exec.Execute.java

protected void waitFor(Process process) {
    try {//  ww w .  ja va  2 s . c o m
        process.waitFor();
        setExitValue(process.exitValue());
    } catch (InterruptedException e) {
        log.info("waitFor() interrupted ");
    }
}

From source file:org.codelibs.fess.job.SuggestJob.java

protected void executeSuggestCreator() {
    final List<String> cmdList = new ArrayList<>();
    final String cpSeparator = SystemUtils.IS_OS_WINDOWS ? ";" : ":";
    final ServletContext servletContext = ComponentUtil.getComponent(ServletContext.class);
    final ProcessHelper processHelper = ComponentUtil.getProcessHelper();
    final FessConfig fessConfig = ComponentUtil.getFessConfig();

    cmdList.add(fessConfig.getJavaCommandPath());

    // -cp/*  ww w .ja  va  2s  . c o m*/
    cmdList.add("-cp");
    final StringBuilder buf = new StringBuilder(100);
    ResourceUtil.getOverrideConfPath().ifPresent(p -> {
        buf.append(p);
        buf.append(cpSeparator);
    });
    final String confPath = System.getProperty(Constants.FESS_CONF_PATH);
    if (StringUtil.isNotBlank(confPath)) {
        buf.append(confPath);
        buf.append(cpSeparator);
    }
    // WEB-INF/env/suggest/resources
    buf.append("WEB-INF");
    buf.append(File.separator);
    buf.append("env");
    buf.append(File.separator);
    buf.append("suggest");
    buf.append(File.separator);
    buf.append("resources");
    buf.append(cpSeparator);
    // WEB-INF/classes
    buf.append("WEB-INF");
    buf.append(File.separator);
    buf.append("classes");
    // target/classes
    final String userDir = System.getProperty("user.dir");
    final File targetDir = new File(userDir, "target");
    final File targetClassesDir = new File(targetDir, "classes");
    if (targetClassesDir.isDirectory()) {
        buf.append(cpSeparator);
        buf.append(targetClassesDir.getAbsolutePath());
    }
    // WEB-INF/lib
    appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/lib")),
            "WEB-INF" + File.separator + "lib" + File.separator);
    // WEB-INF/env/suggest/lib
    appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/env/suggest/lib")), "WEB-INF"
            + File.separator + "env" + File.separator + "suggest" + File.separator + "lib" + File.separator);
    final File targetLibDir = new File(targetDir, "fess" + File.separator + "WEB-INF" + File.separator + "lib");
    if (targetLibDir.isDirectory()) {
        appendJarFile(cpSeparator, buf, targetLibDir, targetLibDir.getAbsolutePath() + File.separator);
    }
    cmdList.add(buf.toString());

    if (useLocalElasticsearch) {
        final String transportAddresses = System.getProperty(Constants.FESS_ES_TRANSPORT_ADDRESSES);
        if (StringUtil.isNotBlank(transportAddresses)) {
            cmdList.add("-D" + Constants.FESS_ES_TRANSPORT_ADDRESSES + "=" + transportAddresses);
        }
    }

    final String systemLastaEnv = System.getProperty("lasta.env");
    if (StringUtil.isNotBlank(systemLastaEnv)) {
        if (systemLastaEnv.equals("web")) {
            cmdList.add("-Dlasta.env=suggest");
        } else {
            cmdList.add("-Dlasta.env=" + systemLastaEnv);
        }
    } else if (StringUtil.isNotBlank(lastaEnv)) {
        cmdList.add("-Dlasta.env=" + lastaEnv);
    }

    addSystemProperty(cmdList, Constants.FESS_CONF_PATH, null, null);
    cmdList.add("-Dfess.suggest.process=true");
    if (logFilePath == null) {
        final String value = System.getProperty("fess.log.path");
        logFilePath = value != null ? value : new File(targetDir, "logs").getAbsolutePath();
    }
    cmdList.add("-Dfess.log.path=" + logFilePath);
    addSystemProperty(cmdList, "fess.log.name", "fess-suggest", "-suggest");
    if (logLevel == null) {
        addSystemProperty(cmdList, "fess.log.level", null, null);
    } else {
        cmdList.add("-Dfess.log.level=" + logLevel);
    }
    stream(fessConfig.getJvmSuggestOptionsAsArray())
            .of(stream -> stream.filter(StringUtil::isNotBlank).forEach(value -> cmdList.add(value)));

    File ownTmpDir = null;
    final String tmpDir = System.getProperty("java.io.tmpdir");
    if (fessConfig.isUseOwnTmpDir() && StringUtil.isNotBlank(tmpDir)) {
        ownTmpDir = new File(tmpDir, "fessTmpDir_" + sessionId);
        if (ownTmpDir.mkdirs()) {
            cmdList.add("-Djava.io.tmpdir=" + ownTmpDir.getAbsolutePath());
        } else {
            ownTmpDir = null;
        }
    }

    if (StringUtil.isNotBlank(jvmOptions)) {
        split(jvmOptions, " ").of(stream -> stream.filter(StringUtil::isNotBlank).forEach(s -> cmdList.add(s)));
    }

    cmdList.add(SuggestCreator.class.getCanonicalName());

    cmdList.add("--sessionId");
    cmdList.add(sessionId);

    File propFile = null;
    try {
        cmdList.add("-p");
        propFile = File.createTempFile("suggest_", ".properties");
        cmdList.add(propFile.getAbsolutePath());
        try (FileOutputStream out = new FileOutputStream(propFile)) {
            final Properties prop = new Properties();
            prop.putAll(ComponentUtil.getSystemProperties());
            prop.store(out, cmdList.toString());
        }

        final File baseDir = new File(servletContext.getRealPath("/WEB-INF")).getParentFile();

        if (logger.isInfoEnabled()) {
            logger.info("SuggestCreator: \nDirectory=" + baseDir + "\nOptions=" + cmdList);
        }

        final JobProcess jobProcess = processHelper.startProcess(sessionId, cmdList, pb -> {
            pb.directory(baseDir);
            pb.redirectErrorStream(true);
        });

        final InputStreamThread it = jobProcess.getInputStreamThread();
        it.start();

        final Process currentProcess = jobProcess.getProcess();
        currentProcess.waitFor();
        it.join(5000);

        final int exitValue = currentProcess.exitValue();

        if (logger.isInfoEnabled()) {
            logger.info("SuggestCreator: Exit Code=" + exitValue + " - SuggestCreator Process Output:\n"
                    + it.getOutput());
        }
        if (exitValue != 0) {
            throw new FessSystemException("Exit Code: " + exitValue + "\nOutput:\n" + it.getOutput());
        }
        ComponentUtil.getPopularWordHelper().clearCache();
    } catch (final FessSystemException e) {
        throw e;
    } catch (final InterruptedException e) {
        logger.warn("SuggestCreator Process interrupted.");
    } catch (final Exception e) {
        throw new FessSystemException("SuggestCreator Process terminated.", e);
    } finally {
        try {
            processHelper.destroyProcess(sessionId);
        } finally {
            if (propFile != null && !propFile.delete()) {
                logger.warn("Failed to delete {}.", propFile.getAbsolutePath());
            }
            deleteTempDir(ownTmpDir);
        }
    }
}