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:pl.nask.hsn2.service.scdbg.TimedScdbgProcess.java

@Override
public Integer call() throws Exception {
    for (String s : commandLine) {
        System.out.print(s + " ");
    }/*w ww  . j  a va 2s.c  o m*/
    System.out.println();

    Process p = Runtime.getRuntime().exec(commandLine, null, localTmp);

    try {
        writer = new PrintWriter(p.getOutputStream());
        // have to emit ENTER to make scdbg end processing.
        writer.println();
        writer.flush();

        // read as much as possible and buffer since if the process produces too much data it will result with a deadlock.
        bytes = IOUtils.toByteArray(p.getInputStream());
    } catch (IOException e) {
        throw new ResourceException("Error executing scdbg", e);
    } finally {
        IOUtils.closeQuietly(writer);
        if (p != null) {
            p.destroy();
        }
    }
    return p.waitFor();
}

From source file:org.wso2.carbon.integration.tests.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 getting the command directory
 *//*  ww w  . jav  a2 s  .  c  o m*/
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) < CarbonIntegrationConstants.DEFAULT_WAIT_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 expected 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 BufferedReader  ", e);
            }
        }
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:Main.java

public static int getSuVersionCode() {
    Process process = null;
    String inLine = null;// w w  w  .j  av  a  2s  .c o m

    try {
        process = Runtime.getRuntime().exec("sh");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        BufferedReader is = new BufferedReader(
                new InputStreamReader(new DataInputStream(process.getInputStream())), 64);
        os.writeBytes("su -v\n");

        // We have to hold up the thread to make sure that we're ready to read
        // the stream, using increments of 5ms makes it return as quick as
        // possible, and limiting to 1000ms makes sure that it doesn't hang for
        // too long if there's a problem.
        for (int i = 0; i < 400; i++) {
            if (is.ready()) {
                break;
            }
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                Log.w(TAG, "Sleep timer got interrupted...");
            }
        }
        if (is.ready()) {
            inLine = is.readLine();
            if (inLine != null && Integer.parseInt(inLine.substring(0, 1)) > 2) {
                inLine = null;
                os.writeBytes("su -V\n");
                inLine = is.readLine();
                if (inLine != null) {
                    return Integer.parseInt(inLine);
                }
            } else {
                return 0;
            }
        } else {
            os.writeBytes("exit\n");
        }
    } catch (IOException e) {
        Log.e(TAG, "Problems reading current version.", e);
        return 0;
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    return 0;
}

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

@Test
public void reportNotExists() {
    Process process = null;
    try {//  w w  w  .j a va  2  s . c om
        PROCESS_BUILDER.command(getCommand(new ReportCommand().getClass().getAnnotation(Command.class).name(),
                ReportCommand.ReportOptions.READ.getOptionName(), "72"));
        process = PROCESS_BUILDER.start();
        final String result = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
        assertTrue(result.contains("- Report 72 doesn't exist"));
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:cn.edu.zjnu.acm.judge.core.Judger.java

private boolean compile(RunRecord runRecord) throws IOException {
    String source = runRecord.getSource();
    if (StringUtils.isEmptyOrWhitespace(source)) {
        return false;
    }/*from   ww  w .j a v  a2 s . c  o  m*/
    Path work = runRecord.getWorkDirectory();
    final String main = "Main";
    Files.createDirectories(work);
    Path sourceFile = work.resolve(main + "." + runRecord.getLanguage().getSourceExtension()); //???
    Files.copy(new ByteArrayInputStream(source.getBytes(Platform.getCharset())), sourceFile,
            StandardCopyOption.REPLACE_EXISTING);

    String compileCommand = runRecord.getLanguage().getCompileCommand();
    log.debug("Compile Command: {}", compileCommand); //
    if (StringUtils.isEmptyOrWhitespace(compileCommand)) {
        return true;
    }
    assert compileCommand != null;
    //
    // VC++?
    // G++?
    Path compileInfo = work.resolve("compileinfo.txt");
    Process process = ProcessCreationHelper.execute(new ProcessBuilder(compileCommand.split("\\s+"))
            .directory(work.toFile()).redirectOutput(compileInfo.toFile()).redirectErrorStream(true)::start);
    process.getInputStream().close();
    try {
        process.waitFor(45, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        throw new InterruptedIOException();
    }
    //?
    String errorInfo;
    if (process.isAlive()) {
        process.destroy();
        try {
            process.waitFor();
        } catch (InterruptedException ex) {
            throw new InterruptedIOException();
        }
        errorInfo = "Compile timeout\nOutput:\n" + collectLines(compileInfo);
    } else {
        errorInfo = collectLines(compileInfo);
    }
    log.debug("errorInfo = {}", errorInfo);
    Path executable = work.resolve(main + "." + runRecord.getLanguage().getExecutableExtension()); //??
    log.debug("executable = {}", executable);
    boolean compileOK = Files.exists(executable);
    //
    if (!compileOK) {
        submissionMapper.updateResult(runRecord.getSubmissionId(), ResultType.COMPILE_ERROR, 0, 0);
        submissionMapper.saveCompileInfo(runRecord.getSubmissionId(), errorInfo);
        updateSubmissionStatus(runRecord);
    }
    return compileOK;
}

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

@Test
public void policyError() {
    Process process = null;
    try {/*  w  ww  .ja  v a 2s .c om*/
        PROCESS_BUILDER.command(getCommand(new PolicyCommand().getClass().getAnnotation(Command.class).name(),
                PolicyCommand.PolicyOptions.READ.getOptionName(), "wrong"));
        process = PROCESS_BUILDER.start();
        final String result = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
        assertTrue(result.contains("- Policy wrong doesn't exist"));
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:pl.robakowski.repository.Repository.java

@Override
public List<JSONObject> getNextResults(final IProgressMonitor monitor) {
    moreResults = false;/*from  w w w  . ja  v a 2  s .  c om*/
    List<JSONObject> list = new ArrayList<JSONObject>(30);
    if (!checkRuntime()) {
        sync.asyncExec(new Runnable() {
            @Override
            public void run() {
                MessageDialog dialog = new MessageDialog(shell, "Wrong paths", null,
                        "Invalid path to PHP or composer.phar", MessageDialog.ERROR, new String[] { "OK" }, 0);
                dialog.setBlockOnOpen(true);
                dialog.open();
                Map<String, String> params = new HashMap<String, String>();
                params.put("preferencePageId", "pl.robakowski.composer.plugin.page1");
                ParameterizedCommand command = commandService.createCommand("org.eclipse.ui.window.preferences",
                        params);
                handlerService.executeHandler(command);
            }
        });
        return list;
    }

    writeJson(json);

    try {
        final Process exec = new ProcessBuilder().command(phpPath, composerPath, "search", query).start();
        Thread killer = new Thread() {

            private boolean terminated(Process exec) {
                try {
                    exec.exitValue();
                    return true;
                } catch (IllegalThreadStateException e) {
                    return false;
                }
            }

            @Override
            public void run() {
                while (!terminated(exec)) {
                    if (monitor.isCanceled()) {
                        exec.destroy();
                    }
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                    }
                }
            };
        };
        killer.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            int space = line.indexOf(' ');
            String name = line.substring(0, space);
            String repository = line.substring(space + 1);
            JSONObject obj = new JSONObject();
            obj.put("name", name);
            obj.put("description", repository);
            list.add(obj);
        }
        exec.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return list;
}

From source file:org.ballerinalang.test.context.ServerInstance.java

/**
 * Stop the server instance which is started by start method.
 *
 * @throws BallerinaTestException if service stop fails
 *//* ww  w .j a  v  a 2 s  .com*/
@Override
public void stopServer() throws BallerinaTestException {
    log.info("Stopping server..");
    if (process != null) {
        String pid;
        try {
            pid = getServerPID();
            if (Utils.getOSName().toLowerCase(Locale.ENGLISH).contains("windows")) {
                Process killServer = Runtime.getRuntime().exec("TASKKILL -F /PID " + pid);
                log.info(readProcessInputStream(killServer.getInputStream()));
                killServer.waitFor(15, TimeUnit.SECONDS);
                killServer.destroy();
            } else {
                Process killServer = Runtime.getRuntime().exec("kill -9 " + pid);
                killServer.waitFor(15, TimeUnit.SECONDS);
                killServer.destroy();
            }
        } catch (IOException e) {
            log.error("Error getting process id for the server in port - " + httpServerPort + " error - "
                    + e.getMessage(), e);
            throw new BallerinaTestException("Error while getting the server process id", e);
        } catch (InterruptedException e) {
            log.error("Error stopping the server in port - " + httpServerPort + " error - " + e.getMessage(),
                    e);
            throw new BallerinaTestException("Error waiting for services to stop", e);
        }
        process.destroy();
        serverInfoLogReader.stop();
        serverErrorLogReader.stop();
        process = null;
        //wait until port to close
        Utils.waitForPortToClosed(httpServerPort, 30000);
        log.info("Server Stopped Successfully");

        deleteWorkDir();
    }
}

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

@Override
public void run() {
    //start monitoring the udp traffic
    //this is used to reverse map the ip to the domain
    Process pr = null;
    try {//from  ww  w .  j  a  v a  2 s.  c o m
        pr = NetworkMonitor
                .execCommand(String.format(UDP_CAPTURE, WindowUpdate.adbLocation, device.getSerialNumber()));
        BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String s = null;

        while ((s = br.readLine()) != null) {
            String forPrinting = NetworkMonitor.getStringforPrinting(device.getSerialNumber(),
                    System.currentTimeMillis(), "udp dump: ", s);
            FileUtils.write(new File(MonkeyMe.udpDumpLocation), forPrinting + "\n", true);
            logger.debug(forPrinting);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (pr != null) {
            pr.destroy();
        }
    }

}

From source file:org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl.java

/**
 * Stops Accumulo and Zookeeper processes. If stop is not called, there is a shutdown hook that is setup to kill the processes. However it's probably best to
 * call stop in a finally block as soon as possible.
 *///  w  ww.j  av  a 2s.  co m
@Override
public synchronized void stop() throws IOException, InterruptedException {
    if (null == executor) {
        // keep repeated calls to stop() from failing
        return;
    }

    for (LogWriter lw : logWriters) {
        lw.flush();
    }

    MiniAccumuloClusterControl control = getClusterControl();

    control.stop(ServerType.GARBAGE_COLLECTOR, null);
    control.stop(ServerType.MASTER, null);
    control.stop(ServerType.TABLET_SERVER, null);
    control.stop(ServerType.ZOOKEEPER, null);

    // ACCUMULO-2985 stop the ExecutorService after we finished using it to stop accumulo procs
    if (null != executor) {
        List<Runnable> tasksRemaining = executor.shutdownNow();

        // the single thread executor shouldn't have any pending tasks, but check anyways
        if (!tasksRemaining.isEmpty()) {
            log.warn("Unexpectedly had " + tasksRemaining.size()
                    + " task(s) remaining in threadpool for execution when being stopped");
        }

        executor = null;
    }

    if (config.useMiniDFS() && miniDFS != null)
        miniDFS.shutdown();
    for (Process p : cleanup) {
        p.destroy();
        p.waitFor();
    }
    miniDFS = null;
}