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.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.java

int stopProcessWithTimeout(final Process proc, long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
    FutureTask<Integer> future = new FutureTask<>(() -> {
        proc.destroy();
        return proc.waitFor();
    });/*w w w. j  av  a  2s . com*/

    executor.execute(future);

    return future.get(timeout, unit);
}

From source file:org.apache.hadoop.hbase.allocation.group.MoveConfImpl.java

/**
 * Scp configuration between regionservers
 * /*from   ww w  . j  av  a 2  s.c  o m*/
 * @param server
 *          regionserver name ,example "dw83.kgb.sqa.cm4,60020"
 * @param command
 *          if command is "get" ,it will get remote regionserver configuration
 *          and library to local temp file ; if command is "put", it will put
 *          temp configuration and library to remote regionserver.
 * @return true if success ,else false
 */
public boolean ScpConf(String server, String command) {
    Process process = null;
    if (!command.equals("get") && !command.equals("put")) {
        LOG.info("This shell script only support get and put command.");
        return false;
    }
    String[] getcommand = new String[5];
    getcommand[0] = currentdir + "/moveremoteconf.sh";
    getcommand[1] = server;
    getcommand[2] = ConfDIR;
    getcommand[3] = HbaseDIR;
    getcommand[4] = command;
    try {
        process = Runtime.getRuntime().exec(getcommand, null, new File(currentdir));
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    try {
        process.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
        return false;
    }
    process.destroy();
    return true;
}

From source file:net.opentsdb.tsd.GraphHandler.java

/**
 * Runs Gnuplot in a subprocess to generate the graph.
 * <strong>This function will block</strong> while Gnuplot is running.
 * @param query The query being handled (for logging purposes).
 * @param basepath The base path used for the Gnuplot files.
 * @param plot The plot object to generate Gnuplot's input files.
 * @return The number of points plotted by Gnuplot (0 or more).
 * @throws IOException if the Gnuplot files can't be written, or
 * the Gnuplot subprocess fails to start, or we can't read the
 * graph from the file it produces, or if we have been interrupted.
 * @throws GnuplotException if Gnuplot returns non-zero.
 *///from   ww  w. j a  v a  2 s.  c  om
static int runGnuplot(final HttpQuery query, final String basepath, final Plot plot) throws IOException {
    final int nplotted = plot.dumpToFiles(basepath);
    final long start_time = System.nanoTime();
    final Process gnuplot = new ProcessBuilder(GNUPLOT, basepath + ".out", basepath + ".err",
            basepath + ".gnuplot").start();
    final int rv;
    try {
        rv = gnuplot.waitFor(); // Couldn't find how to do this asynchronously.
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // Restore the interrupted status.
        throw new IOException("interrupted", e); // I hate checked exceptions.
    } finally {
        // We need to always destroy() the Process, otherwise we "leak" file
        // descriptors and pipes.  Unless I'm blind, this isn't actually
        // documented in the Javadoc of the !@#$%^ JDK, and in Java 6 there's no
        // way to ask the stupid-ass ProcessBuilder to not create fucking pipes.
        // I think when the GC kicks in the JVM may run some kind of a finalizer
        // that closes the pipes, because I've never seen this issue on long
        // running TSDs, except where ulimit -n was low (the default, 1024).
        gnuplot.destroy();
    }
    gnuplotlatency.add((int) ((System.nanoTime() - start_time) / 1000000));
    if (rv != 0) {
        final byte[] stderr = readFile(query, new File(basepath + ".err"), 4096);
        // Sometimes Gnuplot will error out but still create the file.
        new File(basepath + ".png").delete();
        if (stderr == null) {
            throw new GnuplotException(rv);
        }
        throw new GnuplotException(new String(stderr));
    }
    // Remove the files for stderr/stdout if they're empty.
    deleteFileIfEmpty(basepath + ".out");
    deleteFileIfEmpty(basepath + ".err");
    return nplotted;
}

From source file:org.wso2.carbon.integration.tests.patching.CARBON14488ForceFullyStopTestCase.java

/**
 * This method reads logs of running AS and when patch verification starts this will kill the process
 * of running AS//from w  ww .  ja  v  a2 s  .  co m
 *
 * @param process - Process which executes AS
 */
private void readInputStream(Process process) throws Exception {
    InputStreamHandler errorStreamHandler = new InputStreamHandler("errorStream", process.getErrorStream());
    InputStreamHandler inputStreamHandler = new InputStreamHandler("inputStream", process.getInputStream());

    // start the stream readers
    inputStreamHandler.start();
    errorStreamHandler.start();

    long time = System.currentTimeMillis() + 20 * 1000;

    String output = inputStreamHandler.getOutput();

    //Time duration is to avoid infinitely running the loop
    while (!output.contains(PATCH_VERIFICATION_MESSAGE) && System.currentTimeMillis() < time) {
        output = inputStreamHandler.getOutput();
    }

    if (output.contains(PATCH_VERIFICATION_MESSAGE)) {
        killProcess();
    }
    process.destroy();
}

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

@Test
public void connectorCount() {
    Process process = null;
    try {//w  w w .ja  v  a2  s  . c  om
        PROCESS_BUILDER
                .command(getCommand(new ConnectorCommand().getClass().getAnnotation(Command.class).name(),
                        ConnectorCommand.ConnectorOptions.LIST_BUNDLES.getOptionName()));
        process = PROCESS_BUILDER.start();

        long bundles = IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8).stream()
                .filter(line -> line.startsWith(" > BUNDLE NAME:")).count();
        assertEquals(connectorService.getBundles(null).size(), bundles);
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:org.opf_labs.utils.ProcessRunnerImpl.java

private synchronized int execute(final Process p) {
    long startTime = System.currentTimeMillis();
    feedProcess(p, this.processInput);
    int return_value;

    while (true) {
        // is the thread finished?
        try {/*from  ww w.ja v  a  2  s . c  o  m*/
            // then return
            return_value = p.exitValue();
            break;
        } catch (IllegalThreadStateException e) {
            // not finished
        }
        // is the runtime exceeded?
        if (System.currentTimeMillis() - startTime > this.timeout) {
            // then return
            p.destroy();
            return_value = -1;
            this.timedOut = true;
        }
        // else sleep again
        try {
            wait(POLLING_INTERVAL);
        } catch (InterruptedException e) {
            // just go on.
        }

    }
    return return_value;

}

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

@Test
public void entitlementCount() {
    Process process = null;
    try {//from w  ww .  j  a v a  2  s .com
        PROCESS_BUILDER
                .command(getCommand(new EntitlementCommand().getClass().getAnnotation(Command.class).name(),
                        EntitlementCommand.EntitlementOptions.LIST.getOptionName()));
        process = PROCESS_BUILDER.start();

        long entitlements = IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8).stream()
                .filter(line -> line.startsWith("-")).count();
        assertEquals(syncopeService.platform().getEntitlements().size(), entitlements);
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:de.smartics.maven.plugin.buildmetadata.scm.maven.ScmAccessInfo.java

/**
 * Fetches the version from the remote Git repository. The implementation uses
 * the Git Command Line Utils./*w  w w. j  a  v a 2s. c  o  m*/
 *
 * @param repository the reference to the repository (currently not used).
 * @param remoteVersion the version to fetch.
 * @return the revision information.
 * @throws ScmException on any problem accessing the remote repository.
 */
public Revision fetchRemoteGitVersion(final ScmRepository repository, final ScmVersion remoteVersion)
        throws ScmException {
    try {
        final Commandline cl = GitCommandLineUtils.getBaseGitCommandLine(rootDirectory, "log");
        cl.createArg().setLine("-n 1");
        cl.createArg().setLine("--pretty=format:\"%H %ct\"");
        cl.createArg().setLine(remoteVersion.getName());
        final Process process = cl.execute();
        try {
            process.waitFor();
            final int exitValue = process.exitValue();
            if (exitValue != 0) {
                throw new ScmException("Cannot fetch remote version from repository (" + exitValue + "): "
                        + IOUtils.toString(process.getErrorStream()));
            }
            final String result = IOUtils.toString(process.getInputStream());
            final Revision revision = createRevision(result);
            return revision;
        } finally {
            process.destroy();
        }
    } catch (final Exception e) {
        throw new ScmException("Cannot fetch remote version from repository.", e);
    }
}

From source file:org.apache.hadoop.hbase.allocation.group.MoveConfImpl.java

/**
 * DistributeConf configuration to regionserver
 * //from  ww  w .  ja  va2s .  c  o m
 * @param server
 *          regionserver name ,example "dw83.kgb.sqa.cm4,60020"
 * @param command
 *          if command is "distribute " ,it will distribute hbase-site,xml to
 *          remote regionservwer
 * @return true if success ,else false
 */
public boolean DistributeConf(String server, String command) {
    Process process = null;
    if (!command.equals("distribute")) {
        LOG.info("This shell script only support distribute  command.");
        return false;
    }
    String[] distributecommand = new String[5];
    distributecommand[0] = currentdir + "/moveremoteconf.sh";
    distributecommand[1] = server;
    distributecommand[2] = ConfDIR;
    distributecommand[3] = HbaseDIR;
    distributecommand[4] = command;
    try {
        process = Runtime.getRuntime().exec(distributecommand, null, new File(currentdir));
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    try {
        process.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
        return false;
    }
    process.destroy();
    return true;
}

From source file:org.ensembl.healthcheck.util.StreamGobbler.java

private static int waitForProcess(Thread outputGobbler, Thread errorGobbler, boolean discard, Process proc) {

    // kick them off
    errorGobbler.start();/*from  w w w .j  a v  a  2s  .  co m*/
    outputGobbler.start();

    // return exit status
    try {

        // get the exit status of the command once finished
        //
        int exit = proc.waitFor();

        // now wait for the output and error to be read with a suitable
        // timeout
        //
        outputGobbler.join(TIMEOUT);
        errorGobbler.join(TIMEOUT);
        return exit;

    } catch (InterruptedException e) {

        // While the Process is running, the Thread is in the state 
        // called "WAITING". If an interrupt has been requested and caught
        // within the thread, reinterrupting is requested.
        //
        // See
        // http://download.oracle.com/javase/1,5.0/docs/guide/misc/threadPrimitiveDeprecation.html
        // chapter
        // Section "How do I stop a thread that waits for long periods (e.g., for input)?"
        // for more details on this.
        // 
        Thread.currentThread().interrupt();

        return -1;

    } finally {

        // to make sure the all streams are closed to avoid open file handles
        //
        IOUtils.closeQuietly(proc.getErrorStream());
        IOUtils.closeQuietly(proc.getInputStream());
        IOUtils.closeQuietly(proc.getOutputStream());

        // Otherwise we will be waiting for the process to terminate on 
        // its own instead of interrupting as the user has requested.
        //
        proc.destroy();
    }
}