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

/**
 * This method returns the pid of the service which is using the provided port.
 *
 * @param httpServerPort port of the service running
 * @return the pid of the service// w w  w  .jav a  2  s  .  com
 * @throws BallerinaTestException if pid could not be retrieved
 */
private String getPidWithLsof(int httpServerPort) throws BallerinaTestException {
    String pid;
    Process tmp = null;
    try {
        String[] cmd = { "bash", "-c",
                "lsof -Pi tcp:" + httpServerPort + " | grep LISTEN | awk \'{print $2}\'" };
        tmp = Runtime.getRuntime().exec(cmd);
        pid = readProcessInputStream(tmp.getInputStream());

    } catch (Exception err) {
        throw new BallerinaTestException("Error retrieving the PID : ", err);
    } finally {
        if (tmp != null) {
            tmp.destroy();
        }
    }
    return pid;
}

From source file:org.wso2.carbon.integration.tests.carbontools.CarbonServerBasicOperationTestCase.java

@Test(groups = { "carbon.core" }, description = "Testing server startup argument --stop", dependsOnMethods = {
        "testServerRestartCommand" })
public void testStopCommand() throws Exception {
    String[] cmdArray;//from  w  w  w.j a  v  a2 s  .co m
    Process processStop = null;
    boolean startupStatus = false;
    try {
        if ((CarbonCommandToolsUtil.getCurrentOperatingSystem()
                .contains(OperatingSystems.WINDOWS.name().toLowerCase()))) {
            //Skipping the test execution on Windows
            throw new SkipException("--stop command is not available for windows");
        } else {
            cmdArray = new String[] { "sh", "wso2server.sh", "--stop", "-DportOffset=" + portOffset };
        }
        processStop = CarbonCommandToolsUtil.runScript(carbonHome + File.separator + "bin", cmdArray);
        startupStatus = CarbonCommandToolsUtil.isServerDown(portOffset);
    } finally {
        if (processStop != null) {
            processStop.destroy();
        }
    }
    assertTrue(startupStatus, "Unsuccessful login");
}

From source file:service.impl.DatabaseBackupServiceImpl.java

/**
 * To be compatible to Windows 7 and 10 (the original function could just work on win 10), 
 * Using the ProcessBuilder as the main class to initialize the process and generate the file.
 * The ProcessBuilder receives the command as the separated string (by space).
 * The backup file couldn't be generated without calling waitFor().
 * After this function, the uploadFtp() will be called, and upload this file to remote, one day one file.
 * The default path of generated file is located on C:\\
 * This path is defined on the properties backup.properties. 
 *  /*from w w w.  ja va2s  .  c o  m*/
 */
@Override
public void backup() throws ServiceException {
    Process proc = null;

    try {
        ProcessBuilder procBuilder = new ProcessBuilder("cmd", "/c", mysqlBinPath + "mysqldump",
                "--lock-all-tables", "--flush-logs", "-h", srcHost, "-u" + srcUsername, "-p" + srcPassword,
                "--databases", srcDbname);

        procBuilder.directory(new File(bakSqlPath));
        File sqlBackupFile = new File(bakSqlPath + System.getProperty("file.separator") + bakSqlFile);
        sqlBackupFile.delete();
        sqlBackupFile.createNewFile();

        procBuilder.redirectErrorStream(true);
        procBuilder.redirectOutput(Redirect.to(sqlBackupFile));
        proc = procBuilder.start();
        proc.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
        throw new ServiceException(e);
    } finally {
        try {
            if (proc != null) {
                proc.destroy();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.jboss.tools.openshift.internal.common.core.util.CommandLocationLookupStrategy.java

private String readProcess(Process p) {
    try {//w  w  w .  jav  a  2  s .c  o m
        p.waitFor();
    } catch (InterruptedException ie) {
        // Ignore, expected
    }
    InputStream is = null;
    if (p.exitValue() == 0) {
        is = p.getInputStream();
    } else {
        // For debugging only
        //is = p.getErrorStream();
    }
    if (is != null) {
        try {
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            String cmdOutput = s.hasNext() ? s.next() : "";
            if (!cmdOutput.isEmpty()) {
                cmdOutput = StringUtils.trim(cmdOutput);
                return cmdOutput;
            }
        } finally {
            try {
                if (p != null) {
                    p.destroy();
                }
                is.close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }
    return null;
}

From source file:com.github.jarlakxen.embedphantomjs.executor.PhantomJSFileExecutor.java

public ListenableFuture<String> execute(final File sourceFile, final String... args) {
    final String cmd = this.phantomReference.getBinaryPath() + " " + sourceFile.getAbsolutePath() + " "
            + StringUtils.join(args, " ");
    try {//from  w ww  .ja  v  a  2 s.co  m
        final Process process = Runtime.getRuntime().exec(cmd);
        LOGGER.info("Command to execute: " + cmd);

        final ListenableFuture<String> action = processExecutorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                LOGGER.info("Command to execute: " + cmd);
                String output = IOUtils.toString(process.getInputStream());
                process.waitFor();
                LOGGER.debug("Command " + cmd + " output:" + output);
                return output;
            }
        });

        timeoutExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    action.get(executionTimeout.getTimeout(), executionTimeout.getUnit());
                } catch (Exception e) {
                    action.cancel(false);
                    process.destroy();
                }
            }
        });

        return action;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:raptor.speech.ProcessSpeech.java

public void speak(final String text) {
    if (StringUtils.isBlank(text))
        return;//w w w  . j a v  a 2 s.  c  o  m

    speakQueue.add(text);
    ThreadService.getInstance().run(new Runnable() {
        public void run() {
            synchronized (ProcessSpeech.this) {
                try {
                    long startTime = System.currentTimeMillis();
                    Process process = Runtime.getRuntime().exec(new String[] { command, speakQueue.poll() });

                    while (System.currentTimeMillis() - startTime < Raptor.getInstance().getPreferences()
                            .getInt(PreferenceKeys.PROCESS_SPEECH_MAX_TIME_SECONDS) * 1000) {
                        try {
                            process.exitValue();
                            break;
                        } catch (IllegalThreadStateException ie) {
                            try {
                                Thread.sleep(250);
                            } catch (InterruptedException ie2) {
                            }
                        }
                    }

                    // if process is still alive destroy it.
                    try {
                        process.exitValue();
                    } catch (IllegalThreadStateException ie) {
                        try {
                            process.destroy();
                        } catch (Throwable t) {
                        }
                    }
                } catch (Exception e) {
                    Raptor.getInstance().onError("Error occured speaking text: " + text, e);
                }
            }
        }
    });
}

From source file:it.illinois.adsc.ema.softgrid.monitoring.ui.SPMainFrame.java

public void destroyProcess(Process process) {
    final String classGetName = process.getClass().getName();
    if ("JAVA_LANG_WIN32_PROCESS".equals(classGetName)
            || "java.lang.ProcessImpl".equals(process.getClass().getName())) {
        // determine the pid on windowsplattforms
        process.destroy();
        try {//from   w w  w  .  ja  va 2  s  . co  m
            Field field = process.getClass().getDeclaredField("handle");
            field.setAccessible(true);
            final int pid = Kernel32.INSTANCE.GetProcessId((Long) field.get(process));
            // killing the task.
            Runtime.getRuntime().exec("taskkill " + pid);

        } catch (SecurityException e) {
            System.out.println("Error in Killing the process:" + e);
        } catch (NoSuchFieldException e) {
            System.out.println("Error in Killing the process:" + e);
        } catch (IOException e) {
            System.out.println("Error in Killing the process:" + e);
        } catch (IllegalArgumentException e) {
            System.out.println("Error in Killing the process:" + e);
        } catch (IllegalAccessException e) {
            System.out.println("Error in Killing the process:" + e);
        }

    }
}

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

int stopProcessWithTimeout(final Process proc, long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
    FutureTask<Integer> future = new FutureTask<Integer>(new Callable<Integer>() {
        @Override//w  w  w. j  a  v  a  2  s.  co m
        public Integer call() throws InterruptedException {
            proc.destroy();
            return proc.waitFor();
        }
    });

    executor.execute(future);

    return future.get(timeout, unit);
}

From source file:de.flyingsnail.ipv6droid.android.VpnThread.java

/**
 * Try to fix the problem detected by checkRouting. This requires rooted devices :-(
 *///w w  w  .  j  a  v  a 2  s .  c o m
private void fixRouting() {
    try {
        Process routeAdder = Runtime.getRuntime().exec(
                new String[] { "/system/bin/su", "-c", "/system/bin/ip -f inet6 route add default dev tun0" });
        BufferedReader reader = new BufferedReader(new InputStreamReader(routeAdder.getErrorStream()));
        String errors = reader.readLine();
        try {
            routeAdder.waitFor();
        } catch (InterruptedException e) {
            // we got interrupted, so we kill our process
            routeAdder.destroy();
        }
        if (errors != null) {
            Log.e(TAG, "Command to set default route created error message: " + errors);
        }
    } catch (IOException e) {
        Log.d(TAG, "Failed to fix routing", e);
    }
}

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

@Test
public void runScriptWithoutOptions() {
    Process process = null;
    try {//from  w  w w. ja v  a 2 s. co  m
        PROCESS_BUILDER.command(getCommand());
        process = PROCESS_BUILDER.start();

        String result = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8)
                .replaceAll("(?m)^\\s*$[\n\r]{1,}", "");
        assertTrue(result.startsWith("Usage: Main [options]"));
        assertTrue(result.contains(new EntitlementCommand().getClass().getAnnotation(Command.class).name() + " "
                + EntitlementCommand.EntitlementOptions.HELP.getOptionName()));
        assertTrue(result.contains(new GroupCommand().getClass().getAnnotation(Command.class).name() + " "
                + GroupCommand.GroupOptions.HELP.getOptionName()));
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}