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.ballerinalang.test.context.ServerInstance.java

/**
 * reading the server process id.//from www  . j  a v  a 2s .c o m
 *
 * @return process id
 * @throws BallerinaTestException if pid could not be retrieved
 */
private String getServerPID() throws BallerinaTestException {
    String pid = null;
    if (Utils.getOSName().toLowerCase(Locale.ENGLISH).contains("windows")) {
        //reading the process id from netstat
        Process tmp;
        try {
            tmp = Runtime.getRuntime().exec("netstat -a -n -o");
        } catch (IOException e) {
            throw new BallerinaTestException("Error retrieving netstat data", e);
        }

        String outPut = readProcessInputStream(tmp.getInputStream());
        String[] lines = outPut.split("\r\n");
        for (String line : lines) {
            String[] column = line.trim().split("\\s+");
            if (column.length < 5) {
                continue;
            }
            if (column[1].contains(":" + httpServerPort) && column[3].contains("LISTENING")) {
                log.info(line);
                pid = column[4];
                break;
            }
        }
        tmp.destroy();
    } else {

        //reading the process id from ss
        Process tmp = null;
        try {
            String[] cmd = { "bash", "-c",
                    "ss -ltnp \'sport = :" + httpServerPort + "\' | grep LISTEN | awk \'{print $6}\'" };
            tmp = Runtime.getRuntime().exec(cmd);
            String outPut = readProcessInputStream(tmp.getInputStream());
            log.info("Output of the PID extraction command : " + outPut);
            /* The output of ss command is "users:(("java",pid=24522,fd=161))" in latest ss versions
             But in older versions the output is users:(("java",23165,116))
             TODO : Improve this OS dependent logic */
            if (outPut.contains("pid=")) {
                pid = outPut.split("pid=")[1].split(",")[0];
            } else {
                pid = outPut.split(",")[1];
            }

        } catch (Exception e) {
            log.warn("Error occurred while extracting the PID with ss " + e.getMessage());
            // If ss command fails trying with lsof. MacOS doesn't have ss by default
            pid = getPidWithLsof(httpServerPort);
        } finally {
            if (tmp != null) {
                tmp.destroy();
            }
        }
    }
    log.info("Server process id in " + Utils.getOSName() + " : " + pid);
    return pid;
}

From source file:org.sonar.runner.api.CommandExecutor.java

int execute(Command command, StreamConsumer stdOut, StreamConsumer stdErr, long timeoutMilliseconds,
        @Nullable ProcessMonitor processMonitor) {
    ExecutorService executorService = null;
    Process process = null;
    StreamGobbler outputGobbler = null;/* w  ww .j a  v a 2  s. c  o m*/
    StreamGobbler errorGobbler = null;
    try {
        ProcessBuilder builder = new ProcessBuilder(command.toStrings());
        builder.directory(command.directory());
        builder.environment().putAll(command.envVariables());
        process = builder.start();

        outputGobbler = new StreamGobbler(process.getInputStream(), stdOut);
        errorGobbler = new StreamGobbler(process.getErrorStream(), stdErr);
        outputGobbler.start();
        errorGobbler.start();

        executorService = Executors.newSingleThreadExecutor();
        final Future<Integer> futureTask = executeProcess(executorService, process);
        if (processMonitor != null) {
            monitorProcess(processMonitor, executorService, process);
        }

        int exitCode = futureTask.get(timeoutMilliseconds, TimeUnit.MILLISECONDS);
        waitUntilFinish(outputGobbler);
        waitUntilFinish(errorGobbler);
        verifyGobbler(command, outputGobbler, "stdOut");
        verifyGobbler(command, errorGobbler, "stdErr");
        return exitCode;

    } catch (TimeoutException te) {
        process.destroy();
        throw new CommandException("Timeout exceeded: " + timeoutMilliseconds + " ms", command, te);

    } catch (CommandException e) {
        throw e;

    } catch (Exception e) {
        throw new CommandException("Fail to execute command", command, e);

    } finally {
        waitUntilFinish(outputGobbler);
        waitUntilFinish(errorGobbler);
        closeStreams(process);
        if (executorService != null) {
            executorService.shutdown();
        }
    }
}

From source file:org.sipfoundry.sipxconfig.cfgmgt.AgentRunner.java

/**
 * Run a command and pipe io streams accordingly
 *///from  w  ww .  j  av a 2  s .  c o  m
int runCommand(String command, OutputStream log) {
    Process exec = null;
    try {
        LOG.info("Starting agent run " + command);
        exec = Runtime.getRuntime().exec(command);
        StreamGobbler errGobbler = new StreamGobbler(exec.getErrorStream(), log);
        // nothing goes to stdout, so just eat it
        StreamGobbler outGobbler = new StreamGobbler(exec.getInputStream());
        Worker worker = new Worker(exec);
        Thread err = new Thread(errGobbler);
        err.start();
        new Thread(outGobbler).start();
        Thread work = new Thread(worker);
        work.start();
        work.join(m_timeout);
        err.join(1000);
        if (errGobbler.m_error != null) {
            LOG.error("Error logging output stream from agent run", outGobbler.m_error);
        }
        return worker.getExitCode();
    } catch (InterruptedException e) {
        throw new ConfigException(
                format("Interrupted error. Could not complete agent command in %d ms.", m_timeout));
    } catch (IOException e) {
        throw new ConfigException("IO error. Could not complete agent command " + e.getMessage());
    } finally {
        if (exec != null) {
            exec.destroy();
        }
    }
}

From source file:com.netflix.priam.resources.BackupServlet.java

/**
 * Convert SSTable2Json and search for given key
 *//*from ww  w .java  2  s.c o m*/
public void checkSSTablesForKey(String rowkey, String keyspace, String cf, String fileExtension,
        String jsonFilePath) throws Exception {
    try {
        logger.info("Starting SSTable2Json conversion ...");
        //Setting timeout to 10 Mins
        long TIMEOUT_PERIOD = 10l;
        String unixCmd = formulateCommandToRun(rowkey, keyspace, cf, fileExtension, jsonFilePath);

        String[] cmd = { "/bin/sh", "-c", unixCmd.toString() };
        final Process p = Runtime.getRuntime().exec(cmd);

        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int returnCode = p.waitFor();
                return returnCode;
            }
        };

        ExecutorService exeService = Executors.newSingleThreadExecutor();
        try {
            Future<Integer> future = exeService.submit(callable);
            int returnVal = future.get(TIMEOUT_PERIOD, TimeUnit.MINUTES);
            if (returnVal == 0)
                logger.info("Finished SSTable2Json conversion and search.");
            else
                logger.error("Error occurred during SSTable2Json conversion and search.");
        } catch (TimeoutException e) {
            logger.error(ExceptionUtils.getFullStackTrace(e));
            throw e;
        } finally {
            p.destroy();
            exeService.shutdown();
        }

    } catch (IOException e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
    }
}

From source file:com.almunt.jgcaap.systemupdater.MainActivity.java

public String getOS() {
    String outputString = "";
    try {/*from  w  w  w.j  a v  a  2 s .c om*/
        Process su = Runtime.getRuntime().exec("sh");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
        InputStream inputStream = su.getInputStream();
        outputStream.writeBytes("getprop ro.cm.version" + "\nprint alemun@romania\n");
        outputStream.flush();
        outputString = "";
        while (outputString.endsWith("alemun@romania\n") == false) {
            if (inputStream.available() > 0) {
                byte[] dstInput = new byte[inputStream.available()];
                inputStream.read(dstInput);
                String additionalString = new String(dstInput);
                outputString += additionalString;
            }
        }
        outputString = "Current ROM: " + outputString.substring(0, outputString.length() - 15);
        su.destroy();
    } catch (IOException e) {
        currentRomcardView.setVisibility(CardView.GONE);
    }
    if (outputString.replaceAll("jgcaap", "").length() < outputString.length())
        while (outputString.endsWith("bacon") == false)
            outputString = outputString.substring(0, outputString.length() - 1);
    else
        currentRomcardView.setVisibility(CardView.GONE);
    return outputString;
}

From source file:com.utdallas.s3lab.smvhunter.monkey.NetworkMonitor.java

@Override
public void run() {
    try {// w ww.j a  va2s. c o m
        //get the pid first
        String pidString = UIEnumerator.execSpecial(
                String.format(GET_PID, MonkeyMe.adbLocation, device.getSerialNumber(), application));
        if (StringUtils.isEmpty(pidString)) {
            logger.error(getStringforPrinting("pid string empty for app ", application, "trying again"));
            Thread.sleep(5000);
            //try again
            pidString = UIEnumerator.execSpecial(
                    String.format(GET_PID, MonkeyMe.adbLocation, device.getSerialNumber(), application));
        }
        logger.debug(getStringforPrinting("pid string for ", application, pidString));
        List<String> outList = new ArrayList<String>();
        if (StringUtils.isNotEmpty(pidString)) {
            Process pidCmd = null;
            try {
                //read the strace command output
                pidCmd = execCommand(
                        String.format(TRACE_PID, MonkeyMe.adbLocation, device.getSerialNumber(), pidString));

                BufferedReader pidReader = new BufferedReader(new InputStreamReader(pidCmd.getInputStream()));
                String out = "";
                while ((out = pidReader.readLine()) != null) {

                    //break the loop if the current thread has been cancelled
                    if (Thread.currentThread().isInterrupted()) {
                        break;
                    }
                    outList.add(getStringforPrinting(System.currentTimeMillis(), application, out));

                    if (StringUtils.contains(out, "connect")) {
                        logger.debug(out);
                        FileUtils.write(new File(MonkeyMe.straceOutputLocation),
                                getStringforPrinting(System.currentTimeMillis(), application, out) + "\n",
                                true);
                    }
                }
            } finally {
                FileUtils.writeLines(new File(MonkeyMe.straceDumpLocation), outList, true);
                if (pidCmd != null) {
                    pidCmd.destroy();
                }
            }

        }
    } catch (Exception e) {
        logger.error("Error while processing monitoring network for " + application, e);
    }
}

From source file:net.urlgrey.mythpodcaster.transcode.FFMpegTranscoderImpl.java

public void transcode(File workingDirectory, GenericTranscoderConfigurationItem genericConfig, File inputFile,
        File outputFile) throws Exception {
    LOG.info("transcode started: inputFile [" + inputFile.getAbsolutePath() + "], outputFile ["
            + outputFile.getAbsolutePath() + "]");

    FFMpegTranscoderConfigurationItem config = (FFMpegTranscoderConfigurationItem) genericConfig;
    List<String> commandList = new ArrayList<String>();
    commandList.add(niceLocation);/* ww w.j av  a2 s.c o  m*/
    commandList.add("-n");
    commandList.add(Integer.toString(config.getNiceness()));
    commandList.add(ffmpegLocation);
    commandList.add("-i");
    commandList.add(inputFile.getAbsolutePath());
    commandList.addAll(config.getParsedEncoderArguments());
    commandList.add(outputFile.getAbsolutePath());
    ProcessBuilder pb = new ProcessBuilder(commandList);

    // Needed for ffmpeg
    pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:");
    pb.redirectErrorStream(true);
    pb.directory(workingDirectory);
    Process process = null;

    try {
        // Get the ffmpeg process
        process = pb.start();
        // We give a couple of secs to complete task if needed
        Future<List<String>> stdout = pool.submit(new OutputMonitor(process.getInputStream()));
        List<String> result = stdout.get(config.getTimeout(), TimeUnit.SECONDS);
        process.waitFor();
        final int exitValue = process.exitValue();
        LOG.info("FFMPEG exit value: " + exitValue);
        if (exitValue != 0) {
            for (String line : result) {
                LOG.error(line);
            }
            throw new Exception("FFMpeg return code indicated failure: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new Exception("FFMpeg process interrupted by another thread", e);
    } catch (ExecutionException ee) {
        throw new Exception("Something went wrong parsing FFMpeg output", ee);
    } catch (TimeoutException te) {
        // We could not get the result before timeout
        throw new Exception("FFMpeg process timed out", te);
    } catch (RuntimeException re) {
        // Unexpected output from FFMpeg
        throw new Exception("Something went wrong parsing FFMpeg output", re);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    LOG.debug("transcoding finished");
}

From source file:com.taobao.adfs.util.Utilities.java

public static String runCommand(String command, Integer expectedExitCode, String extraPath, String libPath,
        boolean destory) throws IOException {
    BufferedReader stdOutputReader = null;
    StringBuilder output = new StringBuilder();
    Process process = runCommand(command, extraPath, libPath);
    ;//ww  w  .  j  a  va  2  s . co m
    try {
        stdOutputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = stdOutputReader.readLine()) != null) {
            output.append(line).append('\n');
        }
        if (output.length() > 0)
            output.deleteCharAt(output.length() - 1);
        if (expectedExitCode != null && process.waitFor() != expectedExitCode)
            throw new IOException(
                    "exit code=" + process.exitValue() + ", expected exit code=" + expectedExitCode);
    } catch (Throwable t) {
        destory = true;
        throw new IOException("fail to exceute " + command + ", output=" + output
                + (extraPath == null ? "" : ", extraPath=" + extraPath)
                + (libPath == null ? "" : ", libPath=" + libPath), t);
    } finally {
        if (stdOutputReader != null)
            stdOutputReader.close();
        process.getOutputStream().close();
        process.getInputStream().close();
        process.getErrorStream().close();
        if (destory)
            process.destroy();
    }
    return output.toString();
}

From source file:com.clican.pluto.orm.dynamic.impl.DynamicORMManagePojoHibernateImpl.java

private void compile(String file) throws ORMManageException {
    Process proc = null;
    try {/*from   w  ww . jav a 2s  .co m*/
        Set<String> jars = classLoaderUtil.getRuntimeJars();
        StringBuffer command = new StringBuffer();
        command.append("javac ");
        command.append(file);
        command.append("/*.java -encoding utf-8 -classpath \"");
        command.append(StringUtils.getSymbolSplitString(jars, ";"));
        command.append("\"");
        if (log.isDebugEnabled()) {
            log.debug("command=" + command);
        }
        proc = Runtime.getRuntime().exec(command.toString());
        int exitValue = -1;
        while (true) {
            try {
                exitValue = proc.exitValue();
            } catch (IllegalThreadStateException e) {
                Thread.sleep(10);
                continue;
            }
            break;
        }
        if (exitValue != 0) {
            log.error("Compile failure command=[" + command + "]");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Compile successfully.");
            }
        }
    } catch (Exception e) {
        throw new ORMManageException(e);
    } finally {
        proc.destroy();
    }
}

From source file:net.urlgrey.mythpodcaster.transcode.SegmentedVodTranscoderImpl.java

public void transcode(File workingDirectory, GenericTranscoderConfigurationItem genericConfig, File inputFile,
        File outputFile) throws Exception {
    LOG.info("transcode started: inputFile [" + inputFile.getAbsolutePath() + "], outputFile ["
            + outputFile.getAbsolutePath() + "]");

    SegmenterTranscoderConfigurationItem config = (SegmenterTranscoderConfigurationItem) genericConfig;
    List<String> commandList = new ArrayList<String>();
    commandList.add(niceLocation);/*from  www .ja v a2  s.c  o m*/
    commandList.add("-n");
    commandList.add(Integer.toString(config.getNiceness()));
    commandList.add(segmenterLocation);
    commandList.add(inputFile.getAbsolutePath());
    commandList.add(config.getSegmentDuration());
    commandList.add(config.getSegmentFilePrefix());
    commandList.add(config.getPlaylistFileName());
    commandList.add(config.getHttpPrefix());
    ProcessBuilder pb = new ProcessBuilder(commandList);

    pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:");
    pb.redirectErrorStream(true);
    pb.directory(outputFile.getParentFile());
    Process process = null;

    try {
        // Get the segmenter process
        process = pb.start();
        // We give a couple of secs to complete task if needed
        Future<List<String>> stdout = pool.submit(new OutputMonitor(process.getInputStream()));
        List<String> result = stdout.get(config.getTimeout(), TimeUnit.SECONDS);
        process.waitFor();
        final int exitValue = process.exitValue();
        LOG.info("Segmenter exit value: " + exitValue);
        if (exitValue != 0) {
            for (String line : result) {
                LOG.error(line);
            }
            throw new Exception("Segmenter return code indicated failure: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new Exception("Segmenter process interrupted by another thread", e);
    } catch (ExecutionException ee) {
        throw new Exception("Something went wrong parsing Segmenter output", ee);
    } catch (TimeoutException te) {
        // We could not get the result before timeout
        throw new Exception("Segmenter process timed out", te);
    } catch (RuntimeException re) {
        // Unexpected output from Segmenter
        throw new Exception("Something went wrong parsing Segmenter output", re);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    LOG.debug("transcoding finished");
}