package in.cdac.medinfo.csnotk.launch;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaProcessKiller {
	public static void main(String[] args) {
		JavaProcessKiller pKiller = new JavaProcessKiller();

	// To kill a command prompt
	String killcommand=pKiller.isProcessRunning();
	if(killcommand!=null )
	pKiller.killProcess(killcommand);
	
}

	private static final String command=" tskill java /V";
private static final String maccommand="pgrep java"; 
private  String killcommand="kill -9 ";


private void killProcess(String pid) {
	try {
		Runtime.getRuntime().exec(killcommand+pid);
		System.out.println(" killed successfully!");
	} catch (IOException e) {
		e.printStackTrace();
	}
	
}

public String isProcessRunning() {
	try {
		
		String OS=System.getProperty("os.name").toLowerCase();
		Process pro = null;
        if (OS.indexOf("win") >= 0	) {
//            System.out.println("This is Windows");
            pro = Runtime.getRuntime().exec(command);
            killcommand="tskill End Process";
          
        } else if (OS.indexOf("mac") >= 0) {
        	pro=Runtime.getRuntime().exec(maccommand);
//            System.out.println("This is Mac");
         
        } else if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ) {
//            System.out.println("This is Unix or Linux");
            pro = Runtime.getRuntime().exec(command);
            
        } else {
            System.out.println("OS is not support!!");
        }
	
        BufferedReader reader = new BufferedReader(new InputStreamReader(pro.getInputStream()));
		String line;
		while ((line = reader.readLine()) != null) {
			String[] temppid = null;
			System.out.println("line : "+line);
			if (line.contains("Configurator")){
				temppid=line.split(" ");
				return temppid[0];
				//return true;
			}
			else
				return line;
		}
		
	} catch (IOException | SecurityException | IllegalArgumentException e) {
		e.printStackTrace();
	}
	return null;

}



}

