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.ops4j.pax.url.mvnlive.internal.Connection.java

/**
 * Create helper thread to safely shutdown the external framework process
 *
 * @param process framework process//from w ww .  j ava  2 s.c  om
 * @return stream handler
 */
private Thread createShutdownHook(final Process process) {
    final Pipe errPipe = new Pipe(process.getErrorStream(), System.err).start("Error pipe");
    final Pipe outPipe = new Pipe(process.getInputStream(), System.out).start("Out pipe");
    final Pipe inPipe = new Pipe(process.getOutputStream(), System.in).start("In pipe");

    Thread shutdownHook = new Thread(new Runnable() {
        public void run() {
            inPipe.stop();
            outPipe.stop();
            errPipe.stop();

            try {
                process.destroy();
            } catch (Exception e) {
                // ignore if already shutting down
            }
        }
    }, "mvnlive url handler shutdown hook");

    return shutdownHook;
}

From source file:net.unicon.academus.spell.SpellCheckerServlet.java

private boolean checkHTMLFilter() throws Exception {
    boolean rslt = false;

    String[] cmdline = new String[3];
    cmdline[0] = aspell_loc;//from w ww  .  ja  v  a 2 s.co  m
    cmdline[1] = "dump";
    cmdline[2] = "filters";

    Process p = Runtime.getRuntime().exec(cmdline);
    BufferedReader pin = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = pin.readLine();
    while (!rslt && line != null) {
        if (line.startsWith("html"))
            rslt = true;

        line = pin.readLine();
    }
    pin.close();
    p.destroy();

    log.info("Aspell HTML Filter support: " + rslt);
    return rslt;
}

From source file:org.codesearch.commons.plugins.vcs.GitLocalPlugin.java

private void cleanupProcess(Process p) {
    if (p != null) {
        try {/*  ww  w  . j  a  va2 s .  c  om*/
            p.getErrorStream().close();
        } catch (IOException ex) {
        }
        try {
            p.getInputStream().close();
        } catch (IOException ex) {
        }
        try {
            p.getOutputStream().close();
        } catch (IOException ex) {
        }
        p.destroy();
    }
}

From source file:eu.udig.omsbox.OmsBoxPlugin.java

public void killProcess(String id) {
    Process process = runningProcessesMap.get(id);
    if (process != null) {
        runningProcessesMap.remove(id);//  w w w . j a  v  a 2s. c  om
        process.destroy();
    }
    // also cleanup if needed
    Set<Entry<String, Process>> entrySet = runningProcessesMap.entrySet();
    for (Entry<String, Process> entry : entrySet) {
        if (entry.getValue() == null) {
            String key = entry.getKey();
            if (key != null)
                runningProcessesMap.remove(key);
        }
    }
}

From source file:org.kaaproject.kaa.sandbox.AbstractSandboxBuilder.java

protected String execute(boolean logOutput, List<String> command) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(command).directory(basePath);
    Process p = pb.start();
    String result = handleStream(p.getInputStream(), logOutput);
    handleStream(p.getErrorStream(), true);
    p.waitFor();/* w w  w . j  a v a  2  s.  c o  m*/
    p.destroy();
    return result;
}

From source file:org.testeditor.dsl.common.util.MavenExecutor.java

/**
 * Executes a maven build in a new jvm. The executable of the current jvm is
 * used to create a new jvm.//from  w w w.j  av  a  2 s.c o  m
 * 
 * @param parameters
 *            for maven (separated by spaces, e.g. "clean integration-test"
 *            to execute the given goals)
 * @param pathtoPom
 *            path to the folder where the pom.xml is located.
 * @param testParam
 *            pvm parameter to identify the test case to be executed.
 * @param monitor
 *            Progress monitor to handle cancel events.
 * @return the result interpreted as {@link IStatus}.
 * @throws IOException
 *             on failure
 */
public int executeInNewJvm(String parameters, String pathToPom, String testParam, IProgressMonitor monitor,
        OutputStream outputStream) throws IOException {
    List<String> command = createMavenExecCommand(parameters, testParam);
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.directory(new File(pathToPom));
    logger.info("Executing maven in folder='{}'.", pathToPom);
    logger.info("Executing maven in new jvm with command='{}'.", command);
    processBuilder.command(command);
    Process process = processBuilder.start();
    PrintStream out = new PrintStream(outputStream);
    OutputStreamCopyUtil outputCopyThread = new OutputStreamCopyUtil(process.getInputStream(), out);
    OutputStreamCopyUtil errorCopyThread = new OutputStreamCopyUtil(process.getErrorStream(), out);
    outputCopyThread.start();
    errorCopyThread.start();
    try {
        while (!process.waitFor(100, TimeUnit.MILLISECONDS)) {
            if (monitor.isCanceled()) {
                process.destroy();
                out.println("Operation cancelled.");
                return IStatus.CANCEL;
            }
        }
        return process.exitValue() == 0 ? IStatus.OK : IStatus.CANCEL;
    } catch (InterruptedException e) {
        logger.error("Caught exception.", e);
        return IStatus.ERROR;
    }
}

From source file:com.asakusafw.runtime.util.hadoop.ConfigurationProviderTest.java

/**
 * search for confdir from PATH using symlink.
 * @throws IOException IOException/* ww  w.java  2s . com*/
 */
@Test
public void symlink() throws IOException {
    Assume.assumeThat(SystemUtils.IS_OS_WINDOWS, is(false));

    File cmd = putExec("hadoop/bin/hadoop");
    putConf("hadoop/etc/hadoop/core-site.xml");

    File path = folder.newFolder("path");
    try {
        Process proc = new ProcessBuilder("ln", "-s", cmd.getAbsolutePath(),
                new File(path, "hadoop").getAbsolutePath()).start();
        try {
            int exitCode = proc.waitFor();
            Assume.assumeThat(exitCode, is(0));
        } finally {
            proc.destroy();
        }
    } catch (Exception e) {
        System.out.println("Failed to create symlink");
        e.printStackTrace(System.out);
        Assume.assumeNoException(e);
    }

    Map<String, String> envp = new HashMap<>();
    envp.put("PATH", path.getAbsolutePath());

    Configuration conf = new ConfigurationProvider(envp).newInstance();
    assertThat(isLoaded(conf), is(true));

    File file = ConfigurationProvider.findHadoopCommand(envp);
    assertThat(file, is(notNullValue()));
    assertThat(file.toString(), file.canExecute(), is(true));
    assertThat(file.toString(), file.getParentFile().getName(), is("path"));
}

From source file:net.pms.util.ProcessUtil.java

public static void destroy(final Process p) {
    if (p != null) {
        final Integer pid = getProcessID(p);

        if (pid != null) { // Unix only
            LOGGER.trace("Killing the Unix process: " + pid);
            Runnable r = new Runnable() {
                @Override/*from  ww  w  . j a v  a 2  s  .c o  m*/
                public void run() {
                    try {
                        Thread.sleep(TERM_TIMEOUT);
                    } catch (InterruptedException e) {
                    }

                    try {
                        p.exitValue();
                    } catch (IllegalThreadStateException itse) { // still running: nuke it
                        // kill -14 (ALRM) works (for MEncoder) and is less dangerous than kill -9
                        // so try that first
                        if (!kill(pid, 14)) {
                            try {
                                // This is a last resort, so let's not be too eager
                                Thread.sleep(ALRM_TIMEOUT);
                            } catch (InterruptedException ie) {
                            }

                            kill(pid, 9);
                        }
                    }
                }
            };

            Thread failsafe = new Thread(r, "Process Destroyer");
            failsafe.start();
        }

        p.destroy();
    }
}

From source file:net.timbusproject.extractors.debiansoftwareextractor.Engine.java

private Properties doCommand(String command) throws InterruptedException, JSchException, IOException {
    if (isSsh())/*from  w  ww  .ja va 2 s.c  om*/
        return sshManager.sendCommand(command);
    Properties properties = new Properties();
    Process process = new ProcessBuilder("/bin/sh", "-c", command).start();
    StringWriter writer = new StringWriter();
    IOUtils.copy(process.getInputStream(), writer);
    properties.setProperty("stdout", writer.toString());
    IOUtils.copy(process.getErrorStream(), writer);
    properties.setProperty("stderr", writer.toString());
    properties.setProperty("exit-value", String.valueOf(process.waitFor()));
    process.destroy();
    if (Integer.parseInt(properties.getProperty("exit-value")) != 0)
        log.warn("command \"" + command.split(" ")[0] + "\" failed with status: "
                + properties.getProperty("exit-value"));
    return properties;
}

From source file:uk.ac.sanger.cgp.wwdocker.workflow.DEWorkflow.java

@Override
public int cleanDockerPath(BaseConfiguration config) {
    String command = baseDockerCommand(config, null);
    String datastore = config.getString("datastoreDir");
    List<String> args = new ArrayList(Arrays.asList(command.split(" ")));
    args.add("/bin/bash");
    args.add("-c");
    args.add("rm -rf " + datastore + "/oozie-* " + datastore + "/*.ini " + datastore + "/logs.tar.gz "
            + datastore + "/toInclude.lst" + datastore + "/DEWorkflowData/dkfz/gtdownload-*.log");

    ProcessBuilder pb = new ProcessBuilder(args);

    Map<String, String> pEnv = pb.environment();
    pEnv.putAll(Config.getEnvs(config));
    logger.info("Executing: " + String.join(" ", args));
    int exitCode = -1;
    Process p = null;
    try {//from w  w  w.j  av a2 s  .  co  m
        p = pb.start();
        String progErr = IOUtils.toString(p.getErrorStream());
        String progOut = IOUtils.toString(p.getInputStream());
        exitCode = p.waitFor();
        Utils.logOutput(progErr, Level.ERROR);
        Utils.logOutput(progOut, Level.TRACE);
    } catch (InterruptedException | IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (p != null) {
            p.destroy();
            exitCode = p.exitValue();
        }
    }
    return exitCode;
}