package com.nms.server.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.snmp4j.Snmp;

import com.fang.U;
import com.fang.lang.Db;
import com.nms.server.bean.AlarmInfo;
import com.nms.server.bean.DetectInfo;
import com.nms.server.bean.LoopMissionRoundInfo;
import com.nms.server.bean.MissionResult2;
import com.nms.server.bean.MissionStateTable;
import com.nms.server.bean.NmsErrorInfo;
import com.nms.server.bean.ServerIpSegment;
import com.nms.server.bean.ServerTable;
import com.nms.server.bean.SetInfo;
import com.nms.server.bean.SimpleNode;
import com.nms.server.bean.TableColumnsModel;
import com.nms.server.bean.TableModel;
import com.nms.server.dao.CommonDao;
import com.nms.server.thread.alarmData.AlarmDataResoveThread;
import com.nms.server.thread.detecData.NewDetecDataResoveThread;
import com.nms.server.thread.detectDataHandler.DataInsertManagerThread;
import com.nms.server.thread.detectDataHandler.DetectInfoInsertThread;
import com.nms.server.thread.mission.MissionPollingThread;
import com.nms.server.thread.mission.MissionResultThread;
import com.nms.server.thread.monitor.util.MonitorUtil;
import com.nms.server.thread.socket.SocketCMD;
import com.nms.server.util.DateUtil;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.FileUtils;
import com.nms.server.util.IpCovert;
import com.nms.server.util.SNMP4JUtils;
import com.nms.server.util.StringUtil;
import com.nms.server.util.socket.SSLSocketCallable;
import com.nms.server.util.socket.SocketUtils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

/**
 * DataController公共方法类<p>
 * DataController运行正常必要的<p>
 * *线程池、锁、信号计数器及公共数据集合的操作<p>
 * *部分公用工具方法<p>
 * *不涉及数据库<p>
 * ****方法数量较多，涉及广泛，部分方法更涉及到业务方面，优化规整****
 * @author ZGGG3
 * 
 */
public class Common {
	private static final Logger logger = Logger.getLogger(Common.class);
	
	/**
	 * 程序运行标识
	 */
	private volatile static boolean STOP = false;
	
	/**
	 * 数据库操作工具类
	 */
	private static  Db db;
	
	/**
	 * 缓存解析之后的数据
	 * key: info,checkType
	 */
	public static final Hashtable<String,LinkedBlockingDeque> DETECT_QUEUE = new Hashtable<String, LinkedBlockingDeque>();
	
	/**
	 * 保存心跳信息
	 */
	public static final Hashtable<String, Hashtable<String,Object>> HEARTBEAT_IPS = new Hashtable<>();
	
	
	//类加载器
//	private static URLClassLoader classLoader = null;
	
	//#--- DataController 启动成功标志  false 未启动   true 启动成功   默认false	//-废弃
//	private static boolean SYSTEM_INIT_FLAG = false;
	
	/* 数据库可连接状态 */
	public static boolean DB_CONNECT_FLAG = true;
	
	//#--- 当前 DataController 数据库信息 -------
	private static ServerTable serverTable= null;
	
	//#--- Executor Services -------
	
	
	/** 
	 * 线程代码编写注意: 
	 * 1、线程run()或 call()方法产生的异常无法捕获，所以需要对run()和call()方法中的所有代码尽量捕获异常；
	 * 2、不采取捕获的线程，在周期线程池中执行时，如果抛出异常，则该周期任务将被 canceled ，不会再次执行，所以为保证周期任务的稳定运行，尽可能的catch run()的异常 
	 * */
	//-- 非周期执行线程池 用于单次执行线程的运行
	public static final ExecutorService service = Executors.newFixedThreadPool(Constants.EXECUTOR_SOCKET_THREAD_SIZE);	
	public static final ExecutorService dataResoveService = Executors.newFixedThreadPool(Constants.EXECUTOR_DATA_RESOVE_THREAD_SIZE);	
	//-- 定时周期执行线程池	 用于周期执行线程的运行
	public static final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(Constants.EXECUTOR_SCHEDULED_THREAD_SIZE);	
	//-- DataController 程序控制线程池 非守护线程：	独立的执行DC自身监测或优化等操作
	public static final ScheduledExecutorService dcPrivScheduled = Executors.newSingleThreadScheduledExecutor(); 	
	
	/**
	 * 管理 周期线程的集合 Map<线程名称, 线程Future> 用于停用周期线程操作
	 * 
	 * 涉及到方法 线程注册和撤销以及判断线程是否已注册
	 * */
	private static final Map<String, Future<?>> futureMap = new HashMap<String, Future<?>>();	//定时任务变更或取消控制集合
//	private static final Map<String, Runnable> monitorThreadMap = new HashMap<String, Runnable>();	//定时任务变更或取消控制集合
	
	// #--- Node IP & UUID Map ------- 
	private static final Map<String, Long> IP_UUIDMap = new HashMap<String, Long>();	//注册IP集合（临时IP信息和已注册IP信息）
	private static final Map<Long , SimpleNode> nodeInfoMape = new HashMap<Long, SimpleNode>();	//注册IP集合（临时IP信息和已注册IP信息）
	//#--- Node IP & userName password
	private static final Map<String, String[]> IP_USERPWDMap = new HashMap<String, String[]>();	//IP及对应用户名密码信息
	
	// #--- Detection Resove Map -------
	/**
	 * Map<String,List<AlarmInfo>>	=Map<监测设置ID,List<告警设置>> 实现通过监测设置ID 获取对应配置的 告警设置信息，用于数据告警判断和 告警描述
	 * Map<String, Map<Integer, TableColumnsModel>> =Map<监测类别名称标识, Map<解析字段序号（showNumber）, 表字段详细信息>>
	 * Map<String, TableModel> = Map<监测类别名称标识,监测类别信息>
	 * */
	private static final Map<String,List<AlarmInfo>> alarmInfoMap = new HashMap<String,List<AlarmInfo>>();	//告警设置信息集合
	private static final Map<String, Map<Integer, TableColumnsModel>> tableMap = new HashMap<String, Map<Integer,TableColumnsModel>>();	//原数据表及Columns结构集合 checktype_name vs cloumns
	private static final Map<String, TableModel> InsertTable = new HashMap<String, TableModel>();		//check_type VS table_name
	//	private static final Map<String, SetInfo> alarmSetInfoMap = new HashMap<String, SetInfo>();	// 常驻内存的监测设置信息集合 checkTypeName,SetInfo
	
	/**
	 * snmp 监测服务
	 * 
	 * */
	private static Snmp snmp ;	// 全局SNMP对象
	
	/**
	 * snmp_trap 监测类别 特殊处理
	 */
	private static SetInfo snmpTrapSetInfo = null;		//snmp trap 监测设置信息
	/**
	 * Map<Long , String> setInfoNameMape = Map<监测设置ID , 监测设置显示名称>	用于获取监测设置显示名称(邮件 的友好展示)
	 */
	private static final Map<Long , String> setInfoNameMape = new HashMap<Long , String>();	
	/**
	 * Map<String , String> checkTypeNameMape = Map<监测类别标识 , 监测类别显示名称>
	 */
	private static final Map<String , String> checkTypeNameMape = new HashMap<String , String>();	// 监测类别 标识名称 与 显示名称映射
	// #--- Detection Data Set -------
	private static boolean deteDataFlag = true;
	private static final LinkedList<byte[]> deteDataList1 = new LinkedList<byte[]>();
	private static final LinkedList<byte[]> deteDataList2 = new LinkedList<byte[]>();
	
	// #--- Alarm Data Set -------
	private static boolean alarmDataFlag = true;
	private static final LinkedList<String[]> alarmDataList1 = new LinkedList<String[]>();
	private static final LinkedList<String[]> alarmDataList2 = new LinkedList<String[]>();
	
	// #--- Mission Thread -------
	private static final LinkedList<MissionStateTable> reserveMissionList = new LinkedList<MissionStateTable>();		//任务预备队列
//	private static final List<Map<Long,Long>> assignFailMissionList = new LinkedList<Map<Long,Long>>();		//周期任务因节点不通，下发失败队列
	private static final Map<Long, String> missionIdWebIPNMap = new HashMap<Long, String>();	//任务id  下发webIP Map
	private static final MissionPollingThread firstStartThread = new MissionPollingThread("First Polling Thread",1,reserveMissionList);
//	private static final AssignMissionAgainThread assignAgainThread = new AssignMissionAgainThread("下发失败后，首次下发线程",1,assignFailMissionList);
	private static final List<String> assignFailMissIds = new LinkedList<String>();
	
	private static final Map<Long, Future<Object>> bpDownMissionFilesMap = new HashMap<Long, Future<Object>>();	//下载任务文件集合 <MissionID,List<Object[]{fileName,fileMD5,Future<Object>}>>
	private static final Map<Long , MissionStateTable> loopMissionInfoMap = new HashMap<Long, MissionStateTable>();
	private static final Map<Long , List<LoopMissionRoundInfo>> loopMissionRoundInfoList = new HashMap<Long,  List<LoopMissionRoundInfo>>();
	
	//-- 已检查属性 Begin
	public static boolean SERVER_UN_UPGRADE_FLAG = true;			//DataController 升级操作标识
	private static final Semaphore missionSemaphore = new Semaphore(Constants.MISSION_RELEASE_SEMAPHORE_MAX,true);	//任务通信线程最大并发数
	private static final Semaphore monitorSemaphore = new Semaphore(Constants.DETEC_RELEASE_SEMAPHORE_MAX,true);	//主动监测线程最大并发数
	private static final Semaphore changeSemaphore = new Semaphore(Constants.CHANGE_RELEASE_SEMAPHORE_MAX,true);	//主动监测线程最大并发数
	
	// #---任务结果数据集合
	private static final LinkedList<MissionResult2> missionResult2List1 = new LinkedList<MissionResult2>(); 
	private static final LinkedList<MissionResult2> missionResult2List2 = new LinkedList<MissionResult2>(); 
	private static final LinkedList<MissionResult2> missionResult2List3 = new LinkedList<MissionResult2>(); 
	private static final LinkedList<MissionResult2> missionResult2List4 = new LinkedList<MissionResult2>(); 
	private static final LinkedList<MissionResult2> missionResult2List5 = new LinkedList<MissionResult2>(); 
	private static final LinkedList<MissionResult2> missionResult2List6 = new LinkedList<MissionResult2>(); 
	
	//系统异常信息集合
	private static boolean errorInfoFlag = true;
	private static final LinkedList<NmsErrorInfo> errorInfoList1 = new LinkedList<NmsErrorInfo>();
	private static final LinkedList<NmsErrorInfo> errorInfoList2 = new LinkedList<NmsErrorInfo>();
	
	//数据收集线程：限定时间内未获得监测数据节点的存放列表（单独处理）
	public static final ArrayList<String> noDetectDataNodeList = new ArrayList<String>();
	
	//锁
	private static final Byte[] REGISTER_LOCK = new Byte[0];	//线程注册锁
	private static final Byte[] DETEC_DATA_LOCK = new Byte[0];	//监测数据锁
	private static final Byte[] ALARM_DATA_LOCK = new Byte[0];	//告警数据锁
	private static final Byte[] ERROR_INFO_LOCK = new Byte[0];	//告警数据锁
	
	
	private static final Byte[] NO_DETEC_DATA_NODE_LOCK = new Byte[0];	//
	//-- 已检查属性 End

	/**
	 * web 最后一次 握手通信时间
	 */
	private static long LAST_WEB_HANDSHAKE = System.currentTimeMillis();
	
	public static final Map<String,AtomicInteger> SEQUENCE=new HashMap<String,AtomicInteger> ();
	
	static{
		//-- 初始化snmpObject
		/*try {
			logger.debug("创建 classloader  ");
			logger.debug("SNMP_CLASS_PATH  "+new File(Constants.SNMP_CLASS_PATH).toURI().toURL());
			classLoader = new URLClassLoader(new URL[] {new File(Constants.SNMP_CLASS_PATH).toURI().toURL()},ClassLoader.getSystemClassLoader());
		} catch (Error e) {
			logger.error("Class Error", e);
		} catch (Exception e) {
			logger.error("Class Exception", e);
		}*/
		//--
//		service.
	}
	public static void initSequence(java.sql.Connection conn,String ...tableNames){
		logger.info("table sequence init");
		try {
			Statement smt ;
			for (String tableName : tableNames) {
				String sql="select max(SEQUENCE) from "+tableName;
				smt= conn.createStatement();
				ResultSet rs = smt.executeQuery(sql);
				while(rs.next()){
					Integer maxSeq = rs.getInt(1);
					if(maxSeq==null){
						maxSeq=0;
					}
					AtomicInteger tableSequence = new AtomicInteger(maxSeq);
					SEQUENCE.put(tableName, tableSequence);
				}
				smt.close();
				smt=null;
			}
			conn.close();
			conn=null;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void detecSelf(){
		logger.debug("缓存中告警数据量："+(alarmDataList1.size()+alarmDataList2.size()));
		logger.debug("缓存中监测数据量："+(DETE_DATA_QUEUE.size()));
		Set<Entry<String,LinkedBlockingDeque>> entrySet = DETECT_QUEUE.entrySet();
		for(Entry<String,LinkedBlockingDeque> en : entrySet){
			int size = 0;
			LinkedBlockingDeque value = en.getValue();
			if(value != null){
				size = value.size();
			}
			logger.debug("缓存中监测数据-" + en.getKey() +": " + size);
		}
		//logger.debug("缓存中监测数据量："+(deteDataList1.size()+deteDataList2.size()));
		logger.debug("缓存中任务结果数信息数："+(missionResult2List1.size()+missionResult2List4.size()+missionResult2List6.size()));
		logger.debug("缓存中错误信息数据量："+(errorInfoList1.size()+errorInfoList2.size()));
		logger.debug("缓存中监测类别数量2："+(InsertTable.size()));
//		logger.debug("缓存中监测设置信息集合："+(alarmSetInfoMap.size()));
		logger.debug("缓存中告警设置信息集合2："+(alarmInfoMap.size()));
		logger.debug("缓存中IP集合数量："+(IP_UUIDMap.size()));

		
		logger.debug("缓存中文件下载线程数："+(bpDownMissionFilesMap.size()));
		logger.debug("缓存中循环任务信息数1："+(loopMissionInfoMap.size()));
		logger.debug("缓存中循环任务信息数2："+(loopMissionRoundInfoList.size()));
		logger.debug("缓存中任务并发剩余许可："+(missionSemaphore.availablePermits()));
		logger.debug("缓存中监测并发剩余许可："+(monitorSemaphore.availablePermits()));
		logger.debug("缓存中变更并发剩余许可："+(changeSemaphore.availablePermits()));
		
//		logger.debug("基本线程池用量："+(service.));
//		logger.debug("定时线程池用量："+(scheduled));
		
		
	}
	
	
	/**
	 * 当前数据库连接状态
	 * @time Mar 7, 2013-1:45:25 PM
	 * @return
	 */
	public static boolean isDbConnected(){
			return DB_CONNECT_FLAG;
	}
	
	/**
	 * 设置数据库连接状态
	 * @time Mar 7, 2013-1:45:37 PM
	 * @param flag
	 */
	public static void setDbConnectedFlag(boolean flag){
		DB_CONNECT_FLAG = flag;
	}
	
	public static String getDateDirName(){
		return new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
	}
	
/*	public static void changeInitFlag(){
		SYSTEM_INIT_FLAG = (SYSTEM_INIT_FLAG==false? true:false);
	}
	public static boolean getInitFlag(){
		return SYSTEM_INIT_FLAG ;
	}*/
	public static String getLocalIp(){
		/*
		if(StringUtils.isEmpty(SYSTEM_INET_ADDRESS)){
			//-- 获取并判断本机IP
			try {
				Future<Object> future =  Common.service.submit(new GetLocalIpFromWeb(Constants.WEB_SOCKET_IP,Constants.WEB_SOCKET_PORT));
				Object obj = future.get(20,TimeUnit.SECONDS);
				SYSTEM_INET_ADDRESS = (obj==null?null:obj.toString());
			} catch (Exception e) {
				logger.error("获取Server IP 操作 异常", e);
			}
			if(StringUtils.isEmpty(SYSTEM_INET_ADDRESS)){
				logger.warn("Server IP使用默认配置信息");
				SYSTEM_INET_ADDRESS = Constants.SYSTEM_INET_ADDRESS;
			}
		}
	*/
		return Constants.SYSTEM_INET_ADDRESS;
	}
	
	public static String getWebIPByMissionId(Long missionId) {
		return missionIdWebIPNMap.get(missionId);
	}
	
	public static void addMissionIdWebIPMap(Long missionId,String webIp) {
		missionIdWebIPNMap.put(missionId, webIp);
		logger.debug("添加任务ID与系统IP映射: 任务ID["+missionId+"]来自Web["+webIp+"]");
	}
	
	public static void removeMissionIdWebIPMap(Long missionId) {
		missionIdWebIPNMap.remove(missionId);
		logger.debug("删除任务ID与系统IP映射: 任务ID["+missionId+"]");
	}
	public static void clearMissionIdWebIPMap() {
		missionIdWebIPNMap.clear();
		logger.debug("清空任务ID与系统IP映射");
	}
	/**
	 * 改变存放监测数据的数据集合
	 * @time Mar 7, 2012-2:15:38 PM
	 */
	public static void chengeDeteDataFlag() {
		deteDataFlag = deteDataFlag ? false : true;
		logger.info("监测数据缓存集合变更为集合"+(deteDataFlag?"1":"2"));
	}
	
	/**
	 * 获得 非存放状态的数据集合
	 * @time Mar 7, 2012-3:18:11 PM
	 * @return
	 */
	public static synchronized LinkedList<byte[]> getDeteDataList() {
		LinkedList<byte[]> result = U.newLinkedList();
		int i = DETE_DATA_QUEUE.drainTo(result);
		return result;
		/*int dds1 = deteDataList1.size();
		int dds2 = deteDataList2.size();
		logger.debug("集合1缓存数据：" + dds1 +",集合2缓存数据：" + dds2);
		if((dds1 > dds2 && deteDataFlag)  || (dds1<dds2 && !deteDataFlag) ){
			chengeDeteDataFlag();
		}
		if(!deteDataFlag){
			logger.info("取到集合1的缓存数据 共"+deteDataList1.size());
			return deteDataList1;
		}
		else{
			logger.info("取到集合2的缓存数据 共"+deteDataList2.size());
			return deteDataList2;
		}*/
		
	}
	
	
	/**
	 * 返回目前内存中监测数据的总数
	 * TODO 
	 * @author dell Sep 12, 2016
	 * @version 1.0 
	 * @return
	 */
	public static int getAllDeteDataNum() {		
		//return deteDataList1.size()+deteDataList2.size();		
		return DETE_DATA_QUEUE.size();		
	}
	
	/**
	 * 获得 监测数据存放状态的数据集合
	 * @time Mar 7, 2012-3:18:11 PM
	 * @return
	 */
	public static  synchronized LinkedList<byte[]> getNotResovlingDeteDataList() {
		
		/*if(deteDataFlag){
			logger.info("取到集合1的缓存监测数据 共"+deteDataList1.size());
			return deteDataList1;
		}
		else{
			logger.info("取到集合2的缓存监测数据 共"+deteDataList2.size());
			return deteDataList2;
		}*/
		LinkedList<byte[]> result = U.newLinkedList();
		int i = DETE_DATA_QUEUE.drainTo(result);
		return result;
	}
	
	
	/**
	 * 添加或更新Monitor Runnable 到 集合
	 * @time Mar 7, 2012-3:18:11 PM
	 * @return
	 */
//	public static void addOrUpdateMonitorRunnableToMap(String runnableName,Runnable runnable) {
//		monitorThreadMap.put(runnableName, runnable);
//	}
	/**
	 * 根据 key 删除集合中的 Monitor Runnable
	 * @time Mar 7, 2012-3:18:11 PM
	 * @return
	 */
//	public static void removeMonitorRunnableFromMap(String runnableName) {
//		monitorThreadMap.remove(runnableName);
//	}
	/**
	 * 根据Key 获取Monitor Runnable
	 * @time Mar 7, 2012-3:18:11 PM
	 * @return
	 */
//	public static Runnable getMonitorRunnableFromMap(String runnableName) {
//		return monitorThreadMap.get(runnableName);
//	}
	/**
	 * 将监测数据存入存放状态的数据集合中
	 * @time Mar 7, 2012-3:18:58 PM
	 * @param dsb
	 */
	public static void addDeteData(byte[] dsb) {
		
		/*synchronized (DETEC_DATA_LOCK) {
			if(dsb==null || dsb.length==0l){
				logger.debug("监测数据 字节长度0 无需添加到监测数据集合");
				return;
			}
			if(deteDataFlag){
				logger.debug("监测数据 添加到 集合1");
				deteDataList1.add(dsb);}
			else{
				logger.debug("监测数据 添加到 集合2");
				deteDataList2.add(dsb);	}
		}*/
		logger.debug(new String(dsb));
		DETE_DATA_QUEUE.add(dsb);
	}
	
	//无监测数据列表增加删除的同步操作
	public static void moveNoDeteDataNodeFirst(String ip) {
		
		synchronized (NO_DETEC_DATA_NODE_LOCK) {
			if(StringUtils.isNotBlank(ip)){				
				Common.noDetectDataNodeList.remove(ip);
				Common.noDetectDataNodeList.add(0,ip);	
				logger.debug("无监测数据节点列表 移动节点到最前面："+ip);
			}
		}
		
	}
	public static void addNoDeteDataNode(String ip) {
		
		synchronized (NO_DETEC_DATA_NODE_LOCK) {
			if(StringUtils.isNotBlank(ip)){				
				Common.noDetectDataNodeList.add(ip);	
				logger.debug("无监测数据节点列表 添加节点："+ip);
			}
		}
		
	}
	/**
	 * 将监测数据存入存放状态的数据集合中
	 * @time Mar 7, 2012-3:18:58 PM
	 * @param seqId
	 * @param dsb
	 */
	public static void addAllDeteDataList(List<byte[]> dbsList) {
		
		/*synchronized (DETEC_DATA_LOCK) {
			if(dbsList==null || dbsList.size()==0){
				logger.debug("监测数据 个数0 无需添加到监测数据集合");
				return;
			}
			if(deteDataFlag){logger.debug("监测数据 添加到 集合1 : 个数"+(dbsList.size()));
				deteDataList1.addAll(dbsList);}
			else{logger.debug("监测数据 添加到 集合2 : 个数"+dbsList.size());
				deteDataList2.addAll(dbsList);}
		
		}*/
		DETE_DATA_QUEUE.addAll(dbsList);
	}
	/**
	 * 清空非存放状态的数据集合
	 * @time Mar 7, 2012-3:19:30 PM
	 * @param seqId
	 * @param dsb
	 */
	public static void clearDeteDataList() {
		
		synchronized (DETEC_DATA_LOCK) {
			
			getDeteDataList().clear();
			logger.info("清空该集合");
		}
		
	}

	/**
	 * 改变存放监测数据的数据集合
	 * @time Mar 7, 2012-2:15:38 PM
	 */
	public static void changeAlarmDataFlag() {
		
		alarmDataFlag = alarmDataFlag ? false : true;
		logger.info("告警数据缓存集合变更为集合"+(alarmDataFlag?"1":"2"));
	}
	
	/**
	 * 获得 非存放状态的数据集合
	 * @time Mar 7, 2012-3:18:11 PM
	 * @return
	 */
	public static LinkedList<String[]> getAlarmDataList() {
			
			if(!alarmDataFlag){logger.info("取到集合1的缓存告警数据 共"+alarmDataList1.size());
				return alarmDataList1;}
			else{logger.info("取到集合2的缓存告警数据 共"+alarmDataList2.size());
				return alarmDataList2;}
		
	}
	
	/**
	 * 获得 告警数据存放状态的数据集合
	 * @time Mar 7, 2012-3:18:11 PM
	 * @return
	 */
	public static LinkedList<String[]> getNotResovlingWarnDataList() {
		
		if(alarmDataFlag){
			logger.info("取到集合1的缓存告警数据 共"+alarmDataList1.size());
			return alarmDataList1;
		}
		else{
			logger.info("取到集合2的缓存告警数据 共"+alarmDataList2.size());
			return alarmDataList2;
		}
		
	}
	
	/**
	 * 将告警数据存入存放状态的数据集合中
	 * @time Mar 7, 2012-3:18:58 PM
	 * @param dsb
	 */
	public static void addAlarmData(String[] dsb) {
		
		synchronized (ALARM_DATA_LOCK) {
			if(dsb==null || dsb.length==0l){
				logger.debug("告警数据 字节长度0 无需添加到监测数据集合");
				return;
			}
			if(alarmDataFlag){logger.debug("告警数据 添加到 集合1");
				alarmDataList1.add(dsb);}
			else{logger.debug("告警数据 添加到 集合2");
				alarmDataList2.add(dsb);	}
			
		}
		
	}
	/**
	 * 将告警数据存入存放状态的数据集合中
	 * @time Mar 7, 2012-3:18:58 PM
	 * @param seqId
	 * @param dsb
	 */
	public static void addAllAlarmDataList(List<String[]> dbsList) {
		
		synchronized (ALARM_DATA_LOCK) {
			if(dbsList==null || dbsList.size()==0l){
				logger.debug("告警数据 个数0 无需添加到监测数据集合");
				return;
			}
			if(alarmDataFlag){logger.debug("告警数据 添加到 集合1");
				alarmDataList1.addAll(dbsList);}
			else{logger.debug("告警数据 添加到 集合2");
				alarmDataList2.addAll(dbsList);}
		
		}
		
	}
	/**
	 * 清空非存放状态的数据集合
	 * @time Mar 7, 2012-3:19:30 PM
	 * @param seqId
	 * @param dsb
	 */
	public static void clearAlarmDataList() {
		
		synchronized (ALARM_DATA_LOCK) {
			
			getAlarmDataList().clear();
			logger.info("清空该集合");
		}
		
	}
	

	public static void changeErrorInfoFlag() {
		
		errorInfoFlag = errorInfoFlag ? false : true;
		logger.info("错误信息集合变更为集合"+(errorInfoFlag?"1":"2"));
	}
	
	/**
	 * 获得 非存放状态的数据集合
	 * @time Mar 7, 2012-3:18:11 PM
	 * @return
	 */
	public static LinkedList<NmsErrorInfo> getErrorInfoList() {
			
			if(!errorInfoFlag){logger.info("取到集合1的错误信息数据 共"+errorInfoList1.size());
				return errorInfoList1;}
			else{logger.info("取到集合2的错误信息数据 共"+errorInfoList2.size());
				return errorInfoList2;}
		
	}
	
	/**
	 * 获得 错误数据存放状态的数据集合
	 * @time Mar 7, 2012-3:18:11 PM
	 * @return
	 */
	public static LinkedList<NmsErrorInfo> getNotResovlingErrorInfoList() {
		
		if(errorInfoFlag){
			logger.info("取到集合1的缓存错误数据 共"+errorInfoList1.size());
			return errorInfoList1;
		}
		else{
			logger.info("取到集合2的缓存错误数据 共"+errorInfoList2.size());
			return errorInfoList2;
		}
		
	}
	
	/**
	 * 将监测数据存入存放状态的数据集合中
	 * @time Mar 7, 2012-3:18:58 PM
	 * @param dsb
	 */
	public static void addErrorInfo(NmsErrorInfo dsb) {
		
		synchronized (ERROR_INFO_LOCK) {
			if(dsb==null){
				logger.debug("错误信息 为空 无需添加到监测数据集合");
				return;
			}
			if(errorInfoFlag){logger.debug("错误信息 添加到 集合1");
				errorInfoList1.add(dsb);}
			else{logger.debug("错误信息 添加到 集合2");
				errorInfoList2.add(dsb);	}
			
		}
		
	}
	/**
	 * 将监测数据存入存放状态的数据集合中
	 * @time Mar 7, 2012-3:18:58 PM
	 * @param seqId
	 * @param dsb
	 */
	public static void addAllErrorInfoList(List<NmsErrorInfo> dbsList) {
		
		synchronized (ERROR_INFO_LOCK) {
			if(dbsList==null || dbsList.size()==0l){
				logger.debug("错误信息 个数0 无需添加到监测数据集合");
				return;
			}
			if(errorInfoFlag){logger.debug("错误信息 添加到 集合1");
				errorInfoList1.addAll(dbsList);}
			else{logger.debug("错误信息 添加到 集合2");
				errorInfoList2.addAll(dbsList);}
		
		}
		
	}
	/**
	 * 将监测数据存入存放状态的数据集合中
	 * default 本机
	 * @time Mar 7, 2012-3:18:58 PM
	 * @param dsb
	 */
	public static void addErrorInfoForMySelf(String errorCode,Long errorState,String errortDesc) {
//		NmsErrorInfo nei = new NmsErrorInfo(errorCode,Calendar.getInstance().getTime(),Common.getLocalIp(),Common.getLocalIp(),errorState,errortDesc);
//		nei.setErrortGetip(Common.getLocalIp());
//		nei.setErrortIp(Common.getLocalIp());
//		nei.setErrorCode(errorCode);
//		nei.setErrorState(errorState);
//		nei.setErrortDesc(errortDesc);
//		nei.setErrorTime(Calendar.getInstance().getTime());
		addErrorInfo( new NmsErrorInfo(errorCode,Calendar.getInstance().getTime(),Common.getLocalIp(),Common.getLocalIp(),errorState,errortDesc));
	}
	
	/**
	 * 将监测数据存入存放状态的数据集合中
	 * default 本机
	 * @time Mar 7, 2012-3:18:58 PM
	 * @param dsb
	 */
	public static void addErrorInfo(String errorCode,String errortIp,Date errorTime,Long errorState,String errortDesc) {
//		NmsErrorInfo nei = new NmsErrorInfo(errorCode,errorTime,Common.getLocalIp(),errortIp,errorState,errortDesc);
//		nei.setErrortGetip(Common.getLocalIp());
//		nei.setErrortIp(errortIp);
//		nei.setErrorCode(errorCode);
//		nei.setErrorState(errorState);
//		nei.setErrortDesc(errortDesc);
//		nei.setErrorTime(errorTime);
		addErrorInfo(new NmsErrorInfo(errorCode,errorTime,Common.getLocalIp(),errortIp,errorState,errortDesc));
	}
	/**
	 * 将系统错误信息存入存放状态的数据集合中
	 * @time Mar 7, 2012-3:18:58 PM
	 * @param dsb
	 */
	public static void addErrorInfo(String errorCode,String errorGetIp,String errortIp,Date errorTime,Long errorState,String errortDesc) {
//		NmsErrorInfo nei = new NmsErrorInfo(errorCode,errorTime,errorGetIp,errortIp,errorState,errortDesc);
//		nei.setErrortGetip(errorGetIp);
//		nei.setErrortIp(errortIp);
//		nei.setErrorCode(errorCode);
//		nei.setErrorState(errorState);
//		nei.setErrortDesc(errortDesc);
//		nei.setErrorTime(errorTime);
		addErrorInfo(new NmsErrorInfo(errorCode,errorTime,errorGetIp,errortIp,errorState,errortDesc));
	}
	/**
	 * 清空非存放状态的数据集合
	 * @time Mar 7, 2012-3:19:30 PM
	 * @param seqId
	 * @param dsb
	 */
	public static void clearErrorInfoList() {
		
		synchronized (ERROR_INFO_LOCK) {
			
			getErrorInfoList().clear();
			logger.info("清空该集合");
		}
		
	}
	
	/**
	 * 计划任务更新
	 * @time Sep 5, 2011-3:57:17 PM
	 * @param key
	 * @param 
	 */
	public static void registRunnable(String key ,Future<?> future){
		synchronized (REGISTER_LOCK) {
			futureMap.put(key, future);
			logger.info("线程 "+key+" 注册成功");
		}
	}
	
	public static boolean isRunnableRegist(String key){
		synchronized (REGISTER_LOCK) {
			if(futureMap.get(key)!=null){
				logger.info("线程 "+key+" 状态: 已存在");
				return true;
			}else{
				logger.info("线程 "+key+" 状态: 不存在");
				return false;
			}
		}
	}
	
	/**
	 * 即时注销线程
	 * @time Sep 5, 2011-4:08:34 PM
	 * @param key
	 */
	public static void cancelRunnableAtOnce(final String key) {
		synchronized (REGISTER_LOCK) {
			Future<?> future = futureMap.get(key);
			if (future != null) {
				if(future.isDone()||future.isCancelled()){
					logger.info("线程 "+key+" 状态: 已停止");
					futureMap.remove(key);
				}else{
					logger.info("线程 "+key+" 状态: 运行中");
					future.cancel(true);//单次：触发中断标识，这样程序里就可以做判断；周期的就是下一次不再执行
					futureMap.remove(key);
					logger.info("线程 "+key+" 注销成功");
				}
			} else {
				logger.info("线程 "+key+" 状态: 不存在");
			}
		}
	}
	
	/**
	 * 异步注销线程操作
	 * 判断线程是否已存在，再进行注销操作
	 * @time Sep 5, 2011-4:08:34 PM
	 * @param key
	 */
	public static void cancelRunnable(final String key) {
		
		Future<?> future = futureMap.get(key);
		if (future == null) {
			logger.info("线程 "+key+" 状态: 不存在");
		}else{
			service.submit(new Runnable() {
				public void run() {
					synchronized (REGISTER_LOCK) {
//						Thread.currentThread().setName("注销线程" + key);
						Thread.currentThread().setName("Write Off Thread " + key);
						Future<?> future = futureMap.get(key);
						if (future != null) {
							if(future.isDone()||future.isCancelled()){
								logger.info("线程状态: 已停止");
								futureMap.remove(key);
							}else{
								logger.info("线程状态: 运行中");
								future.cancel(true);
								futureMap.remove(key);
								logger.info("注销成功");
							}
						} else {
							logger.info("线程状态: 不存在");
						}
					}
				}
		
			});
		}
	}
	
	
	/**
	 * 在 snmp_class_dir 中加载指定类 并返回该类
	 * 属于临时加载
	 * @time Apr 19, 2012-3:18:15 PM
	 * @param className
	 * @return
	 */
	/*public static Class<?> loadClass(String className) {
		Class<?> c = null;
		try {
			c = classLoader.loadClass(className);
			logger.debug(" className  "+className);
		} catch (ClassNotFoundException e) {
			logger.error("class 加载失败: "+className, e);
		}
		return c;
	}*/
	
	/**
	 * 
	 * <p>key: check_type
	 * <p>value: table_name
	 * @time Jul 15, 2011-2:48:00 PM
	 * @return
	 */
	public static Map<String, TableModel> getInsertTable(){
		return InsertTable;
	}
	
	/**
	 * 主动告警异常信息编写--NC主动发送的给DC的告警（程序异常+程序没运行+（告警值）异常状态连续4次-1级别+（告警值）异常状态1次-设置的告警级别）+DC的一些（例如ping、switchportthread-catch异常）
	   
	 * @time Oct 18, 2011-2:34:07 PM
	 * @param setInfoId
	 * @param checkIp
	 * @param checkType
	 * @param processName
	 * @param checkTime
	 * @param level
	 * @param exInfo
	 * @return
	 */
	public static String[] alarmExceptionInfo(long setInfoId,String checkIp,String checkType,String processName,long checkTime,long level,long state,String exInfo) {
		String[] datas = new String[9];
		datas[0] = setInfoId+"";
		datas[1] = Common.getIpSeqIdMap().get(checkIp)+"";
		datas[2] = checkType;
		datas[3] = processName;//process_iden
		datas[4] = checkTime==0?"":checkTime+"";
		datas[5] = System.currentTimeMillis()+"";
		datas[6] = level+"";
		datas[7] = state+"";//正常、异常
		datas[8] = exInfo==null?"":exInfo.length()>250?exInfo.substring(0, 250):exInfo;
		return datas;
	}
	
	/**
	 * 获取任务下发信号
	 * @time Nov 23, 2011-3:49:38 PM
	 */
	public static void acquireMissionSemaphore() {
//		synchronized (missionSemaphore) {
//			try {
				missionSemaphore.acquireUninterruptibly();
				logger.debug("任务锁 已申请 剩余可用许可:> "+missionSemaphore.availablePermits());
//			} catch (Exception e) {
//				logger.warn("任务锁 线程未申请成功已被中断："+Thread.currentThread().interrupted(),e);
//			}
//		}
	}
	
	/**
	 * 释放任务下发信号
	 * @time Nov 25, 2011-1:24:08 PM
	 */
	public static void releaseMissionSemaphore() {
			missionSemaphore.release();
			logger.debug("任务锁 已释放 当前可用许可:> "+missionSemaphore.availablePermits());
	}
	/**
	 * 获取监测下发信号
	 * @time Nov 23, 2011-3:49:38 PM
	 */
	public static void acquireMonitorSemaphore() {
//		synchronized (monitorSemaphore) {
//			try {
		        logger.debug("监测锁 正在申请 剩余可用许可:> "+monitorSemaphore.availablePermits());
				monitorSemaphore.acquireUninterruptibly();
				logger.debug("监测锁 已申请 剩余可用许可:> "+monitorSemaphore.availablePermits());
//			} catch (Exception e) {
//				logger.warn("监测锁 线程未申请成功已被中断："+Thread.currentThread().interrupted(),e);
//			}
//		}
	}
	/**
	 * 释放监测下发信号
	 * @time Nov 25, 2011-1:24:08 PM
	 */
	public static void releaseMonitorSemaphore() {
//		synchronized (monitorSemaphore) {
		monitorSemaphore.release();
		logger.debug("监测锁 已释放 当前可用许可:> "+monitorSemaphore.availablePermits());
//		}
	}
	/**
	 * 获取变更下发信号
	 * @time Nov 23, 2011-3:49:38 PM
	 */
	public static void acquireChangeSemaphore() {
//		synchronized (changeSemaphore) {
//			try {
				changeSemaphore.acquireUninterruptibly();
				logger.debug("变更锁 已申请 剩余可用许可:> "+changeSemaphore.availablePermits());
//			} catch (Exception e) {
//				logger.warn("变更锁 线程未申请成功已被中断："+Thread.currentThread().interrupted(),e);
//			}
//		}
	}
	/**
	 * 释放变更下发信号
	 * @time Nov 25, 2011-1:24:08 PM
	 */
	public static void releaseChangeSemaphore() {
//		synchronized (changeSemaphore) {
		changeSemaphore.release();
		logger.debug("变更锁 已释放 当前可用许可:> "+changeSemaphore.availablePermits());
//		}
	}
	
	
	/**
	 * 将任务结果存放到任务结果集合中
	 * @time Nov 18, 2011-6:35:48 PM
	 * @param result2
	 */
	public static void addResultToResultList(MissionResult2 result2){
		logger.debug("任务结果加入到 结果队列 "+result2.getMissionType().longValue()+" <> "+result2.getMissionId()+" <> "+result2.getUuid());
//		if(result2 != null && result2.getResult() != null){
			switch (result2.getMissionType().intValue()) {
			case 1:
				synchronized (missionResult2List1) {
					missionResult2List1.add(result2);
				}
				break;
			case 2:
				synchronized (missionResult2List2) {
					missionResult2List2.add(result2);
				}
				break;
			case 3:
				synchronized (missionResult2List3) {
					missionResult2List3.add(result2);
				}
				break;
			case 4:
				synchronized (missionResult2List4) {
					missionResult2List4.add(result2);
				}
				break;
			case 5:
				synchronized (missionResult2List5) {
					missionResult2List5.add(result2);
				}
				break;
			case 6:
				synchronized (missionResult2List6) {
					missionResult2List6.add(result2);
				}
				break;
			default:
				break;
			}
//		}
	}
	/**
	 * 从指定任务类型的任务结果列表中，删除指定的任务结果集合
	 * @time Nov 18, 2011-6:35:48 PM
	 * @param resultList 指定删除的任务结果集合
	 */
	public static void removeResultsFormList(int missionType ,LinkedList<MissionResult2> resultList){
		if(resultList != null && resultList.size() >0){
			switch (missionType){
			case 1:
				synchronized (missionResult2List1) {
					logger.debug("从长度为"+missionResult2List1.size()+" 的 任务结果集合1 中删除 "+resultList.size()+" 个");
					missionResult2List1.removeAll(resultList);
				}
				break;
			case 2:
				synchronized (missionResult2List2) {
					logger.debug("从长度为"+missionResult2List2.size()+" 的 任务结果集合2 中删除 "+resultList.size()+" 个");
					missionResult2List2.removeAll(resultList);
				}
				break;
			case 3:
				synchronized (missionResult2List3) {
					logger.debug("从长度为"+missionResult2List3.size()+" 的 任务结果集合3 中删除 "+resultList.size()+" 个");
					missionResult2List3.removeAll(resultList);
				}
				break;
			case 4:
				synchronized (missionResult2List4) {
					logger.debug("从长度为"+missionResult2List4.size()+" 的 任务结果集合4 中删除 "+resultList.size()+" 个");
					missionResult2List4.removeAll(resultList);
				}
				break;
			case 5:
				synchronized (missionResult2List5) {
					logger.debug("从长度为"+missionResult2List5.size()+" 的 任务结果集合5 中删除 "+resultList.size()+" 个");
					missionResult2List5.removeAll(resultList);
				}
				break;
			case 6:
				synchronized (missionResult2List6) {
					logger.debug("从长度为"+missionResult2List6.size()+" 的 任务结果集合6 中删除 "+resultList.size()+" 个");
					missionResult2List6.removeAll(resultList);
				}
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 返回指定任务类型的任务结果列表（浅克隆）
	 * @time Nov 18, 2011-6:35:48 PM
	 * @param missionType 任务类型 1文件推送  2 3  4脚本命令  5
	 * @return 
	 */
	@SuppressWarnings("unchecked")
	public static LinkedList<MissionResult2> getResultListClone(int missionType){
		LinkedList<MissionResult2> mr2List = null;
			switch (missionType) {
			case 1:
				synchronized (missionResult2List1) {
					mr2List =  (LinkedList<MissionResult2>) missionResult2List1.clone();
				}
				break;
			case 2:
				synchronized (missionResult2List2) {
					mr2List = (LinkedList<MissionResult2>) missionResult2List2.clone();
				}
				break;
			case 3:
				synchronized (missionResult2List3) {
					mr2List = (LinkedList<MissionResult2>) missionResult2List3.clone();
				}
				break;
			case 4:
				synchronized (missionResult2List4) {
					mr2List = (LinkedList<MissionResult2>) missionResult2List4.clone();
				}
				break;
			case 5:
				synchronized (missionResult2List5) {
					mr2List = (LinkedList<MissionResult2>) missionResult2List5.clone();
				}
				break;
			case 6:
				synchronized (missionResult2List6) {
					mr2List = (LinkedList<MissionResult2>) missionResult2List6.clone();
				}
				break;
			default:
				break;
			}
			return mr2List;
	}
	
	/**
	 * 分配任务
	 * 将任务分配到指定线程分类操作
	 * 即时线程队列、线程池-计划线程、线程池-周期线程
	 * @time Nov 10, 2011-4:28:52 PM
	 * @param mission
	 */
	public static void assignMssion(final MissionStateTable mission){
		//刷新即时任务
		try {
			logger.info("分配任务 id: "+mission.getMissionId()+" State: "+mission.getMissionState() + " 分配到即时任务队列");
			//线程不存在情况
			//任务队列存在任务 且第一个任务就是变更任务 终止线程 重新执行该线程
			LinkedList<MissionStateTable> missionList = Common.getReserveMissionListClone();
			if(missionList.size()>0 && missionList.get(0).getMissionId().longValue() == mission.getMissionId().longValue()){ //线程重启:新建之后，马上停掉，0：正在执行的，队列之后的表示还没执行
				Common.getFutureMap().get(Constants.MISSION_THREAD).cancel(true);
				Common.getFutureMap().remove(Constants.MISSION_THREAD);
				Common.removeMissionToReserveMissionList(missionList.get(0));
				Common.addMissionToReserveMissionList(0,mission);
				Common.registRunnable(Constants.MISSION_THREAD,Common.scheduled.schedule(Common.getFirstStartThread(), 0, TimeUnit.SECONDS));
			}else{
				//判断线程是否存在情况 不存在创建
				if(Common.getFutureMap().get(Constants.MISSION_THREAD)==null){
					Common.addMissionToReserveMissionList(mission);
					Common.registRunnable(Constants.MISSION_THREAD,Common.scheduled.schedule(Common.getFirstStartThread(), 0, TimeUnit.SECONDS));
				}else{//已存在 将任务加入队列即可
					boolean flag = true;
					for(int i=0 ; i< missionList.size();i++ ){
						MissionStateTable misTable = missionList.get(i);
						if(misTable.getMissionId().longValue() == mission.getMissionId().longValue()){
							Common.addMissionToReserveMissionList(i, mission);
							flag = false;
							break;
						}
					}
					if(flag){
						Common.addMissionToReserveMissionList(mission);
					}
					if(Common.getFutureMap().get(Constants.MISSION_THREAD).isCancelled()){
						Common.registRunnable(Constants.MISSION_THREAD,Common.scheduled.schedule(Common.getFirstStartThread(), 0, TimeUnit.SECONDS));
					}else if(Common.getFutureMap().get(Constants.MISSION_THREAD).isDone()){
						Common.registRunnable(Constants.MISSION_THREAD,Common.scheduled.schedule(Common.getFirstStartThread(), 0, TimeUnit.SECONDS));
					}
				}
			}
			logger.debug("当前任务队列中任务数： "+Common.getReserveMissionListClone().size());
		} catch (Exception e) {
			logger.error("",e);
		}
	}
	
	/**
	 * 主动监测任务执行操作方法
	 * 引入 申请信号，和释放信号 操作
	 * @time Sep 12, 2012-4:28:45 PM
	 * @param runnable
	 */
	public static void runMonitorRunnable(final Runnable runnable){
		try {
			//-- 针对节点  进行文件推送
			Common.acquireMonitorSemaphore();		//申请监测信号
			
			//-- 启动新线程 推送文件和任务信息
			final Future<?> future = Common.service.submit(runnable);
			final String threadName =  Thread.currentThread().getName();
			Common.service.submit(new Runnable() {
				
				public void run() {
					Thread.currentThread().setName(threadName);
					try {
						future.get(Constants.SINGLE_NODE_DETECT_TIMEOUT, TimeUnit.SECONDS);
					} catch (Exception e) {
						logger.error("Active Monitoring："+threadName+" Wait for timeout anomaly",e);
						if (future != null) {
							if(future.isDone()||future.isCancelled()){
								logger.info("线程 "+threadName+" 状态: 已停止");
							}else{
								logger.info("线程 "+threadName+" 状态: 运行中");
								future.cancel(true);//单次：触发中断标识，这样程序里就可以做判断；周期的就是下一次不再执行
							}
						} else {
							logger.info("线程 "+threadName+" 状态: 不存在");
						}
					}finally{
						Common.releaseMonitorSemaphore();
					}
				}
			});
			
		} catch (Exception e) {
			logger.error("Application signal anomaly",e);
			Common.releaseMonitorSemaphore();
		}finally{
			
		}
	}
	
	/**
	 * 任务通讯操作线程
	 * 引入 申请信号，和释放信号 操作
	 * @time Sep 12, 2012-4:31:27 PM
	 * @param mission
	 * @param callable
	 * @param uuid
	 * @param testNum
	 * @param startTime
	 * @param endTime
	 */
	public static void sendMissionInfo(final MissionStateTable mission,SSLSocketCallable callable,final long uuid,final Integer testNum,final Long startTime,final Long endTime){

		try {
			
			//-- 针对节点  进行文件推送
			Common.acquireMissionSemaphore();		//申请通讯信号

			//-- 启动新线程 推送文件和任务信息
			final Future<Object> future = Common.service.submit(callable);

			//-- 异步线程处理 推送线程执行结果
//			receiveResult(future, mission, uuid,testNum,startTime,endTime);
			final String threadName = Thread.currentThread().getName();
			Common.service.submit(new Runnable() {
				public void run() {
					Thread.currentThread().setName(threadName);
					try {
						MissionResult2 result2 = new MissionResult2();
						result2.setMissionId(mission.getMissionId());
						result2.setMissionType(mission.getMissionType());
						result2.setUuid(uuid);
						result2.setLoopFlag(mission.getLoopFlag());
						result2.setStartTime(startTime);
						result2.setEndTime(endTime);
						//-- 等待推送线程执行完成返回的结果
						/*
						 * 返回值有：null 与 非null
						 * */
						logger.debug("result Info: "+future.get());
						if(future.get() instanceof Integer){
							return ;
						}
						
						String resultStr = (String)future.get();
						if(StringUtils.isNotEmpty(resultStr)){
							String [] str = resultStr.split(Constants.COMMON_DATA_SPLIT,2);
							if(str.length<=1){
								str = resultStr.split(":",2);
							}
							if(StringUtils.isNotEmpty(str[0])){
								result2.setResult(Long.parseLong(str[0]));
							}
							if(str.length>1){
								result2.setDescription(str[1]);
							}
							//-- 将结果追加到结果集和
							Common.addResultToResultList(result2);
						}else{
							if(testNum.intValue() == Constants.MISSION_RELEASE_TIMES.intValue()){
								if(mission.getMissionState().longValue()==6l){
									result2.setResult(6l);
//									result2.setDescription("撤销通讯失败，超过最大尝试次数，等待客户端请求");
//									result2.setDescription("Revocation failed, exceeded maximum number of attempts, waiting for client request");
									result2.setDescription("i18n_server.Common.revokeFail_n81i");
									Common.addResultToResultList(result2);
								}else{
									result2.setResult(1l);
									result2.setResultDetail(41l);
//									result2.setDescription("任务下发失败，通讯中断，且超过最大尝试次数");
//									result2.setDescription("The task failed to be delivered, communication was interrupted, and the maximum number of attempts was exceeded");
									result2.setDescription("i18n_server.Common.missionLssueFail_n81i");
									Common.addResultToResultList(result2);
								}
							}						
						}
					} catch (InterruptedException e) {
						logger.error("",e);
					} catch (Exception e) {
						logger.error("",e);
					}finally{
						Common.releaseMissionSemaphore();
					}
				}
			});
		
		} catch (Exception e) {
			
			logger.warn(nodeInfoMape.get(uuid)+" Task "+mission.getMissionId()+" failure of communication creation");
			if(testNum.intValue() == Constants.MISSION_RELEASE_TIMES.intValue()){
				MissionResult2 result2 = new MissionResult2();
				result2.setMissionId(mission.getMissionId());
				result2.setMissionType(mission.getMissionType());
				result2.setUuid(uuid);
				result2.setResult(1l);
//				result2.setDescription("任务下发失败，建立通讯失败");
//				result2.setDescription("The task failed to be sent and the communication failed to be established");
				result2.setDescription("i18n_server.Common.createConnectionFail_n81i");
				Common.addResultToResultList(result2);
			}
			
			Common.releaseMissionSemaphore();
		}
	}
	/**
	 * 变更操作线程执行方法
	 * 引入 申请信号，和释放信号 操作
	 * @time Sep 12, 2012-4:28:45 PM
	 * @param runnable
	 */
	public static void runChangeRunnable(final Object runnable){
		try {
			//-- 针对节点  进行文件推送
			Common.acquireChangeSemaphore();		//申请监测信号
			
			//-- 启动新线程 推送文件和任务信息
			final Future<?> future;
			if(runnable instanceof Runnable){
				future = Common.service.submit((Runnable)runnable);
			}else if(runnable instanceof Callable){
				future = Common.service.submit((Callable)runnable);
			}else {
				future = null;
			}
			
			final String threadName =  Thread.currentThread().getName();
			Common.service.submit(new Runnable() {
				
				public void run() {
					Thread.currentThread().setName(threadName);
					try {
						future.get();
					} catch (Exception e) {
						logger.error("",e);
					}finally{
						Common.releaseChangeSemaphore();
					}
				}
			});
			
		} catch (Exception e) {
			logger.error("",e);
			Common.releaseChangeSemaphore();
		}finally{
			
		}
	}
	public static boolean hasIpInIpSegment(String ip){
		Long ipn =  IpCovert.ipToLong(ip);
		List<ServerIpSegment> list = Common.getServerTable().getIpSegList();
		if(ipn != 0 && list!= null && list.size()>0){
			for(ServerIpSegment segment : list){
				if(segment != null && segment.getStartIpn() <= ipn && ipn <= segment.getEndIpn()){
					logger.debug("ip 存在于 区间["+segment.getStartIp()+","+segment.getEndIp()+"]");
					return true;
				}
			}
		}
		logger.debug("ip 不在当前Server的管理区间");
		return false;
	}
	
	public static Long getUUIDByIp(String ip) {
		return IP_UUIDMap.get(ip)==null?null:IP_UUIDMap.get(ip);
	}

	public static String getNodeIpByUUID(Long uuid) {
		return nodeInfoMape.get(uuid)==null?null:nodeInfoMape.get(uuid).getNodeIp();
	}
	
	public static Integer getSnmpVerByUUID(Long uuid) {
		return (nodeInfoMape.get(uuid)==null
				|| nodeInfoMape.get(uuid).getSnmpVersion()==null)?Constants.COMMON_SNMP_VERSION
				:nodeInfoMape.get(uuid).getSnmpVersion();
	}
	
	public static String getClassNameByCheckTypeName(String checkTypeName){
		String tableName =  Common.getInsertTable().get(checkTypeName).getTableName();
		if(StringUtils.isNotEmpty(tableName) && tableName.startsWith("DI_")){
			tableName = tableName.replaceFirst("DI_", "");
		}
		return tableName;
	}
//	/**
//	 * 线程执行结果处理方法
//	 * 线程执行结束返回结果信息为string类型数据 格式为 "0:string"
//	 * @time Nov 13, 2011-12:17:36 PM
//	 * @param future
//	 * @param result
//	 */
//	private static void receiveResult(final Future<Object> future,final MissionStateTable mission,final long uuid,final Integer testNum,final Long startTime,final Long endTime){
//		Common.service.submit(new Runnable() {
//			public void run() {
//				Thread.currentThread().setName("任务推送结果处理线程");
//				try {
//					MissionResult2 result2 = new MissionResult2();
//					result2.setMissionId(mission.getMissionId());
//					result2.setMissionType(mission.getMissionType());
//					result2.setUuid(uuid);
//					result2.setLoopFlag(mission.getLoopFlag());
//					result2.setStartTime(startTime);
//					result2.setEndTime(endTime);
//					//-- 等待推送线程执行完成返回的结果
//					/*
//					 * 返回值有：null 与 非null
//					 * */
//					logger.debug("result Info: "+future.get());
//					if(future.get() instanceof Integer){
//						return ;
//					}
//					
//					String resultStr = (String)future.get();
//					if(StringUtils.isNotEmpty(resultStr)){
//						String [] str = resultStr.split(Constants.COMMON_DATA_SPLIT,2);
//						if(str.length<=1){
//							str = resultStr.split(":",2);
//						}
//						if(StringUtils.isNotEmpty(str[0])){
//							result2.setResult(Long.parseLong(str[0]));
//						}
//						if(str.length>1){
//							result2.setDescription(str[1]);
//						}
//						//-- 将结果追加到结果集和
//						Common.addResultToResultList(result2);
//					}else{
//						if(testNum.intValue() == Constants.MISSION_RELEASE_TIMES.intValue()){
//							if(mission.getMissionState().longValue()==6l){
//								result2.setResult(6l);
//								result2.setDescription("撤销通讯失败，超过最大尝试次数，等待客户端请求");
//								Common.addResultToResultList(result2);
//							}else{
//								result2.setResult(1l);
//								result2.setDescription("任务下发失败，通讯中断，且超过最大尝试次数");
//								Common.addResultToResultList(result2);
//							}
//						}
//					}
//				} catch (InterruptedException e) {
//					logger.error("",e);
//				} catch (Exception e) {
//					logger.error("",e);
//				}finally{
//					
//				}
//			}
//		});
//	}
	//获得当前的报警设置信息，与相应字段值比较
	public static String[] getAlarmState(List<AlarmInfo> alarmInfos, String[] sysData) throws Exception{
		String[] strs = null;
//		logger.debug("!!you gaojing  o "+(alarmInfos==null?null:alarmInfos.size()));
		if(alarmInfos!=null){
			strs = new String[]{"", "", ""};
			for(AlarmInfo alarm : alarmInfos){
//				logger.debug("!!you gaojing  o "+alarm.getPoliceValue());
				if(sysData.length>=alarm.getShowNum()){
					if(sysData[alarm.getShowNum()-1]==null){
						logger.error("Monitoring data is empty and can not do alarm verification");
						continue;
					}
					if("equal".equals(alarm.getPoliceSysmbols())){
						if((sysData[alarm.getShowNum()-1]).equals(alarm.getPoliceValue())){
							strs[0] += alarm.getShowNum() + "|";// 告警序列号
							strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
							strs[2] += alarm.getPoliceValue() + "|"; //告警值
						}
					}
					else if("include".equals(alarm.getPoliceSysmbols())){
						if((sysData[alarm.getShowNum()-1]).indexOf(alarm.getPoliceValue())!=-1){
							strs[0] += alarm.getShowNum() + "|";// 告警序列号
							strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
							strs[2] += alarm.getPoliceValue() + "|"; //告警值
						}
					}
					else if("exclude".equals(alarm.getPoliceSysmbols())){
						if((sysData[alarm.getShowNum()-1]).indexOf(alarm.getPoliceValue())==-1){
							strs[0] += alarm.getShowNum() + "|";// 告警序列号
							strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
							strs[2] += alarm.getPoliceValue() + "|"; //告警值
						}
					}
					else{
						Double data = Math.abs(Double.parseDouble(sysData[alarm.getShowNum()-1]));
						double result = data - Double.parseDouble(alarm.getPoliceValue());
						if ((">".equals(alarm.getPoliceSysmbols()) && result > 0)
								|| ("<".equals(alarm.getPoliceSysmbols()) && result < 0)
								|| ("=".equals(alarm.getPoliceSysmbols()) && result == 0)
								|| (">=".equals(alarm.getPoliceSysmbols()) && result >= 0)
								|| ("<=".equals(alarm.getPoliceSysmbols()) && result <=0) ) {
							strs[0] += alarm.getShowNum() + "|";// 告警序列号
							strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
							strs[2] += alarm.getPoliceValue() + "|"; //告警值
						}
					}
				}
			}
			for(int i=0; i<strs.length; i++){
				if(strs[i].length()>0){
					strs[i] = strs[i].substring(0, strs[i].length()-1);
				}
			}
		}
		
		if(strs!=null && "".equals(strs[0])){
			strs = null;
		}
		
		return strs;
	}
	
	//获得当前的报警设置信息，与相应字段值比较
	public static String getStateInfo(String checkType, List<AlarmInfo> alarmInfos, String[] sysData) throws Exception{
		StringBuffer strs = null;
//		logger.debug("!!you gaojing  o "+(alarmInfos==null?null:alarmInfos.size()));
		if(alarmInfos!=null){
			strs = new StringBuffer();
			for(AlarmInfo alarm : alarmInfos){
//				logger.debug("!!you gaojing  o "+alarm.getPoliceValue());
				if(sysData.length>=alarm.getShowNum()){
					if(sysData[alarm.getShowNum()-1]==null){
						logger.error("Monitoring data is empty and can not do alarm verification");
						continue;
					}
					boolean alarmFlag =false;
					if("equal".equals(alarm.getPoliceSysmbols())){
						if((sysData[alarm.getShowNum()-1]).equals(alarm.getPoliceValue())){
							alarmFlag = true;
						}
					}
					else if("include".equals(alarm.getPoliceSysmbols())){
						if((sysData[alarm.getShowNum()-1]).indexOf(alarm.getPoliceValue())!=-1){
							alarmFlag = true;
						}
					}
					else if("exclude".equals(alarm.getPoliceSysmbols())){
						if((sysData[alarm.getShowNum()-1]).indexOf(alarm.getPoliceValue())==-1){
							alarmFlag = true;
						}
					}
					else{
						Double data = Math.abs(Double.parseDouble(sysData[alarm.getShowNum()-1]));
						double result = data - Double.parseDouble(alarm.getPoliceValue());
						if ((">".equals(alarm.getPoliceSysmbols()) && result > 0)
								|| ("<".equals(alarm.getPoliceSysmbols()) && result < 0)
								|| ("=".equals(alarm.getPoliceSysmbols()) && result == 0)
								|| (">=".equals(alarm.getPoliceSysmbols()) && result >= 0)
								|| ("<=".equals(alarm.getPoliceSysmbols()) && result <=0) ) {
							alarmFlag = true;
						}
					}
					
					if(alarmFlag){
						strs.append(Common.getTableMap().get(checkType).get(alarm.getShowNum()).getFiledName()
								+"("+Common.getTableMap().get(checkType).get(alarm.getShowNum()).getFiledComments()+") "+								
								":> "+sysData[alarm.getShowNum()-1]+" "+alarm.getPoliceSysmbols()+" "+alarm.getPoliceValue()+";\n");
					}
				}
			}
		}
		return strs.toString();
	}
	
	
	private static final SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);		//Java Date 类型数据格式化格式
	
	public static SimpleDateFormat getFormat() {
		return format;
	}


	/**
	 * 任务结果解析
	 * @time Nov 12, 2011-8:00:06 PM
	 * @return
	 */
	public static MissionResult2 resoveMissionResult(String [] result){
//		任务ID，任务类型，UUID，周期标识 long,开始执行时候，结束时间，配置截取文本，结果状态，结果描述
		try {
			if(result == null && result.length>=9){
				return null;
			}
			if(StringUtils.isEmpty(result[0]) || StringUtils.isEmpty(result[1])){
				return null;
			}
//			  任务ID、任务类型、UUID、周期任务标识、开始时间、结束时间、resultConfig(备用的字段)、结果状态、结果描述
			
			MissionResult2 result2 = new MissionResult2();
			//- 任务Id long
			result2.setMissionId((StringUtils.isNotEmpty(result[0]) && !"null".equalsIgnoreCase(result[0]))?Long.parseLong(result[0]):null);
			//-- 任务类型 long
			result2.setMissionType((StringUtils.isNotEmpty(result[1]) && !"null".equalsIgnoreCase(result[1]))?Long.parseLong(result[1]):null);
			//- UUID long
			result2.setUuid((StringUtils.isNotEmpty(result[2]) && !"null".equalsIgnoreCase(result[2]))?Long.parseLong(result[2]):null);
			//- 周期标识 long
			result2.setLoopFlag((StringUtils.isNotEmpty(result[3]) && !"null".equalsIgnoreCase(result[3]))?Long.parseLong(result[3]):null);
			//- 开始执行时间 long
			result2.setStartTime((StringUtils.isNotEmpty(result[4]) && !"null".equalsIgnoreCase(result[4]))?Long.parseLong(result[4]):null);
			//- 结束时间 long
			result2.setEndTime((StringUtils.isNotEmpty(result[5]) && !"null".equalsIgnoreCase(result[5]))?Long.parseLong(result[5]):null);
			//- 配置截取文本 string
			result2.setText((StringUtils.isNotEmpty(result[6])&& !"null".equalsIgnoreCase(result[6].trim()))?result[6]:null);
			//- 结果状态 long
			result2.setResult((StringUtils.isNotEmpty(result[7]) && !"null".equalsIgnoreCase(result[7]))?Long.parseLong(result[7]):null);
			//- 结果描述 string
			if(result.length>8){
				result2.setDescription((StringUtils.isNotEmpty(result[8])&& !"null".equalsIgnoreCase(result[8].trim()))?(format.format(result2.getStartTime())+">> "+result[8].trim()):null);
			}
			return result2;
		} catch (Exception e) {
			logger.error("",e);
		}
		return null;
	}
	
	//保存缓存中的监测数据到硬盘
	public static void saveDetectDataToDisk() {
		LinkedList<byte []> notResolvingDetectDataList =  Common.getNotResovlingDeteDataList();	// 获取未在解析的监测数据集合
		try {
			//终止正在解析监测数据的线程，并将正在解析的list里未解析的数据存入硬盘
			Future<?> future = Common.getFutureMap().get(Constants.DETEC_DATA_RESOVE);
			if(future != null && !future.isCancelled() && !future.isDone()){	//运行中
				future.cancel(true);
			}
			LinkedList<byte []> detectDataList = Common.getDeteDataList();	// 获取非存放状态的数据集合(正在解析的list)
			saveByteToFile(detectDataList);
			
			//将未在解析的list存放到硬盘上
			saveByteToFile(notResolvingDetectDataList);			
			
		}catch(IndexOutOfBoundsException e) {
			logger.error("When monitoring data is too much, the data is stored in the hard disk",e);
		}catch (Exception e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
		}
			
	}	
	public static void saveByteToFile(LinkedList<byte[]> dataList) {
		String filePath = "";
		int dataSize = dataList.size();//如果不按此时的size来操作，则list里的数据可能会一直在增加，就会一直循环下去？
		try {
			for(int j=0;j<dataSize;j++) {
				byte[] data= dataList.get(0);//因为每次循环都会dataList.remove(0);所以每次操作的都是第0条记录
				filePath = Constants.OVERRUN_DETEC_FILE_DIR+"/"+Common.getDateDirName()+"/"+Calendar.getInstance().getTimeInMillis()+"_"+j+".csv";
				FileUtils.wirteBytesToFile(data, filePath);
				dataList.remove(0);
			}
			
		}catch(Exception e) {
			logger.error("When monitoring data is too much, the data is stored in the hard disk",e);
		}
	}
	
	//保存缓存中的告警数据到硬盘
	public static void saveWarningDataToDisk() {
		LinkedList<String []> notResolvingWarningDataList =  Common.getNotResovlingWarnDataList();	// 获取未在解析的告警数据集合
		try {
			
			//终止正在解析告警数据的线程，并将正在解析的list里未解析的数据存入硬盘
			Future<?> future = Common.getFutureMap().get(Constants.ALARM_DATA_RESOVE);
			if(future != null && !future.isCancelled() && !future.isDone()){	//运行中
				future.cancel(true);
			}
			LinkedList<String []> warningDataList = Common.getAlarmDataList();	// 获取非存放状态的数据集合(正在解析的list)
			saveStrToFile(warningDataList);
			
			//将未在解析的list存放到硬盘上
			saveStrToFile(notResolvingWarningDataList);
			
			
		}catch(IndexOutOfBoundsException e) {
			logger.error("When the alarm data is too much, the data is stored in the hard disk",e);
		}catch (Exception e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
		}
			
	}	
	private static void saveStrToFile(LinkedList<String[]> dataList) {
		String filePath = "";
		int dataSize = dataList.size();//如果不按此时的size来操作，则list里的数据可能会一直在增加，就会一直循环下去？
		try {
			for(int j=0;j<dataSize;j++) {
				String[] data= dataList.get(0);
				filePath = Constants.OVERRUN_WARNING_FILE_DIR+"/"+Common.getDateDirName()+"/"+Calendar.getInstance().getTimeInMillis()+"_"+j+".csv";
				File file = new File(filePath);
				String dataStr = StringUtil.linkToString(data, Constants.COMMON_DATA_SPLIT, "");
				FileUtils.writeStringToFile(file, dataStr);
//				String[] msg = FileUtils.readFileToString(file).split(Constants.COMMON_DATA_SPLIT);
//				System.out.println(FileUtils.readFileToString(file));
				dataList.remove(0);
				logger.info("告警数据过多，已保存至"+filePath);
			}
			
		}catch(Exception e) {
			logger.error("When the alarm data is too much, the data is stored in the hard disk",e);
		}
	}
	
    //保存缓存中的任务结果到硬盘
	public static void saveResultDataToDisk() {
		try {
			
			//终止正在解析告警数据的线程，并将正在解析的list里未解析的数据存入硬盘
			Future<?> future = Common.getFutureMap().get(Constants.MISSION_RESULT_RESOVE);
			if(future != null && !future.isCancelled() && !future.isDone()){	//运行中
				future.cancel(true);//停解析任务结果数据入库线程
			}
			
			for(int i=1 ;i<=6 ; i++){				
				//-- 获取结果集合
				LinkedList<MissionResult2> result = Common.getResultListClone(i);
				
				//-- 集合不为空则进行解析 存在removeList情况 ，优化方式可参考 监测数据解析的实现方式
				if(result!=null && result.size()>0){
					//将未在解析的list存放到硬盘上
					saveMissObjToFile(result,i);
					result.clear();	//清除mr2List
				}
			}			
			
		}catch(IndexOutOfBoundsException e) {
			logger.error("When the result data is too much, the data is stored in the hard disk exception",e);
		}catch (Exception e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
		}
			
	}	
	
	// 收集数据前先进行握手监测通信
	public static DetectInfo doNmsClientDetect(String ip,SetInfo setInfo,long startTime) {
		logger.info("开始握手监测>" + ip);
		DetectInfo detectInfo = null;
		try {
			// -- 发送握手命令
			String sendTime = Calendar.getInstance().getTimeInMillis() + "";
			// sendMessage(SocketCMD.CLIENT_REQ_HAND_SHAKE);//DC与NC握手通信后，NC会关闭socket，导致无法收集数据
			// String msg = receiveMessage();//收到回复的信息后，说明握手成功了

			String backTime = Calendar.getInstance().getTimeInMillis() + "";
			// -- 信息保存到监测信息对象中
			detectInfo = new DetectInfo();

			StringBuffer nmsClientDetailDetectInfo = new StringBuffer();
			nmsClientDetailDetectInfo.append(SocketCMD.CLIENT_REQ_HAND_SHAKE);// 发送信息
			nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);// 分隔符
			nmsClientDetailDetectInfo.append(SocketUtils.SUCCESS + ":"
					+ SocketCMD.CLIENT_REQ_HAND_SHAKE + "|" + sendTime);// 返回信息:DC端伪造的，因为也不需要NC回复信息了
			nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);// 分隔符
			nmsClientDetailDetectInfo.append("0");// 是否可达,0:可达，1：不可达
			nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);// 分隔符
			nmsClientDetailDetectInfo.append(sendTime);// 发送时间
			nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);// 分隔符
			nmsClientDetailDetectInfo.append(backTime);// 返回时间
			nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);// 分隔符
			nmsClientDetailDetectInfo.append(DateUtil.getSecondsFromBeinToEnd(
					new Date(Long.parseLong(sendTime)).getTime(), new Date(Long
							.parseLong(backTime)).getTime())
					+ "");// 延迟时间

			detectInfo.getDetailDatas().add(
					nmsClientDetailDetectInfo.toString());

//			detectInfo.setDescInfo("开始"
//					+ DateUtil.getStringByLongStr(sendTime)
//					+ " NMSClient握手"
//					+ DateUtil.getStringByLongStr(backTime)
//					+ " 成功 ");
//			detectInfo.setDescInfo("Started"
//					+ DateUtil.getStringByLongStr(sendTime)
//					+ " NMSClient handshake"
//					+ DateUtil.getStringByLongStr(backTime)
//					+ " success ");
			detectInfo.setDescInfo("i18n_server.Common.nmsShakeHandBegin_n81i"
					+ DateUtil.getStringByLongStr(sendTime)
					+ " i18n_server.Common.nmsShakeHand_n81i"
					+ DateUtil.getStringByLongStr(backTime)
					+ " i18n_server.Common.nmsShakeHandSuccess_n81i ");

		} catch (Exception e) {
			logger.error("Generating node："+ip+"information anomaly", e);
		}finally{
			if (Thread.currentThread().isInterrupted()) {
				// 线程被中断，结束收集线程
				logger.info("收集线程 被中断");
				return detectInfo;
			}else {
				Common.createNmsClientDetectData(setInfo, ip, detectInfo, startTime);
			}
		}
		
		return detectInfo;
	}
	
	public static DetectInfo errorNodeToDo(String threadName,boolean nmsclientFlag, SetInfo setInfo,String ip,Long checkTime,long startTime){
//		Thread.currentThread().setName(threadName + "(异常节点)");
		Thread.currentThread().setName(threadName + "(Abnormal node)");
		if (Thread.currentThread().isInterrupted()) {
			// 线程被中断，结束收集线程
			logger.info("收集线程 被中断");
			return null;
		}
		if(!nmsclientFlag){//对于不需要进行握手监测的节点，则不进行握手
			return null;
		}
		DetectInfo detectInfo = null;
		String stateInfo = "";
		try{
			detectInfo = new DetectInfo();
			String failStartTime = Calendar.getInstance().getTimeInMillis()
					+ "";
			long maxTimes = 1l;

			if (setInfo != null && setInfo.getCheckMaxTimes() != null) {
				maxTimes = setInfo.getCheckMaxTimes();
			}

			String[] pingData = pingHandshake(ip, maxTimes);

			String failEndTime = Calendar.getInstance().getTimeInMillis() + "";

			if ((StringUtils.isEmpty(pingData[1]) || "0".equals(pingData[1]))) {// ping不通，无握手监测详细数据
//				stateInfo = "网络异常";
//				stateInfo = "Network abnormality";
				stateInfo = "i18n_server.Common.netErr_n81i";
			} else {
				// 可以ping通进行ssh测试 如果ssh可以通 就产生一条握手失败信息 如果ssh不同就产生一条ssh失败信息
				String sshResult = Constants.SUCCESS;
				if(1==Constants.FLAG_HANDWALK_SSH){					
					String[] userPwdInfo = Common.getIpUserPwdMap().get(ip);
					if (userPwdInfo!=null && 
							userPwdInfo.length>=3 && "1".equals(userPwdInfo[2])) {//应该判断nc的操作系统，不是dc的,1:linux; 2:windows; 3:other
						sshResult = sshConnect(ip,userPwdInfo[0],userPwdInfo[1]);
					}
				}
				
				if (Constants.SUCCESS.equals(sshResult)) {
//					stateInfo = "开始" + DateUtil.getStringByLong(checkTime)
//							+ " NMSClient握手" + DateUtil.getCurrentTime() + " 失败 ";
//					stateInfo = "Started" + DateUtil.getStringByLong(checkTime)
//					+ " NMSClient handshake" + DateUtil.getCurrentTime() + " failed ";
					stateInfo = "i18n_server.Common.nmsShakeHandBegin_n81i" + DateUtil.getStringByLong(checkTime)
							+ " i18n_server.Common.nmsShakeHand_n81i" + DateUtil.getCurrentTime() + " i18n_server.Common.nmsShakeHandFail_n81i ";
			    }else{
					stateInfo = sshResult;
			    }
				StringBuffer detailInfo = new StringBuffer();
				detailInfo.append(SocketCMD.CLIENT_REQ_HAND_SHAKE);// 发送信息
				detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
				detailInfo.append("");// 返回信息
				detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
				detailInfo.append("1");// 是否可达,0:可达，1：不可达
				detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
				detailInfo.append(failStartTime);// 发送时间
				detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
				detailInfo.append(failEndTime);// 返回时间
				detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
				detailInfo.append(DateUtil.getSecondsFromBeinToEnd(new Date(
						Long.parseLong(failStartTime)).getTime(), new Date(Long
								.parseLong(failEndTime)).getTime())
								+ "");// 延迟时间
				detectInfo.getDetailDatas().add(detailInfo.toString());
			}
		}catch (Exception e) {
			logger.error("Generating abnormal nodes："+ip+"information anomaly", e);
		}finally{			
			detectInfo.setDescInfo(stateInfo);
			logger.info("与 " + ip + " 的握手监测发生异常  失败：" + stateInfo);
			createNmsClientDetectData(setInfo,ip,detectInfo, startTime);//生成监测数据信息
		}
		return detectInfo;
	}
	
	//创建握手监测信息
	public static void createNmsClientDetectData(SetInfo setInfo,String ip,DetectInfo  detectInfo,long startTime){
		if(detectInfo!=null){			
			int testTimes = 1;
			Long checkTime = System.currentTimeMillis();		
			detectInfo.setTestTimes(testTimes);//尝试次数
			detectInfo.setCheckTime(checkTime);//监测时间
			try{
				/**
				 * -- 监测数据描述信息非空（web界面的状态信息），才生成监测数据:
				 *    1、监测数据为空可能是收集线程超时导致ping或者ssh未执行完毕，未生成描述信息
				 *    2、此时web端进行超周期设置时，过滤掉异常的节点，异常节点的异常信息还是采用之前周期的-此功能 20160906 web端还未实现						     
				 */
				if(StringUtils.isNotBlank(detectInfo.getDescInfo())){
					MonitorUtil.createMonitorData(ip, setInfo, startTime, Common.getAlarmInfoMap().get(setInfo.getId()+ ""), detectInfo);
				}
			} catch (Exception ex) {
				logger.error(ExceptionPrintUtils.printExceptionStack(ex));
				String processIden = setInfo.getProcessIden()==null ? "" : setInfo.getProcessIden();
				String[] alarm = Common.alarmExceptionInfo(setInfo.getId(), ip, Constants.DETEC_NMSC_STR,processIden , startTime, 1,Constants.DETECTION_INFO_ALARM_WRONG, ex.getMessage());
				Common.addAlarmData(alarm);
			}
		}
	}
	
	public static List<String> pingHandshake(List<String> nodetectdatanodelist) {
		List<String> list = new ArrayList<String>();
		StringBuffer commond = new StringBuffer();
		String system = (String) (System.getProperty("os.name")).toLowerCase();
		Process process = null;
		BufferedReader in = null;
		long a = new Date().getTime();
		for(String str : nodetectdatanodelist){
			if (system.toLowerCase().indexOf("win") != -1) {
				commond.append("ping -n 4 "+ str +" & ");
			} else if (system.toLowerCase().indexOf("linux") != -1) {
				commond.append("ping -c 4 "+ str +" ; ");
			} else {
				commond.append("ping -w 4 "+ str +" & ");
			}
		}
		if(commond.length()>1){
			commond=commond.delete(commond.length()-2, commond.length()-1);
		}
		logger.info("异常节点列表ping commond:"+commond);
		
		String[] cmd = new String[3] ;
		if (system.toLowerCase().indexOf("win") != -1) {
			cmd[0] = "cmd";
			cmd[1] = "/C";
			cmd[2] = commond.toString();
		} else if (system.toLowerCase().indexOf("linux") != -1) {
			cmd[0] = "/bin/sh";
			cmd[1] = "-c";
			cmd[2] = commond.toString();
		}
		try {
			process = Runtime.getRuntime().exec(cmd);
			in = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line="";
			while ((line = in.readLine()) != null) {
				System.out.println(line.toLowerCase());
				if(line.toLowerCase().indexOf("ttl")>0){
					String[] str = line.split(" ");
					String ip = "";
					if (system.toLowerCase().indexOf("win") != -1) {
						ip = str[1];
					}else if(system.toLowerCase().indexOf("linux") != -1){
						ip = str[3].substring(0,str[3].length()-1);
					}
					if(!StringUtils.isBlank(ip)&&!list.contains(ip)){
						list.add(ip.trim());
					}
				}
			}
			long b = System.currentTimeMillis();
			logger.info("-----------执行ping命令  节点数量："+nodetectdatanodelist.size()+"    总耗时："+(b-a)+"毫秒，     "+(b-a)/1000+"秒");
			for(String s : list){logger.info(" ping 成功的ip："+s);	}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	private static String[] pingHandshake(String ip, long maxTimes) {

		String command = ""; // 命令语句
		int minTime = Integer.MAX_VALUE, maxTime = 0, totalTime = 0, curTime; // 最短时间，最长时间，总时间，时间变量
		int snum = 0, fnum = 0; // 发包成功和失败数

		// 判断系统类型 win or Linux
		String system = (String) (System.getProperty("os.name")).toLowerCase();

		if (system.toLowerCase().indexOf("win") != -1) {
			command += "ping -n 4 " + ip;// 尝试次数 -n
		} else if (system.toLowerCase().indexOf("linux") != -1) {
			command += "ping -c 4 " + ip;
		} else {
			command += "ping -w 4 " + ip;
		}

		String stateInfo = "";
		String[] datas2 = new String[7];
		Process process = null;
		BufferedReader in = null; // 读取 Ping命令返回的信息
		StringBuffer buffer = new StringBuffer();
		try {
			logger.debug("ping command:" + command);
			process = Runtime.getRuntime().exec(command);
			in = new BufferedReader(new InputStreamReader(process
					.getInputStream()));
			String line = null;
			long count = maxTimes + 10;
			int index;
			// 最多多读10行
			while ((line = in.readLine()) != null && count != 0) {
				if ("".equals(line)) {
					count--;
					continue;
				} // 空串跳过
				buffer.append(line + "\n");
				line = line.toLowerCase();
				logger.debug("line:" + line);
				if (line.indexOf("ttl") > 0) { // 获得成功响应的数据
					count--; // 计数器自减1
					// 截取time 值
					if ((index = line.lastIndexOf("ms")) != -1) {
						byte[] buf = line.getBytes();
						int start = 0, end = buf.length, i, j;
						// 下标末点
						for (i = index; i >= 0; i--) {
							if (Character.isDigit((char) buf[i])) {
								end = i;
								break;
							}
						}
						if (i == 0)
							continue;
						// 下标起点
						for (j = end; j >= 0; j--) {
							if (!Character.isDigit((char) buf[j])) {
								start = j + 1;
								break;
							}
						}
						// 时间值截取
						curTime = Integer.parseInt(new String(buf, start, end
								+ 1 - start));
						snum++; // 成功接收次数加1
						totalTime += curTime; // 计算总时间

						if (curTime < minTime) {
							minTime = curTime;
						} // 最小时间

						if (curTime > maxTime) {
							maxTime = curTime;
						} // 最大时间
					}
				} else if (line.split(" ").length < 4) {
					count--; // 计数器自减1
					fnum++; // 失败接收次数加1
				} else {
					stateInfo += line + "\n";
				}
			}

			if (totalTime == 0) {
				minTime = 0;
			}

			// 已发送包数
			datas2[0] = "" + (snum + fnum);
			datas2[1] = "" + snum;
			datas2[2] = "" + fnum;

			BigDecimal fnum0 = new BigDecimal(fnum);
			BigDecimal tnum0 = new BigDecimal(snum + fnum);
			DecimalFormat df = new DecimalFormat("####0.00");
			if (tnum0.intValue() != 0) {
				datas2[3] = ""
						+ ((new BigDecimal(df.format(fnum0.divide(tnum0, 4,
								RoundingMode.HALF_UP))))
								.multiply(new BigDecimal(100)));
			}
			datas2[4] = "" + minTime;
			datas2[5] = "" + maxTime;
			datas2[6] = "" + (snum == 0 ? 0 : (totalTime / snum));
		} catch (Exception e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
			if (process != null)
				process.destroy();
			process = null;
		}

		/*
		 * if(state==-1){ isSuccess = false; }else{ isSuccess = true; }
		 */
		return datas2;
	}
	
	//批量ping方法：方法1：使用nmap命令； 方法2：
//	private static List<String[]> pingHandshakeBatch(List<String> ipList, long maxTimes) {
//		
////		List<String> commandList = new ArrayList<String>(); // 命令语句
//		List<String[]> datasList = new ArrayList<String[]>(); // 命令语句
//		int minTime = Integer.MAX_VALUE, maxTime = 0, totalTime = 0, curTime; // 最短时间，最长时间，总时间，时间变量
//		int snum = 0, fnum = 0; // 发包成功和失败数
//		
//		// 判断系统类型 win or Linux
//		String system = (String) (System.getProperty("os.name")).toLowerCase();
//		String os = "";
//		if(system.toLowerCase().indexOf("win") != -1){
//			os  = Constants.OS_WIN;
//		}else if (system.toLowerCase().indexOf("linux") != -1) {
//			os  = Constants.OS_LINUX;
//		}
//		String command = ""; // 命令语句
//		Process process = null;
//		BufferedReader in = null; // 读取 Ping命令返回的信息
//		try {
//			for(String ip:ipList){			
//				if (Constants.OS_WIN.equals(os)) {
//	//				command += "ping -n 4 " + ip+" & ";// 尝试次数 -n
//					command = "ping -n 4 " + ip;// 尝试次数 -n
//				} else if (Constants.OS_LINUX.equals(os)) {
//	//				command += "ping -c 4 " + ip+" ; ";
//					command = "ping -c 4 " + ip;
//				} else {
//					command = "ping -w 4 " + ip;//???
//				}
//	//			commandList.add(command);
//			
//			
//				String stateInfo = "";
//				String[] datas2 = new String[7];
//				
//				StringBuffer buffer = new StringBuffer();
//				
//					logger.debug("ping command:" + command);
//		//			String[] cmds = new String[commandList.size()];
//					
//					process = Runtime.getRuntime().exec(command);
//					in = new BufferedReader(new InputStreamReader(process
//							.getInputStream()));
//					String line = null;
//					long count = maxTimes + 10;
//					int index;
//					// 最多多读10行
//					while ((line = in.readLine()) != null && count != 0) {
//						if ("".equals(line)) {
//							count--;
//							continue;
//						} // 空串跳过
//						buffer.append(line + "\n");
//						line = line.toLowerCase();
//						logger.debug("line:" + line);
//						if (line.indexOf("ttl") > 0) { // 获得成功响应的数据
//							count--; // 计数器自减1
//							// 截取time 值
//							if ((index = line.lastIndexOf("ms")) != -1) {
//								byte[] buf = line.getBytes();
//								int start = 0, end = buf.length, i, j;
//								// 下标末点
//								for (i = index; i >= 0; i--) {
//									if (Character.isDigit((char) buf[i])) {
//										end = i;
//										break;
//									}
//								}
//								if (i == 0)
//									continue;
//								// 下标起点
//								for (j = end; j >= 0; j--) {
//									if (!Character.isDigit((char) buf[j])) {
//										start = j + 1;
//										break;
//									}
//								}
//								// 时间值截取
//								curTime = Integer.parseInt(new String(buf, start, end
//										+ 1 - start));
//								snum++; // 成功接收次数加1
//								totalTime += curTime; // 计算总时间
//								
//								if (curTime < minTime) {
//									minTime = curTime;
//								} // 最小时间
//								
//								if (curTime > maxTime) {
//									maxTime = curTime;
//								} // 最大时间
//							}
//						} else if (line.split(" ").length < 4) {
//							count--; // 计数器自减1
//							fnum++; // 失败接收次数加1
//						} else {
//							stateInfo += line + "\n";
//						}
//					}
//					
//					if (totalTime == 0) {
//						minTime = 0;
//					}
//					
//					// 已发送包数
//					datas2[0] = "" + (snum + fnum);
//					datas2[1] = "" + snum;
//					datas2[2] = "" + fnum;
//					
//					BigDecimal fnum0 = new BigDecimal(fnum);
//					BigDecimal tnum0 = new BigDecimal(snum + fnum);
//					DecimalFormat df = new DecimalFormat("####0.00");
//					if (tnum0.intValue() != 0) {
//						datas2[3] = ""
//							+ ((new BigDecimal(df.format(fnum0.divide(tnum0, 4,
//									RoundingMode.HALF_UP))))
//									.multiply(new BigDecimal(100)));
//					}
//					datas2[4] = "" + minTime;
//					datas2[5] = "" + maxTime;
//					datas2[6] = "" + (snum == 0 ? 0 : (totalTime / snum));
//				
//				datasList.add(datas2);
//			}
//		} catch (Exception e) {
//			logger.error(ExceptionPrintUtils.printExceptionStack(e));
//		} finally {
//			if (in != null) {
//				try {
//					in.close();
//				} catch (IOException e) {
//					logger.error("", e);
//				}
//			}
//			if (process != null)
//				process.destroy();
//			process = null;
//		}
//		/*
//		 * if(state==-1){ isSuccess = false; }else{ isSuccess = true; }
//		 */
//		return datasList;
//	}

	public static String sshConnect(String hostname, String username, String password) {
		String result = Constants.SUCCESS;
		long a = new Date().getTime();
		Connection conn = null;
		Session sess = null;
		try {
			if(StringUtils.isNotBlank(hostname)){
				conn = new Connection(hostname);
				logger.debug("SSHConnect----链接ip:"+hostname+" 用户名："+username+" 密码："+password);
				conn.connect(null,Constants.SSH_CONNECT_TIMEOUT,Constants.SSH_CONNECT_TIMEOUT);
				long b = new Date().getTime();
				logger.debug("SSHConnect----链接ip:"+hostname+"耗时：" + (b - a) + "毫秒," + (b - a)
						/ 1000 + "秒");
				boolean isAuthenticated = conn.authenticateWithPassword(username,
						password);
				if (isAuthenticated == true) {
					sess = conn.openSession();
					sess.execCommand("date");
					InputStream stdout = new StreamGobbler(sess.getStdout());
					BufferedReader stdoutReader = new BufferedReader(
							new InputStreamReader(stdout, Charset.forName("utf-8")));
					while (true) {
						String line = stdoutReader.readLine();
						if (line == null){
							break;
						}
					}
				}else{
//					result = "SSH 登录用户名或密码错误";
//					result = "SSH login username or password error";
					result = "i18n_server.Common.sshLogin_n81i";
				}					
				long c = new Date().getTime();
				logger.debug("SSHConnect----测试完成ip:"+hostname+"，总耗时：" + (c - a) + "毫秒," + (c - a)/1000 + "秒");
			}
		} catch (IOException e) {
			long d = new Date().getTime();
			logger.error("SSHConnect----Connection exception IP:"+hostname+"，Time consuming：" + (d - a) + "Millisecond," + (d - a)
					/ 1000 + "Second", e);			
//			result = "SSH 连接失败";
			result = "i18n_server.Common.sshConnectionFail_n81i";
		} catch (Exception e1) {
			long e = new Date().getTime();
			logger.error("SSHConnect----Connection exception IP:"+hostname+"，Time consuming：" + (e - a) + "Millisecond," + (e - a)
					/ 1000 + "Second", e1);			
//			result = "SSH 连接失败";
//			result = "SSH connection failure";
			result = "i18n_server.Common.sshConnectionFail_n81i";
		}finally {
			if(conn!=null){
				conn.close();
			}
			if(sess!=null){
				sess.close();
			}
		}
		return result;
	}
	
	
	
	//写一个任务对象到一个文件后，清除列表里的这个任务对象
	public static void saveMissObjToFile(LinkedList<MissionResult2> missObjList,int missionType) {
		String filePath = "";
		int missObjSize = missObjList.size();//如果不按此时的size来操作，则list里的数据可能会一直在增加，就会一直循环下去？
		try {
			String parPath = Constants.OVERRUN_RESULT_FILE_DIR.substring(0,Constants.OVERRUN_RESULT_FILE_DIR.length()-1);
			LinkedList<MissionResult2> tmpList = new LinkedList<MissionResult2>();
			for(int j=0;j<missObjSize;j++) {
				MissionResult2 result= missObjList.get(j);
				filePath = parPath+"/missionResult"+missionType+"/"+Common.getDateDirName()+"/"+Calendar.getInstance().getTimeInMillis()+"_"+j+".result";
				File file = new File(filePath);
				FileUtils.writeObjToFile(result, file);
				
				//在Common中删除掉已保存到硬盘的任务结果(其实就一个任务结果对象)
				tmpList.add(result);
				Common.removeResultsFormList(missionType, tmpList);
				tmpList.clear();
				
				logger.info("任务结果数据过多，已保存至"+filePath);
			}
			
		}catch(Exception e) {
			logger.error("When the result data is too much, the data is stored in the hard disk exception",e);
		}
	}
	
	//清理缓存数据:停止收集管理线程、停止收集线程(好多节点，不太好取消)、停止解析管理线程、停止解析线程，存数据入库
	public static void clearDataInMem() throws Exception{
		//-- 第一步 关闭通讯:不再收集数据...
		Common.SERVER_UN_UPGRADE_FLAG = false;
		logger.info("关闭通讯");
		
		//-- 第二步 清理缓存 detection & alarm & results
		
		Common.cancelRunnableAtOnce(Constants.DETEC_DATA_RESOVE_MANAGER);
		Common.cancelRunnableAtOnce(Constants.DATA_COLLECT_MANAGER);
		Common.cancelRunnableAtOnce(Constants.DETECT_RESOVE_THREAD_KEY);//多线程入库监测数据的解析线程
		Common.cancelRunnableAtOnce(Constants.DETECT_INFO_THREAD_KEY);//多线程入库监测数据的 info 入库线程
		Common.cancelRunnableAtOnce(Constants.DETECT_DETAIL_THREAD_KEY);//多线程入库监测数据 detail 入库线程
		
		Future<?> detecFuture = null;
		Future<?> detecFuture2 = null;
		if(Constants.DETECT_INSERT_THREAD_MODE ==1){//单线程模式
			//-- 关闭线程 清理 监测数据
			if(Common.getFutureMap().get(Constants.DETEC_DATA_RESOVE) != null){
				Common.getFutureMap().get(Constants.DETEC_DATA_RESOVE).cancel(true);//此处可能没结束成功
			}
			LinkedList<byte []> dsbList = Common.getDeteDataList();
//			Future<?> detecFuture = Common.scheduled.submit(new NewDetecDataResoveThread("Server关闭前_缓存监测数据入库1",dsbList));
			detecFuture = Common.scheduled.submit(new NewDetecDataResoveThread("Server Before Closing The Cache Monitoring Data Warehouse 1",dsbList));
//			Common.chengeDeteDataFlag();
//			LinkedList<byte []> dsbList2 = Common.getDeteDataList();
//			Future<?> detecFuture2 = Common.scheduled.submit(new NewDetecDataResoveThread("Server关闭前_缓存监测数据入库2",dsbList2));
//			Future<?> detecFuture2 = Common.scheduled.submit(new NewDetecDataResoveThread("Server Before Closing The Cache Monitoring Data Warehouse 2",dsbList2));
		}else if(Constants.DETECT_INSERT_THREAD_MODE == 2){//多线程入库
			detecFuture = Common.service.submit(new DataInsertManagerThread());
			detecFuture2 = Common.service.submit(new DetectInfoInsertThread());
		}
		logger.info("缓存监测数据 清理中");
		
		//-- 关闭线程 清理 告警数据
		if(Common.getFutureMap().get(Constants.ALARM_DATA_RESOVE) != null){
			Common.getFutureMap().get(Constants.ALARM_DATA_RESOVE).cancel(true);
		}
		LinkedList<String []> adList = Common.getAlarmDataList();
//		Future<?> alarmFuture = Common.scheduled.submit(new AlarmDataResoveThread("Server关闭前_缓存告警数据入库1",adList));
		Future<?> alarmFuture = Common.scheduled.submit(new AlarmDataResoveThread("Server Before Closing The Cache Alarm Data Into The Library 1",adList));
		Common.changeAlarmDataFlag();
		LinkedList<String []> adList2 = Common.getAlarmDataList();
//		Future<?> alarmFuture2 = Common.scheduled.submit(new AlarmDataResoveThread("Server关闭前_缓存告警数据入库2",adList2));
		Future<?> alarmFuture2 = Common.scheduled.submit(new AlarmDataResoveThread("Server Before Closing The Cache Alarm Data Into The Library 2",adList2));
		logger.info("缓存告警数据 清理中");
		
		//-- 关闭线程 清理 任务结果数据
		if(Common.getFutureMap().get(Constants.MISSION_RESULT_RESOVE) != null){
			Common.getFutureMap().get(Constants.MISSION_RESULT_RESOVE).cancel(true);
		}
//		Future<?> mrFuture = Common.scheduled.submit(new MissionResultThread("Server关闭前_缓存任务结果入库"));
		Future<?> mrFuture = Common.scheduled.submit(new MissionResultThread("Server Before Closing The Result Of Caching Task"));
		logger.info("缓存任务结果 清理中");
		
		
		//超时未处理完
		try {
			if(detecFuture != null){
				detecFuture.get(Constants.MISSION_UPGRADE_DAILY, TimeUnit.SECONDS);
			}
			if(detecFuture2 != null){
				detecFuture2.get(Constants.MISSION_UPGRADE_DAILY, TimeUnit.SECONDS);
			}
			logger.info("缓存监测数据 清理结束");
			
			alarmFuture.get(Constants.MISSION_UPGRADE_DAILY, TimeUnit.SECONDS);
			alarmFuture2.get(Constants.MISSION_UPGRADE_DAILY, TimeUnit.SECONDS);
			logger.info("缓存告警数据 清理结束");
			
			mrFuture.get(Constants.MISSION_UPGRADE_DAILY, TimeUnit.SECONDS);
			logger.info("缓存任务结果 清理结束");
			
		} catch (Exception e) {
			logger.warn("DC handles (parse, store) cache data timeout, confirm shutdown");
		}
	}
	
	//将缓存中的数据存至硬盘
	public static void saveDataInMemToDisk(){
		try{
			logger.info("缓存数据存至硬盘...");
			logger.info("缓存 监测数据 存至硬盘...");
			Common.saveDetectDataToDisk();//监测数据				
			logger.info("缓存 监测数据 存至硬盘 完成");
			
			logger.info("缓存 告警数据 存至硬盘...");
	        Common.saveWarningDataToDisk();//告警数据				
	        logger.info("缓存 告警数据 存至硬盘 完成");
	        
	        logger.info("缓存 结果数据 存至硬盘...");
			Common.saveResultDataToDisk();//结果数据	
			logger.info("缓存 结果数据 存至硬盘 完成");
		}catch(Exception e){
			logger.error("将缓存中的数据存至硬盘 异常",e);
		}
	}
	
	public static void printMemUse(){
		Runtime.getRuntime().gc();
		long totleByte = Runtime.getRuntime().totalMemory();
		long freeByte = Runtime.getRuntime().freeMemory();
		logger.info("占用内存：目前总内存："+(totleByte/1024/1024)+"M  空闲内存："+(freeByte/1024/1024)+"M 占用内存："+((totleByte-freeByte)/1024/1024)+"M");

	}
	
	
	public static void main(String [] args){		
		
		String result = "261$@$4$@$1$@$0$@$1358241982955$@$1358241996202$@$$@$0$@$";
		resoveMissionResult(result.split(Constants.COMMON_DATA_SPLIT));
		List<String> ipList = new ArrayList<String>();
		ipList.add("10.0.6.102");
		ipList.add("10.0.6.100");
//		pingHandshakeBatch(ipList, 20);
	}
	/**
	 * 原数据表及Columns结构集合
	 * key : CheckTypeName
	 * value : Columns结构集合
	 * @time Apr 9, 2012-3:36:09 PM
	 * @return
	 */
	public static Map<String, Map<Integer, TableColumnsModel>> getTableMap() {
			return tableMap;
	}
	public static Map<String, Future<?>> getFutureMap() {
			return futureMap;
	}
	public static Map<String,List<AlarmInfo>> getAlarmInfoMap() {
		return alarmInfoMap;
	}
	public static Map<String, Long> getIpSeqIdMap() {
		return IP_UUIDMap;
	}
	public static Map<String, String[]> getIpUserPwdMap() {
		return IP_USERPWDMap;
	}

	public static void putSimpleNode(Long uuid, SimpleNode node) {
		nodeInfoMape.put(uuid, node);
	}
	public static LinkedList<MissionStateTable> getReserveMissionListClone() {
		synchronized (reserveMissionList) {
			return (LinkedList<MissionStateTable>) reserveMissionList.clone();
		}
	}
	public static void removeMissionToReserveMissionList(int i) {
		synchronized (reserveMissionList) {
			reserveMissionList.remove(i);
		}
	}
	public static void removeMissionToReserveMissionList(MissionStateTable mission) {
		synchronized (reserveMissionList) {
			reserveMissionList.remove(mission);
		}
	}
	public static void addMissionToReserveMissionList(MissionStateTable mission) {
		synchronized (reserveMissionList) {
			reserveMissionList.add(mission);
		}
	}
	public static void addMissionToReserveMissionList(int i,MissionStateTable mission) {
		synchronized (reserveMissionList) {
			reserveMissionList.add(i,mission);
		}
	}
	
	//下发失败任务
//	public static void removeMissionToAssignFailMissionList(int i) {
//		synchronized (assignFailMissionList) {
//			assignFailMissionList.remove(i);
//		}
//	}
//	public static void removeMissionToAssignFailMissionList(Map<Long,Long> missSeqMap) {
//		synchronized (assignFailMissionList) {
//			assignFailMissionList.remove(missSeqMap);
//		}
//	}
//	public static void addMissionToAssignFailMissionList(Map<Long,Long> missSeqMap) {
//		synchronized (assignFailMissionList) {
//			assignFailMissionList.add(missSeqMap);
//		}
//	}
//	public static void addMissionToAssignFailMissionList(int i,Map<Long,Long> missSeqMap) {
//		synchronized (assignFailMissionList) {
//			assignFailMissionList.add(i,missSeqMap);
//		}
//	}
	//-----
	public static MissionPollingThread getFirstStartThread() {
		return firstStartThread;
	}
	
//	public static AssignMissionAgainThread getAssignAgainThread()
//	{
//		return assignAgainThread;
//	}
	public static Map<Long, MissionStateTable> getLoopMissionInfoMap() {
		return loopMissionInfoMap;
	}
	public static Map<Long, List<LoopMissionRoundInfo>> getLoopMissionRoundInfoList() {
		return loopMissionRoundInfoList;
	}

	public static Map<Long, Future<Object>> getBpDownMissionFilesMap() {
		return bpDownMissionFilesMap;
	}

//	public static Map<String, SetInfo> getAlarmSetInfoMap() {
//		return alarmSetInfoMap;
//	}

	public static Snmp getSnmp() {
		return snmp==null ? SNMP4JUtils.createSnmp():snmp;
	}
	public static ServerTable getServerTable() {
		return serverTable;
	}
	public static void setServerTable(ServerTable serverTable) {
		Common.serverTable = serverTable;
	}


	public static SetInfo getSnmpTrapSetInfo() {
		return snmpTrapSetInfo;
	}


	public static void setSnmpTrapSetInfo(SetInfo snmpTrapSetInfo) {
		Common.snmpTrapSetInfo = snmpTrapSetInfo;
	}


	public static Map<Long, String> getSetInfoNameMape() {
		return setInfoNameMape;
	}


	public static Map<String, String> getCheckTypeNameMape() {
		return checkTypeNameMape;
	}


	
//	public static List<Map<Long, Long>> getAssignFailMissionList()
//	{
//		return assignFailMissionList;
//	}
	
	public static List<String> getAssignFailMissIds()
	{
		return assignFailMissIds;
	}

	public static void addAssignFailMissionIds(String missId) {
		synchronized (assignFailMissIds) {
			assignFailMissIds.add(missId);
		}
	}
	
	public static void addAllAssignFailMissionIds(List<String> missIds) {
		synchronized (assignFailMissIds) {
			assignFailMissIds.addAll(missIds);
		}
	}

	public static void removeAllAssignFailMissionIds() {
		synchronized (assignFailMissIds) {
			assignFailMissIds.clear();
		}
	}

	public static long getLastWebHandshake() {
		return LAST_WEB_HANDSHAKE;
	}

	public static void setLastWebHandshake(long LastWebHandshake) {
		LAST_WEB_HANDSHAKE = LastWebHandshake;
	}
	
	
	
	/**
	 * 2018年7月30日 修改监测数据存放位置，改为保存到队列 中
	 */
	private static final LinkedBlockingDeque<byte[]> DETE_DATA_QUEUE = new LinkedBlockingDeque<byte[]>();
	
	/**
	 * 保存监测数据到缓存队列
	 * @param data
	 */
	public static void addDeteDataQueue(byte[] data){
		DETE_DATA_QUEUE.add(data);
	}
	
	/**
	 * 保存监测数据到缓存队列
	 * @param data
	 */
	public static void addDeteDataQueue(List<byte[]> data){
		DETE_DATA_QUEUE.addAll(data);
	}
	
	/**
	 * 从监测数据缓存队列中 获取元素
	 * @return
	 * @throws InterruptedException
	 */
	public static byte[] takeDeteDataQueue() throws InterruptedException{
		return DETE_DATA_QUEUE.take();
	}
	
	/**
	 * 非阻塞 从监测数据缓存队列中 获取元素
	 * @return
	 * @throws InterruptedException
	 */
	public static byte[] pollDeteDataQueue(){
		return DETE_DATA_QUEUE.poll();
	}
	
	/**
	 * 程序是否停止运行
	 * fasle:运行
	 * true：停止
	 * @return
	 */
	public static boolean isStop(){
		return STOP;
	}
	
	/**
	 * 程序停止运行
	 */
	public static synchronized void stop(){
		STOP = true;
	}
	
	public static void initDb(Db db){
		Common.db = db;
	}
	
	public static Db getDb(){
		return Common.db;
	}
	
	/**
	 * 将监测数据缓存到队列，等待入库线程入库
	 * @param type
	 * @param obj
	 */
	public synchronized static void putDetectQueue(String type,Map<String, String> detail){
		LinkedBlockingDeque queue = DETECT_QUEUE.get(type);
		if(queue == null){
			queue = new LinkedBlockingDeque();
			DETECT_QUEUE.put(type, queue);
		}
		queue.add(detail);
	}
	
	public synchronized static void putDetectInfoQueue(Object[] info){
		LinkedBlockingDeque queue = DETECT_QUEUE.get(DetectInfo.INFO_KEY);
		if(queue == null){
			queue = new LinkedBlockingDeque();
			DETECT_QUEUE.put(DetectInfo.INFO_KEY, queue);
		}
		queue.add(info);
	}
	
	/**
	 * 添加多条
	 * @param type
	 * @param details
	 */
	public synchronized static void putAllDetectQueue(String type,List<Map<String, String>>details){
		LinkedBlockingDeque queue = DETECT_QUEUE.get(type);
		if(queue == null){
			queue = new LinkedBlockingDeque();
			DETECT_QUEUE.put(type, queue);
		}
		queue.addAll(details);
	}
	
	/**
	 * 保存 心跳信息
	 * @param ip
	 * @param key
	 * @param value
	 */
	public static void saveHbInfo(String ip,String key,Object value){
		Hashtable<String, Object> hashtable = HEARTBEAT_IPS.get(ip);
		if(hashtable == null){
			hashtable = new Hashtable<String, Object>();
			HEARTBEAT_IPS.put(ip, hashtable);
		}
		hashtable.put(key, value);
	}
	
	/**
	 * 获取 心跳信息
	 * @param ip
	 * @param key
	 * @return
	 */
	public static <T> T  getHbInfo(String ip,String key){
		Hashtable<String, Object> hashtable = HEARTBEAT_IPS.get(ip);
		if(hashtable != null){
			return (T) hashtable.get(key);
		}
		return null;
	}
	
	
	public static int byteArrayToInt(byte[] b) {  
	    return   b[3] & 0xFF |  
	            (b[2] & 0xFF) << 8 |  
	            (b[1] & 0xFF) << 16 |  
	            (b[0] & 0xFF) << 24;  
	}  
	  
	public static byte[] intToByteArray(int a) {  
	    return new byte[] {  
	        (byte) ((a >> 24) & 0xFF),  
	        (byte) ((a >> 16) & 0xFF),     
	        (byte) ((a >> 8) & 0xFF),     
	        (byte) (a & 0xFF)  
	    };  
	}
}
