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:ape.RemountFileSysReadOnlyCommand.java

public boolean runImpl(String[] args) throws ParseException, IOException {
    String cmd = "echo u > /proc/sysrq-trigger";
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);/*from   w w w  .j  a  v a 2  s.  com*/
    Process p = null;

    try {
        p = pb.start();
    } catch (IOException e) {
        System.err.println("Executing remount catches IOException");
        e.printStackTrace();
        return false;
    }

    // If the process returns a non-zero value, there is some error executing the command
    try {
        if (p.waitFor() != 0) {
            System.err.println("Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");
            return false;
        }
    } catch (InterruptedException e) {
        System.err.println("Executing '" + cmd + "' was interrupted");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:edu.cornell.med.icb.R.RUtils.java

/**
 * Can be used to start a rserve instance.
 * @param threadPool The ExecutorService used to start the Rserve process
 * @param rServeCommand Full path to command used to start Rserve process
 * @param host Host where the command should be sent
 * @param port Port number where the command should be sent
 * @param username Username to send to the server if authentication is required
 * @param password Password to send to the server if authentication is required
 * @return The return value from the Rserve instance
 *///from   w w w  . j a  v a  2s  .  c  o  m
static Future<Integer> startup(final ExecutorService threadPool, final String rServeCommand, final String host,
        final int port, final String username, final String password) {
    if (LOG.isInfoEnabled()) {
        LOG.info("Attempting to start Rserve on " + host + ":" + port);
    }

    return threadPool.submit(new Callable<Integer>() {
        public Integer call() throws IOException {
            final List<String> commands = new ArrayList<String>();

            // if the host is not local, use ssh to exec the command
            if (!"localhost".equals(host) && !"127.0.0.1".equals(host)
                    && !InetAddress.getLocalHost().equals(InetAddress.getByName(host))) {
                commands.add("ssh");
                commands.add(host);
            }

            // TODO - this will fail when spaces are in the the path to the executable
            CollectionUtils.addAll(commands, rServeCommand.split(" "));
            commands.add("--RS-port");
            commands.add(Integer.toString(port));

            final String[] command = commands.toArray(new String[commands.size()]);
            LOG.debug(ArrayUtils.toString(commands));

            final ProcessBuilder builder = new ProcessBuilder(command);
            builder.redirectErrorStream(true);
            final Process process = builder.start();
            BufferedReader br = null;
            try {
                final InputStream is = process.getInputStream();
                final InputStreamReader isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(host + ":" + port + "> " + line);
                    }
                }

                process.waitFor();
                if (LOG.isInfoEnabled()) {
                    LOG.info("Rserve on " + host + ":" + port + " terminated");
                }
            } catch (InterruptedException e) {
                LOG.error("Interrupted!", e);
                process.destroy();
                Thread.currentThread().interrupt();
            } finally {
                IOUtils.closeQuietly(br);
            }

            final int exitValue = process.exitValue();
            if (LOG.isInfoEnabled()) {
                LOG.info("Rserve on " + host + ":" + port + " returned " + exitValue);
            }
            return exitValue;
        }
    });
}

From source file:ape.KernelPanicCommand.java

public boolean runImpl(String[] args) throws ParseException, IOException {
    String cmd = "echo c > /proc/sysrq-trigger";
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);// w  w  w.ja v  a 2 s. co m
    Process p = null;

    try {
        p = pb.start();
    } catch (IOException e) {
        System.err.println("Executing kernel panic catches IOException");
        e.printStackTrace();
        return false;
    }

    // If the process returns a non-zero value, there is some error executing the command
    try {
        if (p.waitFor() != 0) {
            System.err.println("Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");
            return false;
        }
    } catch (InterruptedException e) {
        System.err.println("Executing '" + cmd + "' was interrupted");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.fcrepo.importexport.integration.ExecutableJarIT.java

@Test
public void testConfigFileExport() throws Exception {
    // Create a repository resource
    final FcrepoResponse response = create(url);
    assertEquals(SC_CREATED, response.getStatusCode());
    assertEquals(url, response.getLocation());

    // Create test config file
    final File configFile = File.createTempFile("config-test", ".txt");
    final FileWriter writer = new FileWriter(configFile);
    writer.append("-d\n");
    writer.append(TARGET_DIR);/*from  w w  w.j  av  a  2 s. c  o  m*/
    writer.append("\n");
    writer.append("-m\n");
    writer.append("export\n");
    writer.append("-r\n");
    writer.append(url.toString());
    writer.append("\n");
    writer.flush();

    // Run an export process
    final Process process = startJarProcess("-c", configFile.getAbsolutePath(), "-u", "fedoraAdmin:password");

    // Verify
    assertTrue("Process did not exit before timeout!", process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS));
    assertEquals("Did not exit with success status!", 0, process.exitValue());

    assertTrue(new File(TARGET_DIR, TransferProcess.encodePath(url.getPath() + ArgParser.DEFAULT_RDF_EXT))
            .exists());
    assertTrue(new File(System.getProperty("java.io.tmpdir"), ArgParser.CONFIG_FILE_NAME).exists());
}

From source file:org.opencb.cellbase.mongodb.loader.MongoDBCellBaseLoader.java

protected boolean runCreateIndexProcess(Path indexFilePath) throws IOException, InterruptedException {
    List<String> args = new ArrayList<>();
    args.add("mongo");
    args.add("--host");
    args.add(cellBaseConfiguration.getDatabase().getHost());
    if (cellBaseConfiguration.getDatabase().getUser() != null
            && !cellBaseConfiguration.getDatabase().getUser().equals("")) {
        args.addAll(Arrays.asList("-u", cellBaseConfiguration.getDatabase().getUser(), "-p",
                cellBaseConfiguration.getDatabase().getPassword()));
    }//from  w  ww  .  j ava2s.c  o  m
    if (cellBaseConfiguration != null
            && cellBaseConfiguration.getDatabase().getOptions().get("authenticationDatabase") != null) {
        args.add("--authenticationDatabase");
        args.add(cellBaseConfiguration.getDatabase().getOptions().get("authenticationDatabase"));
        logger.debug("MongoDB 'authenticationDatabase' database parameter set to '{}'",
                cellBaseConfiguration.getDatabase().getOptions().get("authenticationDatabase"));
    }
    args.add(database);
    args.add(indexFilePath.toString());

    ProcessBuilder processBuilder = new ProcessBuilder(args);
    logger.debug("Executing command: '{}'", StringUtils.join(processBuilder.command(), " "));

    //        processBuilder.redirectErrorStream(true);
    //        if (logFilePath != null) {
    //            processBuilder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath)));
    //        }

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

    // Check process output
    boolean executedWithoutErrors = true;
    int genomeInfoExitValue = process.exitValue();
    if (genomeInfoExitValue != 0) {
        logger.warn("Error executing {}, error code: {}", indexFilePath, genomeInfoExitValue);
        executedWithoutErrors = false;
    }
    return executedWithoutErrors;
}

From source file:org.ops4j.pax.url.mvnlive.internal.Connection.java

/**
 * Will trigger a "mvn clean install"/*  ww  w .j a  v a 2  s . c  o  m*/
 *
 * @param projectRoot
 */
private void triggerBuild(File projectRoot) {
    try {
        LOG.info("Root is " + projectRoot.getCanonicalPath());
        String[] commandLine = new String[] { getMavenExecutable(), "clean", "install" };
        Process frameworkProcess = Runtime.getRuntime().exec(commandLine, null, projectRoot);

        Thread shutdownHook = createShutdownHook(frameworkProcess);
        Runtime.getRuntime().addShutdownHook(shutdownHook);
        long start = System.currentTimeMillis();
        int ex = -1;
        do {
            try {
                ex = frameworkProcess.exitValue();
                LOG.info("maven returned with value: " + ex);
                break;
            } catch (IllegalThreadStateException e) {
                // ignore the fact that the process is still running..
            }
        } while (start + MAVEN_TIMEOUT > System.currentTimeMillis());

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:edu.clemson.cs.nestbed.server.util.UsbDeviceInformation.java

private void updateInternal() {
    ProcessBuilder processBuilder;
    Process process;
    int exitValue;

    // tmp// w ww  . j a  va  2 s. c  o m
    //if (GET_DEV_INFO == null) return;

    try {
        //processBuilder = new ProcessBuilder(GET_DEV_INFO, "-s", moteSerialID);
        processBuilder = new ProcessBuilder("/usr/bin/sudo", GET_DEV_INFO, "-s", moteSerialID);
        process = processBuilder.start();

        process.waitFor();
        exitValue = process.exitValue();

        if (exitValue == 0) {
            Properties p = new Properties();
            p.load(process.getInputStream());

            String busString = p.getProperty("bus");
            String deviceString = p.getProperty("device");
            String portString = p.getProperty("port");

            log.debug("busString    = " + busString);
            log.debug("deviceString = " + deviceString);
            log.debug("portString   = " + portString);

            if ((busString != null) && (deviceString != null) && (portString != null)) {
                try {
                    bus = Integer.parseInt(busString);
                    device = Integer.parseInt(deviceString);
                    port = Integer.parseInt(portString);
                } catch (NumberFormatException ex) {
                    log.error("Error converting string to int", ex);
                }
            } else {
                log.error("Required property not set");
            }
        } else {
            log.error("Unable to get USB device information for " + "moteSerialID: " + moteSerialID);
        }
    } catch (InterruptedException ex) {
        log.error("Process interrupted", ex);
    } catch (IOException ex) {
        log.error("I/O Exception occured while reading device info", ex);
    }
}

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

protected void executeThumbnailGenerator() {
    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  .  j  a  v a  2 s.com*/
    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/thumbnail/resources
    buf.append("WEB-INF");
    buf.append(File.separator);
    buf.append("env");
    buf.append(File.separator);
    buf.append("thumbnail");
    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/thumbnail/lib
    appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/env/thumbnail/lib")),
            "WEB-INF" + File.separator + "env" + File.separator + "thumbnail" + 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=thumbnail");
        } 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.thumbnail.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, Constants.FESS_VAR_PATH, null, null);
    addSystemProperty(cmdList, Constants.FESS_THUMBNAIL_PATH, null, null);
    addSystemProperty(cmdList, "fess.log.name", "fess-thumbnail", "-thumbnail");
    if (logLevel != null) {
        cmdList.add("-Dfess.log.level=" + logLevel);
    }
    stream(fessConfig.getJvmThumbnailOptionsAsArray())
            .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(ThumbnailGenerator.class.getCanonicalName());

    cmdList.add("--sessionId");
    cmdList.add(sessionId);
    cmdList.add("--numOfThreads");
    cmdList.add(Integer.toString(numOfThreads));
    if (cleanup) {
        cmdList.add("--cleanup");
    }

    File propFile = null;
    try {
        cmdList.add("-p");
        propFile = File.createTempFile("thumbnail_", ".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("ThumbnailGenerator: \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("ThumbnailGenerator: Exit Code=" + exitValue + " - ThumbnailGenerator 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("ThumbnailGenerator Process interrupted.");
    } catch (final Exception e) {
        throw new FessSystemException("ThumbnailGenerator Process terminated.", e);
    } finally {
        try {
            processHelper.destroyProcess(sessionId);
        } finally {
            if (propFile != null && !propFile.delete()) {
                logger.warn("Failed to delete {}.", propFile.getAbsolutePath());
            }
            deleteTempDir(ownTmpDir);
        }
    }
}

From source file:org.noroomattheinn.utils.ThreadManager.java

private void watch(final String name, final Process p, final long timeout) {
    Runnable watchdog = new Runnable() {
        @Override/*  ww  w.  ja va  2  s  . com*/
        public void run() {
            long targetTime = System.currentTimeMillis() + timeout;
            while (System.currentTimeMillis() < targetTime) {
                if (hasExited(p)) {
                    int exitVal = p.exitValue();
                    logger.info("External process completed: " + name + "(" + exitVal + ")");
                    return;
                }
                Utils.sleep(Math.min(5 * 1000, targetTime - System.currentTimeMillis()));
            }
            // p hasn't terminated yet! Kill it.
            p.destroy();
            logger.warning("External process timed out - killing it: " + name);
        }
    };

    launch(watchdog, String.format("Watchdog %d", wdID++));
}

From source file:ape.NetworkDropPacketsCommand.java

/**
 * This method implement the event by using the netem module
 * @param percent The percentage of packets that are to be dropped
 * @param period The duration that the packet loss should last
 * @return True if the execution was successful, false if an error occurred 
 * @throws IOException/*from w  ww  .  jav a  2 s .c om*/
 */
private boolean executecommand(double percent, double period) throws IOException {
    String cmd = "tc qdisc add dev eth0 root netem loss " + percent + "% && sleep " + period
            + " && tc qdisc del dev eth0 root netem";
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process p = null;

    try {
        p = pb.start();
    } catch (IOException e) {
        System.err.println(
                "Executing network connection simulation catches IOException, enter VERBOSE mode to see the Stack Trace");
        e.printStackTrace();
        return false;
    }

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

            ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "tc qdisc del dev eth0 root netem");
            Process ptmp = tmp2.start();
            if (ptmp.waitFor() == 0)
                System.out.println("Connection resumed");
            else {
                System.out.println("Connection resumed failed");
                return false;
            }

            return false;
        }
    } catch (InterruptedException e1) {
        e1.printStackTrace();
        return false;
    }

    return true;
}