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:org.codelibs.fess.thumbnail.impl.CommandGenerator.java

protected void executeCommand(final String thumbnailId, final List<String> cmdList) {
    ProcessBuilder pb = null;//ww  w .  j  a v  a  2s  .  co  m
    Process p = null;

    if (logger.isDebugEnabled()) {
        logger.debug("Thumbnail Command: " + cmdList);
    }

    TimerTask task = null;
    try {
        pb = new ProcessBuilder(cmdList);
        pb.directory(baseDir);
        pb.redirectErrorStream(true);

        p = pb.start();

        task = new ProcessDestroyer(p, cmdList);
        try {
            destoryTimer.schedule(task, commandTimeout);

            String line;
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.defaultCharset()));
                while ((line = br.readLine()) != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(line);
                    }
                }
            } finally {
                IOUtils.closeQuietly(br);
            }

            p.waitFor();
        } catch (final Exception e) {
            p.destroy();
        }
    } catch (final Exception e) {
        logger.warn("Failed to generate a thumbnail of " + thumbnailId, e);
    }
    if (task != null) {
        task.cancel();
        task = null;
    }
}

From source file:com.alibaba.otter.shared.common.utils.cmd.Exec.java

public static Result execute(Process process, String cmd, String outputLog, byte[] input, File workingDir)
        throws Exception {
    // ???/*w w w  .j  a va 2  s.  c  om*/
    Thread inputThread = new InputPumper((input == null) ? new byte[] {} : input, process.getOutputStream());
    StreamCollector stderr = null;
    StreamCollector stdout = null;
    FileOutputStream fileOutput = null;
    StreamAppender outputLogger = null;
    String errString = null;
    String outString = null;

    try {
        if (outputLog == null) {
            stdout = new StreamCollector(process.getInputStream());
            stderr = new StreamCollector(process.getErrorStream());
            stdout.start();
            stderr.start();
        } else {
            errString = "stderr output redirected to file " + outputLog;
            outString = "stdout output redirected to file " + outputLog;
            fileOutput = new FileOutputStream(outputLog);
            outputLogger = new StreamAppender(fileOutput);
            outputLogger.writeInput(process.getErrorStream(), process.getInputStream());
        }

        inputThread.start();

        final int exitCode = process.waitFor();

        inputThread.join();

        if (outputLogger != null) {
            outputLogger.finish();
        }

        if (stdout != null) {
            stdout.join();
            outString = stdout.toString();
        }

        if (stderr != null) {
            stderr.join();
            errString = stderr.toString();
        }

        return new Result(cmd.toString(), outString, errString, exitCode);
    } finally {
        IOUtils.closeQuietly(fileOutput);

        if (process != null) {
            // evitons http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6462165
            process.getInputStream().close();
            process.getOutputStream().close();
            process.getErrorStream().close();
            process.destroy();
        }
    }
}

From source file:org.springframework.xd.extension.process.ShellCommandProcessor.java

/**
 * Runs a thread that waits for the Process result.
 *//*from w  w  w .ja  v  a  2  s .c  om*/
private void monitorProcess() {
    taskExecutor.execute(new Runnable() {

        @Override
        public void run() {
            Process process = ShellCommandProcessor.this.process;
            if (process == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Process destroyed before starting process monitor");
                }
                return;
            }

            int result = Integer.MIN_VALUE;
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Monitoring process '" + command + "'");
                }
                result = process.waitFor();
                if (log.isInfoEnabled()) {
                    log.info("Process '" + command + "' terminated with value " + result);

                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.error("Interrupted - stopping adapter", e);
                stop();
            } finally {
                process.destroy();
            }
        }
    });
}

From source file:com.palantir.opensource.sysmon.linux.LinuxLoadAverageJMXWrapper.java

void readData() throws LinuxMonitoringException {
    Process process = null;
    BufferedReader stdout = null;
    InputStream stderr = null;//from  www  . j  a  v  a  2  s.  c  o m
    OutputStream stdin = null;

    try {
        // start process
        process = Runtime.getRuntime().exec(uptimeCmd); // (authorized)
        // initialize stream
        stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
        stderr = process.getErrorStream();
        stdin = process.getOutputStream();

        // pull what should be the header line
        String line = stdout.readLine();
        if (line == null) {
            throw new LinuxMonitoringException("No data read from uptime process!");
        }

        processUptimeLine(line);
    } catch (IOException e) {
        throw new LinuxMonitoringException("Error while reading data from uptime process", e);
    } finally {
        IOUtils.closeQuietly(stdout);
        IOUtils.closeQuietly(stderr);
        IOUtils.closeQuietly(stdin);
        if (process != null) {
            process.destroy();
        }
    }

}

From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java

/**
 * Run external tesseract-ocr process./*  w  w w . j  a v  a2s. c o m*/
 *
 * @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(),
            config.getOutputType().name().toLowerCase(Locale.US), "-c",
            (config.getPreserveInterwordSpacing()) ? "preserve_interword_spaces=1"
                    : "preserve_interword_spaces=0" };
    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<>(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:de.flyingsnail.ipv6droid.android.VpnThread.java

/**
 *     Android 4.4 has introduced a bug with VPN routing. The android developers appear very
 *     pleased with their broken idea and unwilling to fix in any forseeable future.
 *     This methods tries to check if our device suffers from this problem.
 *     @return true if routing is OK//from   w  w w .j  a  v  a  2s.  c  o m
 */
private boolean checkRouting() {
    try {
        Process routeChecker = Runtime.getRuntime()
                .exec(new String[] { "/system/bin/ip", "-f", "inet6", "route", "show", "default", "::/1" });
        BufferedReader reader = new BufferedReader(new InputStreamReader(routeChecker.getInputStream()));
        BufferedReader errreader = new BufferedReader(new InputStreamReader(routeChecker.getErrorStream()));
        String output = reader.readLine();
        String errors = errreader.readLine();
        try {
            routeChecker.waitFor();
        } catch (InterruptedException e) {
            // we got interrupted, so we kill our process
            routeChecker.destroy();
        }
        int exitValue = 0;
        try {
            exitValue = routeChecker.exitValue();
        } catch (IllegalStateException ise) {
            // command still running. Hmmm.
        }
        if (output == null || exitValue != 0) {
            Log.e(TAG, "error checking route: " + errors);
            return false; // default route is not set on ipv6
        } else
            return true;
    } catch (IOException e) {
        return false; // we cannot even check :-(
    }
}

From source file:org.wso2.appserver.integration.tests.wsdl2java.HelloServiceCodeGenTestCase.java

@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = "wso2.as", description = "extract generated zip", dependsOnMethods = "testGeneratedClass")
public void testExtractGeneratedCode() throws IOException {
    codeGenPath = extractZip(baseDir + File.separator + "generated.zip");

    log.info("Generated code path " + codeGenPath);
    File codeGenFile = new File(codeGenPath);
    Process tempProcess = null;
    String[] cmdArray;/*from w  w  w .ja  v  a 2s.co m*/
    try {
        if (System.getProperty("os.name").toLowerCase().contains("windows")) {
            cmdArray = new String[] { "cmd.exe", "/c", "mvn clean install" };
            tempProcess = Runtime.getRuntime().exec(cmdArray, null, codeGenFile);

        } else {
            cmdArray = new String[] { "mvn", "clean", "install" };
            System.setProperty("user.dir", codeGenPath);
            tempProcess = Runtime.getRuntime().exec(cmdArray, null, codeGenFile);
        }

        boolean buildStatus = waitForMessage(tempProcess.getInputStream(), "BUILD SUCCESS");
        assertTrue(buildStatus, "code generation was not successful");

        boolean status = false;
        if (new File(codeGenPath).exists()) {
            status = true;
        }
        assertTrue(status, "cannot find the generated zip file");
    } finally {
        if (tempProcess != null) {
            tempProcess.destroy();
        }
    }
}

From source file:oracle.CubistOracle.common.CubistOracle.java

/**
 * Following https://www.securecoding.cert.org/confluence/display/java/FIO07-J.+Do+not+let+external+processes+block+on+IO+buffers
 * I am going to rewrite this/*from  w w w . j av  a 2  s. com*/
 *
 * @param filestem
 * @return
 */

private String createCubistModel(String filestem) {
    try {
        String[] command = buildCommand(filestem);
        ProcessBuilder pb = new ProcessBuilder(command);
        if (t)
            log.trace("Invoking " + Arrays.toString(command));
        pb = pb.redirectErrorStream(true);
        Process p = pb.start();
        StringBuffer printErr = new StringBuffer();
        StringBuffer printOut = new StringBuffer();

        // Any error message?
        StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), System.err, printErr, true);

        // Any output?
        StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), System.out, printOut, t);

        errorGobbler.start();
        //if (t) {
        outputGobbler.start();
        //}

        int exitVal = p.waitFor();

        errorGobbler.join(); // Handle condition where the process ends before the threads finish
        //if (t) {
        outputGobbler.join();
        //}

        if (printErr.length() != 0) {
            throw new RuntimeException(printErr.toString());
        }
        if (cubistConfig.isPrintModelOnBuild()) {
            printOutputBuild(p);
        }
        p.destroy();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Could not create CubistModel " + e.getMessage());
    }
    return modelString();
}

From source file:eus.ixa.ixa.pipe.convert.AbsaSemEval.java

public static String absa2015Toabsa2015AnotatedWithMultipleDocClasModelsX(String fileName, String modelsList) {
    //reading the ABSA xml file
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    Document doc = null;//from  w  w  w . j  a  v a  2  s  .  com
    try {
        doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);

        //int cantSent = 0;

        for (Element sent : sentences) {

            Element opinionsElement = sent.getChild("Opinions");
            if (opinionsElement != null) {
                //iterating over every opinion in the opinions element
                List<Element> opinionList = opinionsElement.getChildren();
                for (int i = opinionList.size() - 1; i >= 0; i--) {
                    Element opinion = opinionList.get(i);
                    opinionsElement.removeContent(opinion);
                }
            }

            Path pathx = FileSystems.getDefault().getPath("./", "TEXT.txt");
            Files.deleteIfExists(pathx);

            File f = new File("TEXT.txt");
            FileUtils.writeStringToFile(f, sent.getChildText("text"), "UTF-8");

            /*Path path1 = FileSystems.getDefault().getPath("./", "NAF1.txt");
            Files.deleteIfExists(path1);
            String[] cmd1 = { "/bin/sh", "-c", "cat TEXT.txt | java -jar /home/vector/Documents/Ixa-git/ixa-pipe-tok/target/ixa-pipe-tok-1.8.5-exec.jar tok -l en > NAF1.txt" };
            Process proc1 = Runtime.getRuntime().exec(cmd1);
                    
            try {
             if(!proc1.waitFor(30, TimeUnit.MINUTES)) {
                 //timeout - kill the process. 
                 proc1.destroy(); // consider using destroyForcibly instead
                 throw new Exception("TimeOut Expired in IXA-PIPE-TOK");
             }
            }catch (Exception e) {
             System.out.println("   ERROR: ");
            }*/

            //System.err.println(kaf.toString());

            File file = new File(modelsList);
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            String nextCommand = "";

            //int port = 2000;
            while ((line = bufferedReader.readLine()) != null) {
                //System.err.println("-" + line + "-" + kaf.getLang());
                System.err.println("   Model: " + line);

                //nextCommand +=" | java -jar /home/vector/Documents/Ixa-git/ixa-pipe-doc/target/ixa-pipe-doc-0.0.2-exec.jar client -p " + port;

                nextCommand += " | java -jar /home/vector/Documents/Ixa-git/ixa-pipe-doc/target/ixa-pipe-doc-0.0.2-exec.jar tag -m "
                        + line;

                //File fileTmp = new File("NAF.txt");
                //File fileTmp2 = new File("NAF1.txt");
                //Files.copy(fileTmp.toPath(), fileTmp2.toPath(), StandardCopyOption.REPLACE_EXISTING);
                //Files.delete(fileTmp.toPath());

                //port ++;
            }
            fileReader.close();

            String[] cmd = { "/bin/sh", "-c",
                    "cat TEXT.txt | java -jar /home/vector/Documents/Ixa-git/ixa-pipe-tok/target/ixa-pipe-tok-1.8.5-exec.jar tok -l en"
                            + nextCommand + " > NAF.txt" };

            //System.err.println("cat TEXT.txt | java -jar /home/vector/Documents/Ixa-git/ixa-pipe-tok/target/ixa-pipe-tok-1.8.5-exec.jar tok -l en" + nextCommand + " > NAF.txt");

            Process proc = Runtime.getRuntime().exec(cmd);

            try {
                if (!proc.waitFor(30, TimeUnit.MINUTES)) {
                    //timeout - kill the process. 
                    proc.destroy(); // consider using destroyForcibly instead
                    throw new Exception("TimeOut Expired in IXA");
                }
            } catch (Exception e) {
                System.out.println("   ERROR: ");
            }

            //System.err.println(kaf.toString());
            //cantSent++;

            /*try {
                  Thread.sleep(1000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }*/

            File fileDir = new File("NAF.txt");

            System.err.println("Terminado: " + sent.getChildText("text"));

            BufferedReader breader1 = new BufferedReader(
                    new InputStreamReader(new FileInputStream(fileDir), "UTF-8"));

            KAFDocument kaf = null;

            try {
                kaf = KAFDocument.createFromStream(breader1);
            } catch (Exception e) {
                System.err.println("ENTRA A ERROR");
                e.printStackTrace();
                continue;
            }

            List<Topic> topicList = kaf.getTopics();
            for (Topic topic : topicList) {
                //System.err.println(topic.getTopicValue());
                if (!topic.getTopicValue().equals("NO")) {
                    Element opinionElem = new Element("Opinion");
                    opinionElem.setAttribute("target", "na");
                    opinionElem.setAttribute("category", topic.getTopicValue());
                    //TODO we still do not have polarity here
                    opinionElem.setAttribute("polarity", "na");
                    opinionElem.setAttribute("from", "0");
                    opinionElem.setAttribute("to", "0");
                    opinionsElement.addContent(opinionElem);
                }
            }

        } //end of sentence
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }

    XMLOutputter xmlOutput = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    xmlOutput.setFormat(format);
    return xmlOutput.outputString(doc);
}

From source file:org.codelibs.fess.helper.JobHelper.java

protected void destroyCrawlerProcess(final JobProcess jobProcess) {
    if (jobProcess != null) {
        final InputStreamThread ist = jobProcess.getInputStreamThread();
        try {//w w w .j a va2 s  .c om
            ist.interrupt();
        } catch (final Exception e) {
            logger.warn("Could not interrupt a thread of an input stream.", e);
        }

        final CountDownLatch latch = new CountDownLatch(1);
        final Process process = jobProcess.getProcess();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    IOUtils.closeQuietly(process.getInputStream());
                } catch (final Exception e) {
                    logger.warn("Could not close a process input stream.", e);
                }
                try {
                    IOUtils.closeQuietly(process.getErrorStream());
                } catch (final Exception e) {
                    logger.warn("Could not close a process error stream.", e);
                }
                try {
                    IOUtils.closeQuietly(process.getOutputStream());
                } catch (final Exception e) {
                    logger.warn("Could not close a process output stream.", e);
                }
                latch.countDown();
            }
        }, "ProcessCloser").start();

        try {
            latch.await(10, TimeUnit.SECONDS);
        } catch (final InterruptedException e) {
            logger.warn("Interrupted to wait a process.", e);
        }
        try {
            process.destroy();
        } catch (final Exception e) {
            logger.error("Could not destroy a process correctly.", e);
        }
    }
}