package com.nms.server.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;


public class CommandExecUtil
{
	private static Logger logger = Logger.getLogger(CommandExecUtil.class);
	
	//执行linux命令
	public static String execLinuxCmd(String cmd) throws Exception{
		BufferedReader bReader = null;
		BufferedReader errorReader = null;
		Process process = null;
		try {
			logger.info("execLinuxCmd start-------" + cmd);
			String[] shellCmd = new String[] { "/bin/bash", "-c", cmd };
			process = Runtime.getRuntime().exec(shellCmd);
			process.getOutputStream().close();

			bReader = new BufferedReader(new InputStreamReader(process
					.getInputStream()));
			errorReader = new BufferedReader(new InputStreamReader(process
					.getErrorStream()));
			String line = null;
			while ((line = bReader.readLine()) != null) {
				logger.debug("execLinuxCmd line--->" + line);
			}
			StringBuffer errorSb = new StringBuffer();
			while ((line = errorReader.readLine()) != null) {
				logger.debug("execLinuxCmd error line--->" + line);
				errorSb.append(line + ",");
			}

			if (errorSb.toString().length() > 0) {
				return errorSb.toString().substring(0, errorSb.toString().length()-1);
			}

			logger.info("execLinuxCmd end-------" + cmd);
		} catch (Exception e) {
			throw e;
		} finally {
			 try {
				if (bReader != null) {
					bReader.close();
				}
				if (errorReader != null) {
					errorReader.close();
				}
				if (process != null) {
					process.destroy();
				}
			} catch (Exception e1) {
			}
		}
		return null;
	}
	
	public static boolean startNetService(String cmd) throws Exception{
		boolean flag = false;
		Process process = null;
		System.out.println(cmd);
		String[] cmdArr = new String[] { "cmd.exe", "/C", "net start "+cmd};
		
		try {
			process = Runtime.getRuntime().exec(cmdArr);
			//关闭进程流，保证进程流畅运行
			process.getInputStream().close();
			process.getOutputStream().close();
			process.getErrorStream().close();
			synchronized (process) {
				process.wait(1000 * 2);
			}
			flag = true;
		} catch (IOException e) {
			throw e;
		}finally{
			process.destroy();
		}
		return flag;
	}
	
	public static boolean startProcess(String cmd) throws Exception{
		boolean flag = false;
		Process process = null;
		System.out.println(cmd);
		String[] cmdArr = new String[] { "cmd.exe", "/C", cmd};
		
		try {
			process = Runtime.getRuntime().exec(cmdArr);
			//关闭进程流，保证进程流畅运行
			process.getInputStream().close();
			process.getOutputStream().close();
			process.getErrorStream().close();
			synchronized (process) {
				process.wait(1000 * 2);
			}
			flag = true;
		} catch (IOException e) {
			throw e;
		}finally{
			process.destroy();
		}
		return flag;
	}
	
	public static boolean processRunningCheck(String imageName) throws Exception{
		Thread.sleep(1000);//检查进程是否存在时，先暂停1秒钟
		boolean flag = false;
		String cmd = "TASKLIST /FI \"IMAGENAME eq "+imageName+"\" /FO \"csv\" /NH";
		Process process = null;
		System.out.println(cmd);
		String[] arr = new String[] {"cmd.exe","/C",cmd};
		BufferedReader br = null;
		
		try {
			process = Runtime.getRuntime().exec(arr);
			br = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			while ((line = br.readLine())!= null) {
				System.out.println(line);
				 if(StringUtils.isNotEmpty(line)){
					 break;
				 }
			}
			if(StringUtils.isNotBlank(line) && line.indexOf("\""+imageName+"\"")!= -1){
				System.out.println("IMAGENAME:>"+imageName+" 进程存在");
				flag = true;
			}
		} catch (IOException e) {
			throw e;
		}finally{
			if(br!=null){
				br.close();
				br=null;
			}
			process.destroy();
		}
		return flag;
	}
	
	public static boolean processRunningCheck(Long PID) throws Exception{
		boolean flag = false;
		String cmd = "TASKLIST /FI \"PID eq "+PID+"\" /FO \"csv\" /NH";
		Process process = null;
		String[] arr = new String[] { "cmd.exe", "/C",cmd};
		BufferedReader br = null;
		System.out.println(cmd);
		try {
			process = Runtime.getRuntime().exec(arr);
			br = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			while ((line = br.readLine())!= null) {
				System.out.println(line);
				 if(StringUtils.isNotEmpty(line)){
					 break;
				 }
			}
			if(StringUtils.isNotBlank(line) && line.indexOf("\""+PID+"\"")!= -1){
				System.out.println("PID:>"+PID+" 进程存在");
				flag = true;
			}
		} catch (IOException e) {
			throw e;
		}finally{
			if(br!=null){
				br.close();
				br=null;
			}
			process.destroy();
		}
		return flag;
	}
	
	public static boolean exeCmd(String cmd) throws Exception{
		boolean flag = false;
//		String cmd = "WMIC PROCESS WHERE Name=\""+processName+"\" DELETE";
		Process process = null;
		String[] arr = new String[] {"cmd.exe","/C", cmd};
		System.out.println(cmd);
		BufferedReader br = null;
		try {
			process = Runtime.getRuntime().exec(arr);
			//关闭进程流，保证进程流畅运行
			process.getInputStream().close();
			process.getOutputStream().close();
			process.getErrorStream().close();
			synchronized (process) {
				process.wait(1000 * 2);
			}
			flag = true;
		} catch (IOException e) {
			throw e;
		}finally{
			if(br!=null){
				br.close();
				br=null;
			}
			process.destroy();
		}
		return flag;
	}
	
	public static boolean killProcess(String processName) throws Exception{
		boolean flag = false;
		String cmd = "WMIC PROCESS WHERE Name=\""+processName+"\" DELETE";
		Process process = null;
		String[] arr = new String[] {"cmd.exe","/C", cmd};
		System.out.println(cmd);
		BufferedReader br = null;
		try {
			process = Runtime.getRuntime().exec(arr);
			//关闭进程流，保证进程流畅运行
			process.getInputStream().close();
			process.getOutputStream().close();
			process.getErrorStream().close();
//			br = new BufferedReader(new InputStreamReader(process.getInputStream()));
//			String line = br.readLine();
//			System.out.println(line);
			synchronized (process) {
				process.wait(1000 * 2);
			}
			flag = true;
		} catch (IOException e) {
			throw e;
		}finally{
			if(br!=null){
				br.close();
				br=null;
			}
			process.destroy();
		}
		return flag;
	}
	public static boolean killProcess(Long PID) throws Exception{
		boolean flag = false;
		String cmd = "WMIC PROCESS WHERE PROCESSID="+PID+" DELETE ";
		Process process = null;
		String[] arr = new String[] {"cmd.exe", cmd};
		System.out.println(cmd);
		BufferedReader br = null;
		try {
			process = Runtime.getRuntime().exec(arr);
			br = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = br.readLine();
			System.out.println(line);
			flag = true;
		} catch (IOException e) {
			throw e;
		}finally{
			if(br!=null){
				br.close();
				br=null;
			}
			process.destroy();
		}
		return flag;
	}
	
	//执行windows命令
	public static String execWinCmd(String cmd) throws Exception {
		BufferedReader bReader = null;
		BufferedReader errorReader = null;
		Process process = null;
		try {
			logger.info("execWinCmd start-------" + cmd);
			String[] cmdArr = new String[] { "cmd.exe", "/C", cmd };
			process = Runtime.getRuntime().exec(cmdArr);
			if (cmd.endsWith(".exe")) {
				synchronized (process) {
					process.wait(1000 * 5);
				}
			} else {
				process.getOutputStream().close();
				bReader = new BufferedReader(new InputStreamReader(process
						.getInputStream()));
				errorReader = new BufferedReader(new InputStreamReader(process
						.getErrorStream()));
				String line = null;
				while ((line = bReader.readLine()) != null) {
					logger.debug("execWinCmd line--->" + line);
				}
				StringBuffer errorSb = new StringBuffer();
				while ((line = errorReader.readLine()) != null) {
					logger.debug("execWinCmd error--->" + line);
					errorSb.append(line + ",");
				}
				if (errorSb.toString().length() > 0) {
					return errorSb.toString().substring(0,
							errorSb.toString().length() - 1);
				}
			}
			
			logger.info("execWinCmd end-------" + cmd);

		} catch (Exception e) {
			throw e;
		} finally {
			 try {
				if (bReader != null) {
					bReader.close();
				}
				if (errorReader != null) {
					errorReader.close();
				}
				if (process != null) {
					process.destroy();
				}
			} catch (Exception e1) {
			}
		}
		
		return null;
	}
	
	public static void main(String[] args) {
		try
		{
//			System.out.println(System.getProperty("user.dir"));
//			String pp =  new File(System.getProperty("user.dir")).getParentFile().getAbsolutePath()+"/conf/myconfig.properties";
//			System.out.println(pp);
//			CommandExecUtil.execWinCmd("tasklist");
			CommandExecUtil.execWinCmd("net start DataController");
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
