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:io.appium.java_client.service.local.AppiumServiceBuilder.java

private static void validateNodeJSVersion() {
    Runtime rt = Runtime.getRuntime();
    String result = null;//from  ww w.ja v  a 2s .  c om
    Process p = null;
    try {
        p = rt.exec(NODE_COMMAND_PREFIX + " node -v");
        p.waitFor();
        result = getProcessOutput(p.getInputStream());
    } catch (Exception e) {
        throw new InvalidNodeJSInstance("Node.js is not installed", e);
    } finally {
        if (p != null)
            p.destroy();
    }

    String versionNum = result.replace("v", "");
    String[] tokens = versionNum.split("\\.");
    if (Integer.parseInt(tokens[0]) < REQUIRED_MAJOR_NODE_JS
            || Integer.parseInt(tokens[1]) < REQUIRED_MINOR_NODE_JS)
        throw new InvalidNodeJSInstance("Current node.js version " + versionNum + "is lower than "
                + "required (" + REQUIRED_MAJOR_NODE_JS + "." + REQUIRED_MINOR_NODE_JS + " or greater)");
}

From source file:io.github.bonigarcia.wdm.Downloader.java

public static final File extractMsi(File msi) throws IOException {
    File tmpMsi = new File(Files.createTempDir().getAbsoluteFile() + File.separator + msi.getName());
    Files.move(msi, tmpMsi);// www. ja va 2s  .c  o m
    log.trace("Temporal msi file: {}", tmpMsi);

    Process process = Runtime.getRuntime()
            .exec(new String[] { "msiexec", "/a", tmpMsi.toString(), "/qb", "TARGETDIR=" + msi.getParent() });
    try {
        process.waitFor();
    } catch (InterruptedException e) {
        log.error("Exception waiting to msiexec to be finished", e);
    } finally {
        process.destroy();
    }

    tmpMsi.delete();

    Collection<File> listFiles = FileUtils.listFiles(new File(msi.getParent()), new String[] { "exe" }, true);
    return listFiles.iterator().next();
}

From source file:Main.java

private static String propReader(String filter) {
    Process process = null;
    try {/*from   ww  w . j  av a2  s.com*/
        process = new ProcessBuilder().command("/system/bin/getprop").redirectErrorStream(true).start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

    StringBuilder log = new StringBuilder();
    String line;
    try {
        while ((line = bufferedReader.readLine()) != null) {
            if (line.contains(filter))
                log.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    process.destroy();
    return log.toString();
}

From source file:eu.stratosphere.nephele.instance.HardwareDescriptionFactory.java

/**
 * Returns the size of the physical memory in bytes on a Mac OS-based
 * operating system//from  w ww.  j a v  a 2  s  .c o  m
 * 
 * @return the size of the physical memory in bytes or <code>-1</code> if
 *         the size could not be determined
 */
private static long getSizeOfPhysicalMemoryForMac() {

    BufferedReader bi = null;

    try {
        Process proc = Runtime.getRuntime().exec("sysctl hw.memsize");

        bi = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        String line;

        while ((line = bi.readLine()) != null) {
            if (line.startsWith("hw.memsize")) {
                long memsize = Long.parseLong(line.split(":")[1].trim());
                bi.close();
                proc.destroy();
                return memsize;
            }
        }

    } catch (Exception e) {
        LOG.error(e);
        return -1;
    } finally {
        if (bi != null) {
            try {
                bi.close();
            } catch (IOException ioe) {
            }
        }
    }
    return -1;
}

From source file:eu.stratosphere.nephele.instance.HardwareDescriptionFactory.java

/**
 * Returns the size of the physical memory in bytes on FreeBSD.
 * /*from www. j ava 2  s  . com*/
 * @return the size of the physical memory in bytes or <code>-1</code> if
 *         the size could not be determined
 */
private static long getSizeOfPhysicalMemoryForFreeBSD() {
    BufferedReader bi = null;
    try {
        Process proc = Runtime.getRuntime().exec("sysctl hw.physmem");

        bi = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        String line;

        while ((line = bi.readLine()) != null) {
            if (line.startsWith("hw.physmem")) {
                long memsize = Long.parseLong(line.split(":")[1].trim());
                bi.close();
                proc.destroy();
                return memsize;
            }
        }

        LOG.error("Cannot determine the size of the physical memory using 'sysctl hw.physmem'.");
        return -1;
    } catch (Exception e) {
        LOG.error(
                "Cannot determine the size of the physical memory using 'sysctl hw.physmem': " + e.getMessage(),
                e);
        return -1;
    } finally {
        if (bi != null) {
            try {
                bi.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:com.tc.process.Exec.java

@SuppressWarnings("resource")
public static Result execute(final Process process, String cmd[], String outputLog, byte[] input,
        File workingDir, final long timeout) throws Exception {
    final AtomicBoolean processFinished = new AtomicBoolean();
    if (timeout > 0) {
        Thread timeoutThread = new Thread() {
            @Override//from   w w w.  j  a  va2  s  .  c  om
            public void run() {
                ThreadUtil.reallySleep(timeout);
                if (!processFinished.get()) {
                    process.destroy();
                }
            }
        };
        timeoutThread.start();
    }

    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) {
            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());
        } else {
            stderr = new StreamCollector(process.getErrorStream());
            stdout = new StreamCollector(process.getInputStream());
            stderr.start();
            stdout.start();
        }

        inputThread.start();

        final int exitCode = process.waitFor();
        processFinished.set(true);

        inputThread.join();

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

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

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

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

From source file:ubic.pubmedgate.treetagger.TreeTaggerRunner.java

public static ArrayList<String> runTreeTagger(File inputFile) throws IOException {
    String line;/*  w  w  w. j a v  a 2s . c om*/
    String[] command = getTreeTaggerCommand(inputFile);
    // log.info( Arrays.asList( command ) );
    Process p = Runtime.getRuntime().exec(command);

    // get tree tagger output (gate input)
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

    ArrayList<String> lines = new ArrayList<String>();
    while ((line = input.readLine()) != null) {
        lines.add(line);
    }
    input.close();
    p.destroy();
    return lines;
}

From source file:org.apache.tika.eval.TikaEvalCLITest.java

private static void execute(List<String> incomingArgs, long maxMillis) throws IOException {
    List<String> args = new ArrayList<>();
    String cp = System.getProperty("java.class.path");
    args.add("java");
    args.add("-cp");
    args.add(cp);/*from  w w w .j a v a2s  . c  o  m*/
    args.add("org.apache.tika.eval.TikaEvalCLI");
    args.addAll(incomingArgs);

    ProcessBuilder pb = new ProcessBuilder(args);
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);
    Process process = pb.start();
    long started = new Date().getTime();
    long elapsed = new Date().getTime() - started;
    int exitValue = Integer.MIN_VALUE;
    while (elapsed < maxMillis && exitValue == Integer.MIN_VALUE) {
        try {
            exitValue = process.exitValue();
        } catch (IllegalThreadStateException e) {

        }
        elapsed = new Date().getTime() - started;
    }
    if (exitValue == Integer.MIN_VALUE) {
        process.destroy();
        throw new RuntimeException(
                "Process never exited within the allowed amount of time.\n" + "I needed to destroy it");
    }
}

From source file:org.kududb.client.BaseKuduTest.java

/**
 * Helper method to easily kill the leader master.
 *
 * This method is thread-safe./*from  w w  w . ja  v a 2  s .c  o  m*/
 * @throws Exception If there is an error finding or killing the leader master.
 */
protected static void killMasterLeader() throws Exception {
    int leaderPort = findLeaderMasterPort();
    Process master = MASTERS.get(leaderPort);
    if (master == null) {
        // The master is already dead, good.
        return;
    }
    LOG.info("Killing master at port " + leaderPort);
    master.destroy();
    master.waitFor();
    MASTERS.remove(leaderPort);
}

From source file:org.kududb.client.BaseKuduTest.java

/**
 * Helper method to easily kill a tablet server that serves the given table's only tablet's
 * leader. The currently running test case will be failed if there's more than one tablet,
 * if the tablet has no leader after some retries, or if the tablet server was already killed.
 *
 * This method is thread-safe./*  w  w w.j  a v  a  2  s  . com*/
 * @param table a KuduTable which will get its single tablet's leader killed.
 * @throws Exception
 */
protected static void killTabletLeader(KuduTable table) throws Exception {
    LocatedTablet.Replica leader = null;
    DeadlineTracker deadlineTracker = new DeadlineTracker();
    deadlineTracker.setDeadline(DEFAULT_SLEEP);
    while (leader == null) {
        if (deadlineTracker.timedOut()) {
            fail("Timed out while trying to find a leader for this table: " + table.getName());
        }
        List<LocatedTablet> tablets = table.getTabletsLocations(DEFAULT_SLEEP);
        if (tablets.isEmpty() || tablets.size() > 1) {
            fail("Currently only support killing leaders for tables containing 1 tablet, table "
                    + table.getName() + " has " + tablets.size());
        }
        LocatedTablet tablet = tablets.get(0);
        if (tablet.getReplicas().size() == 1) {
            fail("Table " + table.getName() + " only has 1 tablet, please enable replication");
        }
        leader = tablet.getLeaderReplica();
        if (leader == null) {
            LOG.info("Sleeping while waiting for a tablet LEADER to arise, currently slept "
                    + deadlineTracker.getElapsedMillis() + "ms");
            Thread.sleep(50);
        }
    }

    Integer port = leader.getRpcPort();
    Process ts = TABLET_SERVERS.get(port);
    if (ts == null) {
        // The TS is already dead, good.
        return;
    }
    LOG.info("Killing server at port " + port);
    ts.destroy();
    ts.waitFor();
    TABLET_SERVERS.remove(port);
}