Example usage for java.lang Process destroy

List of usage examples for java.lang Process destroy

Introduction

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

Prototype

public abstract void destroy();

Source Link

Document

Kills the process.

Usage

From source file:uk.ac.kcl.tika.parsers.PDFPreprocessorParser.java

private File makeTiffFromPDF(File input, File output, ImageMagickConfig config)
        throws IOException, TikaException {
    String[] cmd = { config.getImageMagickPath() + getImageMagickProg(), "-density", config.getDensity(),
            input.getPath(), "-depth", config.getDepth(), "-quality", config.getQuality(), output.getPath() };

    ProcessBuilder pb = new ProcessBuilder(cmd);
    //setEnv(config, pb);
    final Process process = pb.start();

    process.getOutputStream().close();/*from  w  ww  .  j a  v  a  2s.c  om*/
    InputStream out = process.getInputStream();
    InputStream err = process.getErrorStream();

    logStream("IMAGEMAGICK MSG", out, input);
    logStream("IMAGEMAGICK ERROR", err, input);

    FutureTask<Integer> waitTask = new FutureTask<Integer>(new Callable<Integer>() {
        public Integer call() throws Exception {
            return process.waitFor();
        }
    });

    Thread waitThread = new Thread(waitTask);
    waitThread.start();

    try {
        waitTask.get(config.getTimeout(), TimeUnit.SECONDS);
        return output;
    } catch (InterruptedException e) {
        waitThread.interrupt();
        process.destroy();
        Thread.currentThread().interrupt();
        throw new TikaException("ImageMagickOCRPDFParser interrupted", e);

    } catch (ExecutionException e) {
        // should not be thrown

    } catch (TimeoutException e) {
        waitThread.interrupt();
        process.destroy();
        throw new TikaException("ImageMagickOCRPDFParser timeout", e);
    }
    return null;
}

From source file:org.apache.syncope.fit.cli.CLIITCase.java

@Test
public void lastStatements() {
    Process process = null;
    try {/*from w  w w .j  ava  2  s.  c  o  m*/
        PROCESS_BUILDER.command(getCommand(new LoggerCommand().getClass().getAnnotation(Command.class).name(),
                LoggerCommand.LoggerOptions.LAST_STATEMENTS.getOptionName(), "connid"));
        process = PROCESS_BUILDER.start();
        final String result = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
        assertTrue(result.contains("\"level\" : \"INFO\","));
        assertTrue(result.contains(
                "\"loggerName\" :" + " \"org.apache.syncope.core.provisioning.api.ConnIdBundleManager\""));
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:org.rhq.maven.plugins.ExecCliScriptMojo.java

@Override
protected void doExecute() throws MojoExecutionException, MojoFailureException {
    Process process = null;
    try {/*w  w w .j a  v  a2s .c  o  m*/
        File rhqCliStartScriptFile = getRhqCliStartScriptFile();
        // Run the CLI in forked process
        ProcessBuilder processBuilder = new ProcessBuilder() //
                .directory(rhqCliStartScriptFile.getParentFile()) // bin directory
                .command(buildRhqCliCommand(rhqCliStartScriptFile));
        getLog().info(
                "Executing RHQ CLI script file: " + IOUtils.LINE_SEPARATOR + scriptFile.getAbsolutePath());
        process = processBuilder.start();
        redirectOuput(process);
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            handleFailure("CLI stopped with status code: " + exitCode);
        }
    } catch (Exception e) {
        handleException(e);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:org.grouplens.lenskit.eval.traintest.ExternalEvalJob.java

@Override
protected void buildRecommender() throws RecommenderBuildException {
    Preconditions.checkState(userPredictions == null, "recommender already built");
    File dir = getStagingDir();//from   w w w  .jav  a2  s .  co m
    logger.info("using output/staging directory {}", dir);
    if (!dir.exists()) {
        logger.info("creating directory {}", dir);
        dir.mkdirs();
    }

    final File train;
    try {
        train = trainingFile(dataSet);
    } catch (IOException e) {
        throw new RecommenderBuildException("error preparing training file", e);
    }
    final File test;
    try {
        test = testFile(dataSet);
    } catch (IOException e) {
        throw new RecommenderBuildException("error preparing test file", e);
    }
    final File output = getFile("predictions.csv");
    List<String> args = Lists.transform(algorithm.getCommand(), new Function<String, String>() {
        @Nullable
        @Override
        public String apply(@Nullable String input) {
            if (input == null) {
                throw new NullPointerException("command element");
            }
            String s = input.replace("{OUTPUT}", output.getAbsolutePath());
            s = s.replace("{TRAIN_DATA}", train.getAbsolutePath());
            s = s.replace("{TEST_DATA}", test.getAbsolutePath());
            return s;
        }
    });

    logger.info("running {}", StringUtils.join(args, " "));

    Process proc;
    try {
        proc = new ProcessBuilder().command(args).directory(algorithm.getWorkDir()).start();
    } catch (IOException e) {
        throw new RecommenderBuildException("error creating process", e);
    }
    Thread listen = new LoggingStreamSlurper("external-algo", proc.getErrorStream(), logger, "external: ");
    listen.run();

    int result = -1;
    boolean done = false;
    while (!done) {
        try {
            result = proc.waitFor();
            done = true;
        } catch (InterruptedException e) {
            logger.info("thread interrupted, killing subprocess");
            proc.destroy();
            throw new RecommenderBuildException("recommender build interrupted", e);
        }
    }

    if (result != 0) {
        logger.error("external command exited with status {}", result);
        throw new RecommenderBuildException("recommender exited with code " + result);
    }

    Long2ObjectMap<SparseVector> vectors;
    try {
        vectors = readPredictions(output);
    } catch (FileNotFoundException e) {
        logger.error("cannot find expected output file {}", output);
        throw new RecommenderBuildException("recommender produced no output", e);
    }

    userPredictions = vectors;

    userTrainingEvents = dataSet.getTrainingData().getUserEventDAO();
    userTestEvents = dataSet.getTestData().getUserEventDAO();
}

From source file:uk.ac.kcl.tika.parsers.TesseractOCRParser.java

/**
 * Run external tesseract-ocr process./*from w w w .jav a 2 s  .com*/
 *
 * @param input
 *          File to be ocred
 * @param output
 *          File to collect ocr result
 * @param config
 *          Configuration of tesseract-ocr engine
 * @throws TikaException
 *           if the extraction timed out
 * @throws IOException
 *           if an input error occurred
 */
private void doOCR(File input, File output, TesseractOCRConfig config) throws IOException, TikaException {
    String[] cmd = { config.getTesseractPath() + getTesseractProg(), input.getPath(), output.getPath(), "-l",
            config.getLanguage(), "-psm", config.getPageSegMode() };

    ProcessBuilder pb = new ProcessBuilder(cmd);
    setEnv(config, pb);
    final Process process = pb.start();

    process.getOutputStream().close();
    InputStream out = process.getInputStream();
    InputStream err = process.getErrorStream();

    logStream("OCR MSG", out, input);
    logStream("OCR ERROR", err, input);

    FutureTask<Integer> waitTask = new FutureTask<Integer>(new Callable<Integer>() {
        public Integer call() throws Exception {
            return process.waitFor();
        }
    });

    Thread waitThread = new Thread(waitTask);
    waitThread.start();

    try {
        waitTask.get(config.getTimeout(), TimeUnit.SECONDS);

    } catch (InterruptedException e) {
        waitThread.interrupt();
        process.destroy();
        Thread.currentThread().interrupt();
        throw new TikaException("TesseractOCRParser interrupted", e);

    } catch (ExecutionException e) {
        // should not be thrown

    } catch (TimeoutException e) {
        waitThread.interrupt();
        process.destroy();
        throw new TikaException("TesseractOCRParser timeout", e);
    }
}

From source file:com.synopsys.integration.blackduck.codelocation.signaturescanner.command.ScanCommandCallable.java

@Override
public ScanCommandOutput call() {
    String commandToExecute = "command_not_yet_configured";
    try {/*from  w  ww  .j av a2 s . co m*/
        final ScanPaths scanPaths = scanPathsUtility
                .determineSignatureScannerPaths(scanCommand.getInstallDirectory());

        final List<String> cmd = scanCommand.createCommandForProcessBuilder(logger, scanPaths,
                scanCommand.getOutputDirectory().getAbsolutePath());
        cmd.add(scanCommand.getTargetPath());

        commandToExecute = createPrintableCommand(cmd);
        logger.info(String.format("Black Duck CLI command: %s", commandToExecute));

        final File standardOutFile = scanPathsUtility.createStandardOutFile(scanCommand.getOutputDirectory());
        try (FileOutputStream outputFileStream = new FileOutputStream(standardOutFile)) {
            final ScannerSplitStream splitOutputStream = new ScannerSplitStream(logger, outputFileStream);
            final ProcessBuilder processBuilder = new ProcessBuilder(cmd);
            processBuilder.environment().putAll(intEnvironmentVariables.getVariables());

            if (!scanCommand.isDryRun()) {
                if (!StringUtils.isEmpty(scanCommand.getApiToken())) {
                    processBuilder.environment().put("BD_HUB_TOKEN", scanCommand.getApiToken());
                } else {
                    processBuilder.environment().put("BD_HUB_PASSWORD", scanCommand.getPassword());
                }
            }
            processBuilder.environment().put("BD_HUB_NO_PROMPT", "true");

            final Process blackDuckCliProcess = processBuilder.start();

            // The cli logs go the error stream for some reason
            final StreamRedirectThread redirectThread = new StreamRedirectThread(
                    blackDuckCliProcess.getErrorStream(), splitOutputStream);
            redirectThread.start();

            int returnCode = -1;
            try {
                returnCode = blackDuckCliProcess.waitFor();

                // the join method on the redirect thread will wait until the thread is dead
                // the thread will die when it reaches the end of stream and the run method is finished
                redirectThread.join();
            } finally {
                if (blackDuckCliProcess.isAlive()) {
                    blackDuckCliProcess.destroy();
                }
                if (redirectThread.isAlive()) {
                    redirectThread.interrupt();
                }
            }

            splitOutputStream.flush();

            logger.info(IOUtils.toString(blackDuckCliProcess.getInputStream(), StandardCharsets.UTF_8));

            logger.info("Black Duck Signature Scanner return code: " + returnCode);
            logger.info(
                    "You can view the logs at: '" + scanCommand.getOutputDirectory().getCanonicalPath() + "'");

            if (returnCode != 0) {
                return ScanCommandOutput.FAILURE(scanCommand.getName(), logger, scanCommand, commandToExecute,
                        returnCode);
            }
        }
    } catch (final Exception e) {
        final String errorMessage = String.format("There was a problem scanning target '%s': %s",
                scanCommand.getTargetPath(), e.getMessage());
        return ScanCommandOutput.FAILURE(scanCommand.getName(), logger, scanCommand, commandToExecute,
                errorMessage, e);
    }

    if (!scanCommand.isDryRun() && cleanupOutput) {
        FileUtils.deleteQuietly(scanCommand.getOutputDirectory());
    } else if (scanCommand.isDryRun() && cleanupOutput) {
        // delete everything except dry run files
        final File[] outputFiles = scanCommand.getOutputDirectory().listFiles();
        for (final File outputFile : outputFiles) {
            if (!DRY_RUN_FILES_TO_KEEP.contains(outputFile.getName())) {
                FileUtils.deleteQuietly(outputFile);
            }
        }
    }

    return ScanCommandOutput.SUCCESS(scanCommand.getName(), logger, scanCommand, commandToExecute);
}

From source file:com.twosigma.beaker.kdb.KdbProcess.java

private void runImpl() throws Exception {
    // Guess at QLIC if it's not set.
    String qlic = System.getenv(QLIC);
    if (qlic == null) {
        qlic = qhome + File.separator + "k4.lic";
    }/*from   ww w . j a  v a2s.  co  m*/

    // Start kdb.
    Process kdbProcess = Runtime.getRuntime().exec(new String[] { qbin, "-p", Integer.toString(kdbPort) },
            new String[] { QHOME + "=" + qhome, QLIC + "=" + qlic,
                    BEAKER_CORE_PASSWORD + "=" + System.getenv(BEAKER_CORE_PASSWORD),
                    BEAKER_CORE_PORT + "=" + System.getenv(BEAKER_CORE_PORT), SESSION_ID + "=" + sessionId });

    errorGobbler = new ErrorGobbler(kdbProcess.getErrorStream());
    errorGobbler.start();

    outputHandler = new KdbOutputHandler(kdbProcess.getInputStream());
    outputHandler.start();

    // Wait until kdb exits or we're interrupted.
    while (true) {
        try {
            // Wait for kdb to exit.
            kdbProcess.waitFor();
            break;
        } catch (InterruptedException e) {
            // Interrupted - destroy the process.
            kdbProcess.destroy();
        }
    }
}

From source file:org.atilika.kuromoji.server.KuromojiServer.java

private String getViterbiSVG(String dot) {
    Process process = null;
    try {//  w  ww .j a  v  a 2s  .  co  m
        log.info("Running " + DOT_COMMAND);
        process = Runtime.getRuntime().exec(DOT_COMMAND);
        process.getOutputStream().write(dot.getBytes("utf-8"));
        process.getOutputStream().close();

        InputStream input = process.getInputStream();
        String svg = new Scanner(input, "utf-8").useDelimiter("\\A").next();

        int exitValue = process.exitValue();

        log.debug("Read " + svg.getBytes("utf-8").length + " bytes of SVG output");
        log.info("Process exited with exit value " + exitValue);
        return svg;
    } catch (IOException e) {
        log.error("Error running process " + process, e.getCause());
        return null;
    } finally {
        if (process != null) {
            log.info("Destroying process " + process);
            process.destroy();
        }
    }
}

From source file:com.utdallas.s3lab.smvhunter.monkey.LogcatMonitor.java

@Override
public void run() {

    //monitor the logcat for analysis
    Process pr = null;
    try {//from   w  w w.j a v  a 2s .  c  om
        pr = NetworkMonitor
                .execCommand(String.format(LOGCAT, WindowUpdate.adbLocation, device.getSerialNumber()));
        BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String s = null;

        ArrayList<String> tmpList = new ArrayList<String>();
        while ((s = br.readLine()) != null) {
            String forPrinting = NetworkMonitor.getStringforPrinting(device.getSerialNumber(),
                    System.currentTimeMillis(), s);
            tmpList.add(forPrinting);

            //write every 100 lines
            if (tmpList.size() == 100) {
                FileUtils.writeLines(new File(MonkeyMe.logCatLocation), tmpList, true);
                tmpList.clear();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (pr != null) {
            pr.destroy();
        }
    }
}

From source file:org.oscarehr.util.WKHtmlToPdfUtils.java

/**
 * Normally you can just run a command and it'll complete. The problem with doing that is if the command takes a while and you need to know when it's completed, like if it's cpu intensive like image processing and possibly in this case pdf creation.
 * This method will run the command and it has 2 stopping conditions, 1) normal completion as per the process.exitValue() or if the process does not appear to be doing anything. As a result there's a polling thread to check the out put file to see if
 * anything is happening. The example is if you're doing image processing and you're scaling an image with say imagemagick it could take 5 minutes to finish. You don't want to set a time out that long, but you don't want to stop if it it's proceeding
 * normally. Normal proceeding is defined by the out put file is still changing. If the out put file isn't changing, and it's taking "a while" then we would assume it's failed some how or hung or stalled at which point we'll terminate it.
 *//*  w  w w .  j ava  2  s . c om*/
private static void runtimeExec(ArrayList<String> command, String outputFilename) throws IOException {
    File f = new File(outputFilename);
    Process process = null;
    try {
        process = Runtime.getRuntime().exec(command.toArray(new String[0]));
    } catch (Exception e) {
        logger.error("PDF conversion exception: ", e);
    }
    long previousFileSize = 0;
    int noFileSizeChangeCounter = 0;

    try {
        while (true) {
            try {
                Thread.sleep(PROCESS_COMPLETION_CYCLE_CHECK_PERIOD);
            } catch (InterruptedException e) {
                logger.error("Thread interrupted", e);
            }

            try {
                int exitValue = process.exitValue();

                if (exitValue != 0) {
                    logger.debug("Error running command : " + command);

                    String errorMsg = StringUtils.trimToNull(IOUtils.toString(process.getInputStream()));
                    if (errorMsg != null)
                        logger.debug(errorMsg);

                    errorMsg = StringUtils.trimToNull(IOUtils.toString(process.getErrorStream()));
                    if (errorMsg != null)
                        logger.debug(errorMsg);
                }

                return;
            } catch (IllegalThreadStateException e) {
                long tempSize = f.length();

                logger.debug("Progress output filename=" + outputFilename + ", filesize=" + tempSize);

                if (tempSize != previousFileSize)
                    noFileSizeChangeCounter = 0;
                else {
                    noFileSizeChangeCounter++;

                    if (noFileSizeChangeCounter > MAX_NO_CHANGE_COUNT)
                        break;
                }
            }
        }

        logger.error("Error, process appears stalled. command=" + command);
    } finally {
        process.destroy();
    }
}