package com.leanwo.activiti.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.management.ManagementFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 程序关闭通用类
 * @author YangZhiJie
 *
 */
public class ProgramStopUtil {
	private static Logger logger = LoggerFactory.getLogger(ProgramStopUtil.class);

	/**
	 * 生成停止程序的BAT文件
	 */
	public static void generateStopBat() {
		File file = new File("stop.bat");
		if(file.exists() == false) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				logger.error("stop.bat文件创建失败.");
				e.printStackTrace();
			}
		}
		
		logger.info("stop.bat文件的路径如下:" + file.getAbsolutePath());
		
		try {
	         BufferedWriter out = new BufferedWriter(new FileWriter(file, false));
	         String command = "taskkill /pid " + getPid() + " -t -f";
	         out.write(command);
	         out.close();
		} catch (IOException e) {
			logger.error("stop.bat文件写入失败。");
		}
	}
	
	/**
	 * 获取PID
	 * @return
	 */
	private static String getPid() {
		// get name representing the running Java virtual machine.    
		String name = ManagementFactory.getRuntimeMXBean().getName();    
		// get pid    
		String pid = name.split("@")[0];    
		logger.debug("Pid is:" + pid);
		return pid;
	}
}
