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:com.emc.vipr.sync.source.FilesystemSource.java

protected void delete(File file) {
    // Try to lock the file first.  If this fails, the file is
    // probably open for write somewhere.
    // Note that on a mac, you can apparently delete files that
    // someone else has open for writing, and can lock files
    // too.//from w  ww . j av a2s  . c  o  m
    // Must make sure to throw exceptions when necessary to flag actual failures as opposed to skipped files.
    if (file.isDirectory()) {
        File metaDir = getMetaFile(file).getParentFile();
        if (metaDir.exists())
            metaDir.delete();
        // Just try and delete dir
        if (!file.delete()) {
            LogMF.warn(l4j, "Failed to delete directory {0}", file);
        }
    } else {
        boolean tryDelete = true;
        if (deleteOlderThan > 0) {
            if (System.currentTimeMillis() - file.lastModified() < deleteOlderThan) {
                LogMF.info(l4j, "not deleting {0}; it is not at least {1} ms old", file, deleteOlderThan);
                tryDelete = false;
            }
        }
        if (deleteCheckScript != null) {
            String[] args = new String[] { deleteCheckScript.getAbsolutePath(), file.getAbsolutePath() };
            try {
                l4j.debug("delete check: " + Arrays.asList(args));
                Process p = Runtime.getRuntime().exec(args);
                while (true) {
                    try {
                        int exitCode = p.exitValue();

                        if (exitCode == 0) {
                            LogMF.debug(l4j, "delete check OK, exit code {0}", exitCode);
                        } else {
                            LogMF.info(l4j, "delete check failed, exit code {0}.  Not deleting file.",
                                    exitCode);
                            tryDelete = false;
                        }
                        break;
                    } catch (IllegalThreadStateException e) {
                        // Ignore.
                    }
                }
            } catch (IOException e) {
                LogMF.info(l4j, "error executing delete check script: {0}.  Not deleting file.", e.toString());
                tryDelete = false;
            }
        }
        RandomAccessFile raf = null;
        if (tryDelete) {
            try {
                raf = new RandomAccessFile(file, "rw");
                FileChannel fc = raf.getChannel();
                FileLock flock = fc.lock();
                // If we got here, we should be good.
                flock.release();
                if (!file.delete()) {
                    throw new RuntimeException(MessageFormat.format("Failed to delete {0}", file));
                }
            } catch (IOException e) {
                throw new RuntimeException(MessageFormat
                        .format("File {0} not deleted, it appears to be open: {1}", file, e.getMessage()));
            } finally {
                if (raf != null) {
                    try {
                        raf.close();
                    } catch (IOException e) {
                        // Ignore.
                    }
                }
            }
        }
    }
}

From source file:edu.pitt.dbmi.ccd.queue.service.AlgorithmQueueService.java

@Async
public Future<Void> runAlgorithmFromQueue(JobQueueInfo jobQueueInfo) {
    Long queueId = jobQueueInfo.getId();
    String fileName = jobQueueInfo.getFileName() + ".txt";
    String jsonFileName = jobQueueInfo.getFileName() + ".json";
    String commands = jobQueueInfo.getCommands();
    String tmpDirectory = jobQueueInfo.getTmpDirectory();
    String outputDirectory = jobQueueInfo.getOutputDirectory();

    List<String> cmdList = new LinkedList<>();
    cmdList.addAll(Arrays.asList(commands.split(";")));

    cmdList.add("--out");
    cmdList.add(tmpDirectory);/*www .ja  va 2  s.c o  m*/

    StringBuilder sb = new StringBuilder();
    cmdList.forEach(cmd -> {
        sb.append(cmd);
        sb.append(" ");
    });
    LOGGER.info("Algorithm command: " + sb.toString());

    String errorFileName = String.format("error_%s", fileName);
    Path error = Paths.get(tmpDirectory, errorFileName);
    Path errorDest = Paths.get(outputDirectory, errorFileName);
    Path src = Paths.get(tmpDirectory, fileName);
    Path dest = Paths.get(outputDirectory, fileName);
    Path json = Paths.get(tmpDirectory, jsonFileName);
    Path jsonDest = Paths.get(outputDirectory, jsonFileName);

    try {
        ProcessBuilder pb = new ProcessBuilder(cmdList);
        pb.redirectError(error.toFile());
        Process process = pb.start();

        //Get process Id
        Long pid = Processes.processId(process);
        JobQueueInfo queuedJobInfo = jobQueueInfoService.findOne(queueId);
        LOGGER.info("Set Job's pid to be: " + pid);
        queuedJobInfo.setPid(pid);
        jobQueueInfoService.saveJobIntoQueue(queuedJobInfo);

        process.waitFor();

        if (process.exitValue() == 0) {
            LOGGER.info(String.format("Moving txt file %s to %s", src, dest));
            Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING);
            LOGGER.info(String.format("Moving json file %s to %s", json, dest));
            Files.move(json, jsonDest, StandardCopyOption.REPLACE_EXISTING);
            Files.deleteIfExists(error);
        } else {
            LOGGER.info(String.format("Deleting tmp txt file %s", src));
            Files.deleteIfExists(src);
            LOGGER.info(String.format("Moving error file %s to %s", error, errorDest));
            Files.move(error, errorDest, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException | InterruptedException exception) {
        LOGGER.error("Algorithm did not run successfully.", exception);
    }

    LOGGER.info("Delete Job ID from queue: " + queueId);
    jobQueueInfoService.deleteJobById(queueId);

    return new AsyncResult<>(null);
}

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

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

    // Run an export process
    final Process process = startJarProcess("-m", "export", "-d", TARGET_DIR, "-r", url.toString(), "-u",
            "fedoraAdmin:password");

    // Verify/*from www. j a  v  a2s. co  m*/
    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, url.getPath() + ArgParser.DEFAULT_RDF_EXT).exists());
}

From source file:org.cloudcoder.submitsvc.oop.builder.ProcessRunner.java

public boolean isRunning() {
    Process p = process;

    if (p == null) {
        // Process hasn't started yet.
        // Count that as "running".
        return true;
    }/* w w  w  .j  av  a 2  s .c om*/

    try {
        p.exitValue();
        return false;
    } catch (IllegalThreadStateException e) {
        return true;
    }
}

From source file:com.thoughtworks.go.task.rpmbuild.RPMBuildTask.java

@Override
public TaskExecutor executor() {
    return new TaskExecutor() {
        @Override/*from ww  w .j  a v a2 s. co m*/
        public ExecutionResult execute(TaskConfig taskConfig, TaskExecutionContext taskExecutionContext) {
            String targetArch = taskConfig.getValue(TARGET_ARCH);
            String specFilePath = taskConfig.getValue(SPEC_FILE);
            List<String> command = Arrays.asList("rpmbuild", "--target", targetArch, "-bb", "-v", "--clean",
                    specFilePath);
            try {
                taskExecutionContext.console().printLine("[exec] " + StringUtils.join(command, " "));
                Process process = runProcess(taskExecutionContext, command);
                taskExecutionContext.console().readOutputOf(process.getInputStream());
                taskExecutionContext.console().readErrorOf(process.getErrorStream());
                try {
                    process.waitFor();
                } catch (InterruptedException e) {
                    // continue
                }
                int exitValue = process.exitValue();
                if (exitValue != 0) {
                    return ExecutionResult.failure("[exec] FAILED with return code " + exitValue);
                }
            } catch (IOException e) {
                return ExecutionResult.failure("[exec] Exception: " + e.getMessage(), e);
            }
            return ExecutionResult.success(
                    String.format("[exec] Successfully executed command [%s]", StringUtils.join(command, " ")));
        }
    };
}

From source file:net.urlgrey.mythpodcaster.transcode.FFMpegTranscoderImpl.java

public void transcode(File workingDirectory, GenericTranscoderConfigurationItem genericConfig, File inputFile,
        File outputFile) throws Exception {
    LOG.info("transcode started: inputFile [" + inputFile.getAbsolutePath() + "], outputFile ["
            + outputFile.getAbsolutePath() + "]");

    FFMpegTranscoderConfigurationItem config = (FFMpegTranscoderConfigurationItem) genericConfig;
    List<String> commandList = new ArrayList<String>();
    commandList.add(niceLocation);/*w ww .j  a va 2  s.  com*/
    commandList.add("-n");
    commandList.add(Integer.toString(config.getNiceness()));
    commandList.add(ffmpegLocation);
    commandList.add("-i");
    commandList.add(inputFile.getAbsolutePath());
    commandList.addAll(config.getParsedEncoderArguments());
    commandList.add(outputFile.getAbsolutePath());
    ProcessBuilder pb = new ProcessBuilder(commandList);

    // Needed for ffmpeg
    pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:");
    pb.redirectErrorStream(true);
    pb.directory(workingDirectory);
    Process process = null;

    try {
        // Get the ffmpeg process
        process = pb.start();
        // We give a couple of secs to complete task if needed
        Future<List<String>> stdout = pool.submit(new OutputMonitor(process.getInputStream()));
        List<String> result = stdout.get(config.getTimeout(), TimeUnit.SECONDS);
        process.waitFor();
        final int exitValue = process.exitValue();
        LOG.info("FFMPEG exit value: " + exitValue);
        if (exitValue != 0) {
            for (String line : result) {
                LOG.error(line);
            }
            throw new Exception("FFMpeg return code indicated failure: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new Exception("FFMpeg process interrupted by another thread", e);
    } catch (ExecutionException ee) {
        throw new Exception("Something went wrong parsing FFMpeg output", ee);
    } catch (TimeoutException te) {
        // We could not get the result before timeout
        throw new Exception("FFMpeg process timed out", te);
    } catch (RuntimeException re) {
        // Unexpected output from FFMpeg
        throw new Exception("Something went wrong parsing FFMpeg output", re);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    LOG.debug("transcoding finished");
}

From source file:net.urlgrey.mythpodcaster.transcode.SegmentedVodTranscoderImpl.java

public void transcode(File workingDirectory, GenericTranscoderConfigurationItem genericConfig, File inputFile,
        File outputFile) throws Exception {
    LOG.info("transcode started: inputFile [" + inputFile.getAbsolutePath() + "], outputFile ["
            + outputFile.getAbsolutePath() + "]");

    SegmenterTranscoderConfigurationItem config = (SegmenterTranscoderConfigurationItem) genericConfig;
    List<String> commandList = new ArrayList<String>();
    commandList.add(niceLocation);//www .  java2 s.co  m
    commandList.add("-n");
    commandList.add(Integer.toString(config.getNiceness()));
    commandList.add(segmenterLocation);
    commandList.add(inputFile.getAbsolutePath());
    commandList.add(config.getSegmentDuration());
    commandList.add(config.getSegmentFilePrefix());
    commandList.add(config.getPlaylistFileName());
    commandList.add(config.getHttpPrefix());
    ProcessBuilder pb = new ProcessBuilder(commandList);

    pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:");
    pb.redirectErrorStream(true);
    pb.directory(outputFile.getParentFile());
    Process process = null;

    try {
        // Get the segmenter process
        process = pb.start();
        // We give a couple of secs to complete task if needed
        Future<List<String>> stdout = pool.submit(new OutputMonitor(process.getInputStream()));
        List<String> result = stdout.get(config.getTimeout(), TimeUnit.SECONDS);
        process.waitFor();
        final int exitValue = process.exitValue();
        LOG.info("Segmenter exit value: " + exitValue);
        if (exitValue != 0) {
            for (String line : result) {
                LOG.error(line);
            }
            throw new Exception("Segmenter return code indicated failure: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new Exception("Segmenter process interrupted by another thread", e);
    } catch (ExecutionException ee) {
        throw new Exception("Something went wrong parsing Segmenter output", ee);
    } catch (TimeoutException te) {
        // We could not get the result before timeout
        throw new Exception("Segmenter process timed out", te);
    } catch (RuntimeException re) {
        // Unexpected output from Segmenter
        throw new Exception("Something went wrong parsing Segmenter output", re);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    LOG.debug("transcoding finished");
}

From source file:com.openshift.internal.restclient.capability.resources.OpenShiftBinaryRSync.java

private void waitForExit(String source, String destination, Process process) {
    try {//  w w  w. j a v  a  2s  .  c  o  m
        if (process == null) {
            throw new OpenShiftException("Could not sync %s to %s, no process was launched.", destination);
        }
        if (!process.waitFor(WAIT_FOR_EXIT_TIMEOUT, TimeUnit.MINUTES)) {
            throw new OpenShiftException("Syncing %s to %s did not terminate within %d minutes.", source,
                    destination, WAIT_FOR_EXIT_TIMEOUT);
        }

        if (process.exitValue() != 0) {
            String errorMessage = getErrorMessage(process.getErrorStream());
            throw new OpenShiftException(
                    "Syncing %s to %s failed" + (StringUtil.isBlank(errorMessage) ? "" : ":%s"), source,
                    destination, errorMessage);
        }
    } catch (InterruptedException e) {
        throw new OpenShiftException(e, "Syncing %s to %s was interrupted.", source, destination);
    }
}

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

@Test
public void testExportBinaryAndRDFToSamePath() throws Exception {
    final File binaryFile = new File(TARGET_DIR, "test-classes/sample/binary/bin/rest/bin1.binary");
    final byte[] content = FileUtils.readFileToByteArray(binaryFile);

    // create a binary resource
    final FcrepoResponse response = createBinary(binaryFile);
    assertEquals(SC_CREATED, response.getStatusCode());
    assertEquals(url, response.getLocation());

    // Run an export process
    final Process process = startJarProcess("-m", "export", "-d", TARGET_DIR, "-b", TARGET_DIR, "-r",
            url.toString(), "-u", "fedoraAdmin:password");

    // Verify/*www. j ava  2 s.c  o m*/
    assertTrue("Process did not exit before timeout!", process.waitFor(1000, TimeUnit.SECONDS));
    assertEquals("Did not exit with success status!", 0, process.exitValue());

    final List<URI> describedByHeaders = response.getLinkHeaders("describedby");
    assertFalse("Fedora should have given us at least one describedby header!", describedByHeaders.isEmpty());
    describedByHeaders.forEach(uri -> assertTrue("RDF for exported " + uri + " not found!",
            new File(TARGET_DIR, TransferProcess.encodePath(uri.getPath()) + ArgParser.DEFAULT_RDF_EXT)
                    .exists()));
    final File exportedBinary = new File(TARGET_DIR,
            TransferProcess.encodePath(url.getPath()) + BINARY_EXTENSION);
    assertTrue(exportedBinary.exists());
    final byte[] contentFromFile = FileUtils.readFileToByteArray(exportedBinary);
    assertEquals("Content was corrupted on export!", new String(content), new String(contentFromFile));
    assertEquals(binaryFile.length(), exportedBinary.length());
}

From source file:com.github.harti2006.neo4j.StartNeo4jServerMojo.java

private void startNeo4jServer() throws MojoExecutionException {
    final Log log = getLog();
    try {//from   w  ww  . j  a  v a  2 s. c om
        final Path serverLocation = getServerLocation();
        final String[] neo4jCommand = new String[] {
                serverLocation.resolve(Paths.get("bin", "neo4j")).toString(), "start" };
        final File workingDir = serverLocation.toFile();

        final Process neo4jStartProcess = Runtime.getRuntime().exec(neo4jCommand, null, workingDir);
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(neo4jStartProcess.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                log.info("NEO4J SERVER > " + line);
            }
        }

        if (neo4jStartProcess.waitFor(5, SECONDS) && neo4jStartProcess.exitValue() == 0) {
            log.info("Started Neo4j server");
        } else {
            throw new MojoExecutionException("Neo4j server did not start up properly");
        }
    } catch (IOException | InterruptedException e) {
        throw new MojoExecutionException("Could not start neo4j server", e);
    }
}