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.apache.axis.components.compiler.Jikes.java

/**
 * Execute the compiler/*from ww  w. j  a  va2 s. c o m*/
 */
public boolean compile() throws IOException {

    List args = new ArrayList();
    // command line name
    args.add("jikes");
    // indicate Emacs output mode must be used
    args.add("+E");
    // avoid warnings
    // Option nowarn with one hyphen only
    args.add("-nowarn");

    int exitValue;
    ByteArrayOutputStream tmpErr = new ByteArrayOutputStream(OUTPUT_BUFFER_SIZE);

    try {
        Process p = Runtime.getRuntime().exec(toStringArray(fillArguments(args)));

        BufferedInputStream compilerErr = new BufferedInputStream(p.getErrorStream());

        StreamPumper errPumper = new StreamPumper(compilerErr, tmpErr);

        errPumper.start();

        p.waitFor();
        exitValue = p.exitValue();

        // Wait until the complete error stream has been read
        errPumper.join();
        compilerErr.close();

        p.destroy();

        tmpErr.close();
        this.errors = new ByteArrayInputStream(tmpErr.toByteArray());

    } catch (InterruptedException somethingHappened) {
        log.debug("Jikes.compile():SomethingHappened", somethingHappened);
        return false;
    }

    // Jikes returns 0 even when there are some types of errors.
    // Check if any error output as well
    // Return should be OK when both exitValue and
    // tmpErr.size() are 0 ?!
    return ((exitValue == 0) && (tmpErr.size() == 0));
}

From source file:lohbihler.process.epoll.ProcessMonitor.java

public ProcessMonitor(final Process process, final ExecutorService executorService, final long timeout)
        throws InterruptedException {
    final InputReader out = new InputReader(process.getInputStream());
    final InputReader err = new InputReader(process.getErrorStream());

    executorService.execute(out);//from  www .  j  a  v a 2 s .c o  m
    executorService.execute(err);

    ProcessTimeout processTimeout = null;
    if (timeout > 0) {
        processTimeout = new ProcessTimeout(process, timeout);
        executorService.execute(processTimeout);
    }

    process.waitFor();
    out.join();
    err.join();
    process.destroy();

    // If we've made it this far, the process exited properly, so kill the
    // timeout thread if it exists.
    if (processTimeout != null)
        processTimeout.interrupt();

    this.out = out.getInput();
    this.err = err.getInput();
}

From source file:cognition.common.service.DocumentConversionService.java

private File makeTiffFromPDF(DNCWorkCoordinate coordinate, File input) throws IOException, TikaException {
    File output = File.createTempFile(coordinate.getFileName(), ".tiff");
    String[] cmd = { getImageMagickProg(), "-density", "300", input.getPath(), "-depth", "8", "-quality", "1",
            output.getPath() };//from ww  w .  ja  v  a  2s  .c  o m
    Process process = new ProcessBuilder(cmd).start();
    IOUtils.closeQuietly(process.getOutputStream());
    InputStream processInputStream = process.getInputStream();
    logStream(processInputStream);
    FutureTask<Integer> waitTask = new FutureTask<>(process::waitFor);
    Thread waitThread = new Thread(waitTask);
    waitThread.start();
    try {
        waitTask.get(240, TimeUnit.SECONDS);
        return output;
    } catch (Exception e) {
        logger.error(e.getMessage());
        waitThread.interrupt();
        process.destroy();
        waitTask.cancel(true);
    } finally {
        IOUtils.closeQuietly(processInputStream);
        process.destroy();
        waitThread.interrupt();
        waitTask.cancel(true);
    }
    return null;
}

From source file:uk.ac.kcl.iop.brc.core.pipeline.common.service.DocumentConversionService.java

private File makeTiffFromPDF(DNCWorkCoordinate coordinate, File input) throws IOException, TikaException {
    File output = File.createTempFile(coordinate.getFileName(), ".tiff");
    String[] cmd = { getImageMagickProg(), "-density", "300", input.getPath(), "-depth", "8", "-quality", "1",
            output.getPath() };//ww w  .  java 2 s .  co m
    Process process = new ProcessBuilder(cmd).start();
    IOUtils.closeQuietly(process.getOutputStream());
    InputStream processInputStream = process.getInputStream();
    logStream(processInputStream);
    FutureTask<Integer> waitTask = new FutureTask<>(process::waitFor);
    Thread waitThread = new Thread(waitTask);
    waitThread.start();
    try {
        waitTask.get(240, TimeUnit.SECONDS);
        return output;
    } catch (Exception e) {
        logger.error(e.getMessage());
        waitThread.interrupt();
        process.destroy();
        Thread.currentThread().interrupt();
        waitTask.cancel(true);
    } finally {
        IOUtils.closeQuietly(processInputStream);
        process.destroy();
        waitThread.interrupt();
        waitTask.cancel(true);
    }
    return null;
}

From source file:er.extensions.ERXExtensions.java

/**
 * Frees all of the resources associated with a given
 * process and then destroys the process.
 * @param p process to destroy//from ww w  . jav a 2  s . c  o m
 */
public static void freeProcessResources(Process p) {
    if (p != null) {
        try {
            if (p.getInputStream() != null)
                p.getInputStream().close();
            if (p.getOutputStream() != null)
                p.getOutputStream().close();
            if (p.getErrorStream() != null)
                p.getErrorStream().close();
            p.destroy();
        } catch (IOException e) {
        }
    }
}

From source file:org.sonatype.nexus.testsuite.obr.ObrITSupport.java

protected void deployUsingObrIntoFelix(final String repoId) throws Exception {
    final File felixHome = util.resolveFile("target/org.apache.felix.main.distribution-3.2.2");
    final File felixRepo = util.resolveFile("target/felix-local-repository");
    final File felixConfig = testData().resolveFile("felix.properties");

    // ensure we have an obr.xml
    final Content content = content();
    final Location obrLocation = new Location(repoId, ".meta/obr.xml");
    content.download(obrLocation, new File(testIndex().getDirectory("downloads"), repoId + "-obr.xml"));

    FileUtils.deleteDirectory(new File(felixHome, "felix-cache"));
    FileUtils.deleteDirectory(new File(felixRepo, ".meta"));

    final ProcessBuilder pb = new ProcessBuilder("java", "-Dfelix.felix.properties=" + felixConfig.toURI(),
            "-jar", "bin/felix.jar");
    pb.directory(felixHome);//w ww .  j  a  v  a  2s.c  o m
    pb.redirectErrorStream(true);
    final Process p = pb.start();

    final Object lock = new Object();

    final Thread t = new Thread(new Runnable() {
        public void run() {
            // just a safeguard, if felix get stuck kill everything
            try {
                synchronized (lock) {
                    lock.wait(5 * 1000 * 60);
                }
            } catch (final InterruptedException e) {
                // ignore
            }
            p.destroy();
        }
    });
    t.setDaemon(true);
    t.start();

    synchronized (lock) {
        final InputStream input = p.getInputStream();
        final OutputStream output = p.getOutputStream();
        waitFor(input, "g!");

        output.write(("obr:repos add " + nexus().getUrl() + "content/" + obrLocation.toContentPath() + "\r\n")
                .getBytes());
        output.flush();
        waitFor(input, "g!");

        output.write(("obr:repos remove http://felix.apache.org/obr/releases.xml\r\n").getBytes());
        output.flush();
        waitFor(input, "g!");

        output.write(("obr:repos list\r\n").getBytes());
        output.flush();
        waitFor(input, "g!");

        output.write("obr:deploy -s org.apache.felix.webconsole\r\n".getBytes());
        output.flush();
        waitFor(input, "done.");

        p.destroy();

        lock.notifyAll();
    }
}

From source file:org.jodconverter.office.OfficeProcessManagerPoolEntryITest.java

/**
 * Tests that an office process is restarted successfully after a crash.
 *
 * @throws Exception if an error occurs.
 *///from www  .  j av  a 2  s  . c o m
@Test
public void execute_WhenOfficeProcessCrash_ShouldRestartAfterCrash() throws Exception {

    final OfficeProcessManagerPoolEntry officeManager = new OfficeProcessManagerPoolEntry(CONNECT_URL);

    try {
        officeManager.start();
        assertThat(officeManager.isRunning()).isTrue();
        assertThat(officeManager)
                .extracting("officeProcessManager.process.running", "officeProcessManager.connection.connected")
                .containsExactly(true, true);

        // Submit the task to an executor
        final ExecutorService pool = Executors.newFixedThreadPool(1);
        try {
            final Callable<Boolean> task = new RestartAfterCrashTask(officeManager);
            final Future<Boolean> future = pool.submit(task);

            Thread.sleep(500); // NOSONAR

            // Simulate crash
            final Process underlyingProcess = (Process) FieldUtils.readField(getOfficeProcess(officeManager),
                    "process", true);
            assertThat(underlyingProcess).isNotNull();
            LOGGER.debug("Simulating the crash");
            underlyingProcess.destroy();

            // Wait until the task is completed
            try {
                future.get();
                fail("Exception expected");
            } catch (ExecutionException ex) {
                assertThat(ex.getCause()).isInstanceOf(OfficeException.class);
                assertThat(ex.getCause().getCause()).isInstanceOf(CancellationException.class);
            }

        } finally {
            pool.shutdownNow();
        }

        assertRestartedAndReconnected(officeManager, RESTART_INITIAL_WAIT, RESTART_WAIT_TIMEOUT);

        final MockOfficeTask goodTask = new MockOfficeTask();
        officeManager.execute(goodTask);
        assertThat(goodTask.isCompleted()).isTrue();

    } finally {

        officeManager.stop();
        assertThat(officeManager.isRunning()).isFalse();
        assertThat(officeManager)
                .extracting("officeProcessManager.process.running", "officeProcessManager.connection.connected")
                .containsExactly(false, false);
        assertThat(getOfficeProcess(officeManager).getExitCode(0, 0)).isEqualTo(0);
    }
}

From source file:io.fabric8.maven.plugin.DebugMojo.java

private void portForward(Controller controller, String podName) throws MojoExecutionException {
    File file = getKubeCtlExecutable(controller);
    String command = file.getName();
    log.info(/*from   ww w .  j ava 2 s. c o  m*/
            "Port forwarding to port " + remoteDebugPort + " on pod " + podName + " using command: " + command);

    String arguments = " port-forward " + podName + " " + localDebugPort + ":" + remoteDebugPort;
    String commands = command + arguments;
    log.info("Executing command: " + commands);
    final String message = "port forward";
    final Process process;
    try {
        process = Runtime.getRuntime().exec(file.getAbsolutePath() + arguments);
        Runtime.getRuntime().addShutdownHook(new Thread("mvn fabric8:run-interactive shutdown hook") {
            @Override
            public void run() {
                if (process != null) {
                    log.info("Terminating port forward process:");
                    try {
                        process.destroy();
                    } catch (Exception e) {
                        log.error("Failed to terminate process " + message);
                    }
                    try {
                        if (process != null && process.isAlive()) {
                            process.destroyForcibly();
                        }
                    } catch (Exception e) {
                        log.error("Failed to forcibly terminate process " + message);
                    }
                }
            }
        });

        log.info("");
        log.info("Now you can start a Remote debug execution in your IDE by using localhost and the debug port "
                + localDebugPort);
        log.info("");

        processCommandAsync(process, createExternalProcessLogger(command + "> "), commands, message);
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to execute process " + commands + " for " + message + ": " + e,
                e);
    }
}

From source file:com.xpn.xwiki.plugin.graphviz.GraphVizPlugin.java

/**
 * Executes GraphViz, writes the resulting image (in the requested format) in a temporary file on disk, and returns
 * the generated content from that file.
 * /*from ww  w .  j av  a2 s. co m*/
 * @param hashCode the hascode of the content, to be used as the temporary file name
 * @param content the dot source code
 * @param extension the output file extension
 * @param dot which engine to execute: {@code dot} if {@code true}, {@code neato} if {@code false}
 * @return the content of the generated file
 * @throws IOException if writing the input or output files to the disk fails, or if writing the response body fails
 */
private byte[] getDotImage(int hashCode, String content, String extension, boolean dot) throws IOException {
    File dfile = getTempFile(hashCode, "input.dot", dot);
    if (!dfile.exists()) {
        FileUtils.write(dfile, content, XWiki.DEFAULT_ENCODING);
    }

    File ofile = getTempFile(hashCode, extension, dot);
    if (!ofile.exists()) {
        Runtime rt = Runtime.getRuntime();
        String[] command = new String[5];
        command[0] = dot ? this.dotPath : this.neatoPath;
        command[1] = "-T" + extension;
        command[2] = dfile.getAbsolutePath();
        command[3] = "-o";
        command[4] = ofile.getAbsolutePath();
        Process p = rt.exec(command);
        int exitValue = -1;
        final Thread thisThread = Thread.currentThread();
        Thread t = new Thread(new Hangcheck(thisThread), "dot-hangcheck");
        t.run();
        try {
            exitValue = p.waitFor();
            t.interrupt();
        } catch (InterruptedException ex) {
            p.destroy();
            LOGGER.error("Timeout while generating image from dot", ex);
        }

        if (exitValue != 0) {
            LOGGER.error("Error while generating image from dot: "
                    + IOUtils.toString(p.getErrorStream(), XWiki.DEFAULT_ENCODING));
        }
    }
    return FileUtils.readFileToByteArray(ofile);
}

From source file:org.wso2.appserver.integration.common.utils.CarbonCommandToolsUtil.java

/**
 * This method is to execute commands and reading the logs to find the expected string.
 *
 * @param directory      - Directory which has the file to be executed .
 * @param cmdArray       - Command array to be executed.
 * @param expectedString - Expected string in  the log.
 * @return boolean - true : Found the expected string , false : not found the expected string.
 * @throws CarbonToolsIntegrationTestException - Error while running the command.
 *//* w w  w .  j  av a 2 s  .  com*/
public static boolean isScriptRunSuccessfully(String directory, String[] cmdArray, String expectedString)
        throws CarbonToolsIntegrationTestException {
    boolean isFoundTheMessage = false;
    BufferedReader br = null;
    Process process = null;
    try {
        File commandDir = new File(directory);
        process = Runtime.getRuntime().exec(cmdArray, null, commandDir);
        String line;
        long startTime = System.currentTimeMillis();
        while (!isFoundTheMessage && (System.currentTimeMillis() - startTime) < TIMEOUT_MS) {
            br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            while ((line = br.readLine()) != null) {
                log.info(line);
                if (line.contains(expectedString)) {
                    log.info("found the string " + expectedString + " in line " + line);
                    isFoundTheMessage = true;
                    break;
                }
            }
        }
        return isFoundTheMessage;
    } catch (IOException ex) {
        log.error("Error when reading the InputStream when running shell script  ", ex);
        throw new CarbonToolsIntegrationTestException(
                "Error when reading the InputStream when " + "running shell script ", ex);
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                log.warn("Error when closing the buffer reader ", e);
            }
        }
        if (process != null) {
            process.destroy();
        }
    }
}