package com.nms.server.service;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;

import sun.misc.BASE64Decoder;

import com.nms.server.bean.AlarmInfo;
import com.nms.server.bean.DetectInfo;
import com.nms.server.bean.EmailInfo;
import com.nms.server.bean.NmsErrorInfo;
import com.nms.server.bean.NodeModel;
import com.nms.server.bean.NodegroupModel;
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.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.common.EmailTypeConstants;
import com.nms.server.dao.CommonDao;
import com.nms.server.util.DateUtil;
import com.nms.server.util.IpCovert;
import com.nms.server.util.SQLExecuteTimeoutException;
import com.nms.server.util.StringUtil;


/**
 * 	公用业务操作类
 *  @date Jul 20, 2011 3:16:00 PM
 *	@author ZhangGang
 *
 */
public class CommonService {
	private final Logger logger = Logger.getLogger(CommonService.class);
	private final SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);		//Java Date 类型数据格式化格式
	private final String PING_STR = Constants.DETEC_PING_STR;
	private final String NMSC_STR = Constants.DETEC_NMSC_STR;
	protected CommonDao dao = null;

	public CommonService(CommonDao dao){
		this.dao = dao;
	}
	
	public int getFlagEmail() {
		int emailFlag = 0;//1:启动，0：关闭
		try {
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("type_identity");
			
			//参数配置中0表示启用，1表示停用
			String selectSql = "select type_identity from type_table t where t.type_state=0 and lower(t.type_identity)=lower('"+Constants.EMAIL_TYPE_IDENTITY+"')";
			List list = dao.dbSelect(selectSql, fields);
			if(list!=null && list.size()>0) {
				emailFlag = 1;
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return emailFlag;
	}
	/**
	 * 获取指定ID的SetInfo信息
	 * @time Oct 12, 2011-10:45:54 AM
	 * @param setInfoId		SetInfo ID
	 * @return
	 */
	public SetInfo getSetInfoById(Long setInfoId) {
		SetInfo setInfo = new SetInfo();
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("id");
			fields.add("node_ips_id");
			fields.add("check_type_id");
			fields.add("check_gap");
			fields.add("check_out_time");
			fields.add("check_max_times");
			fields.add("process_Iden");
			fields.add("process_file");
			fields.add("process_path");
			fields.add("detection_set_state");
			fields.add("check_way");
			fields.add("check_type_name");
			fields.add("is_control_start");
			fields.add("control_start_time");
			fields.add("upload_gap");
			fields.add("plan_check_time");
			fields.add("is_schedule");
			fields.add("is_snmp");
			fields.add("node_groups_id");
			fields.add("process_search_keycode");
			
			ArrayList<Map<String, String>> mapList = dao
					.dbSelect(
							"select dsi.id,dsi.check_type_id,dsi.node_ips_id,dsi.check_gap,dsi.check_out_time,dsi.check_max_times,check_way,dsi.process_Iden,dsi.process_file,dsi.process_path,cti.check_type_name,cti.is_snmp,dsi.detection_set_state, "
									+ "to_char(dsi.plan_check_time,'" + Constants.DB_DATE_FORMAT + "') plan_check_time, "
									+ "dsi.is_control_start,dsi.upload_gap,dsi.control_start_time,is_schedule,dsi.node_groups_id,dsi.process_search_keycode "
									+ "from detection_set_info dsi "
									+ "left join check_type_info cti on cti.id = dsi.check_type_id "
									+ "where  dsi.id = '" + setInfoId.longValue() + "' ",
							fields);
			if (mapList != null && mapList.size() > 0) {
				for (Map<String, String> map : mapList) {
					setInfo.setId(setInfoId);
					setInfo.setCheckTypeId(StringUtils.isEmpty(map.get("check_type_id"))?null:Long.valueOf(map.get("check_type_id")));
					setInfo.setCheckGap(StringUtils.isEmpty(map.get("check_gap"))?null:Long.valueOf(map.get("check_gap")));
					setInfo.setCheckOutTime(
							StringUtils.isEmpty(map.get("check_out_time"))?null:Long.valueOf(map.get("check_out_time")));
					setInfo.setCheckMaxTimes(
							StringUtils.isEmpty(map.get("check_max_times"))?null:Long.valueOf(map.get("check_max_times")));
					setInfo.setProcessIden(map.get("process_Iden"));
					setInfo.setProcessFile(map.get("process_file"));
					setInfo.setProcessPath(map.get("process_path"));
					setInfo.setCheckWay(map.get("check_way"));
					setInfo.setCheckState(map.get("detection_set_state"));
					setInfo.setCheckTypeName(map.get("check_type_name"));
					setInfo.setIsControlStart(map.get("is_control_start"));
					setInfo.setUploadGap(
							StringUtils.isEmpty(map.get("upload_gap"))?null:Long.valueOf(map.get("upload_gap"))
							);
					if (!StringUtils.isEmpty(map.get("plan_check_time"))) {
						setInfo.setPlanCheckTime(format.parse(map.get("plan_check_time")).getTime());
					}
					
					if (!StringUtils.isEmpty(map.get("control_start_time"))) {
						setInfo.setControlStartTime(format.parse(map.get("control_start_time")).getTime());
					}
					setInfo.setIsSchedule(StringUtils.trim(map.get("is_schedule")));
					setInfo.setIsSNMP(StringUtils.isBlank(map.get("is_snmp"))?null:Long.valueOf(StringUtils.trim(map.get("is_snmp"))));
					setInfo.setNodeIpsId(StringUtils.trim(map.get("node_ips_id")));
					setInfo.setNodeGroupsId(StringUtils.trim(map.get("node_groups_id")));
					setInfo.setProcessSearchKeyCode(StringUtils.trim(map.get("process_search_keycode")));
//					setInfo.setNodeIp(map.get("node_ip"));
//					setInfo.setGroupId(StringUtils.isEmpty(map.get("group_id"))?null:Long.valueOf(map.get("group_id")));
					break;
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return setInfo;
	}
	
	
	/**
	 * 获取指定ID的SetInfo信息
	 * @time Oct 12, 2011-10:45:54 AM
	 * @param setInfoId		SetInfo ID
	 * @return
	 */
	public List<SetInfo> getAllSetInfo(Integer setInfoState,Integer checkWay) {
		List<SetInfo> setInfoList = new ArrayList<SetInfo>();
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("id");
			fields.add("node_ips_id");
			fields.add("check_type_id");
			fields.add("check_gap");
			fields.add("check_out_time");
			fields.add("check_max_times");
			fields.add("process_Iden");
			fields.add("process_file");
			fields.add("process_path");
			fields.add("detection_set_state");
			fields.add("check_way");
			fields.add("check_type_name");
			fields.add("is_control_start");
			fields.add("control_start_time");
			fields.add("upload_gap");
			fields.add("plan_check_time");
			fields.add("is_schedule");
			fields.add("is_snmp");
			fields.add("node_groups_id");
			fields.add("process_search_keycode");
			
			String sql = "select dsi.id,dsi.check_type_id,dsi.node_ips_id,dsi.check_gap,dsi.check_out_time,dsi.check_max_times,check_way,dsi.process_Iden,dsi.process_file,dsi.process_path,cti.check_type_name,cti.is_snmp,dsi.detection_set_state, "
				+ "to_char(dsi.plan_check_time,'" + Constants.DB_DATE_FORMAT + "') plan_check_time, "
				+ "dsi.is_control_start,dsi.upload_gap,dsi.control_start_time,is_schedule,dsi.node_groups_id,dsi.process_search_keycode "
				+ "from detection_set_info dsi "
				+ "left join check_type_info cti on cti.id = dsi.check_type_id " 
				+ "where 1=1";
			if(setInfoState != null ){
				if(!sql.trim().endsWith("where")){
					sql += " and ";
				}
				sql += "  dsi.DETECTION_SET_STATE ='"+setInfoState+"'";
			}
			if(checkWay != null ){
				sql += " and dsi.CHECK_WAY ='"+checkWay+"'";
			}
			sql += " and lower(cti.check_type_name) <>lower('"+Constants.ALARM_SNMP_TRAP_STR+"')";
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			if (mapList != null && mapList.size() > 0) {
				for (Map<String, String> map : mapList) {
					SetInfo setInfo = new SetInfo();
					setInfo.setId(StringUtils.isEmpty(map.get("id"))?null:Long.valueOf(map.get("id")));
					setInfo.setCheckTypeId(StringUtils.isEmpty(map.get("check_type_id"))?null:Long.valueOf(map.get("check_type_id")));
					setInfo.setCheckGap(StringUtils.isEmpty(map.get("check_gap"))?null:Long.valueOf(map.get("check_gap")));
					setInfo.setCheckOutTime(
							StringUtils.isEmpty(map.get("check_out_time"))?null:Long.valueOf(map.get("check_out_time")));
					setInfo.setCheckMaxTimes(
							StringUtils.isEmpty(map.get("check_max_times"))?null:Long.valueOf(map.get("check_max_times")));
					setInfo.setProcessIden(map.get("process_Iden"));
					setInfo.setProcessFile(map.get("process_file"));
					setInfo.setProcessPath(map.get("process_path"));
					setInfo.setCheckWay(map.get("check_way"));
					setInfo.setCheckState(map.get("detection_set_state"));
					setInfo.setCheckTypeName(map.get("check_type_name"));
					setInfo.setIsControlStart(map.get("is_control_start"));
					setInfo.setUploadGap(
							StringUtils.isEmpty(map.get("upload_gap"))?null:Long.valueOf(map.get("upload_gap"))
							);
					if (!StringUtils.isEmpty(map.get("plan_check_time"))) {
						setInfo.setPlanCheckTime(format.parse(map.get("plan_check_time")).getTime());
					}
					
					if (!StringUtils.isEmpty(map.get("control_start_time"))) {
						setInfo.setControlStartTime(format.parse(map.get("control_start_time")).getTime());
					}
					setInfo.setIsSchedule(StringUtils.trim(map.get("is_schedule")));
					setInfo.setIsSNMP(StringUtils.isBlank(map.get("is_snmp"))?null:Long.valueOf(StringUtils.trim(map.get("is_snmp"))));
					setInfo.setNodeIpsId(StringUtils.trim(map.get("node_ips_id")));
					setInfo.setNodeGroupsId(StringUtils.trim(map.get("node_groups_id")));
					setInfo.setProcessSearchKeyCode(StringUtils.trim(map.get("process_search_keycode")));
//					setInfo.setNodeIp(map.get("node_ip"));
//					setInfo.setGroupId(StringUtils.isEmpty(map.get("group_id"))?null:Long.valueOf(map.get("group_id")));
					setInfoList.add(setInfo);
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return setInfoList;
	}
	/**
	 * 获取指定SetInfo ID的告警信息集合
	 * @time Oct 12, 2011-10:46:18 AM
	 * @param setInfoId		SetInfo ID
	 * @return
	 */
	public List<AlarmInfo> getAlarmInfoListBySetInfoId(Long setInfoId) {
		List<AlarmInfo> alarmList = new ArrayList<AlarmInfo>();
		ArrayList<String> fields = new ArrayList<String>();
		ArrayList<Map<String, String>> mapList = null;
		try {
			// 告警信息查询
			fields.add("id");
			fields.add("detection_set_info_id");
			fields.add("check_type_name");
			fields.add("process_iden");
			fields.add("metadata_id");
			fields.add("show_num");
			fields.add("filed_comments");
			fields.add("police_state");
			fields.add("police_value");
			fields.add("police_unit");
			fields.add("police_symbols");
			fields.add("police_level");
			fields.add("marker");
			fields.add("MARKER_FILED_ID");
			mapList = dao
					.dbSelect(
							"select dpr.id,dpr.detection_set_info_id,cti.check_type_name,dsi.process_iden,dpr.metadata_id,md.show_num,md.filed_comments,dpr.police_state,dpr.police_value,dpr.police_unit,dpr.police_symbols,dpr.police_level,dpr.marker,dpr.MARKER_FILED_ID  "
									+ "from data_police_relation dpr "
									+ "left join metadata md on md.id = dpr.metadata_id "
									+ "left join detection_set_info dsi on dsi.id = dpr.detection_set_info_id "
									+ "left join check_type_info cti on cti.id = dsi.check_type_id "
									+ "where dpr.detection_set_info_id = '"
									+ setInfoId
									+ "' "
									+ "and dpr.police_state=0 "
									+ "order by md.show_num, DPR.POLICE_LEVEL ASC",
							fields);
			if (mapList != null && mapList.size() > 0) {
				Map<Integer,Integer> metadataIdShownumMap= selectAllMetadata();
				for (Map<String, String> map : mapList) {
					AlarmInfo info = new AlarmInfo();
					info.setId(StringUtils.isEmpty(map.get("id")) ? null : Long
							.valueOf(map.get("id")));
					info.setSetInfoId(StringUtils.isEmpty(map
							.get("detection_set_info_id")) ? null : Long
							.valueOf(map.get("detection_set_info_id")));
					info.setCheckType(map.get("check_type_name"));
					info.setProcessIden(map.get("process_iden"));
					info.setMetadataId(StringUtils.isEmpty(map
							.get("metadata_id")) ? null : Long.valueOf(map
							.get("metadata_id")));
					info
							.setShowNum(StringUtils
									.isEmpty(map.get("show_num")) ? null
									: Integer.valueOf(map.get("show_num")));
					info.setPoliceState(map.get("police_state"));
					info.setPoliceValue(map.get("police_value"));
					info.setPoliceUnit(map.get("police_unit"));
					info.setPoliceSysmbols(map.get("police_symbols"));
					info.setPoliceLevel(Integer
							.valueOf(map.get("police_level")));
					info.setFiledCommonts(map.get("filed_comments"));
					
					info.setMarker(map.get("marker"));
					info.setMarkerFiledId(StringUtils.isEmpty(map.get("MARKER_FILED_ID"))?null:Integer.valueOf(map.get("MARKER_FILED_ID")));
					info.setMarkerFiledShowNum(metadataIdShownumMap.get(StringUtils.isEmpty(map.get("MARKER_FILED_ID"))?null:Integer.valueOf(map.get("MARKER_FILED_ID"))));
					
					alarmList.add(info);
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		} finally {
			dao.clearConn();
		}
		return alarmList;
	}
	
	public ServerTable getNMSServerParams(String ip) throws Exception{
		ServerTable serverTable = null;
		try {
			//查询server 信息
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("id");
			fields.add("server_name");
			fields.add("server_state");
			fields.add("server_ip");
			fields.add("server_ipn");
			ArrayList<Map<String, String>> mapsList = dao.dbSelect("select st.id,st.server_name,st.server_state, st.server_ip,st.server_ipn from server_table st where st.server_state=0 order by st.id", fields);
//			pl(""+mapsList.size());
			if(mapsList != null && mapsList.size() > 0){
				int index = 1;
				for(Map<String,String> map :mapsList){
					String sip = map.get("server_ip");
					if(ip.equalsIgnoreCase(sip)){
						serverTable = new ServerTable();
						serverTable.setId(StringUtils.isEmpty(map.get(fields.get(0))) ? null :  Long.parseLong(map.get(fields.get(0))));
						serverTable.setServerName(StringUtils.isEmpty(map.get(fields.get(1))) ? null : map.get(fields.get(1)));
						serverTable.setServerState(StringUtils.isEmpty(map.get(fields.get(2))) ? null : Long.parseLong(map.get(fields.get(2))));
						serverTable.setServerIp(StringUtils.isEmpty(map.get(fields.get(3))) ? null : map.get(fields.get(3)));
						serverTable.setServerIpn(StringUtils.isEmpty(map.get(fields.get(4))) ? null :  Long.parseLong(map.get(fields.get(4))));
						serverTable.setIndex(index);
						serverTable.setConut(mapsList.size());
						break;
					}
					index ++;
				}
				
			}else{
				throw new Exception("IP为 "+ip+" 的DataController信息 数据库中不存在，请检查网络设置或进行人工DataController配置");
			}
			
			//查询server 的管理IP段信息
			if(serverTable != null && serverTable.getId() != null){
				serverTable.setIpSegList(new LinkedList<ServerIpSegment>());
				fields.clear();
				fields.add("start_ip");
				fields.add("start_ipn");
				fields.add("end_ip");
				fields.add("end_ipn");
				mapsList = dao.dbSelect("select sis.start_ip,sis.start_ipn,sis.end_ip,sis.end_ipn from server_ip_segment sis where sis.server_id='" + serverTable.getId().longValue() + "'", fields);
//				pl(""+mapsList.size());
				if(mapsList!=null && mapsList.size()>0){
					for(Map<String, String> map : mapsList){
						ServerIpSegment segment = new ServerIpSegment();
						segment.setStartIp(StringUtils.isEmpty(map.get(fields.get(0))) ? null : map.get(fields.get(0)));
						segment.setStartIpn(StringUtils.isEmpty(map.get(fields.get(1))) ? null :  Long.parseLong(map.get(fields.get(1))));
						segment.setEndIp(StringUtils.isEmpty(map.get(fields.get(2))) ? null : map.get(fields.get(2)));
						segment.setEndIpn(StringUtils.isEmpty(map.get(fields.get(3))) ? null :  Long.parseLong(map.get(fields.get(3))));
						serverTable.getIpSegList().add(segment);
					}
				}else{
					throw new Exception("IP为 "+ip+" 的DataController的IP段信息 数据库中不存在 请进行人工配置");
				}
			}else{
				throw new Exception("IP为 "+ip+" 的DataController信息 查询异常 无法查询出ID");
			}
//		} catch (Exception e) {
//			logger.error("由参数："+ ip+" 获取 DataController 参数失败",e);
		}finally{
			dao.clearConn();
		}
		return serverTable;
	}
	
	/**
	 * 获取指定SetInfo ID的所涉及到的节点IP集合
	 * @time Oct 12, 2011-10:46:49 AM
	 * @param checkTypeId		checkTypeinfo ID
	 * @return
	 */
	public String getCheckTypeNameById(Long checkTypeId) {
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("check_type_name");
		String checkTypeName = null;
		String searchSql = "select t.check_type_name from check_type_info t where t.id = '"+checkTypeId+"'";
		ArrayList<Map<String, String>> mapList = null;
		try {
				mapList = dao.dbSelect(searchSql,fields);
				if (mapList != null && mapList.size() > 0) {
					for (Map<String, String> map : mapList) {
						checkTypeName = map.get("check_type_name");
					}
				}
		} catch (Exception e) {
			logger.error("By parameter："+ checkTypeId+" to gain monitoring class name failure",e);
		}finally{
			dao.clearConn();
		}
		return checkTypeName;
	}
	/**
	 * 根据节点ID获取节点信息
	 * @time Dec 23, 2011-2:20:22 PM
	 * @return
	 */
	public NodeModel getNodeInfoById(Long nodeId) {
		NodeModel node = null;
		if(nodeId == null){
			return node;
		}
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_id");
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("node_type");
//			fields.add("node_name");
			fields.add("node_state");
			fields.add("system_id");
			fields.add("node_group_id");

			String sql="select t.node_id,t.node_ip, t.seq_id, t.node_type, t.node_name, t.node_state, t.system_id, t.node_group_id from node_table t where t.node_id = '"+nodeId.longValue()+"' ";
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			if (mapList != null && mapList.size() > 0) {
				node = new NodeModel();
				Map<String, String> map  = mapList.get(0);
				node.setNodeId(nodeId);
				node.setNodeIp(map.get("node_ip"));
//				node.setNodeName(map.get("node_name"));
				node.setSeqId(StringUtils.isEmpty(map.get("seq_id"))?null:Long.valueOf(map.get("seq_id")));
				node.setNodeType(StringUtils.isEmpty(map.get("node_type"))?null:Long.valueOf(map.get("node_type")));
				node.setNodeState(StringUtils.isEmpty(map.get("node_state"))?null:Long.valueOf(map.get("node_state")));
				node.setSystemId(StringUtils.isEmpty(map.get("system_id"))?null:Long.valueOf(map.get("system_id")));
				node.setGroupId(StringUtils.isEmpty(map.get("node_group_id"))?null:Long.valueOf(map.get("node_group_id")));
			}
		} catch (Exception e) {
			logger.error("From parameter："+ nodeId +" to get node information failure",e);
		}finally{
			dao.clearConn();
		}
		return node;
	}
	
	/**
	 * 根据节点ID获取节点信息
	 * @time Dec 23, 2011-2:20:22 PM
	 * @return
	 */
	public List<NodeModel> getNodeInfoByGroupId(Long groupId) {
		List<NodeModel> nmList = null;
		if(groupId == null){
			return nmList;
		}
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_id");
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("node_type");
			fields.add("node_name");
			fields.add("node_state");
			fields.add("system_id");
			fields.add("node_group_id");
			
			
			//@2018年4月26日15:57:27 适配mysql 数据库
			String startWithConnectBy = dao.startWithConnectBy("select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 ", " nt.group_id in ('"+groupId.longValue()+"') ", "group_id", "parent_group_id");
//			String sql="select t.node_id,t.node_ip, t.seq_id, t.node_type, t.node_name, t.node_state, t.system_id, t.node_group_id " +
//					" from node_table t where t.node_group_id in ( " +
//					"          select nt.group_id " +
//					"          from NODEGROUP_TABLE nt " +
//					"          where nt.leaf_group = 1 start with nt.group_id in ('"+groupId.longValue()+"') connect by prior  nt.group_id = nt.parent_group_id ) and t.node_state='0' "+" "+getIpnSelect();
			String sql="select t.node_id,t.node_ip, t.seq_id, t.node_type, t.node_name, t.node_state, t.system_id, t.node_group_id " +
					" from node_table t where t.node_group_id in ("+startWithConnectBy+") and t.node_state='0' "+" "+getIpnSelect();
			nmList = new ArrayList<NodeModel>();
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				NodeModel node = new NodeModel();
				node.setNodeId(StringUtils.isEmpty(map.get("node_id"))?null:Long.valueOf(map.get("node_id")));
				node.setNodeIp(map.get("node_ip"));
//				node.setNodeName(map.get("node_name"));
				node.setSeqId(StringUtils.isEmpty(map.get("seq_id"))?null:Long.valueOf(map.get("seq_id")));
				node.setNodeType(StringUtils.isEmpty(map.get("node_type"))?null:Long.valueOf(map.get("node_type")));
				node.setNodeState(StringUtils.isEmpty(map.get("node_state"))?null:Long.valueOf(map.get("node_state")));
				node.setSystemId(StringUtils.isEmpty(map.get("system_id"))?null:Long.valueOf(map.get("system_id")));
				node.setGroupId(StringUtils.isEmpty(map.get("node_group_id"))?null:Long.valueOf(map.get("node_group_id")));
				nmList.add(node);
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return nmList;
	}
	public List<NodeModel> getAllEffectiveNodeInfo() {
		List<NodeModel> nmList = null;
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
//			fields.add("node_id");
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("node_type");
//			fields.add("node_name");
//			fields.add("node_state");
//			fields.add("system_id");
//			fields.add("node_group_id");
			
			
			String sql="select distinct t.node_ip, t.seq_id, t.node_type from node_table t left join nodegroup_table ngt on ngt.group_id = t.node_group_id where t.node_state='0' and ngt.is_valid ='1' "+" "+getIpnSelect();
			nmList = new ArrayList<NodeModel>();
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				NodeModel node = new NodeModel();
//				node.setNodeId(StringUtils.isEmpty(map.get("node_id"))?null:Long.valueOf(map.get("node_id")));
				node.setNodeIp(map.get("node_ip"));
//				node.setNodeName(map.get("node_name"));
				node.setSeqId(StringUtils.isEmpty(map.get("seq_id"))?null:Long.valueOf(map.get("seq_id")));
				node.setNodeType(StringUtils.isEmpty(map.get("node_type"))?null:Long.valueOf(map.get("node_type")));
//				node.setNodeState(StringUtils.isEmpty(map.get("node_state"))?null:Long.valueOf(map.get("node_state")));
//				node.setSystemId(StringUtils.isEmpty(map.get("system_id"))?null:Long.valueOf(map.get("system_id")));
//				node.setGroupId(StringUtils.isEmpty(map.get("node_group_id"))?null:Long.valueOf(map.get("node_group_id")));
				nmList.add(node);
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return nmList;
	}
	
	public List<String> getAllComputerIp() {
		List<String> nmList = null;
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_ip");			
			
			String sql="select distinct t.node_ip from node_table t left join nodegroup_table ngt on ngt.group_id = t.node_group_id where t.node_state='0' and ngt.is_valid ='1' and t.node_type='0' "+" "+getIpnSelect();
			nmList = new ArrayList<String>();
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				nmList.add(map.get("node_ip"));
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return nmList;
	}
	
	/**
	 * 获取所有detection_info_new 表中当前dc的监测数据
	 * @author fang
	 * 2016年2月26日 10:55:59
	 * @return
	 */
	public Map<String,Map<String,Object[]>> getAllDetectionInfoNew(){
		//存放结果
		Map<String,Map<String,Object[]>> result = null;
		try {
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("ID");
			fields.add("DETECTION_SET_INFO_ID");
			fields.add("CHECK_WAY");
			fields.add("DETECTION_STATE_INFO");
			fields.add("PERFORMACE_DATA");
			fields.add("CURRENT_TIMES");
			fields.add("START_TIME");
			fields.add("WAIT_TIME");
			fields.add("DELAY_TIME");
			fields.add("NEXT_CHECK_TIME");
			fields.add("OFF_LINE");
			fields.add("POLICE_LEVEL");
			fields.add("DATA_CHECK_TIME");
			fields.add("DATA_ARRIVE_TIME");
			fields.add("DETECTIONED_STATE");
			fields.add("NODE_IP");
			fields.add("STATUS_CHANGE_TIME");
			fields.add("DATA_CHECK_TIME_DIGITAL");
			fields.add("DATA_ARRIVE_TIME_DIGITAL");
			fields.add("SEQ_ID");
			fields.add("DETECTION_INFO_ID");
			fields.add("VALID");
			fields.add("POLICE_EMERGENT");

			//查询dc监控下的节点seq_id
			String querySeqidSql="select distinct t.seq_id from node_table t left join nodegroup_table ngt on ngt.group_id = t.node_group_id where t.node_state='0' and ngt.is_valid ='1' and t.node_type='0' "+" "+getIpnSelect();
			//查询detection_info_new数据
			String sql = "select din.ID,din.DETECTION_SET_INFO_ID,din.CHECK_WAY,din.DETECTION_STATE_INFO,din.PERFORMACE_DATA,din.CURRENT_TIMES,din.START_TIME,din.WAIT_TIME,din.DELAY_TIME,din.NEXT_CHECK_TIME,din.OFF_LINE,din.POLICE_LEVEL,din.DATA_CHECK_TIME,din.DATA_ARRIVE_TIME,din.DETECTIONED_STATE,din.NODE_IP,din.STATUS_CHANGE_TIME,din.DATA_CHECK_TIME_DIGITAL,din.DATA_ARRIVE_TIME_DIGITAL,din.SEQ_ID,din.DETECTION_INFO_ID,din.VALID,din.POLICE_EMERGENT" +
					" from detection_info_new din left join ("+querySeqidSql+") s on din.seq_id = s.seq_id";
		
			ArrayList<Map<String, String>> mapList = dao.dbSelectByFetchSize(sql,fields);
			result = new HashMap<String, Map<String,Object[]>>();
			//整理查询数据
			if(mapList != null && mapList.size() > 0){
				String detecSetInfoId = null;
				String seqId = null;
				for(Map<String,String> temp : mapList){
					//监测设置id
					detecSetInfoId  = temp.get("DETECTION_SET_INFO_ID");
					//监测节点id
					seqId = temp.get("SEQ_ID");
					Object[] obj = new Object[33];
					obj[DetectInfo.SETINFOID] = (detecSetInfoId);
					obj[DetectInfo.SEQID] = (seqId);
					obj[DetectInfo.STATE] = (temp.get("DETECTIONED_STATE") == null ? null : Integer.parseInt(temp.get("DETECTIONED_STATE")));
					obj[DetectInfo.CHECKTIME] = (temp.get("DATA_CHECK_TIME_DIGITAL") == null ? null :Long.parseLong(temp.get("DATA_CHECK_TIME_DIGITAL")));
					obj[DetectInfo.PLEVEL] = (temp.get("POLICE_LEVEL") == null ? -1 : Integer.parseInt(temp.get("POLICE_LEVEL")));
					obj[DetectInfo.URGENTLEVEL] = (temp.get("POLICE_EMERGENT") == null ? -1 : Integer.parseInt(temp.get("POLICE_EMERGENT")));
					obj[DetectInfo.DETECTIONINFOID] = (temp.get("DETECTION_INFO_ID"));
					obj[DetectInfo.STATUSCHANGTIME] = (temp.get("STATUS_CHANGE_TIME")== null ? null : format.parse(temp.get("STATUS_CHANGE_TIME")).getTime());
					obj[DetectInfo.ARRIVETIME] = (temp.get("DATA_ARRIVE_TIME_DIGITAL") == null ? null : Long.parseLong(temp.get("DATA_ARRIVE_TIME_DIGITAL")));
					obj[DetectInfo.DELAYTIME] = (temp.get("DELAY_TIME") == null ? null : Integer.parseInt(temp.get("DELAY_TIME")));
					obj[DetectInfo.NEXTCHECKTIME] = (temp.get("NEXT_CHECK_TIME") == null ? null : format.parse(temp.get("NEXT_CHECK_TIME")).getTime());
					obj[DetectInfo.STARTTIME] = (temp.get("START_TIME") == null ? null :format.parse(temp.get("START_TIME")).getTime());
					obj[DetectInfo.DSINFO] = (temp.get("DETECTION_STATE_INFO"));
					obj[DetectInfo.PDATA] = (temp.get("PERFORMACE_DATA"));
					obj[DetectInfo.CURRENTTIMES] = (temp.get("CURRENT_TIMES") == null ? -1 : Integer.parseInt(temp.get("CURRENT_TIMES")));

					
					if(result.get(detecSetInfoId) == null){//首次放入
						Map<String,Object[]> seqIdMap = new HashMap<String,Object[]>();
						seqIdMap.put(seqId, obj);
						result.put(detecSetInfoId, seqIdMap);
					}else{
						result.get(detecSetInfoId).put(seqId, obj);
					}
					detecSetInfoId = null;
					seqId = null;
				}
			}
			
		}catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		
		return result;
	}
	
	/**
	 * 获取对应监测设置detection_info_new 表中当前dc的监测数据	
	 */
	public Map<String,Object[]> getDetectionInfoNewBySet(String setId){
		if(StringUtils.isBlank(setId)){
			return null;
		}
		//存放结果
		Map<String,Object[]>  result = null;
		try {
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("ID");
			fields.add("DETECTION_SET_INFO_ID");
			fields.add("CHECK_WAY");
			fields.add("DETECTION_STATE_INFO");
			fields.add("PERFORMACE_DATA");
			fields.add("CURRENT_TIMES");
			fields.add("START_TIME");
			fields.add("WAIT_TIME");
			fields.add("DELAY_TIME");
			fields.add("NEXT_CHECK_TIME");
			fields.add("OFF_LINE");
			fields.add("POLICE_LEVEL");
			fields.add("DATA_CHECK_TIME");
			fields.add("DATA_ARRIVE_TIME");
			fields.add("DETECTIONED_STATE");
			fields.add("NODE_IP");
			fields.add("STATUS_CHANGE_TIME");
			fields.add("DATA_CHECK_TIME_DIGITAL");
			fields.add("DATA_ARRIVE_TIME_DIGITAL");
			fields.add("SEQ_ID");
			fields.add("DETECTION_INFO_ID");
			fields.add("VALID");
			fields.add("POLICE_EMERGENT");
			
			//查询dc监控下的节点seq_id
			String querySeqidSql="select distinct t.seq_id from node_table t left join nodegroup_table ngt on ngt.group_id = t.node_group_id where t.node_state='0' and ngt.is_valid ='1' and t.node_type='0' "+" "+getIpnSelect();
			//查询detection_info_new数据			
			String sql = "select din.ID,din.DETECTION_SET_INFO_ID,din.CHECK_WAY,din.DETECTION_STATE_INFO,din.PERFORMACE_DATA,din.CURRENT_TIMES,din.START_TIME,din.WAIT_TIME,din.DELAY_TIME,din.NEXT_CHECK_TIME,din.OFF_LINE,din.POLICE_LEVEL,din.DATA_CHECK_TIME,din.DATA_ARRIVE_TIME,din.DETECTIONED_STATE,din.NODE_IP,din.STATUS_CHANGE_TIME,din.DATA_CHECK_TIME_DIGITAL,din.DATA_ARRIVE_TIME_DIGITAL,din.SEQ_ID,din.DETECTION_INFO_ID,din.VALID,din.POLICE_EMERGENT" +
			" from detection_info_new din left join ("+querySeqidSql+") s on din.seq_id = s.seq_id " +
			" where DETECTION_SET_INFO_ID="+setId;
			
			ArrayList<Map<String, String>> mapList = dao.dbSelectByFetchSize(sql,fields);
			//整理查询数据
			if(mapList != null && mapList.size() > 0){
				result = new HashMap<String,Object[]>();
				String seqId = null;
				for(Map<String,String> temp : mapList){
					//监测节点id
					seqId = temp.get("SEQ_ID");
					Object[] obj = new Object[33];
					
					obj[DetectInfo.SETINFOID] = (setId);
					obj[DetectInfo.SEQID] = (seqId);
					obj[DetectInfo.STATE] = (temp.get("DETECTIONED_STATE") == null ? null : Integer.parseInt(temp.get("DETECTIONED_STATE")));
					obj[DetectInfo.CHECKTIME] = (temp.get("DATA_CHECK_TIME_DIGITAL") == null ? null :Long.parseLong(temp.get("DATA_CHECK_TIME_DIGITAL")));
					obj[DetectInfo.PLEVEL] = (temp.get("POLICE_LEVEL") == null ? -1 : Integer.parseInt(temp.get("POLICE_LEVEL")));
					obj[DetectInfo.URGENTLEVEL] = (temp.get("POLICE_EMERGENT") == null ? -1 : Integer.parseInt(temp.get("POLICE_EMERGENT")));
					obj[DetectInfo.DETECTIONINFOID] = (temp.get("DETECTION_INFO_ID"));
					obj[DetectInfo.STATUSCHANGTIME] = (temp.get("STATUS_CHANGE_TIME")== null ? null : format.parse(temp.get("STATUS_CHANGE_TIME")).getTime());
					obj[DetectInfo.ARRIVETIME] = (temp.get("DATA_ARRIVE_TIME_DIGITAL") == null ? null : Long.parseLong(temp.get("DATA_ARRIVE_TIME_DIGITAL")));
					obj[DetectInfo.DELAYTIME] = (temp.get("DELAY_TIME") == null ? null : Integer.parseInt(temp.get("DELAY_TIME")));
					obj[DetectInfo.NEXTCHECKTIME] = (temp.get("NEXT_CHECK_TIME") == null ? null : format.parse(temp.get("NEXT_CHECK_TIME")).getTime());
					obj[DetectInfo.STARTTIME] = (temp.get("START_TIME") == null ? null :format.parse(temp.get("START_TIME")).getTime());
					obj[DetectInfo.DSINFO] = (temp.get("DETECTION_STATE_INFO"));
					obj[DetectInfo.PDATA] = (temp.get("PERFORMACE_DATA"));
					obj[DetectInfo.CURRENTTIMES] = (temp.get("CURRENT_TIMES") == null ? -1 : Integer.parseInt(temp.get("CURRENT_TIMES")));

					result.put(seqId,obj);					
				}
			}
			
		}catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		
		return result;
	}
	
	
	/**
	 * 获取对应监测设置detection_info_new 表中当前dc的监测数据	
	 */
	public List<String[]> getDetectionInfoNewBySetTest(String setId){
		if(StringUtils.isBlank(setId)){
			return null;
		}
		//存放结果
		List<String[]> rltList = new ArrayList<String[]>();
		try {
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("ID");
			fields.add("DETECTION_SET_INFO_ID");
			fields.add("CHECK_WAY");
			fields.add("DETECTION_STATE_INFO");
			fields.add("PERFORMACE_DATA");
			fields.add("CURRENT_TIMES");
			fields.add("START_TIME");
			fields.add("WAIT_TIME");
			fields.add("DELAY_TIME");
			fields.add("NEXT_CHECK_TIME");
			fields.add("OFF_LINE");
			fields.add("POLICE_LEVEL");
			fields.add("DATA_CHECK_TIME");
			fields.add("DATA_ARRIVE_TIME");
			fields.add("DETECTIONED_STATE");
			fields.add("NODE_IP");
			fields.add("STATUS_CHANGE_TIME");
			fields.add("DATA_CHECK_TIME_DIGITAL");
			fields.add("DATA_ARRIVE_TIME_DIGITAL");
			fields.add("SEQ_ID");
//			fields.add("DETECTION_INFO_ID");
//			fields.add("VALID");
			fields.add("POLICE_EMERGENT");
			
			//查询dc监控下的节点seq_id
			String querySeqidSql="select distinct t.seq_id from node_table t left join nodegroup_table ngt on ngt.group_id = t.node_group_id where t.node_state='0' and ngt.is_valid ='1' and t.node_type='0' "+" "+getIpnSelect();
			//查询detection_info_new数据
			String sql = "select din.ID,din.DETECTION_SET_INFO_ID,din.CHECK_WAY,din.DETECTION_STATE_INFO,din.PERFORMACE_DATA,din.CURRENT_TIMES,din.START_TIME,din.WAIT_TIME,din.DELAY_TIME,din.NEXT_CHECK_TIME,din.OFF_LINE,din.POLICE_LEVEL,din.DATA_CHECK_TIME,din.DATA_ARRIVE_TIME,din.DETECTIONED_STATE,din.NODE_IP,din.STATUS_CHANGE_TIME,din.DATA_CHECK_TIME_DIGITAL,din.DATA_ARRIVE_TIME_DIGITAL,din.SEQ_ID,din.POLICE_EMERGENT" +
			" from detection_info din left join ("+querySeqidSql+") s on din.seq_id = s.seq_id " +
			" where DETECTION_SET_INFO_ID="+setId +" and rownum<=30000";

//			String sql = "select din.ID,din.DETECTION_SET_INFO_ID,din.CHECK_WAY,din.DETECTION_STATE_INFO,din.PERFORMACE_DATA,din.CURRENT_TIMES,din.START_TIME,din.WAIT_TIME,din.DELAY_TIME,din.NEXT_CHECK_TIME,din.OFF_LINE,din.POLICE_LEVEL,din.DATA_CHECK_TIME,din.DATA_ARRIVE_TIME,din.DETECTIONED_STATE,din.NODE_IP,din.STATUS_CHANGE_TIME,din.DATA_CHECK_TIME_DIGITAL,din.DATA_ARRIVE_TIME_DIGITAL,din.SEQ_ID,din.DETECTION_INFO_ID,din.VALID,din.POLICE_EMERGENT" +
//			" from detection_info_new din left join ("+querySeqidSql+") s on din.seq_id = s.seq_id " +
//			" where DETECTION_SET_INFO_ID="+setId;
			
			rltList = dao.dbSelectList(sql, fields);
			//整理查询数据
//			if(mapList != null && mapList.size() > 0){
//				result = new HashMap<String,DetecAllInfo>();
//				String seqId = null;
//				for(Map<String,String> temp : mapList){
//					//监测节点id
//					seqId = temp.get("SEQ_ID");
//					DetecAllInfo info = new DetecAllInfo();
//					info.setSetInfoId(setId);
//					info.setSeqId(seqId);
//					info.setState(temp.get("DETECTIONED_STATE") == null ? null : Integer.parseInt(temp.get("DETECTIONED_STATE")));
//					info.setCheckTime(temp.get("DATA_CHECK_TIME_DIGITAL") == null ? null :Long.parseLong(temp.get("DATA_CHECK_TIME_DIGITAL")));
//					info.setpLevel(temp.get("POLICE_LEVEL") == null ? -1 : Integer.parseInt(temp.get("POLICE_LEVEL")));
//					info.setUrgentLevel(temp.get("POLICE_EMERGENT") == null ? -1 : Integer.parseInt(temp.get("POLICE_EMERGENT")));
//					info.setDetectionInfoId(temp.get("DETECTION_INFO_ID"));
//					info.setStatusChangTime(temp.get("STATUS_CHANGE_TIME")== null ? null : format.parse(temp.get("STATUS_CHANGE_TIME")).getTime());
//					info.setArriveTime(temp.get("DATA_ARRIVE_TIME_DIGITAL") == null ? null : Long.parseLong(temp.get("DATA_ARRIVE_TIME_DIGITAL")));
//					info.setDelayTime(temp.get("DELAY_TIME") == null ? null : Integer.parseInt(temp.get("DELAY_TIME")));
//					info.setNextCheckTime(temp.get("NEXT_CHECK_TIME") == null ? null : format.parse(temp.get("NEXT_CHECK_TIME")).getTime());
//					info.setStartTime(temp.get("START_TIME") == null ? null :format.parse(temp.get("START_TIME")).getTime());
//					info.setDsinfo(temp.get("DETECTION_STATE_INFO"));
//					info.setPdata(temp.get("PERFORMACE_DATA"));
//					info.setCurrentTimes(temp.get("CURRENT_TIMES") == null ? -1 : Integer.parseInt(temp.get("CURRENT_TIMES")));
//					
//					result.put(seqId,info);					
//				}
//			}
			
		}catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		
		return rltList;
	}
	public List<Object[]> getDetectionInfoNewListBySet(String setId,List<String> seqIdList){
		if(StringUtils.isBlank(setId) || seqIdList == null || seqIdList.size() < 1){
			return null;
		}
		//存放结果
		List<Object[]> rltList = new ArrayList<Object[]>();
		String seqIds = StringUtils.join(seqIdList.iterator(), ",");
		seqIdList.clear();//清空seqID信息
		try {
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("ID");
			fields.add("DETECTION_SET_INFO_ID");
			fields.add("CHECK_WAY");
			fields.add("DETECTION_STATE_INFO");
			fields.add("PERFORMACE_DATA");
			fields.add("CURRENT_TIMES");
			fields.add("START_TIME");
			fields.add("WAIT_TIME");
			fields.add("DELAY_TIME");
			fields.add("NEXT_CHECK_TIME");
			fields.add("OFF_LINE");
			fields.add("POLICE_LEVEL");
			fields.add("DATA_CHECK_TIME");
			fields.add("DATA_ARRIVE_TIME");
			fields.add("DETECTIONED_STATE");
			fields.add("NODE_IP");
			fields.add("STATUS_CHANGE_TIME");
			fields.add("DATA_CHECK_TIME_DIGITAL");
			fields.add("DATA_ARRIVE_TIME_DIGITAL");
			fields.add("SEQ_ID");
			fields.add("DETECTION_INFO_ID");
			fields.add("VALID");
			fields.add("POLICE_EMERGENT");
			
			/*//查询dc监控下的节点seq_id
			String querySeqidSql="select distinct t.seq_id from node_table t left join nodegroup_table ngt on ngt.group_id = t.node_group_id where t.node_state='0' and ngt.is_valid ='1' and t.node_type='0' "+" "+getIpnSelect();
			//查询detection_info_new数据			
			String sql = "select din.ID,din.DETECTION_SET_INFO_ID,din.CHECK_WAY,din.DETECTION_STATE_INFO,din.PERFORMACE_DATA,din.CURRENT_TIMES,din.START_TIME,din.WAIT_TIME,din.DELAY_TIME,din.NEXT_CHECK_TIME,din.OFF_LINE,din.POLICE_LEVEL,din.DATA_CHECK_TIME,din.DATA_ARRIVE_TIME,din.DETECTIONED_STATE,din.NODE_IP,din.STATUS_CHANGE_TIME,din.DATA_CHECK_TIME_DIGITAL,din.DATA_ARRIVE_TIME_DIGITAL,din.SEQ_ID,din.DETECTION_INFO_ID,din.VALID,din.POLICE_EMERGENT" +
			" from ("+querySeqidSql+") s left join detection_info_new din   on din.seq_id = s.seq_id " +
			" where DETECTION_SET_INFO_ID="+setId;*/
			StringBuilder sbSql = new StringBuilder();
			sbSql.append("select din.ID,din.DETECTION_SET_INFO_ID,din.CHECK_WAY,din.DETECTION_STATE_INFO,din.PERFORMACE_DATA,din.CURRENT_TIMES,din.START_TIME,din.WAIT_TIME,din.DELAY_TIME,din.NEXT_CHECK_TIME,din.OFF_LINE,din.POLICE_LEVEL,din.DATA_CHECK_TIME,din.DATA_ARRIVE_TIME,din.DETECTIONED_STATE,din.NODE_IP,din.STATUS_CHANGE_TIME,din.DATA_CHECK_TIME_DIGITAL,din.DATA_ARRIVE_TIME_DIGITAL,din.SEQ_ID,din.DETECTION_INFO_ID,din.VALID,din.POLICE_EMERGENT");
			sbSql.append(" from detection_info_new din ");
			sbSql.append(" where DETECTION_SET_INFO_ID = ");
			sbSql.append( setId);
			sbSql.append( " and din.seq_id in ( ");
			sbSql.append(seqIds);
			sbSql.append( " )");
			String sql =sbSql.toString();
//			String sql = "select din.ID,din.DETECTION_SET_INFO_ID,din.CHECK_WAY,din.DETECTION_STATE_INFO,din.PERFORMACE_DATA,din.CURRENT_TIMES,din.START_TIME,din.WAIT_TIME,din.DELAY_TIME,din.NEXT_CHECK_TIME,din.OFF_LINE,din.POLICE_LEVEL,din.DATA_CHECK_TIME,din.DATA_ARRIVE_TIME,din.DETECTIONED_STATE,din.NODE_IP,din.STATUS_CHANGE_TIME,din.DATA_CHECK_TIME_DIGITAL,din.DATA_ARRIVE_TIME_DIGITAL,din.SEQ_ID,din.POLICE_EMERGENT" +
//			" from detection_info din left join ("+querySeqidSql+") s on din.seq_id = s.seq_id " +
//			" where DETECTION_SET_INFO_ID="+setId +" and rownum<=30000";
			logger.debug("查询new表对应监测设置的最新周期数据，进行状态比较："+sql);
			List<String[]> rltArrayList = dao.dbSelectList(sql, fields);
			//整理查询数据
			if(rltArrayList != null && rltArrayList.size() > 0){
				String seqId = null;
				String state = null;
				String checkTime = null;
				String policeLevel = null;
				String policeEmergent = null;
				String detectionInfoId = null;
				String statusChangeTime = null;
				String dataArriveTimeDigital = null;
				String delayTime = null;
				String nextCheckTime = null;
				String startTime = null;
				String detectionStateInfo = null;
				String performaceData = null;
				String currentTimes = null;
				for(String[] temp : rltArrayList){
					//监测节点id
//					seqId = getIndexContent(fields,"SEQ_ID",temp);
//					DetecAllInfo info = new DetecAllInfo();
//					info.setSetInfoId(setId);
//					info.setSeqId(seqId);
//					info.setState(getIndexContent(fields,"DETECTIONED_STATE",temp) == null ? null : Integer.parseInt(getIndexContent(fields,"DETECTIONED_STATE",temp)));
//					info.setCheckTime(getIndexContent(fields,"DATA_CHECK_TIME_DIGITAL",temp) == null ? null :Long.parseLong(temp[getIndex(fields,"DATA_CHECK_TIME_DIGITAL")]));
//					info.setpLevel(getIndexContent(fields,"POLICE_LEVEL",temp) == null ? -1 : Integer.parseInt(temp[getIndex(fields,"POLICE_LEVEL")]));
//					info.setUrgentLevel(getIndexContent(fields,"POLICE_EMERGENT",temp) == null ? -1 : Integer.parseInt(temp[getIndex(fields,"POLICE_EMERGENT")]));
////					info.setDetectionInfoId(temp[getIndex(fields,"DETECTION_INFO_ID")]);
//					info.setStatusChangTime(getIndexContent(fields,"STATUS_CHANGE_TIME",temp)== null ? null : format.parse(temp[getIndex(fields,"STATUS_CHANGE_TIME")]).getTime());
//					info.setArriveTime(getIndexContent(fields,"DATA_ARRIVE_TIME_DIGITAL",temp) == null ? null : Long.parseLong(temp[getIndex(fields,"DATA_ARRIVE_TIME_DIGITAL")]));
//					info.setDelayTime(getIndexContent(fields,"DELAY_TIME",temp) == null ? null : Integer.parseInt(temp[getIndex(fields,"DELAY_TIME")]));
//					info.setNextCheckTime(getIndexContent(fields,"NEXT_CHECK_TIME",temp) == null ? null : format.parse(temp[getIndex(fields,"NEXT_CHECK_TIME")]).getTime());
//					info.setStartTime(getIndexContent(fields,"START_TIME",temp) == null ? null :format.parse(temp[getIndex(fields,"START_TIME")]).getTime());
//					info.setDsinfo(getIndexContent(fields,"DETECTION_STATE_INFO",temp));
//					info.setPdata(getIndexContent(fields,"PERFORMACE_DATA",temp));
//					info.setCurrentTimes(getIndexContent(fields,"CURRENT_TIMES",temp) == null ? -1 : Integer.parseInt(temp[getIndex(fields,"CURRENT_TIMES")]));
					
					seqId = getIndexContent(fields,"SEQ_ID",temp);
					state = getIndexContent(fields,"DETECTIONED_STATE",temp);
					checkTime = getIndexContent(fields,"DATA_CHECK_TIME_DIGITAL",temp);
					policeLevel = getIndexContent(fields,"POLICE_LEVEL",temp);
					policeEmergent = getIndexContent(fields,"POLICE_EMERGENT",temp);
					detectionInfoId = getIndexContent(fields,"DETECTION_INFO_ID",temp);
					statusChangeTime = getIndexContent(fields,"STATUS_CHANGE_TIME",temp);
					dataArriveTimeDigital = getIndexContent(fields,"DATA_ARRIVE_TIME_DIGITAL",temp);
					delayTime = getIndexContent(fields,"DELAY_TIME",temp);
					nextCheckTime = getIndexContent(fields,"NEXT_CHECK_TIME",temp);
					startTime = getIndexContent(fields,"START_TIME",temp);
					detectionStateInfo = getIndexContent(fields,"DETECTION_STATE_INFO",temp);
					performaceData = getIndexContent(fields,"PERFORMACE_DATA",temp);
					currentTimes = getIndexContent(fields,"CURRENT_TIMES",temp);
					Object[] obj = new Object[33];
					
					obj[DetectInfo.SETINFOID] = (setId);
					obj[DetectInfo.SEQID] = (seqId);
					obj[DetectInfo.STATE] = (state == null ? null : Integer.parseInt(state));
					obj[DetectInfo.CHECKTIME] = ( checkTime== null ? null :Long.parseLong(checkTime));
					obj[DetectInfo.PLEVEL] = (policeLevel == null ? -1 : Integer.parseInt(policeLevel));
					obj[DetectInfo.URGENTLEVEL] = (policeEmergent == null ? -1 : Integer.parseInt(policeEmergent));
					obj[DetectInfo.DETECTIONINFOID] = (detectionInfoId);
					obj[DetectInfo.STATUSCHANGTIME] = (statusChangeTime== null ? null : format.parse(statusChangeTime).getTime());
					obj[DetectInfo.ARRIVETIME] = (dataArriveTimeDigital == null ? null : Long.parseLong(dataArriveTimeDigital));
					obj[DetectInfo.DELAYTIME] = (delayTime == null ? null : Integer.parseInt(delayTime));
					obj[DetectInfo.NEXTCHECKTIME] = (nextCheckTime == null ? null : format.parse(nextCheckTime).getTime());
					obj[DetectInfo.STARTTIME] = (startTime == null ? null :format.parse(startTime).getTime());
					obj[DetectInfo.DSINFO] = (detectionStateInfo);
					obj[DetectInfo.PDATA] = (performaceData);
					obj[DetectInfo.CURRENTTIMES] = (currentTimes == null ? -1 : Integer.parseInt(currentTimes));
					
					seqIdList.add(seqId);
					rltList.add(obj);						
				}
			}
			
		}catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
			logger.debug("查询new表对应监测设置的最新周期数据，进行状态比较,new 表共："+rltList.size()+"条");
		}
		
		return rltList;
	}
	
	public String  getIndexContent(List<String> fields,String fieldName,String[] temp){
		String indexContent = null;
		for(int i=0;i<fields.size();i++){
			if(fieldName.equals(fields.get(i))){
				indexContent = temp[i];
				break;
			}
		}
		
		return indexContent;
	}
	
	public Object[]  getIndexObj(List<String> fields,String fieldName,List<Object[]> temp){
		Object[] indexObj = null;
		try
		{
			int fieldsNum = fields.size();
			if(fieldsNum==temp.size()){				
				for(int i=0;i<fieldsNum;i++){
					if(fieldName.equals(fields.get(i))){
						indexObj = temp.get(i);
						break;
					}
				}
			}else {
				logger.error("Finding the corresponding object exception based on the index");
			}
		} catch (Exception e)
		{
			logger.error("", e);
		}
		
		return indexObj;
	}
	/**
	 * 获取当前dc监控下的所有节点网络端口名称
	 * @return
	 */
	public Map<String,List<String>> getAllPortName(){
		//结果
		Map<String,List<String>> result = new HashMap<String, List<String>>();
		try {
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("seqid");
			fields.add("name_flag");
			
			//查询dc监控下的节点seq_id
			String querySeqidSql="select distinct t.seq_id from node_table t left join nodegroup_table ngt on ngt.group_id = t.node_group_id where  t.node_state='0' "+getIpnSelect() + " and ngt.is_valid ='1' and t.node_type='0' ";
			//查询detection_info_new数据
			StringBuffer sql = new StringBuffer();
			sql.append(" select t.seqid, t.name_flag from node_figure_info t ");
			sql.append(" where  (t.port_set_state = 1 or t.port_set_state is null)  ");
			sql.append(" and seqid in (" );
			sql.append(querySeqidSql);
			sql.append(" ) and t.name_flag is not null  and t.is_leaf = 1   ");
		
			ArrayList<Map<String, String>> mapList = dao.dbSelectByFetchSize(sql.toString(),fields);
			//整理查询数据
			if(mapList != null && mapList.size() > 0){
				String nameFlag = null;
				String seqId = null;
				for(Map<String,String> temp : mapList){
					//端口名称
					nameFlag  = temp.get("name_flag");
					//监测节点id
					seqId = temp.get("seqid");
					
					if(result.get(seqId) == null){//首次放入
						List<String> portNameList = new ArrayList<String>();
						portNameList.add(nameFlag);
						result.put(seqId, portNameList);
					}else{
						result.get(seqId).add(nameFlag);
					}
					nameFlag = null;
					seqId = null;
				}
			}
			
		} catch (Exception e) {
			logger.error("Getting node network port name failed",e);
		}finally{
			dao.clearConn();
		}
		return result;
	}
	
	/**
	 * 获取 监测设置对应的联系人，包括：
	 * 1、viewLevel = 1
	 * 2、viewLevel = 2 and 指定联系人
	 * 3、viewLevel = 3 and 指定联系人
	 * 4、viewLevel = 2 and 未指定联系人
	 * 5、viewLevel = 3 and 未指定联系人
	 * 
	 * 不包含:
	 * 1、viewLevel = 4 的情况
	 * @return Map<SetInfoId ,List<eamil_address>>
	 */
	public Map<String,List<String>> getDetecSetEmailListOf123(){
		Map<String,List<String>> result = new HashMap<String, List<String>>();
		StringBuilder sb = new StringBuilder();
		sb.append(" select distinct c.id, xyj1.email  ");
		sb.append(" from xt_yh_jbxx xyj1, ");
		sb.append("    (select dsi.id, ',' || dsi.contact_user_ids || ',' as ids ");
		sb.append("     from detection_set_info dsi ");
		sb.append("    where dsi.contact_user_ids is not null) c ");
		sb.append(" where  c.ids  like ('%,' || xyj1.yhid || ',%') ");
		sb.append(" and xyj1.email  is not null ");
		sb.append("  union  ");
		sb.append(" (select distinct dsi.id,xyj.email ");
		sb.append("   from detection_set_info dsi ");
		sb.append("   left join xt_js_jbxx xjj ");
		sb.append("     on dsi.create_usergroup_id = xjj.jsbh ");
		sb.append("   left join xt_yh_js_index xyji ");
		sb.append("     on xjj.jsbh = xyji.jsbh ");
		sb.append("   left join xt_yh_jbxx xyj ");
		sb.append("     on xyj.yhid = xyji.yhid ");
		sb.append("  where xyj.is_receiveemail = '0' ");
		sb.append("    and xjj.zxbz = 0 ");
		sb.append("    and xjj.type = 1 ");
		sb.append("    and xyj.zxbz = 0 ");
		sb.append("    and dsi.view_level = 2 ");
		sb.append("    and xyj.email is not null ");
		sb.append("    and dsi.create_usergroup_id is not null ");
		sb.append("    and dsi.contact_user_ids is null) ");
		sb.append(" union ");
		sb.append(" ( ");
		sb.append("    select distinct dsi.id,xyj.email from detection_set_info dsi ");
		sb.append("  left join gorup_system_table gst ");
		sb.append("    on gst.system_id = dsi.system_id ");
		sb.append("  left join xt_js_jbxx xjj  ");
		sb.append("  on gst.user_group_id = xjj.jsbh ");
		sb.append(" left join xt_yh_js_index xyji ");
		sb.append(" on xjj.jsbh = xyji.jsbh ");
		sb.append(" left join xt_yh_jbxx xyj ");
		sb.append(" on xyji.yhid = xyj.yhid ");
		sb.append(" where xyj.is_receiveemail = '0' ");
		sb.append("    and xjj.zxbz = 0 ");
		sb.append("    and xjj.type = 1 ");
		sb.append("    and xyj.zxbz = 0 ");
		sb.append("    and dsi.view_level = 3  ");
		sb.append("    and xyj.email is not null ");
		sb.append("    and dsi.contact_user_ids is null ");
		sb.append(" ) ");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("email");
		try {
			List<Map<String, String>> map1 = (List<Map<String, String>>)dao.dbSelect(sb.toString(), fields);
			if(map1 != null && map1.size()>0){
				List<String> tempList = null;
				String email = null;
				String id = null;
				for(Map<String,String> temp : map1){
					id = temp.get("id");
					email = temp.get("email");
					tempList = result.get(id);
					if(tempList == null){//第一次添加
						List<String> emailList = new ArrayList<String>();
						emailList.add(email);
						result.put(id, emailList);
					}else{
						tempList.add(email);
					}
					id = null;
					email = null;
					tempList = null;
				}
			}
		} catch (Exception e) {
			logger.debug("查询邮件列表失败",e);
		}finally{
			dao.clearConn();
		}
		return result;
	}
	
	/**
	 * 获取viewLevel = 4 的邮件地址
	 * @return
	 */
	public Map<String,List<String>> getDetecEmailListOf4(){
		Map<String,List<String>> result = new HashMap<String, List<String>>();
		try {
			//查询dc监控下的节点seq_id
			String querySeqidSql="select distinct t.seq_id from node_table t left join nodegroup_table ngt on ngt.group_id = t.node_group_id where t.node_state='0' and ngt.is_valid ='1' and t.node_type='0' "+" "+getIpnSelect();
			
			StringBuilder sb = new StringBuilder();
			sb.append(" select distinct nt.seq_id ,xyj.email");
			sb.append("   from xt_yh_jbxx xyj ");
			sb.append("   left join xt_yh_js_index xyji ");
			sb.append("     on xyji.yhid = xyj.yhid ");
			sb.append("   left join xt_js_jbxx xjj ");
			sb.append("     on xjj.jsbh = xyji.jsbh ");
			sb.append("   left join gorup_system_table gst ");
			sb.append("     on gst.user_group_id = xjj.jsbh ");
			sb.append("   left join system_table st ");
			sb.append("     on st.system_id = gst.system_id ");
			sb.append("   left join node_table nt ");
			sb.append("     on nt.system_id = gst.system_id ");
			sb.append("   left join nodegroup_table ngt ");
			sb.append("     on ngt.group_id = nt.node_group_id ");
			sb.append("     left join ( "+querySeqidSql+" ) ns ");
			sb.append("     on nt.seq_id = ns.seq_id ");
			sb.append("  where xyj.is_receiveemail = '0' ");
			sb.append("    and nt.node_state = 0 ");
			sb.append("    and ngt.is_valid = 1 ");
			sb.append("    and st.system_state = 0 ");
			sb.append("    and xjj.zxbz = 0 ");
			sb.append("    and xjj.type = 1 ");
			sb.append("    and xyj.zxbz = 0 ");
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("seq_id");
			fields.add("email");
			
			List<Map<String, String>> map1 = (List<Map<String, String>>)dao.dbSelect(sb.toString(), fields);
			if(map1 != null && map1.size()>0){
				List<String> tempList = null;
				String email = null;
				String seqId = null;
				for(Map<String,String> temp : map1){
					seqId = temp.get("seq_id");
					email = temp.get("email");
					tempList = result.get(seqId);
					if(tempList == null){//第一次添加
						List<String> emailList = new ArrayList<String>();
						emailList.add(email);
						result.put(seqId, emailList);
					}else{
						tempList.add(email);
					}
					seqId = null;
					email = null;
					tempList = null;
				}
			}
			
		} catch (Exception e) {
			logger.debug("查询邮件列表失败",e);
		}finally{
			dao.clearConn();
		}
		return result;
	}
	
	
	
	
	//获得 执行完成但无结果 的节点和多个任务id的map
	public Map<String,Map<String,String[]>> getNonRltIpTaskMap(){
		Map<String,Map<String,String[]>> ipTaskMap = new HashMap<String,Map<String,String[]>>();
		try {
			//再次收集结果的间隔时间：5+3*3+2*5+10=34分钟
			int timeStandard = Constants.MISSION_CHECK_NEW_PERIOD//DC新任务检查周期
						            +Constants.MISSION_RELEASE_PERIOD*Constants.MISSION_RELEASE_TIMES//任务下发间隔周期*尝试次数
						            +2*Constants.DATA_COLLECT_PERIOD//2*收集周期
						            +Constants.TASK_RLT_COLLECT_RESERVED_PERIOD;//单位：秒
			//任务类型1的map-测试ok			
			ipTaskMap = addMaps(ipTaskMap,getNonRltIpTaskOneMap(timeStandard));
			
			//任务类型4的map（非周期）		
			ipTaskMap = addMaps(ipTaskMap,getNonRltIpTaskFourNoLoopMap(timeStandard));
			
			//任务类型4的map（周期）	
			ipTaskMap = addMaps(ipTaskMap,getNonRltIpTaskFourLoopMap(timeStandard));
			
			//任务类型6的map
			ipTaskMap = addMaps(ipTaskMap,getNonRltIpTaskSixMap(timeStandard));
			
			logger.info("需要收集结果的任务相关信息");
			Iterator iteAll = ipTaskMap.entrySet().iterator();
			while(iteAll.hasNext()) {
				Entry en = (Entry)iteAll.next();
				String ip = en.getKey().toString();
				Map<String,String[]> allTaskInfo = (Map<String,String[]>)en.getValue();//当前ip上执行成功的任务id
				Iterator iteTackAll = allTaskInfo.entrySet().iterator();
				logger.info("ip="+ip);
				while(iteTackAll.hasNext()) {
					Entry enTask = (Entry)iteTackAll.next();
					String taskId = enTask.getKey().toString();
					String[] tInfo = (String[])enTask.getValue();
					logger.info("taskId="+taskId);
					logger.info("taskOtherInfo="+ArrayUtils.toString(tInfo));
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}		
		
		return ipTaskMap;		
	}
	
	//将两个map合并（将key相同的value合并）
	private Map<String,Map<String,String[]>> addMaps(Map<String,Map<String,String[]>> oldMap,Map<String,Map<String,String[]>> newMap) throws Exception {
		Iterator ite = newMap.entrySet().iterator();
		while(ite.hasNext()) {
			Entry en = (Entry)ite.next();
			String ip = en.getKey().toString();
			Map<String,String[]> taskInfoMaps = (Map<String,String[]>)en.getValue();//当前ip上执行成功的任务信息
			if(oldMap.containsKey(ip)) {
				Map<String,String[]> oldTaskInfoMaps = oldMap.get(ip);				
				oldTaskInfoMaps.putAll(taskInfoMaps);
			}else {
				oldMap.put(ip, taskInfoMaps);
			}
		}
		return oldMap;
	}
	
	//任务类型一：需要重新收集任务结果的ip：taskIds的map
	private Map<String,Map<String,String[]>> getNonRltIpTaskOneMap(int timeStandard) {		
		String task1AllSql = null;
		if(Constants.IS_MYSQL){
			task1AllSql = "select distinct t.mission_id,para.node_groups_id,para.node_ips_id ," +
					"                    1 missionType,t.is_loop,date_format(t.create_time,'%Y-%m-%d %H:%i:%s') startTime,"
							+ "date_format(ifnull(t.end_time,''),'%Y-%m-%d %H:%i:%s') endTime " +
					" from mission_state_table t" +
					"      left join mission_parameter_table1 para" +
					"      on para.mission_id=t.mission_id" +
					" where t.mission_type = 1" +
					" and t.create_time < date_add(now() ,interval -"+timeStandard+ "*24*3600 second)" +" order by t.mission_id desc";//timeStandard是大概估算的，所以不会那么准确
		}else{
			task1AllSql = "select distinct t.mission_id,para.node_groups_id,para.node_ips_id ," +
					"                    1 missionType,t.is_loop,to_char(t.create_time,'" + Constants.DB_DATE_FORMAT + "') startTime,"
							+ "to_char(nvl(t.end_time,''),'" + Constants.DB_DATE_FORMAT + "') endTime " +
					" from mission_state_table t" +
					"      left join mission_parameter_table1 para" +
					"      on para.mission_id=t.mission_id" +
					" where t.mission_type = 1" +
					" and (sysdate-t.create_time)*24*3600>"+timeStandard+" order by t.mission_id desc";//timeStandard是大概估算的，所以不会那么准确
			
		}
		String task1SucSql = "select info.ip,info.mission_id as taskIds" +
			   " from (" +
			   "    select distinct node.node_ip as ip,rlt.mission_id as mission_id" +
			   "    from  mission_result_table1 rlt" +
			   "        left join node_table node" +
			   "        on node.seq_id=rlt.seq_id " +
			   "    where rlt.result  in (1,0,-1)" +
			   "    and rlt.mission_id in( " +
			   "        select distinct t.mission_id " +
			   "        from mission_state_table t    " +
			   "        where t.mission_type = 1" +
//			   "        and (sysdate-t.create_time)*24*3600>" +timeStandard+
			   "        and t.create_time< sysdate- "+timeStandard+"/24/3600 "+
			   "    )" +
			   " )info " ;
		//	   " group by info.ip";
		return getNonRltIpTaskMap(task1AllSql,task1SucSql);		
	}
	
	//任务类型四（非周期）：需要重新收集任务结果的ip：taskIds的map
	private Map<String,Map<String,String[]>> getNonRltIpTaskFourNoLoopMap(int timeStandard) {
		String task4NoLoopAllSql = null;
		if(Constants.IS_MYSQL){//date_format(ifnull(t.end_time,''),'%Y-%m-%d %H:%i:%s')
			task4NoLoopAllSql = "select distinct t.mission_id,para.node_groups_id,para.node_ips_id, " +
			        "                    4 missionType,t.is_loop,to_char(t.create_time,'" + Constants.DB_DATE_FORMAT + "') startTime,"
			        		+ "date_format(ifnull(t.end_time,''),'%Y-%m-%d %H:%i:%s') endTime " +
					" from mission_state_table t" +
					"      left join mission_parameter_table4 para" +
					"      on para.mission_id=t.mission_id" +
					" where t.mission_type = 4" +
					" and t.is_loop!=1" +
					" and t.create_time < date_add(now() ,interval -"+timeStandard+ "*24*3600 second)";
		}else{
			task4NoLoopAllSql = "select distinct t.mission_id,para.node_groups_id,para.node_ips_id, " +
			        "                    4 missionType,t.is_loop,to_char(t.create_time,'" + Constants.DB_DATE_FORMAT + "') startTime,"
			        		+ "to_char(nvl(t.end_time,''),'" + Constants.DB_DATE_FORMAT + "') endTime " +
					" from mission_state_table t" +
					"      left join mission_parameter_table4 para" +
					"      on para.mission_id=t.mission_id" +
					" where t.mission_type = 4" +
					" and t.is_loop!=1" +
					" and (sysdate-t.create_time)*24*3600>"+timeStandard;
		}
		
//		System.out.println(task4NoLoopAllSql);
		String task4NoLoopSucSql = "select info.ip,info.mission_id as taskIds" +
			   " from (" +
			   "    select distinct node.node_ip as ip,rlt.mission_id as mission_id" +
			   "    from  mission_result_table4 rlt" +
			   "        left join node_table node" +
			   "        on node.seq_id=rlt.seq_id " +
			   "    where rlt.result  in (1,0,-1)" +
			   "    and rlt.mission_id in( " +
			   "        select distinct t.mission_id " +
			   "        from mission_state_table t    " +
			   "        where t.mission_type = 4" +
			   "        and t.is_loop!=1" +
//			   "        and (sysdate-t.create_time)*24*3600>" + timeStandard +
			   "        and t.create_time< sysdate- "+timeStandard+"/24/3600 "+
			   
			   "    )" +
			   " )info " ;
			//   " group by info.ip";
//		System.out.println(task4NoLoopSucSql);
		return getNonRltIpTaskMap(task4NoLoopAllSql,task4NoLoopSucSql);
	}
	
	//任务类型四（周期）：需要重新收集任务结果的ip：taskIds的map
	private Map<String,Map<String,String[]>> getNonRltIpTaskFourLoopMap(int timeStandard) {
		String task4LoopAllSql = "select distinct t.mission_id as mission_id,para.node_groups_id,para.node_ips_id," +
		           " 4 missionType,t.is_loop,to_char(loopMis.Start_Time,'" + Constants.DB_DATE_FORMAT + "') startTime,to_char(loopMis.End_Time,'" + Constants.DB_DATE_FORMAT + "') endTime" +
			       " from mission_state_table t" +
			       "    left join mission_parameter_table4 para" +
			       "    on para.mission_id=t.mission_id" +
			       "    left join loopmission_state_table loopMis" +
			       "    on loopMis.Mission_Id=t.mission_id" +
			       " where t.mission_type = 4" +
			       " and t.is_loop=1" +
			       " and loopMis.Mission_State=2" +
//			       " and (sysdate-loopMis.Start_Time)*24*3600>"+timeStandard;
		   		   " and loopMis.Start_Time< sysdate- "+timeStandard+"/24/3600 ";

		String task4LoopSucSql = "select info.ip,info.mission_id as taskIds" +
				   " from (" +
				   "    select distinct node.node_ip as ip,rlt.mission_id as mission_id" +
				   "    from  mission_result_table4 rlt" +
				   "        left join node_table node" +
				   "        on node.seq_id=rlt.seq_id   " +
				   "    where rlt.result  in (1,0,-1)" +
				   "    and rlt.mission_id in(" +
				   "         select distinct t.mission_id as mission_id" +
				   "         from mission_state_table t   " +
				   "              left join loopmission_state_table loopMis" +
				   "              on loopMis.Mission_Id=t.mission_id" +
				   "              where t.mission_type = 4" +
				   "              and t.is_loop=1" +
				   "              and loopMis.Mission_State=2" +
//				   "              and (sysdate-loopMis.Start_Time)*24*3600>" + timeStandard +
				   " and loopMis.Start_Time< sysdate-"+timeStandard+"/24/3600 " +
				   "    )" +
				   " )info " ;
			//	   " group by info.ip";
		return getNonRltIpTaskMap(task4LoopAllSql,task4LoopSucSql);
	}
	
	//任务类型六：需要重新收集任务结果的ip：taskIds的map
	private Map<String,Map<String,String[]>> getNonRltIpTaskSixMap(int timeStandard) {
		String task6AllSql = null;
		String task6SucSql = null;
		if(Constants.IS_MYSQL){
			task6AllSql = "select distinct t.mission_id,para.node_groups_id,para.node_ips_id, " +
					"6 missionType,t.is_loop,"
					+ "date_format(greatest(t.create_time, ifnull(para.start_time, t.create_time)),'%Y-%m-%d %H:%i:%s') startTime,"
							+ "date_format(ifnull(t.end_time,''),'%Y-%m-%d %H:%i:%s') endTime" + 
				" from mission_state_table t" +
				"      left join mission_parameter_table6 para" +
				"      on para.mission_id=t.mission_id" +
				" where t.mission_type = 6" +
				" and greatest(t.create_time,ifnull(para.start_time,t.create_time))>date_add(now() ,interval -"+timeStandard+ "*24*3600 second)";
			task6SucSql = "select info.ip,info.mission_id as taskIds" +
					   " from (" +
					   "    select distinct node.node_ip as ip,rlt.mission_id as mission_id" +
					   "    from  mission_result_table6 rlt" +
					   "        left join node_table node" +
					   "        on node.seq_id=rlt.seq_id " +
					   "    where rlt.result  in (1,0,-1)" +
					   "    and rlt.mission_id in( " +
					   "        select distinct t.mission_id " +
					   "        from mission_state_table t    " +
					   "           left join mission_parameter_table6 para" +
						"          on para.mission_id=t.mission_id" +
					   "        where t.mission_type = 6" +
					  /* "        and (sysdate-greatest(t.create_time,nvl(para.start_time,t.create_time)))*24*3600>" + timeStandard +
					   "    )" +*/
						" and greatest(t.create_time,ifnull(para.start_time,t.create_time))>date_add(now() ,interval -"+timeStandard+ "*24*3600 second))"+
					   " )info " ;
		}else{
			task6AllSql = "select distinct t.mission_id,para.node_groups_id,para.node_ips_id, " +
					"6 missionType,t.is_loop,to_char(greatest(t.create_time, nvl(para.start_time, t.create_time)),'" + Constants.DB_DATE_FORMAT + "') startTime,"
							+ "to_char(nvl(t.end_time,''),'" + Constants.DB_DATE_FORMAT + "') endTime" + 
				" from mission_state_table t" +
				"      left join mission_parameter_table6 para" +
				"      on para.mission_id=t.mission_id" +
				" where t.mission_type = 6" +
				" and (sysdate-greatest(t.create_time,nvl(para.start_time,t.create_time)))*24*3600>"+timeStandard;
			task6SucSql = "select info.ip,info.mission_id as taskIds" +
					   " from (" +
					   "    select distinct node.node_ip as ip,rlt.mission_id as mission_id" +
					   "    from  mission_result_table6 rlt" +
					   "        left join node_table node" +
					   "        on node.seq_id=rlt.seq_id " +
					   "    where rlt.result  in (1,0,-1)" +
					   "    and rlt.mission_id in( " +
					   "        select distinct t.mission_id " +
					   "        from mission_state_table t    " +
					   "           left join mission_parameter_table6 para" +
						"          on para.mission_id=t.mission_id" +
					   "        where t.mission_type = 6" +
					   "        and (sysdate-greatest(t.create_time,nvl(para.start_time,t.create_time)))*24*3600>" + timeStandard +
					   "    )" +
					   " )info " ;
		}
		
		return getNonRltIpTaskMap(task6AllSql,task6SucSql);
	}
	
	//获得 执行完成但无结果 的节点和多个任务id的map:1.1.1.1:,123,234,235,
	private Map<String,Map<String,String[]>> getNonRltIpTaskMap(String taskAllSql,String taskSucSql) {
		Map<String,Map<String,String[]>> ipTaskAllMap = new HashMap<String,Map<String,String[]>>();
		Map<String,String> ipTaskSucMap = new HashMap<String,String>();
		Map<String,Map<String,String[]>> ipTaskFailMap = new HashMap<String,Map<String,String[]>>();
		try {
			ipTaskAllMap = getNonRltIpTaskAllMap(taskAllSql);//ip（当前DC管理的）和每个ip上对应的任务id（按时间算该执行完毕的）
			ipTaskSucMap = getNonRltIpTaskSucMap(taskSucSql);//ip（当前DC管理的）和每个ip上对应的任务id（执行成功的）
			//打印所有的该有结果的任务的相关信息
//			System.out.println("所有的");
//			Iterator iteAll = ipTaskAllMap.entrySet().iterator();
//			while(iteAll.hasNext()) {
//				Entry en = (Entry)iteAll.next();
//				String ip = en.getKey().toString();
//				Map<String,String[]> allTaskInfo = (Map<String,String[]>)en.getValue();//当前ip上执行成功的任务id
//				Iterator iteTackAll = allTaskInfo.entrySet().iterator();
//				System.out.println("ip="+ip);
//				while(iteTackAll.hasNext()) {
//					Entry enTask = (Entry)iteTackAll.next();
//					String taskId = enTask.getKey().toString();
//					String[] tInfo = (String[])enTask.getValue();
//					System.out.println("taskId="+taskId);
//					System.out.println("taskOtherInfo="+ArrayUtils.toString(tInfo));
//				}
//			}
			
			//已有结果的任务
//			System.out.println("成功的");
//			Iterator iteSucc = ipTaskSucMap.entrySet().iterator();
//			while(iteSucc.hasNext()) {
//				Entry en = (Entry)iteSucc.next();
//				String ip = en.getKey().toString();
//				String failTaskIds = en.getValue().toString();//当前ip上执行成功的任务id
//				System.out.println("key="+ip+",value="+failTaskIds);
//			}
			
			Iterator iteSuc = ipTaskSucMap.entrySet().iterator();
			while(iteSuc.hasNext()) {
				Entry en = (Entry)iteSuc.next();
				if(en!=null && en.getKey()!=null) {
					String ip = en.getKey().toString();
					String sucTaskIds = en.getValue().toString();//当前ip上执行成功的任务id
//				System.out.println("成功的：key="+ip+",value="+sucTaskIds);
					Map<String,String[]> taskInfoMaps = ipTaskAllMap.get(en.getKey());//当前ip上应有结果的任务id
					if(taskInfoMaps!=null&&taskInfoMaps.size()>0) {
						String[] sucTaskIdAry = sucTaskIds.split(",");
						for(String sucTaskId:sucTaskIdAry) {//从总任务信息中，去掉有任务结果的信息
							taskInfoMaps.remove(sucTaskId);//总的-执行成功的=失败的
						}			
						if(taskInfoMaps.size()==0) {//如果所有减去成功的只剩下一个逗号，说明，当前ip上的任务都执行成功了
							ipTaskAllMap.remove(ip);
						}
//					else {
//						ipTaskAllMap.put(ip, taskIds);
//					}
					}
				}
			}
			
			ipTaskFailMap = ipTaskAllMap;
			
//			System.out.println("失败的");
//			Iterator iteAllFail = ipTaskFailMap.entrySet().iterator();
//			while(iteAllFail.hasNext()) {
//				Entry en = (Entry)iteAllFail.next();
//				String ip = en.getKey().toString();
//				Map<String,String[]> allTaskInfo = (Map<String,String[]>)en.getValue();//当前ip上执行成功的任务id
//				Iterator iteTackAll = allTaskInfo.entrySet().iterator();
//				System.out.println("ip="+ip);
//				while(iteTackAll.hasNext()) {
//					Entry enTask = (Entry)iteTackAll.next();
//					String taskId = enTask.getKey().toString();
//					String[] tInfo = (String[])enTask.getValue();
//					System.out.println("taskId="+taskId);
//					System.out.println("taskOtherInfo="+ArrayUtils.toString(tInfo));
//				}
//			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}		
		
		return ipTaskFailMap;
	}
	
	//返回当前DC管理的ip和每个ip上对应的任务id（按时间算该执行完毕的）
	private Map<String,Map<String,String[]>> getNonRltIpTaskAllMap(String task1AllSql) {
		Map<String,Map<String,String[]>> ipTaskAllMap = new HashMap<String,Map<String,String[]>>();
		try {
			//任务类型1的map
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("mission_id");	
			fields.add("node_groups_id");	
			fields.add("node_ips_id");	
			fields.add("missionType");	
			fields.add("is_loop");	
			fields.add("startTime");	
			fields.add("endTime");	
			ArrayList<Map<String, String>> mapList = dao.dbSelect(task1AllSql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			List<NodeModel> nmList = this.getAllNodeModel();//node_table获取的当前dc管控的所有节点的node信息
			Map<Long,List<Long>> allGroupIDs = this.getAllGroupIdAndParentGroupID();//获取所有子节点组id对应的父节点组id
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				String node_ips_id = map.get("node_ips_id");
				String taskId = map.get("mission_id");		
				String[] taskInfoTmp = new String[4];
				taskInfoTmp[0] =  map.get("missionType");
				taskInfoTmp[1] = map.get("is_loop");
				taskInfoTmp[2] = map.get("startTime");
				taskInfoTmp[3] = map.get("endTime");
				//如果没有选择节点，则根据节点组id查询所有的节点
				List<NodeModel> nodeList = new ArrayList<NodeModel>();
				if(node_ips_id==null || "".equals(node_ips_id)) {
					String node_groups_id = map.get("node_groups_id");
					if(node_groups_id != null && !"".equals(node_groups_id)) {
						//1、将字符串型nodeGroupid 转换为 long 并去重
						String[] tempIds = node_groups_id.split(",");
						Set<Long> tempLongIds = new HashSet<Long>();
						for(String temp : tempIds){
							try {
								tempLongIds.add(Long.parseLong(temp));
							} catch (Exception e) {
								logger.debug("",e);
							}
						}
						//2、获取所有节点组id
						Set<Long> groupIds = null;
						if(tempLongIds.size() > 0 && allGroupIDs != null && allGroupIDs.size() > 0){
							groupIds = this.getNodeGroupId(tempLongIds, allGroupIDs);
						}
						//3、获取节点
						if(groupIds != null && groupIds.size() > 0){
							nodeList = this.getNodeModelByGroupIds(groupIds, nmList);
						}
					}
				}else {//如果选择了节点，则只根据节点来，不管节点组
					//1、将字符串型nodeid 转换为 long 并去重
					String[] tempIds = node_ips_id.split(",");
					Set<Long> tempLongIds = new HashSet<Long>();
					for(String temp : tempIds){
						try {
							tempLongIds.add(Long.parseLong(temp));
						} catch (Exception e) {
							logger.debug("",e);
						}
					}
					//2、从缓存中查找 指定nodeid的信息
					if(tempLongIds.size() > 0){
						if(nmList != null && nmList.size() > 0){
							for(NodeModel tempModel : nmList){
								if(tempLongIds.contains(tempModel.getNodeId())){
									nodeList.add(tempModel);
								}
							}
						}
					}				
				}
				for(NodeModel node:nodeList) {
					String ip = node.getNodeIp();
					if(ipTaskAllMap.containsKey(ip)) {
						Map<String,String[]> taskInfoMapTmp = ipTaskAllMap.get(ip);
						if(taskInfoMapTmp.get(taskId)==null) {
							taskInfoMapTmp.put(taskId, taskInfoTmp);	
						}							
					}else if(StringUtils.isNotBlank(ip)){
						Map<String,String[]> taskInfoMap = new HashMap<String,String[]>();
						taskInfoMap.put(taskId, taskInfoTmp);
						ipTaskAllMap.put(ip,taskInfoMap);
					}
				}
			}			
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}		
		return ipTaskAllMap;	
	}
	
	
	//返回当前DC管理的ip和每个ip上对应的任务id（执行成功的）
	private Map<String,String> getNonRltIpTaskSucMap(String task1SucSql) {
		Map<String,String> ipTaskSucMap = new HashMap<String,String>();
		try {
			//任务类型1的map
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("ip");	
			fields.add("taskIds");	
			
			ArrayList<Map<String, String>> mapList = dao.dbSelect(task1SucSql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				String ip = map.get("ip");
				String taskId = map.get("taskIds");
				if(StringUtils.isNotBlank(ip)&&StringUtils.isNotBlank(taskId)) {
					if(StringUtils.isBlank(ipTaskSucMap.get(ip))){
						ipTaskSucMap.put(ip, ","+taskId.trim()+",");
					}else{
						String val = ipTaskSucMap.get(ip);
						if(!val.contains(","+taskId+",")){
							val = val + taskId+",";
							ipTaskSucMap.put(ip, val);
						}
					}
				}
			}			
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}		
		
		return ipTaskSucMap;	
	}

	/**
	 * 查询任务下发节点的IPN信息，
	 * 条件1 节点状态有效 值0
	 * 条件2 节点类型为服务器 值0
	 * @time Dec 23, 2011-2:20:22 PM
	 * @param ids 节点组ids [id1,id2..id3]
	 * @return
	 */
//	public List<Long> getNodeIPNForTaskByNodeIds(String ids) {
//		List<Long> nmList = new LinkedList<Long>();
//		if(StringUtils.isBlank(ids)){
//			return nmList;
//		}
//		
//		try {
//			// SetInfo信息查询
//			ArrayList<String> fields = new ArrayList<String>();
//			fields.add("ipn");
//			
//			String sql="select t.ipn from node_table t where t.node_id in ("+(StringUtils.isNotBlank(ids)?ids:0)+") and t.node_state='0' and t.node_type ='0' ";
//
//			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
//			Iterator<Map<String, String>> ite = mapList.iterator();
//			while (ite.hasNext()) {
//				Map<String, String> map = (Map<String, String>) ite.next();
//				if(StringUtils.isNotEmpty(map.get("ipn"))){
//					nmList.add(Long.parseLong(map.get("ipn").trim()));
//				}
//			}
//		} catch (Exception e) {
//			logger.error("",e);
//		}finally{
//			dao.clearConn();
//		}
//		return nmList;
//	}
	
	/**
	 * 查询任务下发节点的IPN信息，
	 * 条件1 节点状态有效 值0
	 * 条件2 节点组状态有效 值1
	 * 条件3 节点类型为服务器 值0
	 * @time Dec 23, 2011-2:20:22 PM
	 * @param gidsStr 节点组ids [gid1,gid2..gid3]
	 * @return
	 */
//	public List<Long> getNodeIPNForTaskByGroupsIds(String gidsStr) {
//		List<Long> nmList = new LinkedList<Long>();
//		if(StringUtils.isBlank(gidsStr)){
//			return nmList;
//		}
//		
//		try {
//			// SetInfo信息查询
//			ArrayList<String> fields = new ArrayList<String>();
//			fields.add("ipn");
//			
//			String sql="select t.ipn from node_table t left join nodegroup_table ngt on t.group_id=ngt.group_id  where t.group_id in ("+(StringUtils.isNotBlank(gidsStr)?gidsStr:0)+") and t.node_state='0' and t.node_type='0' and ngt.is_valid = '1' ";
//			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
//			Iterator<Map<String, String>> ite = mapList.iterator();
//			while (ite.hasNext()) {
//				Map<String, String> map = (Map<String, String>) ite.next();
//				if(StringUtils.isNotEmpty(map.get("ipn"))){
//					nmList.add(Long.parseLong(map.get("ipn").trim()));
//				}
//			}
//		} catch (Exception e) {
//			logger.error("",e);
//		}finally{
//			dao.clearConn();
//		}
//		return nmList;
//	}
	
	/**
	 * 根据节点组ID 获取有效节点信息
	 * @time Dec 23, 2011-2:20:22 PM
	 * @return
	 */
	public List<NodeModel> getNodeInfoByGroupsIdsWithoutManageSegment(String gids) {
		List<NodeModel> nmList = null;
		if(StringUtils.isEmpty(gids)){
			return nmList;
		}
		try {
			String gidsStr = null;
			if(StringUtils.isNotEmpty(gids)){
//				gidsStr = "and t.node_group_id in( select ngt.group_id from NODEGROUP_TABLE ngt where ngt.leaf_group = 1  and ngt.is_valid = '1' start with ngt.group_id in ("+gids+") connect by prior ngt.group_id = ngt.parent_group_id)";
				//@2018年4月26日15:57:27 适配mysql 数据库
				String startWithConnectBy = dao.startWithConnectBy("select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 and ngt.is_valid = '1' ", " nt.group_id in ("+gids+") ", "group_id", "parent_group_id");
				gidsStr = "and t.node_group_id in( "+startWithConnectBy+" )";
			}
			
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_id");
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("node_type");
			fields.add("node_name");
			fields.add("node_state");
			fields.add("system_id");
			fields.add("node_group_id");
			 
			
			String sql="select t.node_id,t.node_ip, t.seq_id, t.node_type, t.node_name, t.node_state, t.system_id, t.node_group_id from node_table t where t.node_state='0' "+(StringUtils.isEmpty(gidsStr)?"":gidsStr);
			nmList = new ArrayList<NodeModel>();
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				NodeModel node = new NodeModel();
				node.setNodeId(StringUtils.isEmpty(map.get("node_id"))?null:Long.valueOf(map.get("node_id")));
				node.setNodeIp(map.get("node_ip"));
//				node.setNodeName(map.get("node_name"));
				node.setSeqId(StringUtils.isEmpty(map.get("seq_id"))?null:Long.valueOf(map.get("seq_id")));
				node.setNodeType(StringUtils.isEmpty(map.get("node_type"))?null:Long.valueOf(map.get("node_type")));
				node.setNodeState(StringUtils.isEmpty(map.get("node_state"))?null:Long.valueOf(map.get("node_state")));
				node.setSystemId(StringUtils.isEmpty(map.get("system_id"))?null:Long.valueOf(map.get("system_id")));
				node.setGroupId(StringUtils.isEmpty(map.get("node_group_id"))?null:Long.valueOf(map.get("node_group_id")));
				nmList.add(node);
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return nmList;
	}
	
	/**
	 * 根据节点ids 获取有效节点信息
	 * @time Dec 23, 2011-2:20:22 PM
	 * @return
	 */
	public List<NodeModel> getNodeModelByNodeIdsWithoutManageSegment(String ids) {
		List<NodeModel> nmList = new LinkedList<NodeModel>();
		if(StringUtils.isBlank(ids)){
			return nmList;
		}
		
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_id");
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("node_type");
			fields.add("node_name");
			fields.add("node_state");
			fields.add("system_id");
			fields.add("node_group_id");
			
			String sql="select t.node_id,t.node_ip, t.seq_id, t.node_type, t.node_name, t.node_state, t.system_id, t.node_group_id from node_table t where t.node_id in ("+(StringUtils.isNotBlank(ids)?ids:0)+") and t.node_state='0' ";

			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				NodeModel node = new NodeModel();
				node.setNodeId(StringUtils.isEmpty(map.get("node_id"))?null:Long.valueOf(map.get("node_id")));
				node.setNodeIp(map.get("node_ip"));
//				node.setNodeName(map.get("node_name"));
				node.setSeqId(StringUtils.isEmpty(map.get("seq_id"))?null:Long.valueOf(map.get("seq_id")));
				node.setNodeType(StringUtils.isEmpty(map.get("node_type"))?null:Long.valueOf(map.get("node_type")));
				node.setNodeState(StringUtils.isEmpty(map.get("node_state"))?null:Long.valueOf(map.get("node_state")));
				node.setSystemId(StringUtils.isEmpty(map.get("system_id"))?null:Long.valueOf(map.get("system_id")));
				node.setGroupId(StringUtils.isEmpty(map.get("node_group_id"))?null:Long.valueOf(map.get("node_group_id")));
				nmList.add(node);
//				break;
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return nmList;
	}
	/**
	 * 根据节点IP 获取节点信息
	 * @time Dec 23, 2011-2:20:22 PM
	 * @return
	 */
	public List<NodeModel> getNodeModelByIds(String ids) {
		List<NodeModel> nmList = new LinkedList<NodeModel>();
		if(StringUtils.isBlank(ids)){
			return nmList;
		}
		
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_id");
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("node_type");
			fields.add("node_name");
			fields.add("node_state");
			fields.add("system_id");
			fields.add("node_group_id");
			
			String sql="select t.node_id,t.node_ip, t.seq_id, t.node_type, t.node_name, t.node_state, t.system_id, t.node_group_id from node_table t where t.node_id in ("+(StringUtils.isNotBlank(ids)?ids:0)+") and t.node_state='0' "+" "+getIpnSelect();

			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				NodeModel node = new NodeModel();
				node.setNodeId(StringUtils.isEmpty(map.get("node_id"))?null:Long.valueOf(map.get("node_id")));
				node.setNodeIp(map.get("node_ip"));
//				node.setNodeName(map.get("node_name"));
				node.setSeqId(StringUtils.isEmpty(map.get("seq_id"))?null:Long.valueOf(map.get("seq_id")));
				node.setNodeType(StringUtils.isEmpty(map.get("node_type"))?null:Long.valueOf(map.get("node_type")));
				node.setNodeState(StringUtils.isEmpty(map.get("node_state"))?null:Long.valueOf(map.get("node_state")));
				node.setSystemId(StringUtils.isEmpty(map.get("system_id"))?null:Long.valueOf(map.get("system_id")));
				node.setGroupId(StringUtils.isEmpty(map.get("node_group_id"))?null:Long.valueOf(map.get("node_group_id")));
				nmList.add(node);
//				break;
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return nmList;
	}
	
	/**
	 * 根据节点id 获取节点信息
	 * @time 2013-1-30 hyx
	 * @return
	 */
	public List<NodeModel> getNodesByIds(String ids) {
		List<NodeModel> nmList = new LinkedList<NodeModel>();
		if(StringUtils.isBlank(ids)){
			return nmList;
		}
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("node_type");			
			
			String sql="select distinct t.node_ip, t.seq_id, t.node_type " +
					" from node_table t " +
					" where t.node_id in ("+(StringUtils.isNotBlank(ids)?ids:0)+") and t.node_state='0' "+" "+getIpnSelect();
			
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				NodeModel node = new NodeModel();
				node.setNodeIp(map.get("node_ip"));
				node.setSeqId(StringUtils.isEmpty(map.get("seq_id"))?null:Long.valueOf(map.get("seq_id")));
				node.setNodeType(StringUtils.isEmpty(map.get("node_type"))?null:Long.valueOf(map.get("node_type")));
				nmList.add(node);
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return nmList;
	}
	
	public Map<String,String> getIpAndNewNmsclientInfo(SetInfo setInfo) {
		Map<String,String> ipAndInfoMap = new HashMap<String,String>();
		if(setInfo==null){
			return ipAndInfoMap;
		}
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_ip");
			fields.add("detection_state_info");
			
			String sql="select nt.node_ip,t.detection_state_info " +
			"  from detection_info_new t left join node_table nt on  nt.seq_id=t.seq_id " +
			" where t.detection_set_info_id="+setInfo.getId()+getIpnSelect();
			
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				ipAndInfoMap.put(map.get("node_ip"),map.get("detection_state_info"));
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return ipAndInfoMap;
	}
	
	
	public Long getNodeTypeByIp(String ip) {
		Long nodeType = null;
		String sql = "select distinct nt.node_type from node_table nt where nt.node_ip = '"+ip+"' ";
		ArrayList<String>fields = new ArrayList<String>();
		fields.add("node_type");
		try {
			ArrayList<Map<String, String>> mapsList = dao.dbSelect(sql, fields);
			if(mapsList!=null && mapsList.size()>0){
				for(Map<String, String> map : mapsList){
					nodeType = StringUtils.isBlank(map.get("node_type"))?null:Long.parseLong(StringUtils.trim(map.get("node_type")));
					break;
				}
			}
		} catch (Exception e) {
			logger.error("By parameter："+ ip+" to get node type failure",e);
		}
		return nodeType;
	}
		
	/**
	 * 获取所有节点信息
	 * @return
	 */
	public List<NodeModel> getAllNodeModel(){
		List<NodeModel> nmList = null;
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_id");
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("node_type");
			fields.add("node_name");
			fields.add("node_state");
			fields.add("system_id");
			fields.add("node_group_id");
			String sql="select t.node_id,t.node_ip, t.seq_id, t.node_type, t.node_name, t.node_state, t.system_id, t.node_group_id from node_table t where t.node_state='0'  "+getIpnSelect();
			nmList = new ArrayList<NodeModel>();
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				NodeModel node = new NodeModel();
				node.setNodeId(StringUtils.isEmpty(map.get("node_id"))?null:Long.valueOf(map.get("node_id")));
				node.setNodeIp(map.get("node_ip"));
				node.setSeqId(StringUtils.isEmpty(map.get("seq_id"))?null:Long.valueOf(map.get("seq_id")));
				node.setNodeType(StringUtils.isEmpty(map.get("node_type"))?null:Long.valueOf(map.get("node_type")));
				node.setNodeState(StringUtils.isEmpty(map.get("node_state"))?null:Long.valueOf(map.get("node_state")));
				node.setSystemId(StringUtils.isEmpty(map.get("system_id"))?null:Long.valueOf(map.get("system_id")));
				node.setGroupId(StringUtils.isEmpty(map.get("node_group_id"))?null:Long.valueOf(map.get("node_group_id")));
				nmList.add(node);
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return nmList;
	}	
	
	/**
	 * 根据节点组id 获取 符合条件的（属于当前dc管理）节点信息
	 * @param groupIds
	 * @return
	 */
	public List<NodeModel> getNodeModelByGroupIds(Set<Long> groupIds,List<NodeModel> nodeModelList){
		List<NodeModel> result = null;
		try {
			result = new ArrayList<NodeModel>();
			Long groupId = null;
			for(NodeModel tempNode : nodeModelList){
				groupId = tempNode.getGroupId();//节点组id
				if(groupIds.contains(groupId)){
					result.add(tempNode);
				}
			}
		} catch (Exception e) {
			logger.debug("",e);
		}
		return result;
	}
	
	
	/**
	 * 查询多个节点组 对应的所有 子节点组
	 * @param groupIds
	 * @param allGroupIDs
	 * @return
	 */
	public Set<Long> getNodeGroupId(Set<Long> groupIds,Map<Long,List<Long>> allGroupIDs){
		Set<Long> result = null;
		try {
			if(allGroupIDs != null && allGroupIDs.size() >0 ){
				result = new HashSet<Long>();
				Set<Long> condition = new HashSet<Long>();//查询条件
				Set<Long> tempResult = new HashSet<Long>();//查询结果
				condition.addAll(groupIds);//初始化查询条件
				result.addAll(groupIds);
				while(condition.size() > 0){
					for(Map.Entry<Long, List<Long>> tempGroupIds : allGroupIDs.entrySet()){
						Long parentGroupId = tempGroupIds.getKey();//父节点组id
						if(condition.contains(parentGroupId)){
							tempResult.addAll(tempGroupIds.getValue());//子节点组ids
						}
					}
					condition.clear();//清空条件
					if(tempResult.size() > 0){//如果有对应的子节点，作为查询条件，准备下一次查询
						result.addAll(tempResult);
						condition.addAll(tempResult);//结果作为下一次查询条件
						tempResult.clear();//清空查询结果
					}
				}
			}
		} catch (Exception e) {
			logger.debug("",e);
		}
		return result;
	}
	
	
	/**
	 * 获取所有group_id及对应的parent_group_id
	 * @return Map<String,List<String>> key为 parent_group_id
	 * 2016年3月21日 11:24:47
	 */
	public Map<Long,List<Long>> getAllGroupIdAndParentGroupID(){
		Map<Long,List<Long>> result = new HashMap<Long, List<Long>>();
		try {
			String sql = "select ngt.group_id, ngt.parent_group_id " +
							"  from NODEGROUP_TABLE ngt " + 
							" where ngt.leaf_group = 1 " + 
							"   and ngt.is_valid = 1 ";
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("group_id");
			fields.add("parent_group_id");
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			String groupId = null;
			String parentGroupId = null;
			List<Long> tempList = null;
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				groupId = map.get("group_id");
				parentGroupId = map.get("parent_group_id");
				if(StringUtils.isNotBlank(groupId) &&StringUtils.isNotBlank(parentGroupId)){
					tempList = result.get(Long.parseLong(parentGroupId));
					if(tempList == null){//第一次添加
						tempList = new ArrayList<Long>();
						tempList.add(Long.parseLong(groupId));
						result.put(Long.parseLong(parentGroupId), tempList);
					}else{
						tempList.add(Long.parseLong(groupId));
					}
				}
				groupId = null;
				parentGroupId = null;
				tempList = null;
			}
			
		} catch (Exception e) {
			logger.debug("获取节点组信息失败",e);
			result = null;
		} finally{
			dao.clearConn();
		}
		return result;
	}

	/**
	 * 根据节点组ID获取节点信息
	 * @time Dec 23, 2011-2:20:22 PM
	 * @return
	 */
	public List<NodeModel> getNodeModelByGroupIds(String gids) {
		List<NodeModel> nmList = null;
		if(StringUtils.isEmpty(gids)){
			return nmList;
		}
		
//		String sql = "select distinct nt.node_ip from node_table nt "+(StringUtils.isEmpty(gidsStr)?"":gidsStr);
		
		try {
			
			String gidsStr = null;
			if(StringUtils.isNotEmpty(gids)){
//				gidsStr = "and t.node_group_id in( select ngt.group_id from NODEGROUP_TABLE ngt where ngt.leaf_group = 1  and ngt.is_valid = '1' start with ngt.group_id in ("+gids+") connect by prior ngt.group_id = ngt.parent_group_id)";
				//@2018年4月26日15:57:27 适配mysql 数据库
				String startWithConnectBy = dao.startWithConnectBy("select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 and ngt.is_valid = '1' ", " nt.group_id in ("+gids+") ", "group_id", "parent_group_id");
				gidsStr = "and t.node_group_id in( "+startWithConnectBy+" )";
			}
			
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_id");
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("node_type");
			fields.add("node_name");
			fields.add("node_state");
			fields.add("system_id");
			fields.add("node_group_id");
			 
			
			String sql="select t.node_id,t.node_ip, t.seq_id, t.node_type, t.node_name, t.node_state, t.system_id, t.node_group_id from node_table t where t.node_state='0' "+(StringUtils.isEmpty(gidsStr)?"":gidsStr)+" "+getIpnSelect();
			nmList = new ArrayList<NodeModel>();
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				NodeModel node = new NodeModel();
				node.setNodeId(StringUtils.isEmpty(map.get("node_id"))?null:Long.valueOf(map.get("node_id")));
				node.setNodeIp(map.get("node_ip"));
//				node.setNodeName(map.get("node_name"));
				node.setSeqId(StringUtils.isEmpty(map.get("seq_id"))?null:Long.valueOf(map.get("seq_id")));
				node.setNodeType(StringUtils.isEmpty(map.get("node_type"))?null:Long.valueOf(map.get("node_type")));
				node.setNodeState(StringUtils.isEmpty(map.get("node_state"))?null:Long.valueOf(map.get("node_state")));
				node.setSystemId(StringUtils.isEmpty(map.get("system_id"))?null:Long.valueOf(map.get("system_id")));
				node.setGroupId(StringUtils.isEmpty(map.get("node_group_id"))?null:Long.valueOf(map.get("node_group_id")));
				nmList.add(node);
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return nmList;
	}
	/**
	 * 根据节点组ID获取节点信息
	 * @time 2013-1-30 hyx
	 * @return
	 */
	public List<NodeModel> getNodesByGroupIds(String gids) {
		List<NodeModel> nmList = null;
		if(StringUtils.isEmpty(gids)){
			return nmList;
		}
		
		try {
			String gidsStr = null;
			if(StringUtils.isNotEmpty(gids)){
//				gidsStr = "and t.node_group_id in( select ngt.group_id from NODEGROUP_TABLE ngt where ngt.leaf_group = 1  and ngt.is_valid = '1' start with ngt.group_id in ("+gids+") connect by prior ngt.group_id = ngt.parent_group_id)";
				//@2018年4月26日15:57:27 适配mysql 数据库
				String startWithConnectBy = dao.startWithConnectBy("select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 and nt.is_valid = '1' ", " nt.group_id in ("+gids+") ", "group_id", "parent_group_id");
				gidsStr = "and t.node_group_id in( "+startWithConnectBy+" )";
			}
			
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("node_type");			
			
			String sql="select distinct t.node_ip, t.seq_id, t.node_type" +
					" from node_table t" +
					" where t.node_state='0' "+(StringUtils.isEmpty(gidsStr)?"":gidsStr)+" "+getIpnSelect();
			nmList = new ArrayList<NodeModel>();
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			Iterator<Map<String, String>> ite = mapList.iterator();
			while (ite.hasNext()) {
				Map<String, String> map = (Map<String, String>) ite.next();
				NodeModel node = new NodeModel();
				node.setNodeIp(map.get("node_ip"));
				node.setSeqId(StringUtils.isEmpty(map.get("seq_id"))?null:Long.valueOf(map.get("seq_id")));
				node.setNodeType(StringUtils.isEmpty(map.get("node_type"))?null:Long.valueOf(map.get("node_type")));
				nmList.add(node);
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return nmList;
	}
	
	public boolean checkUpdateNodeIsPhysicalNode(NodeModel node) {
		if(node==null || node.getNodeId()==null || node.getSeqId()==null){
			return false;
		}
		//--第二步，查询节点状态 有效 唯一的Id或者null （已完成）
		// SetInfo信息查询
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("node_id");
//		fields.add("seq_id");
//		fields.add("node_state");
//		fields.add("system_id");
//		fields.add("node_group_id");
		String sql=" select nt.node_id " +
				  "  from node_table nt " +
				  "  left join ( " +
				                   " select count(nt.node_id) node_count,nt.seq_id " +
				                   " from node_table nt " +
				                   " where nt.seq_id = "+node.getSeqId().longValue()+" and nt.node_state=0 " +
				                   " group by nt.seq_id ) ntc " +
				  " on nt.seq_id =ntc.seq_id  " +
				  " where ntc.node_count=1 and nt.node_group_id="+node.getGroupId().longValue();//一个节点组内不允许有重复的节点
		ArrayList<Map<String, String>> mapList;
		try {
			mapList = dao.dbSelect(sql,fields);
			//--第三步，当第一步节点有效时：比较第一步的节点id和第二步的节点Id是有相等 或者 当第一步节点无效时：null
			//node state 0有效 1无效
			if(new Long(1l).equals(node.getNodeState())){//节点无效
				if (mapList != null && mapList.size() > 0) {	//不为空，是逻辑节点
					return false;
				}else{	//为空，是物理节点
					return true;
				}
			}else{//节点有效
				if (mapList != null && mapList.size() > 0) {	//不为空，是物理节点
					return true;
				}else{	//为空，是逻辑节点
					return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally{
			dao.clearConn();
		}
	}
	/**
	 * 根据节点组ID获取节点组信息
	 * @time Dec 23, 2011-2:20:37 PM
	 * @return
	 */
	public NodegroupModel getNodeGroupInfoById(Long nodeGroupId) {
		NodegroupModel nodeGroup = null;
		if(nodeGroupId == null){
			return nodeGroup;
		}
		try {
			// SetInfo信息查询
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("group_id");
			fields.add("group_name");
			fields.add("group_type");
			fields.add("system_id");
			fields.add("is_valid");
			
			String sql="select t.group_id,t.group_name, t.group_type, t.system_id, t.is_valid from nodegroup_table t where t.group_id = '"+nodeGroupId.longValue()+"' ";
			ArrayList<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			if (mapList != null && mapList.size() > 0) {
				nodeGroup = new NodegroupModel();
				Map<String, String> map  = mapList.get(0);
				nodeGroup.setGroupId(nodeGroupId);
				nodeGroup.setGroupName(map.get("group_name"));
				nodeGroup.setGroupType(StringUtils.isEmpty(map.get("group_type"))?null:Long.valueOf(map.get("group_type")));
				nodeGroup.setIsValid(StringUtils.isEmpty(map.get("is_valid"))?null:Long.valueOf(map.get("is_valid")));
				nodeGroup.setSystemId(StringUtils.isEmpty(map.get("system_id"))?null:Long.valueOf(map.get("system_id")));
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return nodeGroup;
	}
	/**
	 * 获取指定SetInfo ID的所涉及到的节点IP集合
	 * @time Oct 12, 2011-10:46:49 AM
	 * @param setInfoId		SetInfo ID
	 * @return
	 */
//	public List<String> getUpdateNodeIpListBySetInfoId(Long setInfoId) {
//		List<String> nodeList = new ArrayList<String>();
//		SetInfo setInfo = this.getSetInfoById(setInfoId);
//		ArrayList<String> fields = new ArrayList<String>();
//		ArrayList<Map<String, String>> mapList = null;
//		try {
//			if (StringUtils.isNotEmpty(setInfo.getNodeIp())) { // 单节点监测任务变更
//				nodeList.add(setInfo.getNodeIp());
//			} else { // setInfo为缺省设置，查询需要更新监测任务的主机
//				fields.add("node_ip");
//				mapList = dao
//						.dbSelect(
//								"select distinct nt.node_ip from node_table  nt where nt.node_ip not in (select dsi.node_ip from detection_set_info dsi where dsi.check_type_id ='"
//										+ setInfoId
//										+ "' and dsi.node_ip is not null )",
//								fields);
//				if (mapList != null && mapList.size() > 0) {
//					for (Map<String, String> map : mapList) {
//						nodeList.add(map.get("node_ip"));
//					}
//				}
//			}
//		} catch (Exception e) {
//			logger.error("",e);
//		}finally{
//			dao.clearConn();
//		}
//		return nodeList;
//	}
	/**
	 * 获取指定SetInfo ID的所涉及到的节点IP集合
	 * @time Oct 12, 2011-10:46:49 AM
	 * @param setInfoId		SetInfo ID
	 * @return
	 */
//	public List<String> getNodeIpListBySetInfoId(Long setInfoId) {
//		List<String> nodeList = new ArrayList<String>();
//		SetInfo setInfo = this.getSetInfoById(setInfoId);
//		ArrayList<String> fields = new ArrayList<String>();
//		ArrayList<Map<String, String>> mapList = null;
//		try {
//			if (StringUtils.isNotEmpty(setInfo.getNodeIpsId())) { // 单节点监测任务变更
//				nodeList.addAll(getNodeIpListByIds(setInfo.getNodeIpsId()));
//			} else { // setInfo为缺省设置，查询需要更新监测任务的主机
//				nodeList.addAll(getNodeIpListByGroupIds(setInfo.getNodeGroupsId()));
//			}
//		} catch (Exception e) {
//			logger.error("",e);
//		}finally{
//			dao.clearConn();
//		}
//		return nodeList;
//	}
	
	/**
	 * 根据多个node_id 查询ip
	 * @time Jun 15, 2011-4:52:41 PM
	 * @param ids
	 * @return
	 */
//	public List<String> getNodeIpListByIds(String ids){
//		List<String> ips = new LinkedList<String>();
//		ArrayList<String> fields = new ArrayList<String>();
//		fields.add("node_ip");
//		String sql = "select distinct nt.node_ip from node_table  nt where nt.node_id in("+(StringUtils.isEmpty(ids)?0:ids)+") "+" "+getIpnSelect();
//		ArrayList<Map<String, String>> mapList = null;
//		try {
//			mapList = dao.dbSelect(sql,fields);
//			if (mapList != null && mapList.size() > 0) {
//				for (Map<String, String> map : mapList) {
//					ips.add(map.get("node_ip"));
//				}
//			}
//		} catch (Exception e) {
//			logger.error("", e);
//		}
//		return ips;
//	}
	
	/**
	 * 根据多个node_id 查询ip
	 * @time Jun 15, 2011-4:52:41 PM
	 * @param ids
	 * @return
	 */
//	public List<String> getNodeIpListByGroupIds(String gids){
//		List<String> ips = new LinkedList<String>();
//		ArrayList<String> fields = new ArrayList<String>();
//		fields.add("node_ip");
//		String gidsStr = null;
//		if(StringUtils.isNotEmpty(gids)){
//			gidsStr = "and nt.node_group_id in( select ngt.group_id from NODEGROUP_TABLE ngt where ngt.leaf_group = 1 start with ngt.group_id in ("+gids+") connect by prior ngt.group_id = ngt.parent_group_id)";
//		}
//		String sql = "select distinct nt.node_ip from node_table nt where 1=1 "+(StringUtils.isEmpty(gidsStr)?"":gidsStr)+" "+getIpnSelect();
//		ArrayList<Map<String, String>> mapList = null;
//		try {
//			mapList = dao.dbSelect(sql,fields);
//			if (mapList != null && mapList.size() > 0) {
//				for (Map<String, String> map : mapList) {
//					ips.add(map.get("node_ip"));
//				}
//			}
//		} catch (Exception e) {
//			logger.error("", e);
//		}
//		return ips;
//	}
	
	/**
	 * 更新监测设置ID_设置名称映射
	 * @time Sep 20, 2011-9:07:24 AM
	 * @param checkTable	监测类型和表名Map集合
	 * @param typeName		监测类型（为空即为整体更新）
	 */
	public void updateSetInfoName(Map<Long, String> setInfoNameMap,Long siId) {
		String selectSql = "select dsi.id,dsi.process_iden_name from detection_set_info dsi where dsi.detection_set_state =1 and id is not null" ;
		if (siId != null && siId.longValue() != 0) {		//更新指定typeName的表信息
				selectSql += "and dsi.id = "+siId.toString();
		}else{		//整体更新--先清空集合
			setInfoNameMap.clear();
		}
		selectSql += ""  ;
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("process_iden_name");
		try {
			ArrayList<Map<String, String>> datas = dao.dbSelect(selectSql,fields);
			if(datas!=null && datas.size()>0){
				for(Map<String, String> data : datas){
					Common.getSetInfoNameMape().put(Long.parseLong(data.get("id")), data.get("process_iden_name"));
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	
	/**
	 * 更新监测类型表及表名Map集合
	 * @time Sep 20, 2011-9:07:24 AM
	 * @param checkTable	监测类型和表名Map集合
	 * @param typeName		监测类型（为空即为整体更新）
	 */
	public void updateCheckTableInfo(Map<String, TableModel> checkTable,String typeName) {
		String selectSql = "select cti.check_type_name,cti.table_name,cti.is_snmp,cti.oid,cti.check_type_name1 from check_type_info cti where CRETE_STATE =0 " ;
		if (StringUtils.isNotEmpty(typeName)) {		//更新指定typeName的表信息
			if(Constants.DETEC_SNMP_STR.equals(typeName)){
				selectSql += "and nvl(cti.IS_SNMP,2) <> '2' ";
			}else{
				selectSql += "and lower(cti.check_type_name) = lower('"+typeName+"') ";
			}
		}else{		//整体更新--先清空集合
			checkTable.clear();
		}
		selectSql += ""  ;
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("check_type_name");
		fields.add("table_name");
		fields.add("is_snmp");
		fields.add("oid");
		fields.add("check_type_name1");
		try {
			ArrayList<Map<String, String>> datas = dao.dbSelect(selectSql,fields);
			if(datas!=null && datas.size()>0){
				for(Map<String, String> data : datas){
					checkTable.put(data.get("check_type_name"),new TableModel(data.get("table_name"),data.get("oid"),StringUtils.isEmpty(data.get("is_snmp"))?null:Long.parseLong(data.get("is_snmp"))));
					Common.getCheckTypeNameMape().put(data.get("check_type_name"), data.get("check_type_name1"));
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	/**
	 * 更新表字段结构Map 用于监测数据详细数据解析部分
	 * @time Sep 7, 2011-5:39:51 PM
	 * @param tableColumnsMap		集合
	 * @param typeName				类型名称（监测类型与表名一对一可以根据类型名查询）
	 */
	public void updateTableColumnsMap(Map<String, Map<Integer, TableColumnsModel>> tableColumnsMap,String typeName){
		String selectSql = "select cti.check_type_name,md.show_num, md.filed_name,md.filed_comments,md.filed_type,md.oid " +
				"from metadata md " +
				"left join check_type_info cti on cti.id = md.check_type_id " +
				"where md.state = 0 and cti.check_type_name is not null " ;
		if (StringUtils.isNotEmpty(typeName)) {		//清理指定集合的数据
			selectSql +="and lower(cti.check_type_name) = lower('"+typeName+"') " ;
			tableColumnsMap.remove(typeName);
		}else{		//整体更新，清空集合
			tableColumnsMap.clear();
		}
		selectSql += "order by cti.check_type_name,md.show_num asc";
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("check_type_name");
		fields.add("show_num");
		fields.add("filed_name");
		fields.add("filed_comments");
		fields.add("filed_type");
		fields.add("oid");
		try {
			ArrayList<Map<String, String>> datas = dao.dbSelect(selectSql,fields);
			String oldType = "";
			if(datas!=null && datas.size()>0){
				Map<Integer, TableColumnsModel> map = null;
				for(Map<String, String> data : datas){
					if(!oldType.equals(data.get("check_type_name"))){
						map = tableColumnsMap.get(data.get("check_type_name"));
						oldType = data.get("check_type_name")+"";
					}
					if(map==null){
						map = new HashMap<Integer, TableColumnsModel>();
					}
//					System.out.println("--"+data.get("check_type_name")+"  "+data.get("show_num")+"  "+data.get("filed_name")+"  "+data.get("filed_comments"));
					map.put(Integer.parseInt(data.get("show_num")),new TableColumnsModel(data.get("filed_name"),data.get("filed_comments"),data.get("filed_type"),data.get("oid")));
					tableColumnsMap.put(oldType, map);
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	
	protected String getIpnSelect(){
		ServerTable serverTable = Common.getServerTable();
		StringBuffer ipnStr = new StringBuffer();
		if(serverTable!=null && serverTable.getIpSegList()!=null && serverTable.getIpSegList().size()>0){
			for(ServerIpSegment ipSegment : serverTable.getIpSegList()){
				if(ipnStr.length()==0l){		//首
					ipnStr.append("(ipn >= '"+ipSegment.getStartIpn().longValue()+"' and ipn <= '"+ipSegment.getEndIpn().longValue()+"')");
				}else{	
					ipnStr.append("or (ipn >= '"+ipSegment.getStartIpn().longValue()+"' and ipn <= '"+ipSegment.getEndIpn().longValue()+"')");
				}
			}
			ipnStr.insert(0, " and (");
			ipnStr.append(")");
		}
		return ipnStr.toString();
	}
	
	/**
	 * 更新节点列表 用于升级下发和主动监测
	 * @time Sep 20, 2011-9:37:29 AM
	 * @param map
	 */
//	private void updateNodeList(Map<String,String> map,ServerTable serverTable) {
//		ArrayList<String> fields = new ArrayList<String>();
//		fields.add("node_ip");
//		fields.add("is_temp");
//		List<Map<String, String>> list = null;
//		try {
//			StringBuffer ipnStr = new StringBuffer();
//			if(serverTable.getIpSegList().size()>0){
//				for(ServerIpSegment ipSegment : serverTable.getIpSegList()){
//					if(ipnStr.length()==0l){		//首
//						ipnStr.append("(nt.ipn > '"+ipSegment.getStartIpn().longValue()+"' and nt.ipn < '"+ipSegment.getEndIpn().longValue()+"')");
//					}else{	
//						ipnStr.append("or (nt.ipn > '"+ipSegment.getStartIpn().longValue()+"' and nt.ipn < '"+ipSegment.getEndIpn().longValue()+"')");
//					}
//				}
//				ipnStr.append(" and ("+ipnStr+")");
//			}
//			
//			list = dao.dbSelect("select nt.node_ip,nvl(nt.is_temp,1) is_temp from node_table nt " +
//					"where nvl(nt.node_state,0)='0'"+ipnStr, fields);
//			if(list!=null && list.size()>0){	//已存在
//				for(Map<String, String> map0 : list){
//					map.put(map0.get("node_ip"), map0.get("is_temp"));
//				}
//				return;//跳过
//			}
//		} catch (Exception e) {
//			logger.error("",e);
//		}finally{
//			dao.clearConn();
//		}
//	}
	/**
	 * @time Sep 9, 2011-10:25:01 AM
	 * @param setInfoId
	 * @return
	 */
	public void updateAlarmInfo(Map<String,List<AlarmInfo>> alarmMap,Long setId){
	try {
		String selectSql = "select dpr.id,dpr.detection_set_info_id, dpr.metadata_id, dpr.police_state, dpr.police_value, dpr.police_unit, dpr.police_symbols, md.show_num, dpr.police_level,dpr.police_emergent,md.filed_comments,dpr.marker,dpr.MARKER_FILED_ID " +
				"from data_police_relation dpr left join metadata md on md.id = dpr.metadata_id " +
				"left join detection_set_info dsi on dsi.id = dpr.detection_set_info_id " +
				"where dpr.police_state = 0 " +
				"and dsi.detection_set_state = 1 ";
				if(setId!=null){
					selectSql += "and dsi.id =  "+setId;
				}
				selectSql += " order by md.show_num, DPR.POLICE_LEVEL ASC";
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("detection_set_info_id");
		fields.add("metadata_id");
		fields.add("police_state");
		fields.add("police_value");
		fields.add("police_unit");
		fields.add("police_symbols");
		fields.add("show_num");
		fields.add("police_level");
		fields.add("police_emergent");
		fields.add("filed_comments");
		fields.add("marker");
		fields.add("MARKER_FILED_ID");
		List<Map<String, String>> mapList = dao.dbSelect(selectSql,	fields);
		
		//清理缓存中告警信息
		if(setId==null){
			alarmMap.clear();
		}else{
			List<AlarmInfo> policeList =  alarmMap.get(setId.longValue()+"");
			if(policeList!=null){
				policeList.clear();
			}
		}
		
		//填入新告警信息
		if(mapList!=null && mapList.size()>0){
			Map<Integer,Integer> metadataIdShownumMap= selectAllMetadata();
			for(Map<String,String> map : mapList){
				List<AlarmInfo> policeList =  alarmMap.get(map.get("detection_set_info_id"));
				if(policeList==null){
					policeList = new ArrayList<AlarmInfo>();
					alarmMap.put(map.get("detection_set_info_id"), policeList);
				}
				AlarmInfo info = new AlarmInfo();
				info.setId(StringUtils.isEmpty(map.get("id"))?null:Long.valueOf(map.get("id")));
				info.setSetInfoId(StringUtils.isEmpty(map.get("detection_set_info_id"))?null:Long.valueOf(map.get("detection_set_info_id")));
				info.setMetadataId(StringUtils.isEmpty(map.get("metadata_id"))?null:Long.valueOf(map.get("metadata_id")));
				info.setShowNum(StringUtils.isEmpty(map.get("show_num"))?null:Integer.valueOf(map.get("show_num")));
				info.setPoliceLevel(StringUtils.isEmpty(map.get("police_level"))?null:Integer.valueOf(map.get("police_level")));
				info.setPoliceState(map.get("police_state"));
				info.setPoliceValue(map.get("police_value"));
				info.setPoliceUnit(map.get("police_unit"));
				info.setPoliceSysmbols(map.get("police_symbols"));
				info.setPoliceEmergent(StringUtils.isEmpty(map.get("police_emergent"))?null:Integer.valueOf(map.get("police_emergent")));
				info.setFiledCommonts(map.get("filed_comments"));
				
				info.setMarker(map.get("marker"));
				info.setMarkerFiledId(StringUtils.isEmpty(map.get("MARKER_FILED_ID"))?null:Integer.valueOf(map.get("MARKER_FILED_ID")));
				info.setMarkerFiledShowNum(metadataIdShownumMap.get(StringUtils.isEmpty(map.get("MARKER_FILED_ID"))?null:Integer.valueOf(map.get("MARKER_FILED_ID"))));
				
				policeList.add(info);
			}
		}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	/**
	 * 查询某个监测的告警信息
	 * @time Sep 7, 2011-7:13:21 PM
	 * @param tableMap
	 * @param typeName
	 */
	public List<Map<String, String>> getAlarmInfo(String setInfoId,String showNums,String levels){
		String selectSql = "select md.filed_comments,md.show_num,dpr.police_level,dpr.police_symbols,dpr.police_value,dpr.police_unit " +
				"from data_police_relation dpr " +
				"left join metadata md on dpr.metadata_id = md.id " +
				"where md.state = 0 " +
				"and dpr.detection_set_info_id = '"+setInfoId+"' " +
				"and md.show_num in ("+showNums+") " +
				"and dpr.police_level in ("+levels+") " +
				"order by md.show_num,dpr.police_level asc";
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("filed_comments");
		fields.add("show_num");
		fields.add("police_level");
		fields.add("police_symbols");
		fields.add("police_value");
		fields.add("police_unit");
		try {
			return dao.dbSelect(selectSql, fields);
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return null;
	}
	//--------------------------------------------------------------------------------------------
	public List<SetInfo> getDrivingSetInfo(String checktype,Long seqId) {
		if(StringUtils.isEmpty(checktype)){
			return new LinkedList<SetInfo>();
		}
		//获取主动监测设置 ，最后参数 为false
		return selectSetInfoList(null, null,seqId, checktype, null, 1l, null, 0l,false);
	}

	public static void p(Object ss){
		System.out.print(ss==null?null:ss.toString());
	}
	public static void pl(Object ss){
		System.out.println(ss==null?null:ss.toString());
	}
	/**
	 * 获取主动监测设置信息列表
	 * @time Nov 21, 2011-2:56:16 PM
	 * @param checktype
	 * @param setInfoId
	 * @return
	 */
	public List<SetInfo> getDrivingSetInfo(String checktype) {
		List<SetInfo> setList = new LinkedList<SetInfo>();
		if(StringUtils.isEmpty(checktype)){
			return setList;
		}
		//获取主动监测设置 ，最后参数 为false
		return selectSetInfoList(0l,null,null, checktype, null, 1l, null, 0l,false);
	}
	
	/**
	 * 查询DetectionSetInfo 信息 
	 * @time Jan 21, 2013-9:51:18 AM
	 * @param checkWay		监测方式		0主动 1被动
	 * @param setInfoId		监测设置ID
	 * @param seqId			节点物理标示ID
	 * @param checktype		节点类型  
	 * @param groupId		节点组ID
	 * @param groupState	节点组状态	1有效 0无效
	 * @param nodeId		节点ID
	 * @param nodeState		节点状态		0有效 1无效
	 * @param agentFlag		是否是agent获取标示   true 是Agent获取，不是DC下发，不增加DC管理范围ID过滤  false 是DC下发，增加DC管理范围ID过滤
	 * @return
	 */
	public List<SetInfo> selectSetInfoList(Long checkWay ,Long setInfoId ,Long seqId , String checktype ,String groupId ,Long groupState,String nodeId,Long nodeState,boolean agentFlag) {
		List<SetInfo> setInfoList = new LinkedList<SetInfo>();
		//-- 查询执行Ping的节点
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("node_ips_id");
		fields.add("check_type_id");
		fields.add("process_Iden");
		fields.add("process_file");
		fields.add("process_path");
		fields.add("check_gap");
		fields.add("check_out_time");
		fields.add("check_max_times");
		fields.add("plan_check_time");
		fields.add("check_type_name");
		fields.add("detection_set_state");
		fields.add("node_groups_id");
		fields.add("check_way");
		fields.add("is_control_start");
		fields.add("control_start_time");
		fields.add("upload_gap");
		fields.add("VIEW_LEVEL");
		fields.add("IS_SNMP");
		fields.add("is_schedule");
		fields.add("process_search_keycode");
		
		ArrayList<Map<String, String>> pingList = null;
		try {
			String searchSql = this.selectSetInfoSql(checkWay ,setInfoId,seqId,checktype,groupId,groupState,nodeId,nodeState,agentFlag);
			pingList = dao.dbSelect(searchSql, fields);
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		if(pingList!=null && pingList.size()>0){
			try {
				for(Map<String, String> map : pingList){
					SetInfo info = new SetInfo();
					info.setId(StringUtils.isEmpty(map.get("id"))?null:Long.valueOf(map.get("id")));
					info.setCheckTypeId(StringUtils.isEmpty(map.get("check_type_id"))?null:Long.valueOf(map.get("check_type_id")));
					info.setCheckGap(StringUtils.isEmpty(map.get("check_gap"))?null:Long.valueOf(map.get("check_gap")));
					info.setCheckOutTime(StringUtils.isEmpty(map.get("check_out_time"))?null:Long.valueOf(map.get("check_out_time")));
					info.setCheckMaxTimes(StringUtils.isEmpty(map.get("check_max_times"))?null:Long.valueOf(map.get("check_max_times")));
					info.setProcessIden(map.get("process_Iden"));
					info.setProcessFile(map.get("process_file"));
					info.setProcessPath(map.get("process_path"));
					info.setCheckWay(map.get("check_way"));
					info.setCheckState(map.get("detection_set_state"));
					info.setCheckTypeName(map.get("check_type_name"));
					info.setIsControlStart(map.get("is_control_start"));
					info.setUploadGap(StringUtils.isEmpty(map.get("upload_gap"))?null:Long.valueOf(map.get("upload_gap")));
					info.setViewLevel(StringUtils.isEmpty(map.get("VIEW_LEVEL"))?null:Long.valueOf(map.get("VIEW_LEVEL")));
					info.setIsSNMP(StringUtils.isEmpty(map.get("IS_SNMP"))?null:Long.valueOf(map.get("IS_SNMP")));
					if(!StringUtils.isEmpty(map.get("plan_check_time"))){
						info.setPlanCheckTime(format.parse(map.get("plan_check_time")).getTime());
					}
					if(!StringUtils.isEmpty(map.get("control_start_time"))){
						info.setControlStartTime(format.parse(map.get("control_start_time")).getTime());
					}
					info.setIsSchedule(map.get("is_schedule"));
					info.setNodeIpsId(StringUtils.trim(map.get("node_ips_id")));
					info.setNodeGroupsId(StringUtils.trim(map.get("node_groups_id")));
					info.setProcessSearchKeyCode(StringUtils.trim(map.get("process_search_keycode")));
//					info.setGroupId(map.get("group_id"));
//					info.setNodeIp(map.get("node_ip"));
					setInfoList.add(info);
				}
			} catch (ParseException e) {
				logger.error("",e);
			}
		}
		return setInfoList;
	}
//	public String getSetInfoByGroupID(Long checkWay ,Long seqId, String checktype,String groupIds,Long groupState,String nodeIds,Long nodeState){
//		
//	}
	/**
	 * 查询DetectionSetInfo 信息 
	 * @time Apr 9, 2012-10:00:16 AM
	 * @param checkWay
	 * @param setInfoId
	 * @param seqId
	 * @param checktype
	 * @param groupId
	 * @param groupState
	 * @param nodeId
	 * @param nodeState
	 * @return
	 */
	/*public List<SetInfo> selectSetInfoListWithoutIPSegment(Long checkWay ,Long setInfoId ,Long seqId , String checktype ,String groupId ,Long groupState,String nodeId,Long nodeState) {
		List<SetInfo> setInfoList = new LinkedList<SetInfo>();
		//-- 查询执行Ping的节点
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("node_ips_id");
		fields.add("check_type_id");
		fields.add("process_Iden");
		fields.add("process_file");
		fields.add("process_path");
		fields.add("check_gap");
		fields.add("check_out_time");
		fields.add("check_max_times");
		fields.add("plan_check_time");
		fields.add("check_type_name");
		fields.add("detection_set_state");
		fields.add("node_groups_id");
		fields.add("check_way");
		fields.add("is_control_start");
		fields.add("control_start_time");
		fields.add("upload_gap");
		fields.add("VIEW_LEVEL");
		fields.add("IS_SNMP");
		fields.add("is_schedule");
		String searchSql = this.selectSetInfoSqlWithoutIPSegment(checkWay ,setInfoId,seqId,checktype,groupId,groupState,nodeId,nodeState);
		ArrayList<Map<String, String>> pingList = null;
		try {
			pingList = dao.dbSelect(searchSql, fields);
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		if(pingList!=null && pingList.size()>0){
			try {
				for(Map<String, String> map : pingList){
					SetInfo info = new SetInfo();
					info.setId(StringUtils.isEmpty(map.get("id"))?null:Long.valueOf(map.get("id")));
					info.setCheckTypeId(StringUtils.isEmpty(map.get("check_type_id"))?null:Long.valueOf(map.get("check_type_id")));
					info.setCheckGap(StringUtils.isEmpty(map.get("check_gap"))?null:Long.valueOf(map.get("check_gap")));
					info.setCheckOutTime(StringUtils.isEmpty(map.get("check_out_time"))?null:Long.valueOf(map.get("check_out_time")));
					info.setCheckMaxTimes(StringUtils.isEmpty(map.get("check_max_times"))?null:Long.valueOf(map.get("check_max_times")));
					info.setProcessIden(map.get("process_Iden"));
					info.setProcessFile(map.get("process_file"));
					info.setProcessPath(map.get("process_path"));
					info.setCheckWay(map.get("check_way"));
					info.setCheckState(map.get("detection_set_state"));
					info.setCheckTypeName(map.get("check_type_name"));
					info.setIsControlStart(map.get("is_control_start"));
					info.setUploadGap(StringUtils.isEmpty(map.get("upload_gap"))?null:Long.valueOf(map.get("upload_gap")));
					info.setViewLevel(StringUtils.isEmpty(map.get("VIEW_LEVEL"))?null:Long.valueOf(map.get("VIEW_LEVEL")));
					info.setIsSNMP(StringUtils.isEmpty(map.get("IS_SNMP"))?null:Long.valueOf(map.get("IS_SNMP")));
					if(!StringUtils.isEmpty(map.get("plan_check_time"))){
						info.setPlanCheckTime(format.parse(map.get("plan_check_time")).getTime());
					}
					if(!StringUtils.isEmpty(map.get("control_start_time"))){
						info.setControlStartTime(format.parse(map.get("control_start_time")).getTime());
					}
					info.setIsSchedule(map.get("is_schedule"));
					info.setNodeIpsId(StringUtils.trim(map.get("node_ips_id")));
					info.setNodeGroupsId(StringUtils.trim(map.get("node_groups_id")));
//					info.setGroupId(map.get("group_id"));
//					info.setNodeIp(map.get("node_ip"));
					setInfoList.add(info);
				}
			} catch (ParseException e) {
				logger.error("",e);
			}
		}
		return setInfoList;
	}
	
	public String selectSetInfoSqlWithoutIPSegment(Long checkWay ,Long setInfoId ,Long seqId, String checktype,String groupIds,Long groupState,String nodeIds,Long nodeState){
		
	 
	 	设置的有效节点范围。
	 	如果有NODES_IP有值则不管节点组的有效范围；
	 	如果NODES_IP无值则使用节点组的范围；
	 	如果NODES_IP和NODE_GROUPS_ID均为空则有效范围是SYSTEM_ID系统内全部有效节点；
	 	如果三者均为空则有效范围为NMS系统内全部有效节点。
	  
	 
		//--叶子节点组查询节点组SQL
		StringBuffer groupsIdsSQL = new StringBuffer();
		
		//查询叶子节点sql1
		StringBuffer nodeGroupSQL = new StringBuffer();
		nodeGroupSQL.append("select ngt.group_id from NODEGROUP_TABLE ngt left join node_table nt on nt.node_group_id = ngt.group_id where ngt.leaf_group = 1 ");
		
		//节点ID不为空
		if(StringUtils.isNotEmpty(nodeIds)){
			nodeGroupSQL.append("and nt.node_id in("+(StringUtils.isEmpty(nodeIds)?"0":nodeIds)+") ");
		}
		//节点物理标识不为空
		if(seqId != null){
			nodeGroupSQL.append("and nt.seq_id ="+seqId.longValue()+" ");
		}
		//节点状态不为空
		if(nodeState != null){
			nodeGroupSQL.append("and nt.node_state ="+nodeState.longValue()+" ");
		}
		//节点组ID不为空
		if(StringUtils.isNotEmpty(groupIds)){
			nodeGroupSQL.append("and nt.node_group_id in ("+(StringUtils.isEmpty(groupIds)?"0":groupIds)+") ");
		}
		//节点组状态不为空
		if(groupState != null){
			nodeGroupSQL.append("and ngt.is_valid = "+groupState.longValue()+" ");
		}
//		nodeGroupSQL.append(getIpnSelect());
		//--逆向查询SQL 查询包括叶子节点组在内的父节点组
		groupsIdsSQL.append("select distinct nt.group_id from NODEGROUP_TABLE nt ");
		groupsIdsSQL.append("start with nt.group_id in (");
		groupsIdsSQL.append(nodeGroupSQL);
		groupsIdsSQL.append(") connect by prior  nt.parent_group_id = nt.group_id ");
		
		
		
		
		
		//全局查询SQL 即节点组、节点为空
		StringBuffer allSql = new StringBuffer();
		StringBuffer groupSql = new StringBuffer();
		StringBuffer nodeSql = new StringBuffer();
		allSql.append("select distinct dsi.id, " +
				" dsi.node_ips_id, " +
				" dsi.check_type_id, " +
				" dsi.process_iden, " +
				" dsi.process_file, " +
				" dsi.process_path, " +
				" dsi.check_gap, " +
				" check_out_time, " +
				" check_max_times, " +
				" to_char(dsi.plan_check_time, '"+Constants.DB_DATE_FORMAT+"') plan_check_time, " +
				" cti.check_type_name, " +
				" detection_set_state, " +
				" dsi.node_groups_id, " +
				" dsi.check_way, " +
				" dsi.is_control_start, " +
				" dsi.upload_gap, " +
				" dsi.VIEW_LEVEL, " +
				" to_char(dsi.control_start_time, '"+Constants.DB_DATE_FORMAT+"') control_start_time, " +
				" IS_SNMP, " +
				" cti.is_schedule " );
		allSql.append("from v_detection_set_info dsi ");
		allSql.append("left join check_type_info cti on cti.id = dsi.check_type_id ");
		allSql.append("where 1=1 " );
		allSql.append("and dsi.detection_set_state = '1' ");
		
		if (checkWay != null) {
			allSql.append("and dsi.check_way = '"+checkWay.longValue()+"' ");
		}
		
		if(StringUtils.isNotEmpty(checktype)){
			//- SNMP监测设置获取
			if(Constants.DETEC_SNMP_STR.equals(checktype)){		//IS_SNMP 0：objectSNMP  1：SNMP4J
				allSql.append("and nvl(cti.IS_SNMP,2) <> '2' ");
			}else{		//IS_SNMP 2或null  通过checktype “NMSClient”“Ping”
				allSql.append("and cti.check_type_name = '"+checktype+"' ");
			}
		}
		
		if (setInfoId != null) {
			allSql.append("and dsi.id = '"+setInfoId.longValue()+"' ");
		}
		
		allSql.append("and dsi.node_groups_id is null ");
		allSql.append("and dsi.node_ips_id is null ");
		
		//-----------------------end
		
		//-- group
//		if(nodeIds == null ){
			groupSql.append("select distinct dsi.id, " +
					" dsi.node_ips_id, " +
					" dsi.check_type_id, " +
					" dsi.process_iden, " +
					" dsi.process_file, " +
					" dsi.process_path, " +
					" dsi.check_gap, " +
					" check_out_time, " +
					" check_max_times, " +
					" to_char(dsi.plan_check_time, '"+Constants.DB_DATE_FORMAT+"') plan_check_time, " +
					" cti.check_type_name, " +
					" detection_set_state, " +
					" dsi.node_groups_id, " +
					" dsi.check_way, " +
					" dsi.is_control_start, " +
					" dsi.upload_gap, " +
					" dsi.VIEW_LEVEL, " +
					" to_char(dsi.control_start_time, '"+Constants.DB_DATE_FORMAT+"') control_start_time, " +
					" IS_SNMP, " +
					" cti.is_schedule ");
			groupSql.append("from v_detection_set_info dsi ");
			groupSql.append("left join check_type_info cti on cti.id = dsi.check_type_id ");
			//groupSql.append("left join nodegroup_table ngt  on ('0,'||dsi.node_groups_id||',0' like '%,' || ngt.group_id || ',%')");
			//groupSql.append("left join node_table nt on nt.node_group_id = dsi.node_group_id ");
			groupSql.append("where 1=1 " );
			groupSql.append("and dsi.detection_set_state = '1' ");
			
			if (checkWay != null) {		//监测方式 0主动 1被动
				groupSql.append("and dsi.check_way = '"+checkWay.longValue()+"' ");
			}
			
			if (groupState != null) {	//节点组状态
				groupSql.append("and dsi.is_valid = '"+groupState.longValue()+"' ");		//--1有效 0无效
			}
			
			if (StringUtils.isNotEmpty(groupsIdsSQL.toString())) {		//节点组ID
				groupSql.append("and dsi.node_group_id in ("+groupsIdsSQL+") " );
			}
			
			if(StringUtils.isNotEmpty(checktype)){	//监测类别名称
				if(Constants.DETEC_SNMP_STR.equals(checktype)){		//IS_SNMP 0：objectSNMP  1：SNMP4J
					groupSql.append("and nvl(cti.IS_SNMP,2) <> '2' ");
				}else{		//IS_SNMP 2或null  通过checktype “NMSClient”“Ping”
					groupSql.append("and cti.check_type_name = '"+checktype+"' ");
				}
			}
			
			if (setInfoId != null) {
				groupSql.append("and dsi.id = '"+setInfoId.longValue()+"' ");
			}
			groupSql.append("and dsi.node_groups_id is not null ");
			groupSql.append("and dsi.node_ips_id is null ");
//		}
			
		//存在node的查询sql
		nodeSql.append("select distinct dsi.id, " +
				" dsi.node_ips_id, " +
				" dsi.check_type_id, " +
				" dsi.process_iden, " +
				" dsi.process_file, " +
				" dsi.process_path, " +
				" dsi.check_gap, " +
				" check_out_time, " +
				" check_max_times, " +
				" to_char(dsi.plan_check_time, '"+Constants.DB_DATE_FORMAT+"') plan_check_time, " +
				" cti.check_type_name, " +
				" detection_set_state, " +
				" dsi.node_groups_id, " +
				" dsi.check_way, " +
				" dsi.is_control_start, " +
				" dsi.upload_gap, " +
				" dsi.VIEW_LEVEL, " +
				" to_char(dsi.control_start_time, '"+Constants.DB_DATE_FORMAT+"') control_start_time, " +
				" IS_SNMP, " +
				" cti.is_schedule ");
		nodeSql.append("from v_detection_set_info dsi ");
		nodeSql.append("left join check_type_info cti on cti.id = dsi.check_type_id ");
		//nodeSql.append("left join nodegroup_table ngt  on ('0,'||dsi.node_groups_id||',0' like '%,' || ngt.group_id || ',%')");
		//nodeSql.append("left join node_table nt on ('0,'||dsi.node_ips_id||',0' like '%,' || nt.node_id || ',%') ");
		nodeSql.append("where 1=1 " );
		nodeSql.append("and dsi.detection_set_state = '1' ");
		if (checkWay != null) {		//监测方式 主动 被动
			nodeSql.append("and dsi.check_way = '"+checkWay.longValue()+"' ");
		}
		if (groupState != null) {	//节点组状态
			nodeSql.append("and dsi.is_valid = '"+groupState.longValue()+"' ");		//--1有效 0无效
		}
		if (StringUtils.isNotEmpty(groupsIdsSQL.toString())) {		//节点组ID
			nodeSql.append("and dsi.node_group_id in ("+groupsIdsSQL+") " );
		}
		if (!StringUtils.isEmpty(nodeIds)) {		//节点ID
			nodeSql.append("and dsi.node_id in("+nodeIds+")" );
		}
		if (nodeState != null) {	//节点状态
			nodeSql.append("and dsi.node_state = '"+nodeState.longValue()+"' ");	//--0有效 1无效
		}
		if(StringUtils.isNotEmpty(checktype)){	//监测类别名称
			if(Constants.DETEC_SNMP_STR.equals(checktype)){		//IS_SNMP 0：objectSNMP  1：SNMP4J
				nodeSql.append("and nvl(cti.IS_SNMP,2) <> '2' ");
			}else{		//IS_SNMP 2或null  通过checktype “NMSClient”“Ping”
				nodeSql.append("and cti.check_type_name = '"+checktype+"' ");
		}
		if(pingList!=null && pingList.size()>0){
			try {
				for(Map<String, String> map : pingList){
					SetInfo info = new SetInfo();
					info.setId(StringUtils.isEmpty(map.get("id"))?null:Long.valueOf(map.get("id")));
					info.setCheckTypeId(StringUtils.isEmpty(map.get("check_type_id"))?null:Long.valueOf(map.get("check_type_id")));
					info.setCheckGap(StringUtils.isEmpty(map.get("check_gap"))?null:Long.valueOf(map.get("check_gap")));
					info.setCheckOutTime(StringUtils.isEmpty(map.get("check_out_time"))?null:Long.valueOf(map.get("check_out_time")));
					info.setCheckMaxTimes(StringUtils.isEmpty(map.get("check_max_times"))?null:Long.valueOf(map.get("check_max_times")));
					info.setProcessIden(map.get("process_Iden"));
					info.setProcessFile(map.get("process_file"));
					info.setProcessPath(map.get("process_path"));
					info.setCheckWay(map.get("check_way"));
					info.setCheckState(map.get("detection_set_state"));
					info.setCheckTypeName(map.get("check_type_name"));
					info.setIsControlStart(map.get("is_control_start"));
					info.setUploadGap(StringUtils.isEmpty(map.get("upload_gap"))?null:Long.valueOf(map.get("upload_gap")));
					info.setViewLevel(StringUtils.isEmpty(map.get("VIEW_LEVEL"))?null:Long.valueOf(map.get("VIEW_LEVEL")));
					info.setIsSNMP(StringUtils.isEmpty(map.get("IS_SNMP"))?null:Long.valueOf(map.get("IS_SNMP")));
					if(!StringUtils.isEmpty(map.get("plan_check_time"))){
						info.setPlanCheckTime(format.parse(map.get("plan_check_time")).getTime());
					}
					if(!StringUtils.isEmpty(map.get("control_start_time"))){
						info.setControlStartTime(format.parse(map.get("control_start_time")).getTime());
					}
					info.setIsSchedule(map.get("is_schedule"));
					info.setNodeIpsId(StringUtils.trim(map.get("node_ips_id")));
					info.setNodeGroupsId(StringUtils.trim(map.get("node_groups_id")));
					info.setProcessSearchKeyCode(StringUtils.trim(map.get("process_search_keycode")));
//					info.setGroupId(map.get("group_id"));
//					info.setNodeIp(map.get("node_ip"));
					setInfoList.add(info);
				}
			} catch (ParseException e) {
				logger.error("",e);
			}
		}
		return setInfoList;
	}
	
	/*
	 * 查询DetectionSetInfo 信息 
	 * @time Jan 21, 2013-9:51:18 AM
	 * @param checkWay		监测方式		0主动 1被动
	 * @param setInfoId		监测设置ID
	 * @param seqId			节点物理标示ID
	 * @param checktype		节点类型  
	 * @param groupId		节点组ID
	 * @param groupState	节点组状态	1有效 0无效
	 * @param nodeId		节点ID
	 * @param nodeState		节点状态		0有效 1无效
	 * @param agentFlag		是否是agent获取标示   true 是Agent获取，不是DC下发，不增加DC管理范围ID过滤  false 是DC下发，增加DC管理范围ID过滤
	 * @return
	 */
	/**
	 * 查询DetectionSetInfo 信息 
	 * @time Jan 21, 2013-9:51:18 AM
	 * @param checkWay		监测方式		0主动 1被动
	 * @param setInfoId		监测设置ID
	 * @param seqId			节点物理标示ID
	 * @param checktype		节点类型  
	 * @param groupId		节点组ID
	 * @param groupState	节点组状态	1有效 0无效
	 * @param nodeId		节点ID
	 * @param nodeState		节点状态		0有效 1无效
	 * @param agentFlag		是否是agent获取标示   true 是Agent获取，不是DC下发，不增加DC管理范围ID过滤  false 是DC下发，增加DC管理范围ID过滤
	 * @return
	 * @throws Exception 
	 */
	public String selectSetInfoSql(Long checkWay ,Long setInfoId ,Long seqId, String checktype,String groupIds,Long groupState,String nodeIds,Long nodeState,boolean agentFlag) throws Exception{
		
		//--节点组查询节点组SQL(包括叶子节点 和 非叶子节点)
		StringBuffer groupsIdsSQL = new StringBuffer();
		
		/* 叶子节点组查询节点组SQL */
		StringBuffer nodeGroupSQL = new StringBuffer();
		nodeGroupSQL.append("select ngt.group_id from NODEGROUP_TABLE ngt left join node_table nt on nt.node_group_id = ngt.group_id where ngt.leaf_group = 1 ");
		
		//节点ID不为空
		if(StringUtils.isNotBlank(nodeIds) && !"null".equals(nodeIds)){
			nodeGroupSQL.append("and nt.node_id in ("+nodeIds+") ");
		}
		//节点物理标识不为空
		if(seqId != null){
			nodeGroupSQL.append("and nt.seq_id ="+seqId.longValue()+" ");
		}
		//节点状态不为空
		if(nodeState != null){
			nodeGroupSQL.append("and nt.node_state ="+nodeState.longValue()+" ");
		}
		//节点组ID不为空
		if(StringUtils.isNotEmpty(groupIds)){
			nodeGroupSQL.append("and nt.node_group_id in ("+(StringUtils.isEmpty(groupIds)?"0":groupIds)+") ");
		}
		//节点组状态不为空
		if(groupState != null){	//节点组状态 1 有效 0无效
			nodeGroupSQL.append("and ngt.is_valid = "+groupState.longValue()+" ");
		}
		
		//是Agent主动获取监测设置，无需增加主动监测ip管理范围过滤
		if(!agentFlag){
			nodeGroupSQL.append(getIpnSelect());
		}

		//--逆向查询SQL 查询包括叶子节点组在内的父节点组
//		groupsIdsSQL.append("select distinct nt.group_id from NODEGROUP_TABLE nt ");
//		groupsIdsSQL.append("start with nt.group_id in (");
//		groupsIdsSQL.append(nodeGroupSQL);
//		groupsIdsSQL.append(") connect by prior  nt.parent_group_id = nt.group_id ");
		
		String gIds = dao.startWithConnectByReverse("NODEGROUP_TABLE", null, "group_id in ( " + nodeGroupSQL.toString() +" ) ", "group_id", "parent_group_id");
		groupsIdsSQL.append(gIds);
		
		StringBuffer allSql = new StringBuffer();
		StringBuffer groupSql = new StringBuffer();
		StringBuffer nodeSql = new StringBuffer();
		/* 查询detec_set_info  node_ips_id为空 node_groups_id为空 system_id不作条件 begin */
		//全局查询SQL 即节点组、节点为空
		allSql.append("select distinct dsi.id, " +
				" dsi.node_ips_id, " +
				" dsi.check_type_id, " +
				" dsi.process_iden, " +
				" dsi.process_file, " +
				" dsi.process_path, " +
				" dsi.check_gap, " +
				" check_out_time, " +
				" check_max_times, " +
				" to_char(dsi.plan_check_time, '"+Constants.DB_DATE_FORMAT+"') plan_check_time, " +
				" cti.check_type_name, " +
				" detection_set_state, " +
				" dsi.node_groups_id, " +
				" dsi.check_way, " +
				" dsi.is_control_start, " +
				" dsi.upload_gap, " +
				" dsi.VIEW_LEVEL, " +
				" to_char(dsi.control_start_time, '"+Constants.DB_DATE_FORMAT+"') control_start_time, " +
				" IS_SNMP, " +
				" cti.is_schedule,dsi.process_search_keycode " );
		allSql.append("from v_detection_set_info dsi ");
		allSql.append("left join check_type_info cti on cti.id = dsi.check_type_id ");
		allSql.append("where 1=1 " );
		allSql.append("and dsi.detection_set_state = '1' ");
		
		if (checkWay != null) {
			allSql.append("and dsi.check_way = '"+checkWay.longValue()+"' ");
		}
		
		if(StringUtils.isNotEmpty(checktype)){
			//- SNMP监测设置获取
			if(Constants.DETEC_SNMP_STR.equals(checktype)){		//IS_SNMP 0：objectSNMP  1：SNMP4J 2或null不是snmp监测
				allSql.append("and nvl(cti.IS_SNMP,2) <> '2' and lower(cti.check_type_name) <> lower('"+Constants.DETEC_SWITCH_STR+"') ");
			}else{		//IS_SNMP 2或null  通过checktype “NMSClient”“Ping”
				allSql.append("and lower(cti.check_type_name) = lower('"+checktype+"') ");
			}
		}
		
		if (setInfoId != null) {
			allSql.append("and dsi.id = '"+setInfoId.longValue()+"' ");
		}
		
		allSql.append("and dsi.node_groups_id is null ");
		allSql.append("and dsi.node_ips_id is null ");
		/* 查询detec_set_info  node_ips_id为空 node_groups_id为空 end */
		
		
		//-- group
		/* 查询detec_set_info  node_ips_id为空 node_groups_id不为空 begin */
//		if(nodeIds == null ){
		groupSql.append("select distinct dsi.id, " +
				" dsi.node_ips_id, " +
				" dsi.check_type_id, " +
				" dsi.process_iden, " +
				" dsi.process_file, " +
				" dsi.process_path, " +
				" dsi.check_gap, " +
				" check_out_time, " +
				" check_max_times, " +
				" to_char(dsi.plan_check_time, '"+Constants.DB_DATE_FORMAT+"') plan_check_time, " +
				" cti.check_type_name, " +
				" detection_set_state, " +
				" dsi.node_groups_id, " +
				" dsi.check_way, " +
				" dsi.is_control_start, " +
				" dsi.upload_gap, " +
				" dsi.VIEW_LEVEL, " +
				" to_char(dsi.control_start_time, '"+Constants.DB_DATE_FORMAT+"') control_start_time, " +
				" IS_SNMP, " +
				" cti.is_schedule,dsi.process_search_keycode ");
		groupSql.append("from v_detection_set_info dsi ");
		groupSql.append("left join check_type_info cti on cti.id = dsi.check_type_id ");
		groupSql.append("where 1=1 " );
		groupSql.append("and dsi.detection_set_state = '1' ");
		
		if (checkWay != null) {		//监测方式 0主动 1被动
			groupSql.append("and dsi.check_way = '"+checkWay.longValue()+"' ");
		}
		
		if (groupState != null) {	//节点组状态
			groupSql.append("and dsi.is_valid = '"+groupState.longValue()+"' ");		//--1有效 0无效
		}
		
		if (StringUtils.isNotEmpty(groupsIdsSQL.toString())) {		//节点组ID
			groupSql.append("and dsi.node_group_id in ("+groupsIdsSQL+") " );
		}
		
		//监测类别名称
		if(StringUtils.isNotEmpty(checktype)){	
			if(Constants.DETEC_SNMP_STR.equals(checktype)){		//IS_SNMP 0：objectSNMP  1：SNMP4J 2或null:不是snmp
				groupSql.append("and nvl(cti.IS_SNMP,2) <> '2' ");
			}else{		//IS_SNMP 2或null  通过checktype “NMSClient”“Ping” 等指定 类型名称的查询
				groupSql.append("and lower(cti.check_type_name) = lower('"+checktype+"') ");
			}
		}
		
		//监测设置ID
		if (setInfoId != null) {
			groupSql.append("and dsi.id = '"+setInfoId.longValue()+"' ");
		}
		groupSql.append("and dsi.node_groups_id is not null ");
		groupSql.append("and dsi.node_ips_id is null ");
//		}
		/* 查询detec_set_info  node_ips_id为空 node_groups_id不为空 end */
			
		/* 查询detec_set_info  node_ips_id不为空 begin */
		//存在node的查询sql
		nodeSql.append("select distinct dsi.id, " +
				" dsi.node_ips_id, " +
				" dsi.check_type_id, " +
				" dsi.process_iden, " +
				" dsi.process_file, " +
				" dsi.process_path, " +
				" dsi.check_gap, " +
				" check_out_time, " +
				" check_max_times, " +
				" to_char(dsi.plan_check_time, '"+Constants.DB_DATE_FORMAT+"') plan_check_time, " +
				" cti.check_type_name, " +
				" detection_set_state, " +
				" dsi.node_groups_id, " +
				" dsi.check_way, " +
				" dsi.is_control_start, " +
				" dsi.upload_gap, " +
				" dsi.VIEW_LEVEL, " +
				" to_char(dsi.control_start_time, '"+Constants.DB_DATE_FORMAT+"') control_start_time, " +
				" IS_SNMP, " +
				" cti.is_schedule,dsi.process_search_keycode ");
		nodeSql.append("from v_detection_set_info dsi ");
		nodeSql.append("left join check_type_info cti on cti.id = dsi.check_type_id ");
		nodeSql.append("where 1=1 " );
		nodeSql.append("and dsi.detection_set_state = '1' ");
		if (checkWay != null) {		//监测方式 主动 被动
			nodeSql.append("and dsi.check_way = '"+checkWay.longValue()+"' ");
		}
		if (groupState != null) {	//节点组状态
			nodeSql.append("and dsi.is_valid = '"+groupState.longValue()+"' ");		//--1有效 0无效
		}
		if (StringUtils.isNotEmpty(groupsIdsSQL.toString())) {		//节点组ID
			nodeSql.append("and dsi.node_group_id in ("+groupsIdsSQL+") " );
		}
		if (!StringUtils.isEmpty(nodeIds)) {		//节点ID
			nodeSql.append("and dsi.node_id in("+nodeIds+")" );
		}
		if (nodeState != null) {	//节点状态
			nodeSql.append("and dsi.node_state = '"+nodeState.longValue()+"' ");	//--0有效 1无效
		}
		if(StringUtils.isNotEmpty(checktype)){	//监测类别名称
			if(Constants.DETEC_SNMP_STR.equals(checktype)){		//IS_SNMP 0：objectSNMP  1：SNMP4J
				nodeSql.append("and nvl(cti.IS_SNMP,2) <> '2' ");
			}else{		//IS_SNMP 2或null  通过checktype “NMSClient”“Ping”
				nodeSql.append("and lower(cti.check_type_name) = lower('"+checktype+"') ");
			}
		}
		if (setInfoId != null) {
			nodeSql.append("and dsi.id = '"+setInfoId.longValue()+"' ");
		}
		if (seqId != null) {
			nodeSql.append("and dsi.seq_id = '"+seqId.longValue()+"' ");
		}
		nodeSql.append("and dsi.node_groups_id is not null ");
		nodeSql.append("and dsi.node_ips_id is not null ");
		/* 查询detec_set_info  node_ips_id不为空 end */
	    
		/* 拼写总的sql */
		StringBuffer unionSql = new StringBuffer();
		unionSql.append("");
		if(allSql.length()!=0 || groupSql.length()!=0){
			unionSql.append("("+nodeSql+")");
			if(groupSql.length() != 0){
				unionSql.append(" union all ("+groupSql+")");
			}
			if(allSql.length() != 0){
				unionSql.append(" union all ("+allSql+")");
			}
		}else{
			unionSql.append(nodeSql);
		}
		return unionSql.toString();
	}
	
	/**
	 * IP & Seq_id one to one
	 * @time Dec 17, 2012-6:49:08 PM
	 * @param uuid
	 * @param newIP
	 * @param systemType
	 * @return
	 */
	public String[] checkAndUpdateNodeParams(Long uuid,String newIP,Integer systemType) {
		String[] resultInfo = new String[2];
		try {
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("NODE_SYSTEM_TYPE");
			String selectSql = "select distinct nt.node_ip,nt.seq_id,nt.NODE_SYSTEM_TYPE from node_table nt where nt.seq_id="+uuid+" or nt.node_ip ='"+newIP+"'";
			ArrayList<Map<String, String>> mapsList = dao.dbSelect(selectSql, fields);
			List<String> oldNodeParams = null;
			List<String> newNodeParams = null;
			if(mapsList !=null && mapsList.size()>0){
				for(Map<String, String> map : mapsList){
					//old node
					if(StringUtils.isNotEmpty(map.get(fields.get(1))) && !map.get(fields.get(1)).equals(uuid.toString())){
						oldNodeParams = new ArrayList<String>(); 
						oldNodeParams.add(StringUtils.isEmpty(map.get(fields.get(0)))?null:map.get(fields.get(0)));
						oldNodeParams.add(StringUtils.isEmpty(map.get(fields.get(1)))?null:map.get(fields.get(1)));
						oldNodeParams.add(StringUtils.isEmpty(map.get(fields.get(2)))?null:map.get(fields.get(2)));
					}
					
					//new node
					if(StringUtils.isNotEmpty(map.get(fields.get(0))) && !map.get(fields.get(1)).equals(uuid.toString())){
						newNodeParams = new ArrayList<String>();
						newNodeParams.add(StringUtils.isEmpty(map.get(fields.get(0)))?null:map.get(fields.get(0)));
						newNodeParams.add(StringUtils.isEmpty(map.get(fields.get(1)))?null:map.get(fields.get(1)));
						newNodeParams.add(StringUtils.isEmpty(map.get(fields.get(2)))?null:map.get(fields.get(2)));
					}
				}
			}
			
			if(oldNodeParams!=null){
				resultInfo[0] = "1";
//				resultInfo[1] = "新IP被占用,更新失败";				
//				resultInfo[1] = "New IP is occupied, update failed";				
				resultInfo[1] = "i18n_server.CommonService.resultInfo1_n81i";				
			}else{
				//新IP未被使用 ，可用于变更操作
				dao.dbUpdate("update node_table nt set nt.node_ip='"+newIP+"' ,nt.NODE_SYSTEM_TYPE='"+systemType+"' where nt.seq_id="+uuid+"");
				resultInfo[0] = "0";
				resultInfo[1] = "更新成功";		
			}
		} catch (Exception e) {
			logger.error("校验并更新节点参数失败", e);
		}finally{
			dao.clearConn();
		}
		return resultInfo;
	}
	//--------------------------------------------------------------------------------------------
	/**
	 * @time Sep 20, 2011-2:38:48 PM
	 * @param alarms
	 * @return
	 */
	public boolean resoveAlarms(String[] alarms) throws Exception{
		boolean flag = false;
		// alarms长度为9 ip type 进程标识，告警信息
		if (alarms == null || alarms.length < 9) {
			return false;
		}
		
		// 整理
		try {
			String setInfoId = alarms[0];
			Map<String, String> publicInfo = new HashMap<String, String>();
			// seqId，
			String seqId = alarms[1];
			publicInfo.put("seq_Id", seqId);
//			publicInfo.put("node_ip", Common.getSeqIdMape().get(Long.parseLong(seqId)));
			// 监测设置ID，
			publicInfo.put("detection_set_info_id", setInfoId);
			publicInfo.put("check_way", "1");
			
//			publicInfo.put("current_times", "");//hyx 2013-6-20 add:由于以前主动告警只是针对NC，所以有特定的格式：common的alarmExceptionInfo方法，没有current_times
			
			// 监测类别，
			String checkType = alarms[2];
			// 进程名称（检查类别设置名称），
			String process = alarms[3];
			// 监测服务启动时间，
			String startTime =format.format(new Date(Long.parseLong(alarms[4])));
			publicInfo.put("start_time", startTime);
			// 本次检测时间，
			String checkTime =format.format(new Date(Long.parseLong(alarms[5])));
			publicInfo.put("DATA_CHECK_TIME".toLowerCase(), checkTime); // 测试时间
			
			
			// 告警级别
			String pLevel = alarms[6];
			String state = alarms[7];
			if(StringUtils.isEmpty(pLevel)){
				if("-2".equals(state)){
					pLevel = Constants.NC_ALARM_POLICE_LEVEL;
				}else if("2".equals(state)){
					pLevel = "99";
				}
			}
			publicInfo.put("police_level", pLevel);
			// 执行状态是否成功，记录的状态是否正常（用于报警 -2主动告警 -1执行失败 0不正常，1正常），
			publicInfo.put("detectioned_state", state);
			
			// 状态信息（描述信息），
			//--状态信息（描述信息），
			String dsinfo = alarms[8];
			if(StringUtils.isNotEmpty(dsinfo)){
				// add by zg 增加对</br>的处理 begin
				dsinfo = dsinfo.replaceAll("</br>", "\n");
				// add by zg 增加对</br>的处理 end
				if(dsinfo.getBytes().length>Constants.VARCHAR_MAX_LENGTH){
					dsinfo = StringUtil.substring(dsinfo,Constants.VARCHAR_MAX_LENGTH);
				}
			}
			
			publicInfo.put("detection_state_info", dsinfo);
			//性能数据，
			publicInfo.put("performace_data",dsinfo);
			
			//--获取第十字段 告警
			String showNum = null;
			int urgentLevel = EmailTypeConstants.URGENT_IMMEDIATELY;//默认为紧急
			if(alarms.length>9){
				showNum = alarms[9];
			}
			
			
			if(StringUtils.isNotBlank(showNum)){
				if(NumberUtils.isNumber(showNum)){
					List<AlarmInfo> alarmList = Common.getAlarmInfoMap().get(setInfoId);
					if(alarmList!=null && alarmList.size()>0){
						for(AlarmInfo info : alarmList){
							if(info!=null && info.getPoliceEmergent()!=null){
								if(info.getShowNum().intValue() == Integer.parseInt(showNum)){
									urgentLevel = info.getPoliceEmergent();
								}
							}
						}
					}
				}
			}
			
			//- 组织邮件信息
			int actionType = EmailTypeConstants.TYPE_ALARM_INFO_EXCEPTION;
			if("99".equals(pLevel)){
				actionType = EmailTypeConstants.TYPE_ALARM_INFO_RECOVER;
				urgentLevel = EmailTypeConstants.URGENT_LATER;
			}
			
			if(Integer.parseInt(pLevel)>0){
				urgentLevel = EmailTypeConstants.URGENT_LATER;
			}
			
			publicInfo.put("POLICE_EMERGENT",urgentLevel+"");
			
			// -- 根据执行状态判断是否需要获取详细数据的信息 及报警信息

			// 将数据保存到历史数据表，并查询出Id
			Calendar arriveTime = Calendar.getInstance();
			publicInfo.put("DATA_ARRIVE_TIME".toLowerCase(), format.format(arriveTime.getTime()));// 获取到数据时间（入库时间）
			publicInfo.put("STATUS_CHANGE_TIME".toLowerCase(), checkTime);// 获取到数据时间（入库时间）
			publicInfo.put("data_check_time_digital".toLowerCase(), alarms[5]);// 获取到数据时间长整形
			publicInfo.put("data_arrive_time_digital".toLowerCase(), arriveTime.getTimeInMillis()+"");// 获取到数据时间长整形
			
			// -- 告警信息整理
			StringBuffer pInfo = new StringBuffer();
			if("99".equals(pLevel)){
//				pInfo.append("告警恢复 监测内容 "  + dsinfo + "\n");
//				pInfo.append("Alarm Recovery Monitoring Content "  + dsinfo + "\n");
				pInfo.append("i18n_server.CommonService.pInfo1_n81i "  + dsinfo + "\n");
			}else{
//				pInfo.append("告警级别 "  + alarms[6] + " 监测内容 "  + dsinfo + "\n");
//				pInfo.append("Alert level "  + alarms[6] + " Monitoring content "  + dsinfo + "\n");
				pInfo.append("i18n_server.CommonService.pInfo2_n81i "  + alarms[6] + " i18n_server.CommonService.monitorContent_n81i "  + dsinfo + "\n");
			}
//			publicInfo.put("notice_info".toLowerCase(), pInfo.toString().toCharArray().length>499?StringUtil.getChineseByLength(pInfo.toString(), 0, 499):pInfo.toString());
			

			ArrayList<String> fields = new ArrayList<String>();
			
			
			//查询detection_info_new 表，判断状态变更，进行报警通知
			String searchSql = "select count(1) counts from detection_info_new din where din.seq_id = ?  and din.detection_set_info_id = ? "
				+ "and (din.detectioned_state <>? or (din.detectioned_state = ? and din.police_level<>?))  and din.data_check_time_digital < ?";
			fields.add("counts");
			List<Map<String, String>> dta = dao.dbSelect(searchSql, fields, seqId, setInfoId,publicInfo.get("detectioned_state"),publicInfo.get("detectioned_state"),publicInfo.get("police_level"),alarms[5]);
			
			/* 第五步：状态变更时发送邮件 */
			//-- 拼写邮件头
			boolean sendEmailFlag = false;			
			if (dta == null || dta.size()==0) {
				sendEmailFlag = true;
			}else{
				if (dta.get(0) != null) {
					String counts = dta.get(0).get("counts");
					if((StringUtils.isNotEmpty(counts) && !"null".equalsIgnoreCase(counts) && !counts.equals("0"))){	//状态变化发送
						sendEmailFlag = true;
					}
				}
			}
			
			if(sendEmailFlag){
				long seqIdLong = Long.parseLong(seqId);
				long setInfoIdLong = Long.parseLong(setInfoId);
				String emailContent = pInfo.toString();
				if(emailContent.getBytes().length>290){
					emailContent = StringUtil.substring(emailContent,290);
				}
				EmailInfo emailInfo = new EmailInfo(actionType,Common.getSetInfoNameMape().get(setInfoIdLong)+"("+Common.getCheckTypeNameMape().get(checkType)+")",Common.getNodeIpByUUID(seqIdLong), checkTime,emailContent,EmailTypeConstants.FLAG_SEND_LATER,urgentLevel);
				new EmailService(dao).sendEmailForDetectionBySeqId(setInfoIdLong,seqIdLong,emailInfo);
			}
			
			
			
			
			// 新增保存报警表信息
//			publicInfo.put("notice_flag".toLowerCase(), "1");// 1已发送 0未发送
			
			//-- 获取ID
			fields.clear();
			
			String id = DetectInfo.computeId(checkTime, seqId, setInfoId);
			
			/*String searchIdSql = "select seq_detection_info.nextval id from dual";
			fields.add("id");
			List<Map<String, String>> sid = dao.dbSelect(searchIdSql, fields);
			String id = null;
			if(sid!=null && sid.size()>0){
				id = sid.get(0).get("id");
			}*/
			dao.setAutoCommit(false);
			publicInfo.put("id", id);
			dao.insertObj("detection_info", publicInfo);
			publicInfo.remove("id");
			publicInfo.put("detection_info_id", id);
			// 保存到报警表
			flag = dao.insertObj("detection_info_warning".toLowerCase(),publicInfo);
			dao.commit();
		} catch (Exception e) {
			logger.error("resoveAlarms 告警信息解析异常："+"",e);
			dao.rollback();
			return false;
		} finally {
			dao.clearConn();
		}
		return flag;
	}


	public Object[] resoveNewData(List<String []> strsList,Map<String,List<String>> allPortName) throws Exception{
		/* 监测数据有效判断*/
		if(strsList==null || strsList.size()==0 
				|| strsList.get(0).length<12){
			return null;
		}
		
		//监测解析结果
		Object[] detectInfo = null;
		Iterator<String []> strsIte = strsList.iterator();//一条监测数据：有多行数据
		String [] datas = strsIte.next();
		
		/** 
		 * 公共部分解析格式：
		 * seqId,
		 * 监测设置ID,
		 * 监测类别,
		 * 进程名称（监测类别设置名称）,
		 * 监测服务启动时间,
		 * 检测时延（秒）,
		 * 本次检测时间,
		 * 尝试次数,
		 * 下次计划监测时间,
		 * 执行状态是否成功是否正常,
		 * 状态信息（描述信息）,
		 * 性能数据
		 **/
		
		/* 基本信息解析格式变量  */
		String seqId = null;		//seqId
		String setInfoId = null;	//监测设置ID
		String checkType = null;	//监测类别
		String process = null;		//进程名称（监测类别设置名称）
		Long startTime = null;		//监测服务启动时间
		
		Integer delayTime = null;	//检测时延（秒）
		Long checkTime = null;		//本次检测时间
		Integer currentTimes = null;	//尝试次数
		Long nextCheckTime = null;		//下次计划监测时间
		int state = -1;				//执行状态是否成功是否正常
		String dsinfo = null;		//状态信息（描述信息）
		String pdata = null;		//性能数据
		
		
		/* 其他变量 */
		StringBuffer errorInfo= new StringBuffer();		//数据文件错误，信息整理
		boolean delyFlag = true;	//详细数据获取标识
		Long stateChangeTime = null;		//状态变更时间
		
		/* 第一步：解析公共数据部分 */
		
		try {
			
			//--seqId，
			seqId = datas[0];
//			logger.debug("被监测节点seqId："+seqId);
			if(StringUtils.isEmpty(seqId)){
//				errorInfo.append("位置"+(0)+"数据 节点seqId(物理主机标识)不能为空；");
				errorInfo.append("Location"+(0)+"data node seqId (physical host ID) cannot be empty；");
			}else if(!StringUtil.isNumber(seqId)){
//				errorInfo.append("位置"+(0)+"数据 节点seqId(物理主机标识)不是正整数:"+seqId);
				errorInfo.append("Location"+(0)+"data node seqId (physical host ID) is not a positive integer:"+seqId);
			}
			
			//--监测设置ID，
			setInfoId = datas[1];
//			logger.debug("监测项："+setInfoId);
			if(StringUtils.isEmpty(setInfoId)){
				errorInfo.append("Location"+(1)+"data Monitoring Settings ID cannot be emp；");
			}else if(!StringUtil.isNumber(setInfoId) && !"0".equals(setInfoId)){
//				errorInfo.append("位置"+(1)+"数据 监测设置ID不是整数(可以为0，默认的系统基础信息的设置就为0):"+setInfoId);
				errorInfo.append("Location"+(1)+"Data Monitoring setting ID is not an integer (can be 0, the default system basic information is set to 0):"+setInfoId);
			}
			
			//--监测类别
			checkType = datas[2];
			if(StringUtils.isEmpty(checkType)){
				errorInfo.append("位置"+(2)+"数据 监测类别不能为空；");
			}
			
			//--进程名称（检查类别设置名称），
			process = datas[3];
			
			//--监测服务启动时间，
			String startTimeStr = datas[4];
			if(StringUtils.isNotEmpty(startTimeStr)){
				try {
					startTime = Long.parseLong(startTimeStr);
				} catch (Exception e) {
					errorInfo.append("位置"+(4)+"数据 “"+startTime+"” 监测服务启动时间须为整形数:"+startTime);
				}
			}else {
				errorInfo.append("位置"+(4)+"数据 监测服务启动时间不能为空；");
			}
			
			//--检测时延（秒），
			String delayTimeStr = datas[5];
			if(StringUtils.isNotEmpty(delayTimeStr)){
				try {
					delayTime = Integer.parseInt(delayTimeStr);
				} catch (Exception e) {
					errorInfo.append("位置"+(5)+"数据 “"+delayTime+"” 检测时延（秒）须为整形数:"+delayTime);
				}
			}
			
			//--本次检测时间，
			String checkTimeStr = datas[6];
			if(StringUtils.isNotEmpty(checkTimeStr)){
				try {
					checkTime = Long.parseLong(checkTimeStr);
				} catch (Exception e) {
					errorInfo.append("位置"+(6)+"数据 “"+checkTimeStr+"” 本次检测时间须为整形数:"+checkTime);
				}
			}else {
				errorInfo.append("位置"+(6)+"数据 本次检测时间不能为空；");
			}
			
			//--尝试次数，
			String currentTimesSre = datas[7];
			if(StringUtils.isNotEmpty(currentTimesSre)){
				try {
					currentTimes = Integer.parseInt(currentTimesSre);
				} catch (Exception e) {
					errorInfo.append("位置"+(7)+"数据 “"+currentTimesSre+"” 尝试次数须为整形数:"+currentTimes);
				}
			}else{
				errorInfo.append("位置"+(7)+"数据 尝试次数不能为空；");
			}
			
			//--下次计划监测时间，
			String nextCheckTimeStr = datas[8];
			if(StringUtils.isNotEmpty(nextCheckTimeStr)){
				try {
					nextCheckTime = Long.parseLong(nextCheckTimeStr);
				} catch (Exception e) {
					errorInfo.append("位置"+(8)+"数据 “"+nextCheckTimeStr+"” 下次计划监测时间须为整形数:"+nextCheckTime);
				}
			}else{
				errorInfo.append("位置"+(8)+"数据 尝试次数不能为空；");
			}
			
			//--执行状态是否成功，记录的状态是否正常（用于报警 -1执行失败 0不正常，1正常），
			String stateStr = datas[9];
			if(StringUtils.isNotEmpty(stateStr)){
				try {
					state = Integer.parseInt(stateStr);
				} catch (Exception e) {
					errorInfo.append("位置"+(9)+"数据 “"+stateStr+"” 执行状态须为整形数:"+state);
				}
			}else{
				errorInfo.append("位置"+(9)+"数据 执行状态不能为空；");
			}
			
			//--状态信息（描述信息），
			dsinfo = datas[10];
			
			
			//--性能数据
			pdata = datas[11];
			if(StringUtils.isNotEmpty(pdata)){
				// add by zg 增加对</br>的处理 begin
				pdata = pdata.replaceAll("</br>", "\n");
				// add by zg 增加对</br>的处理 end
				if(pdata.getBytes().length>Constants.VARCHAR_MAX_LENGTH){
					pdata = StringUtil.substring(pdata,Constants.VARCHAR_MAX_LENGTH);
				}
			}else {//界面异常信息列表的状态信息显示为性能数据，所以如果性能数据为空，则取状态信息
				pdata = dsinfo;
			}
			
		} catch (Exception e) {
			String s = "基本数据部分解析失败"+e.getMessage();
			logger.warn(s);
			errorInfo.append(s);
		}
		
		//--基本信息解析 存在异常值 无须保存，返回错误信息 用于系统告警
		if(errorInfo.length() != 0){
			logger.error("          第一步-1： 新格式监测数据解析异常： seqId:"+seqId+",setInfoId:"+setInfoId+",checkType:"+checkType+" checkTime:"+new Date(checkTime)+" 监测数据解析异常："+errorInfo);
			return null;
		}
		
		//-- 根据执行状态判断是否需要获取详细数据的信息 及报警信息,执行失败，则不要获取
		if(state < 0){	//失败	报警only
			delyFlag = false;//程序执行失败时，不入库详细监测信息
		}
		
		
		//公共信息集合
		Calendar arriveTime = Calendar.getInstance();
		detectInfo = new Object[33];
		//detectInfo[DetectInfo.null] = (CSVUtils.csvBytesPrinter1(strsList, Constants.COMMON_TEXT_CODING));
		detectInfo[DetectInfo.SEQID] = (seqId);
		detectInfo[DetectInfo.SETINFOID] = (setInfoId);
		detectInfo[DetectInfo.STARTTIME] = (startTime);
		detectInfo[DetectInfo.DELAYTIME] = (delayTime);
		detectInfo[DetectInfo.CHECKTIME] = (checkTime);
		detectInfo[DetectInfo.CURRENTTIMES] = (currentTimes);
		detectInfo[DetectInfo.NEXTCHECKTIME] = (nextCheckTime);
		detectInfo[DetectInfo.CHECKTYPE] = (checkType);
		detectInfo[DetectInfo.PDATA] = (pdata);
		detectInfo[DetectInfo.ARRIVETIME] = (arriveTime.getTimeInMillis());
		detectInfo[DetectInfo.PROCESS] = process;
		
		/* 第二步：解析详细数据部分 */
		Map<Integer, TableColumnsModel> tableMap = Common.getTableMap().get(checkType);
		if(tableMap ==null || tableMap.size() == 0){
			logger.error(""+checkType+"无法获取表结构");
			delyFlag = false;
		}
		
		List<Map<String, String>> detaiList = new ArrayList<Map<String, String>>();		//详细数据集合
		int pLevel =99;//默认恢复正常
		StringBuffer alarmInfo = new StringBuffer();
		int urgentLevel = EmailTypeConstants.URGENT_LATER;
		if(delyFlag){
			
			details:while(strsIte.hasNext()){
				String [] detailsArr = strsIte.next();	//取出 
				if(detailsArr == null || detailsArr.length ==0){	//空行不解析
					continue;
				}
				if(detailsArr.length != 2){	//不是[details:0]格式无法解析
					break details;
				}
				if("details".equalsIgnoreCase(detailsArr[0])){
                    int endNum = StringUtils.isEmpty(detailsArr[1])?0:Integer.parseInt(detailsArr[1]);
					/*
					 * 如果是checkType='switchport'监测，且有详细信息，才判断每个详细信息的状态，再确定公共信息的状态：人为设置状态、流量大于0
					 一、根据端口状态，修改监测信息（detection_info、di_switchport表）的detection_state：
					            公共信息状态：-1执行不成功；0异常；1正常
					            端口信息状态：1:正常，0：异常
							   1.查询当前节点人为设置状态port_set_state为up的端口：1up，2down
							   2.对于每个端口
							    if(端口state==1&&当前端口的设置状态为up) {//如果state非0才做判断，并修改，如果state已经为0，则没必要再判断端口的状态（只要有一个端口发生以下异常，则detection_state=0异常）
							   		
								            若IFADMINSTATUS状态为down，则端口state和公共信息state异常(1up,2down)
								           if(端口state==1) {
								           		判断流量（输入速度+输出速度）为0，则端口state和公共信息state异常
								           }
							     }
			   
					*/
					List<String> portNameList = null;
					if(endNum>0 && Constants.DETEC_SWITCH_STR.equalsIgnoreCase(checkType)) {
						//查询当前节点设置状态为up的端口名称，生成list<String>
						portNameList = allPortName.get(seqId);
					}
					
					/**
					 * 储存详细数据前三个字段，恢复数据时使用
					 */
					List<String> showNumList = new LinkedList<String>();
					List<String> plevelList = new LinkedList<String>();
					List<String> alarmList = new LinkedList<String>();
					while(strsIte.hasNext()){
						endNum--;
						String [] detailsArr0 = strsIte.next();	//取出
						Map<String, String> detail = new HashMap<String, String>();		//详细数据集合
						//-- 详细数据解析
						if(detailsArr0!=null && detailsArr0.length>0){
							//告警数据相关信息：0-2
							String showNumStr = detailsArr0[0];
							String pLevelStr = detailsArr0[1];
							String alarmValue = detailsArr0[2];
							
							showNumList.add(showNumStr);
							plevelList.add(pLevelStr);
							alarmList.add(alarmValue);
							
							int index = 3;		//数据集合解析游标
							try {
								//--  详细信息整理 监测具体数据信息（每个字段一列）。
								int i = 0 ;
								while(detail.size() < tableMap.size()){//将metadata表中对应的字段，按shouNum进行组合数据
									TableColumnsModel field = tableMap.get(i);
									++i;
									if((i-1)>tableMap.size()){
										break;
									}
									if(field!=null){
										//当监测数据（index == detailsArr0.length）时，及有效监测数据已经读取完成，tableMap页无需增加空字段数据
										if(index == detailsArr0.length){
											detail.put(field.getFiledName(), null);
											continue;
										}
										try {
											String fileType = field.getFiledType().toUpperCase();
											if("DATE".equals(fileType)){
												if(StringUtils.isNumeric(detailsArr0[index])){//如果为数字型时间，转换
													detail.put(field.getFiledName(), format.format(new Date(Long.parseLong(detailsArr0[index].trim()))));
												}else{//eg:2016-03-06 12:12:12
													detail.put(field.getFiledName(), detailsArr0[index].trim());
												}
											}else{
												if("NUMBER".equals(fileType)){
													if (StringUtils.isBlank(detailsArr0[index])
															|| StringUtil.isRationalNumber(detailsArr0[index])) {
														detail.put(field.getFiledName(), detailsArr0[index].trim());
													}  else if (detailsArr0[index].trim().contains(" days, ")) {
														detail.put(field.getFiledName(), getLongTimeStr(detailsArr0[index].trim()));
													} else {
														throw new Exception("NUMBER数据格式错误！");
													}
												}else{ // VARCHAR2(x)
													String length = fileType.replaceAll("VARCHAR2\\((\\d+)\\)", "$1");
													if(Integer.parseInt(length) < detailsArr0[index].trim().length()) {
														throw new Exception("VARCHAR2数据格式错误！");
													}
													detail.put(field.getFiledName(), detailsArr0[index].trim());
												}
											}
										} catch (Exception e) {
											errorInfo.append(checkType+" 表字段集合信息解析失败；");
											errorInfo.append(field.getFiledName()).append("字段取值")
													.append(detailsArr0[index]).append("发生错误；异常数据行：");
											for (String string : detailsArr0) { // 添加异常数据
												errorInfo.append(string).append(',');
											}
											errorInfo.deleteCharAt(errorInfo.length()-1);
											//监测数据的详细信息如果和指定的字段类型不匹配，则抛弃此条监测数据，避免影响批量入库
											logger.error("          第一步-1： 新格式监测数据解析异常： seqId:"+seqId+",setInfoId:"+setInfoId+",checkType:"+checkType+" checkTime:"+new Date(checkTime)+" 监测数据解析异常："+errorInfo);
											return null;
										}
										index++;
									}
								}
								//组合附加的一些信息
								detail.put("SEQ_ID", seqId);
								String detailDetectionState = "";
								if(StringUtils.isBlank(pLevelStr)){//没有告警，当前详细监测信息正常
									detailDetectionState = "1";//正常
								}else{
									detailDetectionState = "0";//异常
								}								
								//如果是switchport监测,有端口详细信息，且端口状态为正常，才需要再根据以下条件判断端口是否异常
								if(portNameList!=null&&portNameList.size()>0&&"1".equals(detailDetectionState)) {
									String ifDescr = detailsArr0[4];//ifDescr-showNum:2--+2=4（因为有3个告警的字段）
									/**
									 * 1.人为设置端口状态为up时，若IFADMINSTATUS或者IFOPERSTATUS状态为down2（!=1:up），则state=0异常--1up,2down
								           if(state==1) {
								           		2.流量（输入速度+输出速度）为0，则state=0异常
								           }
									 */
									if(portNameList.contains(ifDescr)) {//如果此端口设置的状态为up
										String ifAdminStatus = detailsArr0[9];//showNum=7,1:up,2:down
										if("2".equals(ifAdminStatus)) {
											state = 0;//监测公共信息的状态
											dsinfo += "$@$端口"+ifDescr+"异常(配置状态与实际状态不符)";
											detailDetectionState = "0";//当前端口的状态
											pLevel = Constants.PORT_ALARM_LEVEL;//非界面设置，默认为5级
										}
										
										if("1".equals(detailDetectionState)) {//如果当前端口的状态正常，才需要判断流量是否为0
											double inOctetsSpeed = detailsArr0[25]==null?0d:("".equals(detailsArr0[25])?0d:Double.parseDouble(detailsArr0[25].trim()));//23+2=25,瞬时输入字节速度
											double outOctetsSpeed = detailsArr0[29]==null?0d:("".equals(detailsArr0[29])?0d:Double.parseDouble(detailsArr0[29].trim()));//27+2=29,瞬时输出字节速度
											logger.info("test:port:inOctetsSpeed="+inOctetsSpeed+";outOctetsSpeed="+outOctetsSpeed);
											if((inOctetsSpeed+outOctetsSpeed)<=0) {
												state = 0;//监测公共信息的状态
												dsinfo += "$@$端口"+ifDescr+"异常(流量为0),inOctetsSpeed="+inOctetsSpeed+",outOctetsSpeed="+outOctetsSpeed+",sum="+(inOctetsSpeed+outOctetsSpeed);
												detailDetectionState = "0";//当前端口的状态
												pLevel = Constants.PORT_ALARM_LEVEL;//非界面设置，默认为5级
											}
										}
									}
								}
								
								detail.put("DETECTIONED_STATE", detailDetectionState);
								detail.put("detection_set_info_id",setInfoId);	// 入库时间
								detail.put("data_check_time_digital", checkTime+""); // 测试时间
								detail.put("data_check_time", format.format(new Date(checkTime))); // 测试时间
								detail.put("data_arrive_time_digital", arriveTime.getTimeInMillis()+"");		// 入库时间
								detail.put("data_arrive_time",format.format(arriveTime.getTime()));	// 入库时间
								detaiList.add(detail);
								//--  整理告警信息
								if(state == 0){
									String [] nums = showNumStr.split("\\|");
									String [] levels = pLevelStr.split("\\|");
									String [] values = alarmValue.split("\\|");
									List<AlarmInfo> aList = Common.getAlarmInfoMap().get(setInfoId);
									Iterator<AlarmInfo> ite = null;
									for(int m = 0 ; m<nums.length ;m++){
										String num = nums[m];
										if(StringUtils.isEmpty(num)){
											continue;
										}
										if(aList == null || aList.size() ==0){
											continue;
										}
										ite = aList.iterator();
										String cpInfo="";
										while (ite.hasNext()) {
											AlarmInfo elem = (AlarmInfo) ite.next();
											//判断告警字段和告警级别是否相等
											if(elem.getShowNum().toString().equals(nums[m])){
												/** 修正全局告警级别，取最高级别即plevel越小级别越高 **/
												logger.debug("********修正的告警级别："+elem.getPoliceLevel());
												try
												{//告警级别取决于监测数据的级别，是否紧急取决于级别（0级别：对应紧急，其它对应非紧急）
													if(pLevel >= Integer.parseInt(levels[m].trim())){
														pLevel = Integer.parseInt(levels[m].trim());
														//0级别：对应紧急，其它对应非紧急
														if(pLevel==Constants.LEVEL_OF_EMERGENCY) {
															urgentLevel = EmailTypeConstants.URGENT_IMMEDIATELY;
														}else {
															urgentLevel = EmailTypeConstants.URGENT_LATER;
														}
													}
												} catch (Exception e)
												{
													logger.error("新格式监测数据-修改正告警级别时，解析告警level:"+levels[m]+" 异常", e);
												}
												
												/** 字段名称 intDate 实际值： 80》60%（临界值） 级别 40 **/	
												String filedName = "";
												String filedComments = "";
												if(tableMap !=null){
													TableColumnsModel tm = tableMap.get(elem.getShowNum());
													filedName = tm==null?"":tm.getFiledName();
													filedComments = tm==null?"":tm.getFiledComments();
												}
												cpInfo +=  " "+(StringUtils.isEmpty(elem.getFiledCommonts())?filedName:elem.getFiledCommonts());
												cpInfo +=  " 为："+detail.get(filedName);
												cpInfo +=  (elem.getPoliceUnit()==null ? "" : "null".equals(elem.getPoliceUnit()) ? "" : elem.getPoliceUnit());
												cpInfo +=  "   报警级别："+pLevel;
												cpInfo +=  " \n";
											}
										}
										//如果是握手监测，不添加告警设置字段相关信息
										if(!Constants.DETEC_NMSC_STR.equalsIgnoreCase(checkType)) {
											alarmInfo.append(cpInfo);
										}
									}
								}
							} catch (Exception e) {
								String s = "详细数据部分解析失败"+e.getMessage();
								logger.warn(s);
							}
						}
						
						detectInfo[DetectInfo.SHOWNUMLIST] = (showNumList);
						detectInfo[DetectInfo.PLEVELLIST] = (plevelList);
						detectInfo[DetectInfo.ALARMLIST] = (alarmList);

						if(endNum ==0){
							break details;
						}
					}
					if(dsinfo.startsWith("$@$") && dsinfo.length()>3) {
						dsinfo = dsinfo.substring(3, dsinfo.length());
					}
				}
			}
		}
		if(state == -1){//监测执行失败，是最高级别的告警
			//NMSC 监测失败状态 程序设定为为紧急
			if(checkType.equalsIgnoreCase(Constants.DETEC_NMSC_STR)){
				pLevel = Constants.DETECT_FAIL_NMSC_POLICE_LEVEL;
				urgentLevel = Constants.DETECT_FAIL_NMSC_POLICE_EMERGENT;
			}else {
				pLevel = Constants.DETECT_FAIL_NON_NMSC_POLICE_LEVEL;
				urgentLevel = Constants.DETECT_FAIL_NON_NMSC_POLICE_EMERGENT;				
			}
		}
		
		//--状态信息（描述信息），
		if(StringUtils.isNotEmpty(dsinfo)){
			dsinfo = dsinfo.replaceAll("</br>", "\n");// add by zg 增加对</br>的处理 begin
			if(dsinfo.getBytes().length>Constants.VARCHAR_MAX_LENGTH){
				dsinfo = StringUtil.substring(dsinfo,Constants.VARCHAR_MAX_LENGTH);
			}
		}
		
		detectInfo[DetectInfo.STATE] = (state);
		detectInfo[DetectInfo.DSINFO] = (dsinfo);
		detectInfo[DetectInfo.PLEVEL] = (pLevel);
		detectInfo[DetectInfo.ALARMINFO] = (alarmInfo.toString());//告警信息，发送邮件的时候需要用
		detectInfo[DetectInfo.URGENTLEVEL] = (urgentLevel);//状态是否改变会影响这个告警级别
		detectInfo[DetectInfo.DELYFLAG] = (delyFlag);//根据这个参数，决定是否保存详细信息
		detectInfo[DetectInfo.DETAILS] = (detaiList);//用于批量入库详细信息
		
		//特殊追加信息解析--systeminfo-disk、net
		//-- 特殊信息保存整理
//		logger.debug("新格式解析 第七步 特殊追加信息解析"+(Constants.DETEC_SYSTEMINFO_STR.equalsIgnoreCase(checkType)));
		if(Constants.DETEC_SYSTEMINFO_STR.equalsIgnoreCase(checkType) ) {
			while (strsIte.hasNext()) {
				String [] detailsArr = strsIte.next();	//取出 
				if(detailsArr == null || detailsArr.length ==0){	//空行不解析
					continue;
				}
				if(detailsArr.length != 2){	//不是[details:0]格式无法解析
					break;
				}

				if("disk".equalsIgnoreCase(detailsArr[0])){
					List<String[]> infoList = new ArrayList<String[]>();
					int endNum = StringUtils.isEmpty(detailsArr[1])?0:Integer.parseInt(detailsArr[1]);
					disk:while (strsIte.hasNext()) {
						endNum--;
						String [] detailsArr0 = strsIte.next();	//取出
						int len = detailsArr0.length;
						String[] diskInfo = new String[8];
						//diskInfo[0] = id;
						diskInfo[1] = len>0 ? detailsArr0[0]:"";//盘符
						diskInfo[2] = len>1 ? detailsArr0[1]:"";//大小
						diskInfo[3] = checkTime+"";//监测时间（long）
						diskInfo[4] = format.format(new Date(checkTime));//监测时间（date）
						diskInfo[5] = arriveTime.getTimeInMillis()+"";//录入记录时间（当前时间 long）
						diskInfo[6] = format.format(arriveTime.getTime());//录入记录时间（当前时间 date）
						diskInfo[7] = setInfoId;
						infoList.add(diskInfo);
						if(endNum==0){
							logger.debug("disk解析完成 跳出循环");
							break disk;
						}
					}
					if(infoList.size()>0) {
						detectInfo[DetectInfo.DISKINFOLIST] = (infoList);//插入操作批量执行
					}
				}else if("net".equalsIgnoreCase(detailsArr[0])) {
					List<String[]> infoList = new ArrayList<String[]>();
					int endNum = StringUtils.isEmpty(detailsArr[1])?0:Integer.parseInt(detailsArr[1]);
					net:while (strsIte.hasNext()) {
						endNum--;
						String [] netInfoTmp = strsIte.next();	//取出
						int len = netInfoTmp.length;
						String[] netInfo = new String[13];
						//netInfo[0] = id;
						netInfo[1] = len>0 ? netInfoTmp[0]:"";//网卡名称
						netInfo[2] = len>1 ? netInfoTmp[1]:"";//网卡状态
						netInfo[3] = len>2 ? netInfoTmp[2]:"";//网卡带宽
						netInfo[4] = len>3 ? netInfoTmp[3]:"";//ip
						netInfo[5] = len>4 ? netInfoTmp[4]:"";//子网掩码
						netInfo[6] = len>5 ? netInfoTmp[5]:"";//网关
						netInfo[7] = len>6 ? netInfoTmp[6]:"";//NET_MAC
						netInfo[8] = format.format(new Date(checkTime));//监测时间（date）
						netInfo[9] = format.format(arriveTime.getTime());//录入记录时间（当前时间 date）
						netInfo[10] = checkTime+"";//监测时间（long）
						netInfo[11] = arriveTime.getTimeInMillis()+"";//录入记录时间（当前时间 long）
						netInfo[12] = setInfoId;// id
						infoList.add(netInfo);
						if(endNum ==0){
							break net;
						}
					}
					if(infoList.size()>0) {
						detectInfo[DetectInfo.NETINFOLIST] = (infoList);//插入操作批量执行
					}
				}
			}
		}
		return detectInfo;
	}
//	public DetecAllInfo resoveNewData(List<String []> strsList,Map<String,List<String>> allPortName) throws Exception{
//		/* 监测数据有效判断*/
//		if(strsList==null || strsList.size()==0 
//				|| strsList.get(0).length<12){
//			return null;
//		}
//		
//		//监测解析结果
//		DetecAllInfo detectInfo = null;
//		Iterator<String []> strsIte = strsList.iterator();//一条监测数据：有多行数据
//		String [] datas = strsIte.next();
//		
//		/** 
//		 * 公共部分解析格式：
//		 * seqId,
//		 * 监测设置ID,
//		 * 监测类别,
//		 * 进程名称（监测类别设置名称）,
//		 * 监测服务启动时间,
//		 * 检测时延（秒）,
//		 * 本次检测时间,
//		 * 尝试次数,
//		 * 下次计划监测时间,
//		 * 执行状态是否成功是否正常,
//		 * 状态信息（描述信息）,
//		 * 性能数据
//		 **/
//		
//		/* 基本信息解析格式变量  */
//		String seqId = null;		//seqId
//		String setInfoId = null;	//监测设置ID
//		String checkType = null;	//监测类别
//		String process = null;		//进程名称（监测类别设置名称）
//		Long startTime = null;		//监测服务启动时间
//		
//		Integer delayTime = null;	//检测时延（秒）
//		Long checkTime = null;		//本次检测时间
//		Integer currentTimes = null;	//尝试次数
//		Long nextCheckTime = null;		//下次计划监测时间
//		int state = -1;				//执行状态是否成功是否正常
//		String dsinfo = null;		//状态信息（描述信息）
//		String pdata = null;		//性能数据
//		
//		
//		/* 其他变量 */
//		StringBuffer errorInfo= new StringBuffer();		//数据文件错误，信息整理
//		boolean delyFlag = true;	//详细数据获取标识
//		Long stateChangeTime = null;		//状态变更时间
//		
//		/* 第一步：解析公共数据部分 */
//		
//		try {
//			
//			//--seqId，
//			seqId = datas[0];
////			logger.debug("被监测节点seqId："+seqId);
//			if(StringUtils.isEmpty(seqId)){
//				errorInfo.append("位置"+(0)+"数据 节点seqId(物理主机标识)不能为空；");
//			}else if(!StringUtil.isNumber(seqId)){
//				errorInfo.append("位置"+(0)+"数据 节点seqId(物理主机标识)不是正整数:"+seqId);
//			}
//			
//			//--监测设置ID，
//			setInfoId = datas[1];
////			logger.debug("监测项："+setInfoId);
//			if(StringUtils.isEmpty(setInfoId)){
//				errorInfo.append("位置"+(1)+"数据 监测设置ID不能为空；");
//			}else if(!StringUtil.isNumber(setInfoId) && !"0".equals(setInfoId)){
//				errorInfo.append("位置"+(1)+"数据 监测设置ID不是整数(可以为0，默认的系统基础信息的设置就为0):"+setInfoId);
//			}
//			
//			//--监测类别
//			checkType = datas[2];
//			if(StringUtils.isEmpty(checkType)){
//				errorInfo.append("位置"+(2)+"数据 监测类别不能为空；");
//			}
//			
//			//--进程名称（检查类别设置名称），
//			process = datas[3];
//			
//			//--监测服务启动时间，
//			String startTimeStr = datas[4];
//			if(StringUtils.isNotEmpty(startTimeStr)){
//				try {
//					startTime = Long.parseLong(startTimeStr);
//				} catch (Exception e) {
//					errorInfo.append("位置"+(4)+"数据 “"+startTime+"” 监测服务启动时间须为整形数:"+startTime);
//				}
//			}else {
//				errorInfo.append("位置"+(4)+"数据 监测服务启动时间不能为空；");
//			}
//			
//			//--检测时延（秒），
//			String delayTimeStr = datas[5];
//			if(StringUtils.isNotEmpty(delayTimeStr)){
//				try {
//					delayTime = Integer.parseInt(delayTimeStr);
//				} catch (Exception e) {
//					errorInfo.append("位置"+(5)+"数据 “"+delayTime+"” 检测时延（秒）须为整形数:"+delayTime);
//				}
//			}
//			
//			//--本次检测时间，
//			String checkTimeStr = datas[6];
//			if(StringUtils.isNotEmpty(checkTimeStr)){
//				try {
//					checkTime = Long.parseLong(checkTimeStr);
//				} catch (Exception e) {
//					errorInfo.append("位置"+(6)+"数据 “"+checkTimeStr+"” 本次检测时间须为整形数:"+checkTime);
//				}
//			}else {
//				errorInfo.append("位置"+(6)+"数据 本次检测时间不能为空；");
//			}
//			
//			//--尝试次数，
//			String currentTimesSre = datas[7];
//			if(StringUtils.isNotEmpty(currentTimesSre)){
//				try {
//					currentTimes = Integer.parseInt(currentTimesSre);
//				} catch (Exception e) {
//					errorInfo.append("位置"+(7)+"数据 “"+currentTimesSre+"” 尝试次数须为整形数:"+currentTimes);
//				}
//			}else{
//				errorInfo.append("位置"+(7)+"数据 尝试次数不能为空；");
//			}
//			
//			//--下次计划监测时间，
//			String nextCheckTimeStr = datas[8];
//			if(StringUtils.isNotEmpty(nextCheckTimeStr)){
//				try {
//					nextCheckTime = Long.parseLong(nextCheckTimeStr);
//				} catch (Exception e) {
//					errorInfo.append("位置"+(8)+"数据 “"+nextCheckTimeStr+"” 下次计划监测时间须为整形数:"+nextCheckTime);
//				}
//			}else{
//				errorInfo.append("位置"+(8)+"数据 尝试次数不能为空；");
//			}
//			
//			//--执行状态是否成功，记录的状态是否正常（用于报警 -1执行失败 0不正常，1正常），
//			String stateStr = datas[9];
//			if(StringUtils.isNotEmpty(stateStr)){
//				try {
//					state = Integer.parseInt(stateStr);
//				} catch (Exception e) {
//					errorInfo.append("位置"+(9)+"数据 “"+stateStr+"” 执行状态须为整形数:"+state);
//				}
//			}else{
//				errorInfo.append("位置"+(9)+"数据 执行状态不能为空；");
//			}
//			
//			//--状态信息（描述信息），
//			dsinfo = datas[10];
//			
//			
//			//--性能数据
//			pdata = datas[11];
//			if(StringUtils.isNotEmpty(pdata)){
//				// add by zg 增加对</br>的处理 begin
//				pdata = pdata.replaceAll("</br>", "\n");
//				// add by zg 增加对</br>的处理 end
//				if(pdata.getBytes().length>Constants.VARCHAR_MAX_LENGTH){
//					pdata = StringUtil.substring(pdata,Constants.VARCHAR_MAX_LENGTH);
//				}
//			}
//			
//		} catch (Exception e) {
//			String s = "基本数据部分解析失败"+e.getMessage();
//			logger.warn(s);
//			errorInfo.append(s);
//		}
//		
//		//--基本信息解析 存在异常值 无须保存，返回错误信息 用于系统告警
//		if(errorInfo.length() != 0){
//			logger.error("          第一步-1： 新格式监测数据解析异常： seqId:"+seqId+",setInfoId:"+setInfoId+",checkType:"+checkType+" checkTime:"+new Date(checkTime)+" 监测数据解析异常："+errorInfo);
//			return null;
//		}
//		
//		//-- 根据执行状态判断是否需要获取详细数据的信息 及报警信息,执行失败，则不要获取
//		if(state < 0){	//失败	报警only
//			delyFlag = false;//程序执行失败时，不入库详细监测信息
//		}
//		
//		//公共信息集合
//		detectInfo = new DetecAllInfo();
//		detectInfo.setDsb(CSVUtils.csvBytesPrinter1(strsList, Constants.COMMON_TEXT_CODING));//存储一条监测数据的字节数组格式，以备批量保存异常时，将监测数据暂存硬盘，等待下次再入库
//		detectInfo.setSeqId(seqId);
//		detectInfo.setSetInfoId(setInfoId);
//		detectInfo.setStartTime(startTime);
//		detectInfo.setDelayTime(delayTime);
//		detectInfo.setCheckTime(checkTime);
//		detectInfo.setCurrentTimes(currentTimes);
//		detectInfo.setNextCheckTime(nextCheckTime);
//		detectInfo.setCheckType(checkType);
//		detectInfo.setPdata(pdata);
//		Calendar arriveTime = Calendar.getInstance();
//		detectInfo.setArriveTime(arriveTime.getTimeInMillis());
//		
//		/* 第二步：解析详细数据部分 */
//		Map<Integer, TableColumnsModel> tableMap = Common.getTableMap().get(checkType);
//		if(tableMap ==null || tableMap.size() == 0){
//			logger.error(""+checkType+"无法获取表结构");
//			delyFlag = false;
//		}
//		
//		List<Map<String, String>> detaiList = new ArrayList<Map<String, String>>();		//详细数据集合
//		int pLevel =99;//默认恢复正常
//		StringBuffer alarmInfo = new StringBuffer();
//		int urgentLevel = EmailTypeConstants.URGENT_LATER;
//		if(delyFlag){
//			
//			details:while(strsIte.hasNext()){
//				String [] detailsArr = strsIte.next();	//取出 
//				if(detailsArr == null || detailsArr.length ==0){	//空行不解析
//					continue;
//				}
//				if(detailsArr.length != 2){	//不是[details:0]格式无法解析
//					break details;
//				}
//				if("details".equalsIgnoreCase(detailsArr[0])){
//					int endNum = StringUtils.isEmpty(detailsArr[1])?0:Integer.parseInt(detailsArr[1]);
//					/*
//					 * 如果是checkType='switchport'监测，且有详细信息，才判断每个详细信息的状态，再确定公共信息的状态：人为设置状态、流量大于0
//					 一、根据端口状态，修改监测信息（detection_info、di_switchport表）的detection_state：
//					            公共信息状态：-1执行不成功；0异常；1正常
//					            端口信息状态：1:正常，0：异常
//							   1.查询当前节点人为设置状态port_set_state为up的端口：1up，2down
//							   2.对于每个端口
//							    if(端口state==1&&当前端口的设置状态为up) {//如果state非0才做判断，并修改，如果state已经为0，则没必要再判断端口的状态（只要有一个端口发生以下异常，则detection_state=0异常）
//							   		
//								            若IFADMINSTATUS状态为down，则端口state和公共信息state异常(1up,2down)
//								           if(端口state==1) {
//								           		判断流量（输入速度+输出速度）为0，则端口state和公共信息state异常
//								           }
//							     }
//			   
//					 */
//					List<String> portNameList = null;
//					if(endNum>0 && Constants.DETEC_SWITCH_STR.equalsIgnoreCase(checkType)) {
//						//查询当前节点设置状态为up的端口名称，生成list<String>
//						portNameList = allPortName.get(seqId);
//					}
//					
//					while(strsIte.hasNext()){
//						endNum--;
//						String [] detailsArr0 = strsIte.next();	//取出
//						Map<String, String> detail = new HashMap<String, String>();		//详细数据集合
//						//-- 详细数据解析
//						if(detailsArr0!=null && detailsArr0.length>0){
//							//告警数据相关信息：0-2
//							String showNumStr = detailsArr0[0];
//							String pLevelStr = detailsArr0[1];
//							String alarmValue = detailsArr0[2];
//							int index = 3;		//数据集合解析游标
//							try {
//								//--  详细信息整理 监测具体数据信息（每个字段一列）。
//								int i = 0 ;
//								while(detail.size() < tableMap.size()){//将metadata表中对应的字段，按shouNum进行组合数据
//									TableColumnsModel field = tableMap.get(i);
//									++i;
//									if((i-1)>tableMap.size()){
//										break;
//									}
//									if(field!=null){
//										//当监测数据（index == detailsArr0.length）时，及有效监测数据已经读取完成，tableMap页无需增加空字段数据
//										if(index == detailsArr0.length){
//											detail.put(field.getFiledName(), null);
//											continue;
//										}
//										try {
//											if("DATE".equals(field.getFiledType().toUpperCase())){
//												if(StringUtils.isNotBlank(detailsArr0[index])){
//													detail.put(field.getFiledName(), format.format(new Date(Long.parseLong(detailsArr0[index].trim()))));
//												}else{
//													detail.put(field.getFiledName(), detailsArr0[index].trim());
//												}
//											}else{
//												if("NUMBER".equals(field.getFiledType().toUpperCase())){
//													try {
//														if(StringUtils.isNotBlank(detailsArr0[index])){
//															Double.parseDouble(detailsArr0[index].trim());
//														}
//														detail.put(field.getFiledName(), detailsArr0[index].trim());
//													} catch (Exception e) {
//														detail.put(field.getFiledName(), getLongTimeStr(detailsArr0[index].trim()));
//													}
//												}else{
//													detail.put(field.getFiledName(), detailsArr0[index].trim());
//												}
//											}
//										} catch (Exception e) {
//											errorInfo.append(checkType+" 表字段集合信息加载失败，请检查该监测类别的相关设置后重启本应用程序！");
//										}
//										index++;
//									}
//								}
//								//组合附加的一些信息
//								detail.put("SEQ_ID", seqId);
//								String detailDetectionState = "";
//								if(StringUtils.isBlank(pLevelStr)){//没有告警，当前详细监测信息正常
//									detailDetectionState = "1";//正常
//								}else{
//									detailDetectionState = "0";//异常
//								}								
//								//如果是switchport监测,有端口详细信息，且端口状态为正常，才需要再根据以下条件判断端口是否异常
//								if(portNameList!=null&&portNameList.size()>0&&"1".equals(detailDetectionState)) {
//									String ifDescr = detailsArr0[4];//ifDescr-showNum:2--+2=4（因为有3个告警的字段）
//									/**
//									 * 1.人为设置端口状态为up时，若IFADMINSTATUS或者IFOPERSTATUS状态为down2（!=1:up），则state=0异常--1up,2down
//								           if(state==1) {
//								           		2.流量（输入速度+输出速度）为0，则state=0异常
//								           }
//									 */
//									if(portNameList.contains(ifDescr)) {//如果此端口设置的状态为up
//										String ifAdminStatus = detailsArr0[9];//showNum=7,1:up,2:down
//										if("2".equals(ifAdminStatus)) {
//											state = 0;//监测公共信息的状态
//											dsinfo += "$@$端口"+ifDescr+"异常(配置状态与实际状态不符)";
//											detailDetectionState = "0";//当前端口的状态
//											pLevel = Constants.PORT_ALARM_LEVEL;//非界面设置，默认为5级
//										}
//										
//										if("1".equals(detailDetectionState)) {//如果当前端口的状态正常，才需要判断流量是否为0
//											double inOctetsSpeed = detailsArr0[25]==null?0d:("".equals(detailsArr0[25])?0d:Double.parseDouble(detailsArr0[25].trim()));//23+2=25,瞬时输入字节速度
//											double outOctetsSpeed = detailsArr0[29]==null?0d:("".equals(detailsArr0[29])?0d:Double.parseDouble(detailsArr0[29].trim()));//27+2=29,瞬时输出字节速度
//											logger.info("test:port:inOctetsSpeed="+inOctetsSpeed+";outOctetsSpeed="+outOctetsSpeed);
//											if((inOctetsSpeed+outOctetsSpeed)<=0) {
//												state = 0;//监测公共信息的状态
//												dsinfo += "$@$端口"+ifDescr+"异常(流量为0),inOctetsSpeed="+inOctetsSpeed+",outOctetsSpeed="+outOctetsSpeed+",sum="+(inOctetsSpeed+outOctetsSpeed);
//												detailDetectionState = "0";//当前端口的状态
//												pLevel = Constants.PORT_ALARM_LEVEL;//非界面设置，默认为5级
//											}
//										}
//									}
//								}
//								
//								detail.put("DETECTIONED_STATE", detailDetectionState);
//								detail.put("detection_set_info_id",setInfoId);	// 入库时间
//								detail.put("data_check_time_digital", checkTime+""); // 测试时间
//								detail.put("data_check_time", format.format(new Date(checkTime))); // 测试时间
//								detail.put("data_arrive_time_digital", arriveTime.getTimeInMillis()+"");		// 入库时间
//								detail.put("data_arrive_time",format.format(arriveTime.getTime()));	// 入库时间
//								detaiList.add(detail);
//								//--  整理告警信息
//								if(state == 0){
//									String [] nums = showNumStr.split("\\|");
//									String [] levels = pLevelStr.split("\\|");
//									String [] values = alarmValue.split("\\|");
//									List<AlarmInfo> aList = Common.getAlarmInfoMap().get(setInfoId);
//									Iterator<AlarmInfo> ite = null;
//									for(int m = 0 ; m<nums.length ;m++){
//										String num = nums[m];
//										if(StringUtils.isEmpty(num)){
//											continue;
//										}
//										if(aList == null || aList.size() ==0){
//											continue;
//										}
//										ite = aList.iterator();
//										String cpInfo="";
//										while (ite.hasNext()) {
//											AlarmInfo elem = (AlarmInfo) ite.next();
//											//判断告警字段和告警级别是否相等
//											if(elem.getShowNum().toString().equals(nums[m])){
//												/** 修正全局告警级别，取最高级别即plevel越小级别越高 **/
//												logger.debug("********修正的告警级别："+elem.getPoliceLevel());
//												try
//												{//告警级别取决于监测数据的级别，是否紧急取决于级别（0级别：对应紧急，其它对应非紧急）
//													if(pLevel >= Integer.parseInt(levels[m].trim())){
//														pLevel = Integer.parseInt(levels[m].trim());
//														//0级别：对应紧急，其它对应非紧急
//														if(pLevel==Constants.LEVEL_OF_EMERGENCY) {
//															urgentLevel = EmailTypeConstants.URGENT_IMMEDIATELY;
//														}else {
//															urgentLevel = EmailTypeConstants.URGENT_LATER;
//														}
//													}
//												} catch (Exception e)
//												{
//													logger.error("新格式监测数据-修改正告警级别时，解析告警level:"+levels[m]+" 异常", e);
//												}
//												
//												/** 字段名称 intDate 实际值： 80》60%（临界值） 级别 40 **/	
//												String filedName = "";
//												String filedComments = "";
//												if(tableMap !=null){
//													TableColumnsModel tm = tableMap.get(elem.getShowNum());
//													filedName = tm==null?"":tm.getFiledName();
//													filedComments = tm==null?"":tm.getFiledComments();
//												}
//												cpInfo +=  " "+(StringUtils.isEmpty(elem.getFiledCommonts())?filedName:elem.getFiledCommonts());
//												cpInfo +=  " 为："+detail.get(filedName);
//												cpInfo +=  (elem.getPoliceUnit()==null ? "" : "null".equals(elem.getPoliceUnit()) ? "" : elem.getPoliceUnit());
//												cpInfo +=  "   报警级别："+pLevel;
//												cpInfo +=  " \n";
//											}
//										}
//										//如果是握手监测，不添加告警设置字段相关信息
//										if(!Constants.DETEC_NMSC_STR.equalsIgnoreCase(checkType)) {
//											alarmInfo.append(cpInfo);
//										}
//									}
//								}
//							} catch (Exception e) {
//								String s = "详细数据部分解析失败"+e.getMessage();
//								logger.warn(s);
//							}
//						}
//						if(endNum ==0){
//							break details;
//						}
//					}
//					if(dsinfo.startsWith("$@$") && dsinfo.length()>3) {
//						dsinfo = dsinfo.substring(3, dsinfo.length());
//					}
//				}
//			}
//		}
//		if(state == -1){//监测执行失败，是最高级别的告警
//			//NMSC 监测失败状态 程序设定为为紧急
//			if(checkType.equalsIgnoreCase(Constants.DETEC_NMSC_STR)){
//				pLevel = Constants.DETECT_FAIL_NMSC_POLICE_LEVEL;
//				urgentLevel = Constants.DETECT_FAIL_NMSC_POLICE_EMERGENT;
//			}else {
//				pLevel = Constants.DETECT_FAIL_NON_NMSC_POLICE_LEVEL;
//				urgentLevel = Constants.DETECT_FAIL_NON_NMSC_POLICE_EMERGENT;				
//			}
//		}
//		
//		//--状态信息（描述信息），
//		if(StringUtils.isNotEmpty(dsinfo)){
//			dsinfo = dsinfo.replaceAll("</br>", "\n");// add by zg 增加对</br>的处理 begin
//			if(dsinfo.getBytes().length>Constants.VARCHAR_MAX_LENGTH){
//				dsinfo = StringUtil.substring(dsinfo,Constants.VARCHAR_MAX_LENGTH);
//			}
//		}
//		detectInfo.setState(state);
//		detectInfo.setDsinfo(dsinfo);
//		detectInfo.setpLevel(pLevel);
//		detectInfo.setAlarmInfo(alarmInfo.toString());//告警信息，发送邮件的时候需要用
//		detectInfo.setUrgentLevel(urgentLevel);//状态是否改变会影响这个告警级别
//		detectInfo.setDelyFlag(delyFlag);//根据这个参数，决定是否保存详细信息
//		detectInfo.setDetails(detaiList);//用于批量入库详细信息		
//		
//		//特殊追加信息解析--systeminfo-disk、net
//		//-- 特殊信息保存整理
////		logger.debug("新格式解析 第七步 特殊追加信息解析"+(Constants.DETEC_SYSTEMINFO_STR.equalsIgnoreCase(checkType)));
//		if(Constants.DETEC_SYSTEMINFO_STR.equalsIgnoreCase(checkType) ) {
//			while (strsIte.hasNext()) {
//				String [] detailsArr = strsIte.next();	//取出 
//				if(detailsArr == null || detailsArr.length ==0){	//空行不解析
//					continue;
//				}
//				if(detailsArr.length != 2){	//不是[details:0]格式无法解析
//					break;
//				}
//				
//				if("disk".equalsIgnoreCase(detailsArr[0])){
//					List<String[]> infoList = new ArrayList<String[]>();
//					int endNum = StringUtils.isEmpty(detailsArr[1])?0:Integer.parseInt(detailsArr[1]);
//					disk:while (strsIte.hasNext()) {
//						endNum--;
//						String [] detailsArr0 = strsIte.next();	//取出
//						int len = detailsArr0.length;
//						String[] diskInfo = new String[8];
//						//diskInfo[0] = id;
//						diskInfo[1] = len>0 ? detailsArr0[0]:"";//盘符
//						diskInfo[2] = len>1 ? detailsArr0[1]:"";//大小
//						diskInfo[3] = checkTime+"";//监测时间（long）
//						diskInfo[4] = format.format(new Date(checkTime));//监测时间（date）
//						diskInfo[5] = arriveTime.getTimeInMillis()+"";//录入记录时间（当前时间 long）
//						diskInfo[6] = format.format(arriveTime.getTime());//录入记录时间（当前时间 date）
//						diskInfo[7] = setInfoId;
//						infoList.add(diskInfo);
//						if(endNum==0){
//							logger.debug("disk解析完成 跳出循环");
//							break disk;
//						}
//					}
//					if(infoList.size()>0) {
//						detectInfo.setDiskInfoList(infoList);//插入操作批量执行
//					}
//				}else if("net".equalsIgnoreCase(detailsArr[0])) {
//					List<String[]> infoList = new ArrayList<String[]>();
//					int endNum = StringUtils.isEmpty(detailsArr[1])?0:Integer.parseInt(detailsArr[1]);
//					net:while (strsIte.hasNext()) {
//						endNum--;
//						String [] netInfoTmp = strsIte.next();	//取出
//						int len = netInfoTmp.length;
//						String[] netInfo = new String[13];
//						//netInfo[0] = id;
//						netInfo[1] = len>0 ? netInfoTmp[0]:"";//网卡名称
//						netInfo[2] = len>1 ? netInfoTmp[1]:"";//网卡状态
//						netInfo[3] = len>2 ? netInfoTmp[2]:"";//网卡带宽
//						netInfo[4] = len>3 ? netInfoTmp[3]:"";//ip
//						netInfo[5] = len>4 ? netInfoTmp[4]:"";//子网掩码
//						netInfo[6] = len>5 ? netInfoTmp[5]:"";//网关
//						netInfo[7] = len>6 ? netInfoTmp[6]:"";//NET_MAC
//						netInfo[8] = format.format(new Date(checkTime));//监测时间（date）
//						netInfo[9] = format.format(arriveTime.getTime());//录入记录时间（当前时间 date）
//						netInfo[10] = checkTime+"";//监测时间（long）
//						netInfo[11] = arriveTime.getTimeInMillis()+"";//录入记录时间（当前时间 long）
//						netInfo[12] = setInfoId;// id
//						infoList.add(netInfo);
//						if(endNum ==0){
//							break net;
//						}
//					}
//					if(infoList.size()>0) {
//						detectInfo.setNetInfoList(infoList);//插入操作批量执行
//					}
//				}
//			}
//		}
//		return detectInfo;
//	}
	


	/**
	 * 详细数据解析
	 * 第一步：解析公共数据部分，保存各字段值到Map<String, String> publicInfo 中
	 * 第二步：解析详细数据部分，保存各字段到 Map<String, String> detail 中
	 * 第三步：检查告警信息数据，多字段告警去最高级（Level最小）
	 * 第四步：查询数据库中最新同类监测记录，并判断状态是否变化（同类判定：seq_id、detection_set_info_id，变化判定：DETECTIONED_STATE 和 POLICE_LEVEL 至少一个变化）
	 * 第五步：根据告警信息数据，拼写告警信息 
	 * 第六步：状态变更时发送邮件，将告警信息邮件发送
	 * 第七步：保存到基本信息、非正常数据和状态变更数据信息保存到告警表中
	 * 完成...
	 * @time Sep 8, 2011-3:40:45 PM
	 * @param datas
	 * @param dao
	 */
	public Object[] resoveOldData(List<String []> strsList,Map<String,List<String>> allPortName) throws Exception{
		/* 监测数据有效判断*/
		if(strsList==null || strsList.size()==0){
			logger.debug("旧格式监测数据解析：数据内容为空，不予解析;");
			return null;
		}
		//监测解析结果
		Object[] detectInfo = null;
		Iterator<String[]> strsIte = strsList.iterator();					
		String[] datas = null;
		if(strsIte!=null && strsIte.hasNext()) {
			datas = strsIte.next();//获得第一行基本信息
		}
		if(datas==null){
			logger.debug("旧格式监测数据解析：数据内容为空，不予解析;");
			return null;
		}else if(datas.length>0){/* 数据日志尝试输出 */
			String dateTime = null;
			if(datas.length>6){	//第7字段 为监测时间字段 作展示标记
				dateTime = format.format(Long.parseLong(datas[6])); 
			}
			logger.debug("监测数据-旧格式 监测时间》"+dateTime+"  内容》"+Arrays.toString(datas));
			/* 监测数据有效判断 */
			if(datas.length<15){
				logger.debug("旧格式监测数据解析：数据解析长度："+datas.length+" 小于最小解析标准，不予解析；");
				return null;
			}
			/** 
			 * 公共部分解析格式：
			 * seqId,
			 * 监测设置ID,
			 * 监测类别,
			 * 进程名称（监测类别设置名称）,
			 * 监测服务启动时间,
			 * 检测时延（秒）,
			 * 本次检测时间,
			 * 尝试次数,
			 * 下次计划监测时间,
			 * 执行状态是否成功是否正常,
			 * 告警列序号,
			 * 告警级别,
			 * 告警值,
			 * 状态信息（描述信息）,
			 * 性能数据
			 * （,详细数据部分）....
			 **/
			/* 基本信息解析格式变量  */
			String seqId = null;		//seqId
			String setInfoId = null;	//监测设置ID
			String checkType = null;	//监测类别
			String process = null;		//进程名称（监测类别设置名称）
			Long startTime = null;		//监测服务启动时间
			Integer delayTime = null;	//检测时延（秒）
			Long checkTime = null;		//本次检测时间
			Integer currentTimes = null;	//尝试次数
			Long nextCheckTime = null;		//下次计划监测时间
			int state = -1;				//执行状态是否成功是否正常
			String showNums =  null;	//告警序列(数据)
			String pLevel =  null;		//告警级别(数据)
			int pl = 99;				//告警级别（入库）
			String pValue =  null;		//告 警 值(数据)
			String dsinfo = null;		//状态信息（描述信息）
			String pdata = null;		//性能数据
			
			
			/* 其他变量 */
			StringBuffer errorInfo= new StringBuffer();		//数据文件错误，信息整理
			boolean delyFlag = true;	//详细数据获取标识
			//Long stateChangeTime = null;//状态变更时间
			
			/* 第一步：解析公共数据部分 */
			try {
				//--seqId，
				seqId = datas[0];
				if(StringUtils.isEmpty(seqId)){
//					errorInfo.append("位置"+(0)+"数据 节点seqId(物理主机标识)不能为空；");
					errorInfo.append("Location"+(0)+"data node seqId (physical host ID) cannot be empty；");
				}else if(!StringUtil.isNumber(seqId)){
//					errorInfo.append("位置"+(0)+"数据 节点seqId(物理主机标识)不是正整数:"+seqId);
					errorInfo.append("Location"+(0)+"data node seqId (Physical Host ID) is not a positive integer:"+seqId);
				}
				//--监测设置ID，
				setInfoId = datas[1];
				if(StringUtils.isEmpty(setInfoId)){
					errorInfo.append("位置"+(1)+"数据 监测设置ID不能为空；");
				}else if(!StringUtil.isNumber(setInfoId) && !"0".equals(setInfoId)){
					errorInfo.append("位置"+(1)+"数据 监测设置ID不是整数(包括0):"+setInfoId);
				}
				//--监测类别
				checkType = datas[2];
				if(StringUtils.isEmpty(checkType)){
					errorInfo.append("位置"+(2)+"数据 监测类别不能为空；");
				}
				//--进程名称（检查类别设置名称），
				process = datas[3];
				//--监测服务启动时间，
				String startTimeStr = datas[4];
				if(StringUtils.isNotEmpty(startTimeStr)){
					try {
						startTime = Long.parseLong(startTimeStr);
					} catch (Exception e) {
						errorInfo.append("位置"+(4)+"数据 “"+startTime+"” 监测服务启动时间须为整形数:"+startTime);
					}
				}else {
					errorInfo.append("位置"+(4)+"数据 监测服务启动时间不能为空；");
				}
				//--检测时延（秒），
				String delayTimeStr = datas[5];
				if(StringUtils.isNotEmpty(delayTimeStr)){
					try {
						delayTime = Integer.parseInt(delayTimeStr);
					} catch (Exception e) {
						errorInfo.append("位置"+(5)+"数据 “"+delayTime+"” 检测时延（秒）须为整形数:"+delayTime);
					}
				}
				//--本次检测时间，
				String checkTimeStr = datas[6];
				if(StringUtils.isNotEmpty(checkTimeStr)){
					try {
						checkTime = Long.parseLong(checkTimeStr);
					} catch (Exception e) {
						errorInfo.append("位置"+(6)+"数据 “"+checkTimeStr+"” 本次检测时间须为整形数:"+checkTime);
					}
				}else {
					errorInfo.append("位置"+(6)+"数据 本次检测时间不能为空；");
				}
				//--尝试次数，
				String currentTimesSre = datas[7];
				if(StringUtils.isNotEmpty(currentTimesSre)){
					try {
						currentTimes = Integer.parseInt(currentTimesSre);
					} catch (Exception e) {
						errorInfo.append("位置"+(7)+"数据 “"+currentTimesSre+"” 尝试次数须为整形数:"+currentTimes);
					}
				}else{
					errorInfo.append("位置"+(7)+"数据 尝试次数不能为空；");
				}
				//--下次计划监测时间，
				String nextCheckTimeStr = datas[8];
				if(StringUtils.isNotEmpty(nextCheckTimeStr)){
					try {
						nextCheckTime = Long.parseLong(nextCheckTimeStr);
					} catch (Exception e) {
						errorInfo.append("位置"+(8)+"数据 “"+nextCheckTimeStr+"” 下次计划监测时间须为整形数:"+nextCheckTime);
					}
				}else{
					errorInfo.append("位置"+(8)+"数据 尝试次数不能为空；");
				}
				//--执行状态是否成功，记录的状态是否正常（用于报警 -1执行失败 0不正常，1正常），
				String stateStr = datas[9];
				if(StringUtils.isNotEmpty(stateStr)){
					try {
						state = Integer.parseInt(stateStr);
					} catch (Exception e) {
						errorInfo.append("位置"+(9)+"数据 “"+stateStr+"” 执行状态须为整形数:"+state);
					}
				}else{
					errorInfo.append("位置"+(9)+"数据 执行状态不能为空；");
				}
				//--告警序列
				showNums =  datas[10];
				//--告警级别
				pLevel =  datas[11];
				String [] nums0 = pLevel.split("\\|");
				for(String num : nums0){
					if(StringUtils.isEmpty(num)){
						continue;
					}
					int level = Integer.parseInt(num);
					if(pl>level){
						pl = level;
					}
				}
				//失败	最高级
				if(state == -1){
					if(checkType.equalsIgnoreCase(Constants.DETEC_NMSC_STR)){
						pl = Constants.DETECT_FAIL_NMSC_POLICE_LEVEL;
					}else {
						pl = Constants.DETECT_FAIL_NON_NMSC_POLICE_LEVEL;
					}
				}
				//--  告警值
				pValue =  datas[12];
				//--状态信息（描述信息），
				dsinfo = datas[13];
				if(StringUtils.isNotEmpty(dsinfo)){
					// add by zg 增加对</br>的处理 begin
					dsinfo = dsinfo.replaceAll("</br>", "\n");
					// add by zg 增加对</br>的处理 end
					if(dsinfo.getBytes().length>Constants.VARCHAR_MAX_LENGTH){
						dsinfo = StringUtil.substring(dsinfo,Constants.VARCHAR_MAX_LENGTH);
					}
				}
				//--性能数据
				pdata = datas[14];
				if(StringUtils.isNotEmpty(pdata)){
					// add by zg 增加对</br>的处理 begin
					pdata = pdata.replaceAll("</br>", "\n");
					// add by zg 增加对</br>的处理 end
					if(pdata.getBytes().length>Constants.VARCHAR_MAX_LENGTH){
						pdata = StringUtil.substring(pdata,Constants.VARCHAR_MAX_LENGTH);
					}
				}else {//界面异常信息列表的状态信息显示为性能数据，所以如果性能数据为空，则取状态信息
					pdata = dsinfo;
				}
			} catch (Exception e) {
				String s = "基本数据部分解析失败"+e.getMessage();
				logger.warn(s);
				errorInfo.append(s);
			}
			//--基本信息解析 存在异常值 无须保存，返回错误信息 用于系统告警
			if(errorInfo.length() != 0){
				logger.error("          第一步-1： 旧格式监测数据解析异常：  seqId:"+seqId+",setInfoId:"+setInfoId+",checkType:"+checkType+" checkTime:"+new Date(checkTime)+" 监测数据解析异常："+errorInfo);
				return null;
			}
			//-- 根据执行状态判断是否需要获取详细数据的信息 及报警信息
			if(state < 0){	//失败	报警only
				delyFlag = false;
			}
			Calendar arriveTime = Calendar.getInstance();
			detectInfo = new Object[33];
			//detectInfo[DetectInfo.null] = (CSVUtils.csvBytesPrinter1(strsList, Constants.COMMON_TEXT_CODING));
			detectInfo[DetectInfo.SEQID] = (seqId);
			detectInfo[DetectInfo.SETINFOID] = (setInfoId);
			detectInfo[DetectInfo.STARTTIME] = (startTime);
			detectInfo[DetectInfo.DELAYTIME] = (delayTime);
			detectInfo[DetectInfo.CHECKTIME] = (checkTime);
			detectInfo[DetectInfo.CURRENTTIMES] = (currentTimes);
			detectInfo[DetectInfo.NEXTCHECKTIME] = (nextCheckTime);
			detectInfo[DetectInfo.CHECKTYPE] = (checkType);
			detectInfo[DetectInfo.PDATA] = (pdata);
			detectInfo[DetectInfo.ARRIVETIME] = (arriveTime.getTimeInMillis());
			detectInfo[DetectInfo.STATE] = (state);
			detectInfo[DetectInfo.PLEVEL] = (pl);
			detectInfo[DetectInfo.DSINFO] = (dsinfo);
			detectInfo[DetectInfo.PROCESS] = process;
			
			/**
			 * 储存详细数据前三个字段，恢复数据时使用
			 */
			List<String> showNumList = new LinkedList<String>();
			List<String> plevelList = new LinkedList<String>();
			List<String> alarmList = new LinkedList<String>();
	
			showNumList.add(showNums);
			plevelList.add(pLevel);
			alarmList.add(pValue);
			
			detectInfo[DetectInfo.SHOWNUMLIST] = (showNumList);
			detectInfo[DetectInfo.PLEVELLIST] = (plevelList);
			detectInfo[DetectInfo.ALARMLIST] = (alarmList);
			
			
			/* 第二步：解析详细数据部分 */
			Map<String, String> detail = new HashMap<String, String>();		//详细数据集合
			Map<Integer, TableColumnsModel> tableMap = Common.getTableMap().get(checkType);
			if(tableMap ==null || tableMap.size() == 0){
				logger.error(""+checkType+"无法获取表结构");
				delyFlag = false;
			}
			List<Map<String, String>> detaiList = null;	//详细数据集合
			if(delyFlag){
				detaiList = new ArrayList<Map<String, String>>();//初始化详细数据集合
				int index = 15;		//数据集合解析游标
				try {
					//--  详细信息整理 监测具体数据信息（每个字段一列）。
					int i = 0 ;
					while(detail.size() < tableMap.size()){
						TableColumnsModel field = tableMap.get(i);
						++i;
						if((i-1)>tableMap.size()){
							break;
						}
						if(field!=null){
							//当监测数据（index == datas.length）时，及有效监测数据已经读取完成，tableMap页无需增加空字段数据
							if(index == datas.length){
								detail.put(field.getFiledName(), null);
								continue;
							}
							try {
								String fileType = field.getFiledType().toUpperCase();
								if("DATE".equals(fileType)){
									if(StringUtils.isNumeric(datas[index])){//是数字型时间时格式化
										detail.put(field.getFiledName(), format.format(new Date(Long.parseLong(datas[index].trim()))));
									}else{//字符型时间 2016-06-17 08:02:02
										detail.put(field.getFiledName(), datas[index].trim());
									}
								}else{
									if("NUMBER".equals(fileType)){
										if (StringUtils.isBlank(datas[index])
												|| StringUtil.isRationalNumber(datas[index])) {
											detail.put(field.getFiledName(), datas[index].trim());
										}  else if (datas[index].trim().contains(" days, ")) {
											detail.put(field.getFiledName(), getLongTimeStr(datas[index].trim()));
										} else {
											throw new Exception("NUMBER数据格式错误！");
										}
									}else{
										String length = fileType.replaceAll("VARCHAR2\\((\\d+)\\)", "$1");
										if(Integer.parseInt(length) < datas[index].trim().length()) {
											throw new Exception("VARCHAR2数据格式错误！");
										}
										detail.put(field.getFiledName(), datas[index].trim());
									}
								}
							} catch (Exception e) {
								errorInfo.append(checkType+" 表字段集合信息解析失败；");
								errorInfo.append(field.getFiledName()).append("字段取值")
								.append(datas[index]).append("发生错误；异常数据行：");
								for (String string : datas) { // 添加异常数据
									errorInfo.append(string).append(',');
								}
								errorInfo.deleteCharAt(errorInfo.length()-1);
								//监测数据的详细信息如果和指定的字段类型不匹配，则抛弃此条监测数据，避免影响批量入库
								logger.error("          第一步-1： 旧格式监测数据解析异常： seqId:"+seqId+",setInfoId:"+setInfoId+",checkType:"+checkType+" checkTime:"+new Date(checkTime)+" 监测数据解析异常："+errorInfo);
								return null;
							}
							index++;
						}
					}
					
					detail.put("SEQ_ID", seqId);
					detail.put("DETECTIONED_STATE", state+"");
					detail.put("detection_set_info_id", setInfoId+"");
					detail.put("data_check_time_digital", checkTime+""); // 测试时间
					detail.put("data_check_time", format.format(new Date(checkTime))); // 测试时间				
					detail.put("data_arrive_time_digital", arriveTime.getTimeInMillis()+"");		// 入库时间
					detail.put("data_arrive_time",format.format(arriveTime.getTime()));	// 入库时间
					detaiList.add(detail);
				} catch (Exception e) {
					String s = "详细数据部分解析失败"+e.getMessage();
					logger.warn(s);
				}
			}
	
			int urgentLevel = EmailTypeConstants.URGENT_LATER;
			
			//NMSC 监测失败状态 程序设定为为紧急
			if(state == -1 ){
				if(checkType.equalsIgnoreCase(Constants.DETEC_NMSC_STR)){
					urgentLevel = Constants.DETECT_FAIL_NMSC_POLICE_EMERGENT;
				}else {
					urgentLevel = Constants.DETECT_FAIL_NON_NMSC_POLICE_EMERGENT;
				}
			}
			/*
			 *1.整理告警信息
			 *2.判断告警级别 
			 */
			//根据告警设置，获得当前告警紧急状态:由于之前的处理是当监测状态或者告警级别发生改变时，才发送邮件和根据告警设置来确定是否紧急，当第一次入库就异常时，是否紧急的判断就有问题了，
			String [] nums = showNums.split("\\|");
			String [] levels = pLevel.split("\\|");
			String [] values = pValue.split("\\|");
			List<AlarmInfo> aList = Common.getAlarmInfoMap().get(setInfoId);
			Iterator<AlarmInfo> iteAlarmList = null;
			String cpInfoTmp = "";
			StringBuffer alarmInfo = new StringBuffer();
			if(state == 0){
				int pl0 = 99;
				for(int i = 0 ; i<nums.length ;i++){
					String num = nums[i];
					if(StringUtils.isEmpty(num) || aList == null || aList.size() ==0){
						continue;
					}
					iteAlarmList = aList.iterator();
					while (iteAlarmList.hasNext()) {
						AlarmInfo elem = (AlarmInfo) iteAlarmList.next();
						//判断告警字段和告警级别是否相等
						if(elem.getShowNum().toString().equals(nums[i])){						
							try
							{
								if( pl0>=Integer.parseInt(levels[i].trim())){
									pl0 = Integer.parseInt(levels[i].trim());
									//告警紧急级别随告警级别走
									if(pl0==Constants.LEVEL_OF_EMERGENCY) {
										urgentLevel = EmailTypeConstants.URGENT_IMMEDIATELY;
									}else {
										urgentLevel = EmailTypeConstants.URGENT_LATER;
										
									}
								}
							} catch (Exception e)
							{
								logger.error("旧格式监测数据-修改正告警级别时，解析告警level:"+levels[i]+" 异常", e);
							}
							/** 字段名称 intDate 实际值： 80》60%（临界值） 级别 40 **/	
							String filedName = "";
							String filedComments = "";
							if(tableMap !=null){
								TableColumnsModel tm = tableMap.get(elem.getShowNum());
								filedName = tm==null?"":tm.getFiledName();
								filedComments = tm==null?"":tm.getFiledComments();
							}
							
							cpInfoTmp +=  " "+(StringUtils.isEmpty(elem.getFiledCommonts())?filedName:elem.getFiledCommonts());
							cpInfoTmp +=  " 为："+detail.get(filedName);
							cpInfoTmp +=  ""+(elem.getPoliceUnit()==null ? "" : "null".equals(elem.getPoliceUnit()) ? "" : elem.getPoliceUnit());
							cpInfoTmp +=  "   报警级别："+levels[i];
							cpInfoTmp +=  " \n";
						}
					}
					//如果是握手监测，不添加告警设置字段相关信息
					if(!Constants.DETEC_NMSC_STR.equalsIgnoreCase(checkType)) {
						alarmInfo.append(cpInfoTmp);
					}
				}
			}
			
			detectInfo[DetectInfo.ALARMINFO] = (alarmInfo.toString());
			detectInfo[DetectInfo.URGENTLEVEL] = (urgentLevel);
			detectInfo[DetectInfo.DELYFLAG] = (delyFlag);//用于邮件发送
			detectInfo[DetectInfo.DETAILS] = (detaiList);//用于批量入库详细信息
			
			//特殊追加信息解析--systeminfo-disk、net
			//-- 特殊信息保存整理
			if(Constants.DETEC_SYSTEMINFO_STR.equalsIgnoreCase(checkType) ) {
				while (strsIte.hasNext()) {
					String [] detailsArr = strsIte.next();	//取出 
					if(detailsArr == null || detailsArr.length ==0){	//空行不解析
						continue;
					}
					if(detailsArr.length != 2){	//不是[details:0]格式无法解析
						break;
					}

					if("disk".equalsIgnoreCase(detailsArr[0])){
						List<String[]> infoList = new ArrayList<String[]>();
						int endNum = StringUtils.isEmpty(detailsArr[1])?0:Integer.parseInt(detailsArr[1]);
						disk:while (strsIte.hasNext()) {
							endNum--;
							String [] detailsArr0 = strsIte.next();	//取出
							int len = detailsArr0.length;
							String[] diskInfo = new String[8];
							diskInfo[1] = len>0 ? detailsArr0[0]:"";//盘符
							diskInfo[2] = len>1 ? detailsArr0[1]:"";//大小
							diskInfo[3] = checkTime+"";//监测时间（long）
							diskInfo[4] = format.format(new Date(checkTime));//监测时间（date）
							diskInfo[5] = arriveTime.getTimeInMillis()+"";//录入记录时间（当前时间 long）
							diskInfo[6] = format.format(arriveTime.getTime());//录入记录时间（当前时间 date）
							diskInfo[7] = setInfoId;
							infoList.add(diskInfo);
							if(endNum==0){
								logger.debug("disk解析完成 跳出循环");
								break disk;
							}
						}
						if(infoList.size()>0) {
							detectInfo[DetectInfo.DISKINFOLIST] = (infoList);
						}
					}else if("net".equalsIgnoreCase(detailsArr[0])) {
						List<String[]> infoList = new ArrayList<String[]>();
						int endNum = StringUtils.isEmpty(detailsArr[1])?0:Integer.parseInt(detailsArr[1]);
						net:while (strsIte.hasNext()) {
							endNum--;
							String [] netInfoTmp = strsIte.next();	//取出
							int len = netInfoTmp.length;
							String[] netInfo = new String[13];
							//netInfo[0] = id;
							netInfo[1] = len>0 ? netInfoTmp[0]:"";//网卡名称
							netInfo[2] = len>1 ? netInfoTmp[1]:"";//网卡状态
							netInfo[3] = len>2 ? netInfoTmp[2]:"";//网卡带宽
							netInfo[4] = len>3 ? netInfoTmp[3]:"";//ip
							netInfo[5] = len>4 ? netInfoTmp[4]:"";//子网掩码
							netInfo[6] = len>5 ? netInfoTmp[5]:"";//网关
							netInfo[7] = len>6 ? netInfoTmp[6]:"";//NET_MAC
							netInfo[8] = format.format(new Date(checkTime));//监测时间（date）
							netInfo[9] = format.format(arriveTime.getTime());//录入记录时间（当前时间 date）
							netInfo[10] = checkTime+"";//监测时间（long）
							netInfo[11] = arriveTime.getTimeInMillis()+"";//录入记录时间（当前时间 long）
							netInfo[12] = setInfoId;// id
							infoList.add(netInfo);
							if(endNum ==0){
								break net;
							}
						}
						if(infoList.size()>0) {
							detectInfo[DetectInfo.NETINFOLIST] = (infoList);
						}
					}
				}
			}	
			
		}
		return detectInfo;
	}

	public String resoveErrorInfo(List<NmsErrorInfo> neiList) throws SQLExecuteTimeoutException,SQLException{
		String errorInfo = null;
		String insertSql = "insert into nms_error_info (error_code,error_time,errort_getip,errort_ip,error_state,error_des) values (?,to_date(?,'yyyy-mm-dd hh24:mi:ss'),?,?,?,?)";
		String updateSql = "UPDATE nms_error_info  SET error_state=?,state_update_time=to_date(?,'yyyy-mm-dd hh24:mi:ss') WHERE error_state=1 AND error_code=? AND error_des = ? AND error_time<=to_date(?,'yyyy-mm-dd hh24:mi:ss') and errort_getip=? and errort_ip=?";
		
		List<String[]> paramsList = new LinkedList<String[]>();
		List<String[]> paramsListForUpdate = new LinkedList<String[]>();
		if(neiList != null && neiList.size()>0){
			for(NmsErrorInfo nei : neiList){
//				if(){check info}
//				errorInfo="";
				Long stateTmp = nei.getErrorState();
				if(stateTmp!=null && stateTmp==1l) {//2:恢复，1：异常，0：已解决
					String[] params = new String[] {
							nei.getErrorCode(),
							format.format(nei.getErrorTime()),
							nei.getErrortGetip(),
							nei.getErrortIp(),
							"1",
							nei.getErrortDesc()};
					paramsList.add(params);
				}else {
					String[] params = new String[] {
							(nei.getErrorState() == null ? 0 : nei.getErrorState().intValue())+ "",
							format.format(nei.getErrorTime()),
							nei.getErrorCode(),
							nei.getErrortDesc(),
							format.format(nei.getErrorTime()),
							nei.getErrortGetip(),
							nei.getErrortIp()};
					paramsListForUpdate.add(params);
					
				}
			}
			
			try {
				//以下2个批量更新槽位，执行的顺序不可更改（要先插入异常的信息，再插入恢复的信息）
				dao.dbUpdateByBatch(insertSql, paramsList);//要先插入异常的信息
				dao.dbUpdateByBatch(updateSql, paramsListForUpdate);//再插入恢复的信息
			} catch (SQLExecuteTimeoutException e) {
				dao.rollback();
				throw e;
//			} catch (SQLException e) {
//				e.printStackTrace();
			}finally {
				dao.clearConn();
			}
		}
		return errorInfo;
	}
	/**
	 * "102 days, 8:33:24.19"格式时间转毫秒整形
	 * @time Nov 28, 2012-1:55:29 PM
	 * @param data
	 * @return
	 */
	public static String getLongTimeStr (String data) {
		String[] da = data.split(" days, ");
		if(da.length>1){
			try {
				long date = Long.parseLong(da[0].trim())*24*60*60*1000;		//天-->毫秒
				//System.out.println(da[0].trim()+" "+date);
				String [] da2 = da[1].split(":");
				if(da2.length>=1){
					date += Long.parseLong(da2[0].trim())*60*60*1000;
					//System.out.println(da2[0].trim()+" "+(Long.parseLong(da2[0].trim())*60*60*1000));
				}
				if(da2.length>=2){
					date += Long.parseLong(da2[1].trim())*60*1000;
					//System.out.println(da2[1].trim()+" "+(Long.parseLong(da2[1].trim())*60*1000));
				}
				if(da2.length>=3){
					date += Double.parseDouble(da2[2].trim())*1000;
					//System.out.println(da2[2].trim()+" "+(Double.parseDouble(da2[2].trim())*1000));
				}
				return date+"";
			} catch (Exception e) {
				e.printStackTrace();
				return data;
			}
		}else {
			return data;
		}
	}
	
	public List<NodeModel> getNodeModelListBySetInfo(SetInfo setInfo) {
		
		List<NodeModel> ipList = new LinkedList<NodeModel>();
		//- 单节点 监测
		if(StringUtils.isNotBlank(setInfo.getNodeIp2())){
 			ipList.add(new NodeModel(setInfo.getNodeIp2(),getNodeTypeByIp(setInfo.getNodeIp2())));
		}else
			
		//- 节点IDs 监测
		if(StringUtils.isNotBlank(setInfo.getNodeIpsId())){
//			ipList.addAll(getNodeModelByIds(setInfo.getNodeIpsId()));//根据ip的id获得节点信息-未对ip去重
			ipList.addAll(getNodesByIds(setInfo.getNodeIpsId()));//根据ip的id获得节点信息
		}else
		
		//- 节点组 监测
		if(StringUtils.isNotBlank(setInfo.getNodeGroupsId())){
//			ipList = getNodeModelByGroupIds(setInfo.getNodeGroupsId());//根据节点组id获得节点信息-未对ip去重
			ipList = getNodesByGroupIds(setInfo.getNodeGroupsId());//根据节点组id获得节点信息
		}
		else {//- 全局监测
			ipList = getAllEffectiveNodeInfo();
		}
		
		return ipList;
	}
	
	
	public JSONObject agentInit(String ip) {
		
		if(StringUtils.isEmpty(ip)){//无效ip不做操作
			return null;
		}
		JSONObject jsonObj = new JSONObject();
        try {
            //校验上传目录是否存在
			
        	//1、settings
			try {
				
				boolean agentFlag = true;
				
				//SetInfo
				List<SetInfo> setInfoList = selectSetInfoList(1l, null, Common.getIpSeqIdMap().get(ip), null, null, 1l, null, 0l,agentFlag);
				
				//告警
				List<AlarmInfo> alarmInfoList = selectAlarmInfoBySetIfoList(setInfoList);
				
				//是否启用主动告警
				Boolean startAutoAlarm = selectIsStartAutoAlarm();
				
				//填写Socket数据
				try {
					jsonObj.put("number", Calendar.getInstance().getTimeInMillis());
					jsonObj.put("showAutoAlarm", startAutoAlarm);
					jsonObj.put("setInfo", setInfoList);
					// XXX
					System.out.println("*****");
					System.out.println(jsonObj);
					System.out.println("*****");
					jsonObj.put("alarmInfo", alarmInfoList);
				} catch (JSONException e) {
					logger.error("",e);
				}
			} catch (Exception e1) {
				logger.error("",e1);
			}
        } catch (Exception e) {
        	logger.error("Socket Agent initialization operation 》"+ip+"appears exceptions："+"",e);
        	return null;
        }finally{
        	logger.debug("Socket Agent初始化操作  结束");
    		dao.clearConn();
        }
        
        //- 同步清理 变更记录表信息
        String sql = "delete from event_record_library  where record_type='S2C' and seq_ids=?";
        try {
			dao.dbUpdate(sql,Common.getIpSeqIdMap().get(ip));
		} catch (Exception e) {
			logger.error("同步清理 变更记录表信息 "+ip+" 出现异常",e);
		}
        return jsonObj;
    }
	public List<AlarmInfo> selectAlarmInfoBySetIfoList(List<SetInfo> setInfoList) {
		if(setInfoList==null || setInfoList.size()==0){//无效ip不做操作
			return null;
		}
		ArrayList<AlarmInfo> alarmInfoList = new ArrayList<AlarmInfo>();
        try {
				try {
					ArrayList<String> fields = new ArrayList<String>();
					ArrayList<Map<String,String>> mapList = null;
					Iterator<SetInfo> siIte = setInfoList.iterator();
					StringBuffer ipSb  = new StringBuffer("0");
					while (siIte.hasNext()) {
						SetInfo si = (SetInfo) siIte.next();
						ipSb.append(","+si.getId());
					}
					//告警
					fields.clear();
					fields.add("id");
					fields.add("detection_set_info_id");
					fields.add("check_type_name");
					fields.add("process_iden");
					fields.add("metadata_id");
					fields.add("show_num");
					fields.add("filed_comments");
					fields.add("police_state");
					fields.add("police_value");
					fields.add("police_unit");
					fields.add("police_symbols");
					fields.add("police_level");
					fields.add("marker");
					fields.add("MARKER_FILED_ID");
//					mapList.clear();
					mapList = dao
					.dbSelect(
							"select dpr.id,dpr.detection_set_info_id,cti.check_type_name,dsi.process_iden,dpr.metadata_id,md.show_num,md.filed_comments,dpr.police_state,dpr.police_value,dpr.police_unit,dpr.police_symbols,dpr.police_level,dpr.marker,dpr.MARKER_FILED_ID " +
							"from data_police_relation dpr " +
							"left join metadata md on md.id = dpr.metadata_id " +
							"left join detection_set_info dsi on dsi.id = dpr.detection_set_info_id " +
							"left join check_type_info cti on cti.id = dsi.check_type_id " +
							"where dpr.detection_set_info_id in ("+ipSb+") " +
							"and dpr.police_state=0 " +
							"and lower(cti.check_type_name) not in(lower('"+PING_STR+"'),lower('"+NMSC_STR+"'))" +
							"order by md.show_num, DPR.POLICE_LEVEL ASC",
							fields);
					
					if(mapList!=null && mapList.size()>0){
						Map<Integer,Integer> metadataIdShownumMap= selectAllMetadata();
						for(Map<String,String> map : mapList){
							AlarmInfo info = new AlarmInfo();
							info.setId(StringUtils.isEmpty(map.get("id"))?null:Long.valueOf(map.get("id")));
							info.setSetInfoId(StringUtils.isEmpty(map.get("detection_set_info_id"))?null:Long.valueOf(map.get("detection_set_info_id")));
							info.setCheckType(map.get("check_type_name"));
							info.setProcessIden(map.get("process_iden"));
							info.setMetadataId(StringUtils.isEmpty(map.get("metadata_id"))?null:Long.valueOf(map.get("metadata_id")));
							info.setShowNum(StringUtils.isEmpty(map.get("show_num"))?null:Integer.valueOf(map.get("show_num")));
							info.setFiledCommonts(map.get("filed_comments"));
							info.setPoliceState(map.get("police_state"));
							info.setPoliceValue(map.get("police_value"));
							info.setPoliceUnit(map.get("police_unit"));
							info.setPoliceSysmbols(map.get("police_symbols"));
							info.setPoliceLevel(StringUtils.isEmpty(map.get("police_level"))?null:Integer.valueOf(map.get("police_level")));
							info.setMarker(map.get("marker"));
							info.setMarkerFiledId(StringUtils.isEmpty(map.get("MARKER_FILED_ID"))?null:Integer.valueOf(map.get("MARKER_FILED_ID")));
							info.setMarkerFiledShowNum(metadataIdShownumMap.get(StringUtils.isEmpty(map.get("MARKER_FILED_ID"))?null:Integer.valueOf(map.get("MARKER_FILED_ID"))));
							alarmInfoList.add(info);
						}
					}
				} catch (Exception e1) {
					logger.error("",e1);
				}finally{
					dao.clearConn();
				}
				//填写Socket数据
				return alarmInfoList;
        } catch (Exception e) {
        	logger.error("",e);
        }finally{
    		dao.clearConn();
        }
        return null;
    }
	
	//false:不显示主动告警；true：显示主动告警
	public Boolean selectIsStartAutoAlarm() {		
		Boolean startAutoAlarm = false;//默认不显示
		try {
			ArrayList<String> fields = new ArrayList<String>();
			ArrayList<Map<String,String>> mapList = null;				
			
			fields.clear();
			fields.add("type_state");
			mapList = dao.dbSelect(
					"select t.type_state from type_table t where t.type_identity='showAutoAlarm'",
					fields);
			
			if(mapList!=null && mapList.size()>0){
				String startAutoAlarmStr = mapList.get(0).get("type_state");
				if("0".equals(startAutoAlarmStr)) {//0：启用；1：停用
					startAutoAlarm = true;
				}
			}
		} catch (Exception e1) {
			logger.error("",e1);
		}finally{
			dao.clearConn();
		}
		return startAutoAlarm;
	}
	
	/**
	 * 查询metadata表所有记录，返回id：showNum的map
	 * @author Administrator May 20, 2014
	 * @version 1.0 
	 * @return
	 */
	public Map<Integer,Integer> selectAllMetadata() {
		Map<Integer,Integer> metadataList = new HashMap<Integer,Integer>();
		try {
			ArrayList<Map<String,String>> mapList = null;
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.clear();
			fields.add("id");
			fields.add("show_num");
			mapList = dao.dbSelect(
					" select md.id,md.show_num " +
					" from  metadata md ",
					fields);
			
			if(mapList!=null && mapList.size()>0){
				for(Map<String,String> map : mapList){
					if(StringUtils.isNotBlank(map.get("id")) 
							&& StringUtils.isNotBlank(map.get("show_num"))) {
						metadataList.put(Integer.valueOf(map.get("id")), Integer.valueOf(map.get("show_num")));						
					}
				}
			}
		} catch (Exception e1) {
			logger.error("Querying all records in the metadata table, returning the map exception of id:showNum",e1);
		}finally{
			dao.clearConn();
		}
		return metadataList;
	}
	/**
	 * 
	 * @time Aug 31, 2011-3:55:15 PM
	 */
	public boolean newClientCheck(String ip,Integer snmpVersion){

		try {
			//检查或创建上传目录
			/*File file = new File(Constants.DATA_DIR+File.separator+ip);
			if (!file.exists()) {
				file.mkdirs();
			}*/
			
			//检查或创建临时IP信息
			Long ss = Common.getIpSeqIdMap().get(ip);
			if(ss != null){//已存在
				return false;//跳过
			}
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("node_ip");
			fields.add("seq_id");
			fields.add("snmp_version");
			List<Map<String, String>> list = dao.dbSelect("select nt.node_ip,nt.seq_id,nt.snmp_version from node_table nt where nt.node_ip='"+ip+"' ", fields);
			if(list!=null && list.size()>0){	//已存在 将节点添加到Map
				if(StringUtils.isNotEmpty(list.get(0).get("seq_id"))){
					
					Common.getIpSeqIdMap().put(ip, Long.parseLong(list.get(0).get("seq_id")));
					Common.putSimpleNode(Long.parseLong(list.get(0).get("seq_id")), new SimpleNode(list.get(0).get("node_ip"),StringUtils.isNotEmpty(list.get(0).get("snmp_version"))?Integer.parseInt(list.get(0).get("snmp_version")):null));
					
					return true;
				}
			}
			logger.info("发现新节点:> "+ip+" 临时数据保存");
			Long groupId = getDefaultNodeGroup();
			SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
			Long seqId = getSeqIdIpByNodeIp(ip);
			Map<String, String> info = new HashMap<String, String>();
			info.put("node_id", "");
			info.put("node_ip", ip);
			info.put("node_type", "0");
//			info.put("node_name", "新节点_"+Calendar.getInstance().getTimeInMillis());
			info.put("node_name", "New node_"+Calendar.getInstance().getTimeInMillis());
			info.put("node_state", "0");
			info.put("NODE_GROUP_ID", groupId+"");
			info.put("node_createtime", format.format(Calendar.getInstance().getTime()));
			info.put("is_temp", "0");
			info.put("seq_id", seqId+"");
			info.put("ipn", IpCovert.ipToLong(ip)+"");
			dao.insertObj("node_table", info);
			dao.commit();
			Common.getIpSeqIdMap().put(ip, seqId);
			Common.putSimpleNode(seqId, new SimpleNode(ip,snmpVersion)); //- 此处业务上是否存在问题 snmp_version 为空
			return true;
		} catch (Exception e) {
			logger.error("",e);
			return false;
		}finally{
			dao.clearConn();
		}
	}
	
	/**
	 * 获取 默认节点组 ID
	 * 用于新节点注册入库时关联到该节点组
	 * @time Jan 7, 2013-3:46:31 PM
	 * @return
	 */
	public Long getDefaultNodeGroup(){
		String nodeGroupName = Constants.DEFAULT_NODE_GROUP_NAME;
		Long groupId = null;
		StringBuffer ngtSql = new StringBuffer("select ngt.group_id from nodegroup_table ngt where ngt.group_name='"+nodeGroupName+"' and ngt.is_valid ='1' and nvl(ngt.group_id,-999)<>-999 order by ngt.group_id asc");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("group_id");
		try {
			ArrayList<Map<String, String>>  mapsList = dao.dbSelect(ngtSql.toString(),fields);
			if(mapsList!=null && mapsList.size()>0){
				String groupIdStr = mapsList.get(0).get("group_id");
				groupId = StringUtils.isBlank(groupIdStr)?null:Long.parseLong(groupIdStr);
			}
			
			//节点组ID为空时，生成新的默认节点组，
			if(groupId==null){
				Map<String, String> info = new HashMap<String, String>();
				info.put("GROUP_NAME", nodeGroupName);
				info.put("VIEW_LEVEL", "4");
				info.put("GROUP_TYPE", "0");
//				info.put("GROUP_DESC", "存放自动注册的新节点信息的默认节点组");
//				info.put("GROUP_DESC", "Default node group for automatically registering new node information");
				info.put("GROUP_DESC", "i18n_server.CommonService.saveDefault_n81i");
				info.put("IS_VALID", "1");
				info.put("GROUP_CREATETIME", format.format(Calendar.getInstance().getTime()));
				info.put("PARENT_GROUP_ID", "0");
				info.put("LEAF_GROUP", "1");
				info.put("GROUP_LEVEL", "1");
				info.put("SHOW_INDEX", "0");
				dao.insertObj("nodegroup_table", info);
				
				mapsList = dao.dbSelect(ngtSql.toString(),fields);
				if(mapsList!=null && mapsList.size()>0){
					String groupIdStr = mapsList.get(0).get("group_id");
					groupId = StringUtils.isBlank(groupIdStr)?null:Long.parseLong(groupIdStr);
				}
			}
			
		} catch (Exception e) {
			logger.error("查询 默认节点组异常",e);
		}
		return groupId;
	}
	
	public void updateSeqIdByNodeIp(Map<String, Long> map,String nodeIp){
		StringBuffer sql = new StringBuffer();
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("node_ip");
		fields.add("seq_id");
		sql.append("select distinct nt.node_ip,nt.seq_id from node_table nt where 1=1 ");
		if(StringUtils.isNotEmpty(nodeIp)){
			sql.append("and nt.node_ip='"+nodeIp+"'");
		}
		try {
			ArrayList<Map<String, String>>  mapsList = this.dao.dbSelect(sql.toString(), fields);
			if(mapsList!=null && mapsList.size()>0){
				for (Map<String, String> obj : mapsList) {
					if(StringUtils.isNotEmpty(obj.get("node_ip")) && StringUtils.isNotEmpty(obj.get("seq_id"))){
						map.put(obj.get("node_ip"), Long.parseLong(obj.get("seq_id")));
//						map.put(Long.parseLong(obj.get("seq_id")), new String[]{obj.get("node_ip"),obj.get("snmp_version")});
					}
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	
	public void updateUserPwdByNodeIp(Map<String, String[]> ipNodeMap,String nodeIp) {
		logger.debug("更新节点用户名密码信息。。。");
		StringBuffer sql= new StringBuffer();		
		sql.append("select distinct NODE_IP,NODE_USERNAME,NODE_PASSWORD,NODE_SYSTEM_TYPE from node_table t left join nodegroup_table ngt on ngt.group_id = t.node_group_id where t.node_state='0' and ngt.is_valid ='1' and t.node_type='0'  ");
		if(StringUtils.isNotBlank(nodeIp)){
			sql.append("and t.node_ip='"+nodeIp+"'");
		}else {
			sql.append(getIpnSelect());//不指定IP时，只查询当前DC管理的节点信息
		}
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("NODE_IP");
		fields.add("NODE_USERNAME");
		fields.add("NODE_PASSWORD");
		fields.add("NODE_SYSTEM_TYPE");
		try {
			List<Map<String, String>> sid = dao.dbSelect(sql.toString(), fields);
			if(sid!=null&&sid.size()>0){
				BASE64Decoder decoder = new BASE64Decoder();
				for(Map<String, String> map : sid){
					String[] ipInfo = new String[3];
					ipInfo[0] = map.get("NODE_USERNAME");
					String passward = map.get("NODE_PASSWORD");
					if(StringUtils.isNotBlank(passward)){
						passward = new String(decoder.decodeBuffer(passward));
						ipInfo[1] = passward;
					}
					ipInfo[2] = map.get("NODE_SYSTEM_TYPE");
					ipNodeMap.put(map.get("NODE_IP"), ipInfo);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("Query node username and password failed",e);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("Query node username and password failed",e);
		}finally{
			if(dao != null){
				dao.clearConn();//清空连接，但是不关闭
			}
		}
		
	}
	public void updateSimpleNodeByUUID(Long seqId){
		StringBuffer sql = new StringBuffer();
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("node_ip");
		fields.add("seq_id");
		fields.add("snmp_version");
		sql.append("select distinct nt.node_ip,nt.seq_id,nt.snmp_version from node_table nt where 1=1 ");
		if(seqId != null){
			sql.append("and nt.seq_id='"+seqId.longValue()+"'");
		}
		try {
			ArrayList<Map<String, String>>  mapsList = this.dao.dbSelect(sql.toString(), fields);
			if(mapsList!=null && mapsList.size()>0){
				for (Map<String, String> obj : mapsList) {
					if(StringUtils.isNotEmpty(obj.get("node_ip")) && StringUtils.isNotEmpty(obj.get("seq_id"))){
						Common.putSimpleNode(Long.parseLong(obj.get("seq_id")), new SimpleNode(obj.get("node_ip"),StringUtils.isNotEmpty(obj.get("snmp_version"))?Integer.parseInt(obj.get("snmp_version").trim()):null));
					}else{
						long aa = getSeqIdIpByNodeIp(obj.get("node_ip"));
						dao.dbUpdate("update node_table nt set nt.seq_id='"+aa+"' where nt.node_ip='"+obj.get("node_ip")+"'");
					}
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	private Long getSeqIdIpByNodeIp (String nodeIp) {
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("node_ip");
		fields.add("seq_id");
		List<Map<String, String>> list;
		try {
			list = dao.dbSelect("select nt.node_ip,nt.seq_id from node_table nt where nt.node_ip='"+nodeIp+"' ", fields);
			if(list!=null && list.size()>0){	//已存在
				if(StringUtils.isNotEmpty(list.get(0).get("seq_id"))){
					return Long.parseLong(list.get(0).get("seq_id"));
				}else{
					fields.remove("node_ip");
					list = dao.dbSelect("select seq_seq_id.nextval seq_id from dual", fields);
					return Long.parseLong(list.get(0).get("seq_id"));//跳过
				}
			}else{
				fields.remove("node_ip");
				list = dao.dbSelect("select seq_seq_id.nextval seq_id from dual", fields);
				return Long.parseLong(list.get(0).get("seq_id"));//跳过
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return null;
	}
	
	/**
	 * 初始化DC 自身参数
	 * @time Jan 8, 2013-1:11:33 PM
	 * @param dao
	 * @return
	 */
	public boolean initServerParams() {

		String localIp = Common.getLocalIp();
		
		//无法获取
		if(StringUtils.isEmpty(localIp)){
			logger.error("Failure to read local IP update DC parameter information");
			return false;
		}
		
		try {
			ServerTable serverTable = getNMSServerParams(localIp);
			if(serverTable!=null 
					&& serverTable.getId() !=null 
					&& serverTable.getIpSegList() != null
					&& serverTable.getIpSegList().size() >0){
				Common.setServerTable(serverTable);
				logger.info("DC 参数信息更新");
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			logger.error("DC 参数信息查询失败",e);
			return false;
		}finally{
			dao.clearConn();
		}
	}
	
	//统计 监测数据 或者 告警数据 表: 监测设置<->已有有效数据的seqid
	public Map<String,String[]> getDetectSeq(String tableName){// detection_info_new
		String querySeqidSql="select distinct t.seq_id from node_table t left join nodegroup_table ngt on ngt.group_id = t.node_group_id where t.node_state='0' and ngt.is_valid ='1' and t.node_type='0' "+" "+getIpnSelect();
		String sql = "select t.detection_set_info_id detSetId ,t.seq_id seqIds" +
					" from ("+querySeqidSql+") s left join "+tableName+" t  on t.seq_id = s.seq_id " +//只更新本dc管理的监测数据
					" where t.valid=1" ;//"只查询有效的记录
		Map<String,String[]> detectSetSeqIdsMap = new HashMap<String,String[]>();
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("detSetId");
		fields.add("seqIds");
		try {
			ArrayList<Map<String, String>>  mapsList = dao.dbSelectByFetchSize(sql,fields);
			if(mapsList!=null && mapsList.size()>0){
				Map<String,String> tempMap = new HashMap<String,String>();
				for (Map<String, String> obj : mapsList) {
					String detSetId = obj.get("detSetId");
					String seqId = obj.get("seqIds")==null?"":obj.get("seqIds");
					if(tempMap.get(detSetId)!=null){
						String ids = tempMap.get(detSetId);
						if(!ids.contains(","+seqId+",")){
							tempMap.put(detSetId, ids+seqId+",");
						}
					}else{
						if(!StringUtils.isBlank(detSetId)) {
							tempMap.put(detSetId,","+seqId+",");
						}
					}
				}
				for (Map.Entry<String, String> entry : tempMap.entrySet()) {
					if(entry.getValue().length()>1){
						String val = entry.getValue().substring(1, entry.getValue().length()-1);
						String[] arr = val.split(",");
						Arrays.sort(arr);
						detectSetSeqIdsMap.put(entry.getKey(),arr);
					}
				}
			}
		} catch (Exception e) {
			logger.error("In the statistical monitoring data table, monitoring settings: SEQID anomalies with valid data",e);
		}
		return detectSetSeqIdsMap;
	}
	
	//查询节点组非空的有效监测设置信息
	public Map<String,String> getDetectSetInfo(){
		String sql = " select dsi.id id,dsi.node_groups_id nodeGroupsId,dsi.node_ips_id nodeIpsId" +
		" from detection_set_info dsi" +
		" where dsi.node_groups_id is not null " + 
		" and dsi.detection_set_state='1'";
		Map<String,String> detectSetSeqIdsMap = new HashMap<String,String>();
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("nodeGroupsId");
		fields.add("nodeIpsId");
		try {
			ArrayList<Map<String, String>>  mapsList = dao.dbSelect(sql,fields);
			if(mapsList!=null && mapsList.size()>0){
			    Map<String,Object> allData = this.getAllNodeTableData();
				//获取所有节点组对应的seq_id
				Map<String,List<String>> groupSeq =(Map<String,List<String>>) allData.get("group");
				//获取所有 节点 对应的seq_id
				Map<String,String> nodeSeq = (Map<String,String>) allData.get("node");
				for (Map<String, String> obj : mapsList) {
					String id = obj.get("id");
					String nodeIpsId = obj.get("nodeIpsId");
					String nodeGroupsId = obj.get("nodeGroupsId");
					String seqIds = this.getDetecSetSeq(nodeGroupsId, nodeIpsId, groupSeq, nodeSeq);
					detectSetSeqIdsMap.put(id, seqIds);
				}
			}
			
		} catch (Exception e) {
			logger.error("Invalid non valid monitoring settings information for query node group",e);
		}
		return detectSetSeqIdsMap;
	}
	/**
	 * 获取 指定的 nodeIds 或 nodeGroupIds 对应的 seq_id eg:21,23,34
	 * @param nodeGroupsId 
	 * @param nodeIpsId
	 * @param groupSeq
	 * @param nodeSeq
	 * @return seq_id eg:21,23,34...
	 */
	public String getDetecSetSeq(String nodeGroupsId,String nodeIpsId,Map<String,List<String>> groupSeq,Map<String,String> nodeSeq){
		StringBuilder result = new StringBuilder();
		if(StringUtils.isNotBlank(nodeIpsId)){//如果指定nodeId ,则查找对应的seqId
			String[] nodeIds = nodeIpsId.split(",");
			for(String temp :nodeIds){
				if(StringUtils.isNotBlank(nodeSeq.get(temp.trim()))){
					result.append(","+nodeSeq.get(temp.trim()));
				}
			}
		}else if (StringUtils.isNotBlank(nodeGroupsId)) {//如果没有指定nodeId ,指定nodeGroupId则查找节点组下的所有seqId
			String[] groupIds = nodeGroupsId.split(",");
			for(String temp :groupIds){
				List<String> tempList = groupSeq.get(temp.trim());
				if(tempList != null && tempList.size() > 0){
					for(String tempSeqId : tempList){
						result.append(","+tempSeqId);
					}
				}
			}
		}else{//nodeId 和nodegroupId 都没有则 查找所有 seqId
			for(Map.Entry<String, String> temp : nodeSeq.entrySet()){
				result.append("," + temp.getValue());
			}
		}
		if(result.length()>1){
			result.deleteCharAt(0);//删除第一个","
		}
		return  result.toString();
	}
	
	/**
	 * 查询node_table表的所有数据,组织成nodeid --seqId 和 groupid -- seqId 两个map
	 * @return
	 */
	public Map<String,Object> getAllNodeTableData(){
		Map<String,Object> result = null;
		Map<String,String> nodeSeq = null;
		Map<String,List<String>> groupSeq = null;
		/*
		 * 根据节点id和节点组id，获得有效的seqId，并用逗号连接:1,2,3,5
		 *    1. 去掉对节点是否有效的过滤: 
		 *       因为如果当前监测设置包含节点A，而此时将节点A下线，此时DC端录入监测数据时，
		 *       就会将所有的数据置为无效，而当上线节点后，再去查看，节点仍是无效，
		 *       因为在节点上线和下线操作时，不对监测数据的有效性进行修改
		 *    2. 如果节点下线后，又上线了，此时只会显示新录入的监测数据，之前的旧数据就不会显示了？？要想显示之前旧的数据，只能从web端先去掉下线过的节点，再添加上
		 */
		String sql = "select nt.node_id nodeId , nt.seq_id seqId ,nt.node_group_id nodeGroupId from node_table nt ";
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("nodeId");
		fields.add("seqId");
		fields.add("nodeGroupId");
		try {
			List<Map<String, String>> mapList = dao.dbSelect(sql,fields);
			if(mapList != null && mapList.size() > 0){
				nodeSeq = new HashMap<String, String>();
				groupSeq = new HashMap<String, List<String>>();
				for(Map<String,String> temp : mapList){
					String nodeId = temp.get("nodeId");
					String seqId = temp.get("seqId");
					String nodeGroupId = temp.get("nodeGroupId");
					nodeSeq.put(nodeId, seqId);//nodeId -- seqId
					if(StringUtils.isNotBlank(nodeGroupId)){
						if(groupSeq.get(nodeGroupId) == null){//第一次添加
							List<String> tempList = new ArrayList<String>();
							tempList.add(seqId);
							groupSeq.put(nodeGroupId, tempList);
						}else{
							groupSeq.get(nodeGroupId).add(seqId);
						}
					}
				}
				result = new HashMap<String, Object>();
				result.put("node", nodeSeq);
				result.put("group", groupSeq);
			}
		} catch (Exception e) {
			logger.error("Query all record exceptions of the node_table table",e);
		}
		return result;
	}
	
	
	/**
	 * 获取所有节点组id 对应的节点seq_Id
	 * @return
	 */
	public Map<String,List<String>> getAllNodeGroupSeqId(){
		Map<String,List<String>> result = null;
		String sql = "select ngt.group_id groupId, nt.seq_id  seqId from node_table nt left join nodegroup_table ngt on ngt.group_id = nt.node_group_id order by ngt.group_id";
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("groupId");
		fields.add("seqId");
		try {
			ArrayList<Map<String, String>>  mapsList = dao.dbSelect(sql,fields);
			String nodeGroupId = null;
			String seqId = null;
			List<String> temp = null;
			if(mapsList != null && mapsList.size() > 0){
				result = new HashMap<String, List<String>>();
				for (Map<String, String> obj : mapsList) {
					nodeGroupId = obj.get("groupId");
					seqId = obj.get("seqId");
					temp = result.get(nodeGroupId);
					if(temp != null){
						temp.add(seqId);
					}else{
						temp = new ArrayList<String>();
						temp.add(seqId);
						result.put(nodeGroupId, temp);
					}
					temp = null;
				}
			}
		} catch (Exception e) {
			logger.error("Query the node seqid exception corresponding to all node groups",e);
		}
		return result;
	}
	/**
	 * 获取所有 nodeId 对应的 seqID
	 * @return
	 */
	public Map<String,String> getAllNodeIdSeqId(){
		Map<String,String> result = null;
		String sql = "select nt.node_id nodeId , nt.seq_id seqId  from node_table nt order by nt.node_id";
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("nodeId");
		fields.add("seqId");
		try {
			ArrayList<Map<String, String>>  mapsList = dao.dbSelect(sql,fields);
			String nodeId = null;
			String seqId = null;
			if(mapsList != null && mapsList.size() > 0){
				result = new HashMap<String, String>();
				for (Map<String, String> obj : mapsList) {
					nodeId = obj.get("nodeId");
					seqId = obj.get("seqId");
					result.put(nodeId, seqId);
				}
			}
		} catch (Exception e) {
			logger.error("Query the node seqid exception corresponding to all node groups",e);
		}
		return result;
	}
	
	/*
	 * 根据节点id和节点组id，获得有效的seqId，并用逗号连接:1,2,3,5
	 *    1. 去掉对节点是否有效的过滤: 
	 *       因为如果当前监测设置包含节点A，而此时将节点A下线，此时DC端录入监测数据时，
	 *       就会将所有的数据置为无效，而当上线节点后，再去查看，节点仍是无效，
	 *       因为在节点上线和下线操作时，不对监测数据的有效性进行修改
	 *    2. 如果节点下线后，又上线了，此时只会显示新录入的监测数据，之前的旧数据就不会显示了？？要想显示之前旧的数据，只能从web端先去掉下线过的节点，再添加上
	 */
	public String getValidSeq(String ipIds,String groupIds) {
		String seqIds = "";
		try{
			String sql = "";
			if(ipIds!=null && !"".equals(ipIds.trim())) {//节点非空
				sql=" select distinct t.seq_id seqIds" +
							" from node_table t " +
							" where t.node_id in ("+ipIds+") ";
//							" and t.node_state='0' ";//有效节点
				
			}else if(groupIds!=null && !"".equals(groupIds.trim())) {//节点空，节点组非空
				sql=" select distinct t.seq_id seqIds" +
							" from node_table t " +
							" where t.node_group_id in ("+groupIds+") ";
//							" and t.node_state='0' ";//有效节点
							
			}else {//全局节点-没有业务系统的限制
				sql=" select distinct t.seq_id seqIds" +
							" from node_table t ";
//							" where  t.node_state='0' ";//有效节点
			}
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("seqIds");
			ArrayList<Map<String, String>>  mapsList = dao.dbSelect(sql,fields);
			String str = ",";
			for(Map<String, String> map :mapsList){
				String seqId = map.get("seqIds");
				if(!StringUtils.isBlank(seqId)&&!str.contains(","+seqId+",")){
					str =str+seqId+",";
				}
			}
			if(str.length()>1){
				seqIds = str.substring(1, str.length()-1);
			}else{
				seqIds ="";
			}
		}catch(Exception e) {
			logger.error("According to node ID and node group ID, get valid seqId, and use comma to connect exceptions",e);
		}
		return seqIds;
	}
	
	/**
	 * 查询库表中所有的节点信息
	 * @time Jan 8, 2013-1:11:33 PM
	 * @param dao
	 * @return
	 */
	/*public  boolean initServerParams(CommonDao dao) {
		CommonService service = new CommonService(dao);
		String localIp = Common.getLocalIp();
		
		//无法获取
		if(StringUtils.isEmpty(localIp)){
			return false;
		}
		
		try {
			ServerTable serverTable = service.getNMSServerParams(localIp);
			if(serverTable!=null 
					&& serverTable.getId() !=null 
					&& serverTable.getIpSegList() != null
					&& serverTable.getIpSegList().size() >0){
				Common.setServerTable(serverTable);
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			logger.error("DC 参数信息查询失败",e);
			return false;
		}
	}*/
/*	public static void main(String [] args) {
		CommonDao dao = new CommonDao();
		CommonService service = new CommonService(dao);
		service.newClientCheck("192.168.1.189", 3);
	}*/
	/**
	 * detection_info addbatch
	 * @param id
	 * @param infoStmt
	 * @param temInfo
	 * @throws SQLException
	 */
	
	public void addInfoStmt(long id,Object[] temInfo)
			throws SQLException {
		boolean useSequnce= Common.SEQUENCE.get(DetectInfo.DETECTION_INFO)==null?true:false;
		//插入info表
		String insertInfoSql = "";
		if(useSequnce){
			insertInfoSql = "INSERT INTO DETECTION_INFO (ID, DETECTION_SET_INFO_ID, DETECTION_STATE_INFO, " +
					"PERFORMACE_DATA, CURRENT_TIMES, START_TIME, DELAY_TIME, NEXT_CHECK_TIME, " +
					"POLICE_LEVEL, DATA_CHECK_TIME, DATA_ARRIVE_TIME, DETECTIONED_STATE, " +
					"DATA_CHECK_TIME_DIGITAL, DATA_ARRIVE_TIME_DIGITAL, SEQ_ID, POLICE_EMERGENT,SEQUENCE)"
					+" VALUES (?, ?, ?, ?, ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, ?, ?, ?, ?,?)";
		}else{
			insertInfoSql = "INSERT INTO DETECTION_INFO (ID, DETECTION_SET_INFO_ID, DETECTION_STATE_INFO, " +
					"PERFORMACE_DATA, CURRENT_TIMES, START_TIME, DELAY_TIME, NEXT_CHECK_TIME, " +
					"POLICE_LEVEL, DATA_CHECK_TIME, DATA_ARRIVE_TIME, DETECTIONED_STATE, " +
					"DATA_CHECK_TIME_DIGITAL, DATA_ARRIVE_TIME_DIGITAL, SEQ_ID, POLICE_EMERGENT)"
					+" VALUES (?, ?, ?, ?, ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, ?, ?, ?, ?)";
		}
		
		List<String[]> infoParameter = new ArrayList<String[]>();		
		try{
			String[] params = new String[] {
					id+"",
					(String) temInfo[DetectInfo.SETINFOID],
					(String) temInfo[DetectInfo.DSINFO],
					(String) temInfo[DetectInfo.PDATA],
					temInfo[DetectInfo.CURRENTTIMES]+"",
					temInfo[DetectInfo.STARTTIME] != null ? format.format(new Date((Long)temInfo[DetectInfo.STARTTIME])) : null,
					temInfo[DetectInfo.DELAYTIME]+"",
					temInfo[DetectInfo.NEXTCHECKTIME] != null ? format.format(new Date((Long)temInfo[DetectInfo.NEXTCHECKTIME])) : null,
					temInfo[DetectInfo.PLEVEL]+"",
					temInfo[DetectInfo.CHECKTIME] != null ? format.format(new Date((Long)temInfo[DetectInfo.CHECKTIME])) : null,
					temInfo[DetectInfo.ARRIVETIME] != null ? format.format(new Date((Long)temInfo[DetectInfo.ARRIVETIME])) : null,
					temInfo[DetectInfo.STATE]+"",
					temInfo[DetectInfo.CHECKTIME] +"",
					temInfo[DetectInfo.ARRIVETIME]+"",
					(String) temInfo[DetectInfo.SEQID],
					temInfo[DetectInfo.URGENTLEVEL]+"",
					Common.SEQUENCE.get(DetectInfo.DETECTION_INFO)==null?null:Common.SEQUENCE.get(DetectInfo.DETECTION_INFO).incrementAndGet()+""
					};	
			if(!useSequnce){
				params=Arrays.copyOf(params, params.length-1);
			}
			infoParameter.add(params);
			dao.addRecordToInfo(insertInfoSql,infoParameter);
		} catch (Exception e){
			logger.error("          Third step -1: adding alarm information exception：sql："+insertInfoSql+"  ;  value:"
				+id+", "+temInfo[DetectInfo.SETINFOID]+", "+temInfo[DetectInfo.DSINFO]+", "
				+temInfo[DetectInfo.PDATA]+", "+temInfo[DetectInfo.CURRENTTIMES]+", "+temInfo[DetectInfo.STARTTIME]+", "
				+temInfo[DetectInfo.DELAYTIME]+", "+temInfo[DetectInfo.NEXTCHECKTIME]+", "+temInfo[DetectInfo.PLEVEL]+", "
				+temInfo[DetectInfo.CHECKTIME]+", "+temInfo[DetectInfo.ARRIVETIME]+", "+temInfo[DetectInfo.STATE]+", "
				+temInfo[DetectInfo.CHECKTIME]+", "+temInfo[DetectInfo.ARRIVETIME]+", "+temInfo[DetectInfo.SEQID]+", "
				+temInfo[DetectInfo.URGENTLEVEL]+", ", e);

		}
		
	}
	
	/**
	 * email信息addbatch
	 * @param emailStmt
	 * @param emailInfo
	 * @param tempAddress
	 * @throws SQLException
	 */
	public void addEmailStmt(EmailInfo emailInfo,String tempAddress) throws SQLException {
		
		//插入email_table表
		String insertEmailSql = " insert into email_table (to_address,action_type,content,send_flag,action_ip,action_date,action_desc,send_level,CREATE_TIME)" +
				" values(?,?,?,?,?,to_date(?,'yyyy-mm-dd hh24:mi:ss'),?,?,to_date(?,'yyyy-mm-dd hh24:mi:ss'))";
		List<String[]> infoParameter = new ArrayList<String[]>();		
		String[] params = new String[] {
				tempAddress,
				emailInfo.getActionType()+"",
				emailInfo.getContent()+"",
				emailInfo.getSendFlag()+"",
				emailInfo.getActionIp(),
				emailInfo.getActionDate(),
				emailInfo.getActionDesc(),
				emailInfo.getSendLevel() +"",
				DateUtil.getCurrentTime()				
				};	
		infoParameter.add(params);
		dao.addRecordToEmail(insertEmailSql,infoParameter);
	}
	
	public void addStateChangeStmt(long statusChangeTime,String seqId) throws SQLException {
		
		//插入email_table表
		String sqlUpdateStatusChangeTime = "update detection_info_new din set din.status_change_time =to_date(?,'yyyy-mm-dd hh24:mi:ss')  where din.seq_id=?";
		
		List<String[]> infoParameter = new ArrayList<String[]>();	
		
		String[] params = new String[] {
				format.format(new Date(statusChangeTime)),
				seqId
				};	
		infoParameter.add(params);
		dao.addRecordToStatusChange(sqlUpdateStatusChangeTime,infoParameter);
	}

	/**
	 * 特殊追加信息net addbatch
	 * @param currentId
	 * @param netStmt
	 * @param temNetInfo
	 * @throws SQLException
	 * @throws ParseException
	 */
	public void addNetStmt(long currentId,  
			String[] temNetInfo) throws SQLException, ParseException {
		
		//特殊格式追加 net
		String netSql = " insert into di_systeminfo_net (detection_info_id,net_name,net_state," +
				" net_speed,net_ip,net_submask,net_gateway,NET_MAC," +
				" data_check_time,data_arrive_time," +
				" data_check_time_digital,data_arrive_time_digital,DETECTION_SET_INFO_ID) " +
				" values (?,?,?,?,?,?,?,?,to_date(?,'yyyy-mm-dd hh24:mi:ss'),to_date(?,'yyyy-mm-dd hh24:mi:ss'),?,?,?) ";
		List<String[]> infoParameter = new ArrayList<String[]>();		
		String[] params = new String[] {
				currentId+"",
				temNetInfo[1],//网卡名称
				temNetInfo[2],//网卡状态
				temNetInfo[3],//网卡带宽
				temNetInfo[4],//ip
				temNetInfo[5],//子网掩码
				temNetInfo[6],//网关
				temNetInfo[7],//NET_MAC
				temNetInfo[8],//监测时间(date)
				temNetInfo[9],//录入记录时间（当前时间 date）
				temNetInfo[10],//监测时间（long）
				temNetInfo[11],//录入记录时间（当前时间 long）
				temNetInfo[12]//setInfoId
				};	
		infoParameter.add(params);
		dao.addRecordToNet(netSql,infoParameter);		
	}

	/**
	 * 特殊追加信息disk addbatch
	 * @param currentId
	 * @param diskStmt
	 * @param temDiskInfo
	 * @throws SQLException
	 * @throws ParseException
	 */
	public void addDiskStmt(long currentId, 
			String[] temDiskInfo) throws SQLException, ParseException {
		//特殊格式追加 disk
		String diskSql = " insert into di_systeminfo_disk (detection_info_id,disk_rang,disk_size," +
				" data_check_time_digital,data_check_time," +
				" data_arrive_time_digital,data_arrive_time,DETECTION_SET_INFO_ID) " +
				" values (?,?,?,?,to_date(?,'yyyy-mm-dd hh24:mi:ss'),?,to_date(?,'yyyy-mm-dd hh24:mi:ss'),?) ";
		List<String[]> infoParameter = new ArrayList<String[]>();		
		String[] params = new String[] {
				currentId+"",
				temDiskInfo[1],//盘符
				temDiskInfo[2],//大小
				temDiskInfo[3],//监测时间(long)
				temDiskInfo[4],//监测时间(date)
				temDiskInfo[5],//（当前时间 long）
				temDiskInfo[6],//录入记录时间（当前时间 date）
				temDiskInfo[7]//setInfoId
				};	
		infoParameter.add(params);
		dao.addRecordToDisk(diskSql,infoParameter);		
	}

	/**
	 * 告警信息 addbatch
	 * @param currentId
	 * @param warningStmt
	 * @param temInfo
	 * @throws SQLException
	 */
	
	public void addWarningStmt(String currentId, 
			Object[] temInfo){
		//插入warning表
		String insertWaringSql = "INSERT INTO DETECTION_INFO_WARNING (ID, DETECTION_SET_INFO_ID, DETECTION_STATE_INFO, " +
				"PERFORMACE_DATA, CURRENT_TIMES, START_TIME, DELAY_TIME, NEXT_CHECK_TIME, " +
				"POLICE_LEVEL, DATA_CHECK_TIME, DATA_ARRIVE_TIME, DETECTIONED_STATE, " +
				"DATA_CHECK_TIME_DIGITAL, DATA_ARRIVE_TIME_DIGITAL, SEQ_ID, POLICE_EMERGENT)"
				+" VALUES (?, ?, ?, ?, ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, ?, ?, ?, ?)";
		try
		{
			List<String[]> infoParameter = new ArrayList<String[]>();		
			String[] params = new String[] {
					currentId+"",
					(String) temInfo[DetectInfo.SETINFOID],
					(String) temInfo[DetectInfo.DSINFO],
					(String) temInfo[DetectInfo.PDATA],
					temInfo[DetectInfo.CURRENTTIMES]+"",
					temInfo[DetectInfo.STARTTIME] != null ? format.format(new Date((Long)temInfo[DetectInfo.STARTTIME])) : null,
					temInfo[DetectInfo.DELAYTIME]+"",
					temInfo[DetectInfo.NEXTCHECKTIME] != null ? format.format(new Date((Long)temInfo[DetectInfo.NEXTCHECKTIME])) : null,
					temInfo[DetectInfo.PLEVEL]+"",
					temInfo[DetectInfo.CHECKTIME] != null ? format.format(new Date((Long)temInfo[DetectInfo.CHECKTIME])) : null,
					temInfo[DetectInfo.ARRIVETIME] != null ? format.format(new Date((Long)temInfo[DetectInfo.ARRIVETIME])) : null,
					temInfo[DetectInfo.STATE]+"",
					temInfo[DetectInfo.CHECKTIME] +"",
					temInfo[DetectInfo.ARRIVETIME]+"",
					(String) temInfo[DetectInfo.SEQID],
					temInfo[DetectInfo.URGENTLEVEL]+""
					};
			
			infoParameter.add(params);
			dao.addRecordToWarning(insertWaringSql,infoParameter);
		} catch (Exception e)
		{
			logger.error("          Third step -1: adding alarm information exception：sql："+insertWaringSql+"  ;  value:"
					+currentId+", "+temInfo[DetectInfo.SETINFOID]+", "+temInfo[DetectInfo.DSINFO]+", "
					+temInfo[DetectInfo.PDATA]+", "+temInfo[DetectInfo.CURRENTTIMES]+", "+temInfo[DetectInfo.STARTTIME]+", "
					+temInfo[DetectInfo.DELAYTIME]+", "+temInfo[DetectInfo.NEXTCHECKTIME]+", "+temInfo[DetectInfo.PLEVEL]+", "
					+temInfo[DetectInfo.CHECKTIME]+", "+temInfo[DetectInfo.ARRIVETIME]+", "+temInfo[DetectInfo.STATE]+", "
					+temInfo[DetectInfo.CHECKTIME]+", "+temInfo[DetectInfo.ARRIVETIME]+", "+temInfo[DetectInfo.SEQID]+", "
					+temInfo[DetectInfo.URGENTLEVEL]+", ", e);

		}
		
	}
	
	/**
	 * 获取detection_info sequenceid 和 increment_by
	 * @return
	 */
	public long[] getDetectionInfoSequenceID(){
		long[] result = new long[2];
		try {
			String searchIdSql = null;
			if(Constants.IS_MYSQL){
				searchIdSql = "select  t.INCREMENT ival from sys_sequence t where t.name = 'SEQ_DETECTION_INFO'";
				ArrayList<String> fields = new ArrayList<String>();
				fields.add("ival");
				List<Map<String, String>> sid = dao.dbSelect(searchIdSql, fields);
				if(sid!=null && sid.size()>0){
					result[1] = Long.parseLong(sid.get(0).get("ival"));
				}
				searchIdSql = "select  nextval('seq_detection_info') val from dual";
				fields = new ArrayList<String>();
				fields.add("val");
				sid = dao.dbSelect(searchIdSql, fields);
				if(sid!=null && sid.size()>0){
					result[0] = Long.parseLong(sid.get(0).get("val"));
				}
			}else{
				searchIdSql = "select seq_detection_info.NEXTVAL val, t.increment_by ival from user_sequences t where t.sequence_name = 'SEQ_DETECTION_INFO'";
				ArrayList<String> fields = new ArrayList<String>();
				fields.add("val");
				fields.add("ival");
				List<Map<String, String>> sid = dao.dbSelect(searchIdSql, fields);
				if(sid!=null && sid.size()>0){
					result[0] = Long.parseLong(sid.get(0).get("val"));
					result[1] = Long.parseLong(sid.get(0).get("ival"));
				}
			}
			logger.info("获取的detection_info表的sequence已使用完毕，重新获取,间隔为："+result[1]+",next值为："+result[0]);
		} catch (SQLException e) {
			logger.warn("获取detection_info 的sequence id 失败",e);
			result[0] = -1;
			result[1] = -1;
		}finally{
			if(dao != null){
				//dao.clearConn();//清空连接，但是不关闭
			}
		}
		return result;
	}

	/**
	 * 获取数据库当前时间
	 * @return
	 */
	public Date getDbTime(){
		String sql = "select to_char(sysdate,'"+Constants.DB_DATE_FORMAT+"') now from dual";
		try {
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("now");
			String now = dao.dbSelect(sql, fields).get(0).get("now");
			return Common.getFormat().parse(now);
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			try {
				dao.clearConn();
			} catch (Exception e2) {
			}
		}
		return null;
	}
	public  void saveToNew(List<Object[]> dataList,int flag ,PreparedStatement stmt ){
		if(dataList==null||dataList.size()<1){
			return ;
		}
		if(dataList!=null&&dataList.size()>0){
			if(flag==0){//insert
				String sql=DetectInfo.getSaveToNewSql();
				try {
					if(stmt==null){
						stmt=dao.getConn().prepareStatement(sql);
					}
					
					for (Object[] newData : dataList) {
						// 计算 详细表的 外键 时间戳（10） + seqId（5）+ setId (3)，主要是为了使用 java 中long 类型
						String checkTime = newData[DetectInfo.CHECKTIME].toString();
						String setId = newData[DetectInfo.SETINFOID].toString();
						String seqId = newData[DetectInfo.SEQID].toString();
						String id = DetectInfo.computeId(checkTime, seqId, setId);
						Object []params={
								newData[DetectInfo.SETINFOID],
								newData[DetectInfo.DSINFO],
								newData[DetectInfo.PDATA],
								newData[DetectInfo.CURRENTTIMES],
								newData[DetectInfo.STARTTIME] != null ? format.format(new Date((Long) newData[DetectInfo.STARTTIME])) : null,
								newData[DetectInfo.WAITTIME],
								newData[DetectInfo.DELAYTIME],
								newData[DetectInfo.NEXTCHECKTIME]!= null ? format.format(new Date((Long) newData[DetectInfo.NEXTCHECKTIME])) : null,
								newData[DetectInfo.PLEVEL],
								newData[DetectInfo.CHECKTIME]!= null ? format.format(new Date((Long) newData[DetectInfo.CHECKTIME])) : null,
								newData[DetectInfo.ARRIVETIME]!= null ? format.format(new Date((Long) newData[DetectInfo.ARRIVETIME])) : null,
								newData[DetectInfo.STATE],
								newData[DetectInfo.STATUSCHANGTIME]!= null ? format.format(new Date((Long) newData[DetectInfo.STATUSCHANGTIME])) : null,
								newData[DetectInfo.SEQID],
								id,
								newData[DetectInfo.CHECKTIME],
								newData[DetectInfo.ARRIVETIME],
								newData[DetectInfo.URGENTLEVEL]
						};
						addRecordToStatement(stmt, params);
					}
					stmt.executeBatch();
					
					logger.info("info_new table insert success! size : "+ dataList.size());
				} catch (SQLException e) {
					logger.error("save info to info_new table error"+e.getMessage());
				}
			}else if(flag==1){//update
				String sql=DetectInfo.getUpdateToNewSql();
				try {
					if(stmt==null){
						stmt=dao.getConn().prepareStatement(sql);
					}
					for (Object[] newData : dataList) {
						// 计算 详细表的 外键 时间戳（10） + seqId（5）+ setId (3)，主要是为了使用 java 中long 类型
						String checkTime = newData[DetectInfo.CHECKTIME].toString();
						String setId = newData[DetectInfo.SETINFOID].toString();
						String seqId = newData[DetectInfo.SEQID].toString();
						String id = DetectInfo.computeId(checkTime, seqId, setId);
						Object []params={newData[DetectInfo.DSINFO],
								newData[DetectInfo.PDATA],
								newData[DetectInfo.CURRENTTIMES],
								newData[DetectInfo.STARTTIME] != null ? format.format(new Date((Long) newData[DetectInfo.STARTTIME])) : null,
								newData[DetectInfo.WAITTIME],
								newData[DetectInfo.DELAYTIME],
								newData[DetectInfo.NEXTCHECKTIME]!= null ? format.format(new Date((Long) newData[DetectInfo.NEXTCHECKTIME])) : null,
								newData[DetectInfo.PLEVEL],
								newData[DetectInfo.CHECKTIME]!= null ? format.format(new Date((Long) newData[DetectInfo.CHECKTIME])) : null,
								newData[DetectInfo.ARRIVETIME]!= null ? format.format(new Date((Long) newData[DetectInfo.ARRIVETIME])) : null,
								newData[DetectInfo.STATE],
								newData[DetectInfo.STATUSCHANGTIME]!= null && (Long)newData[DetectInfo.STATUSCHANGTIME]!= -1? format.format(new Date((Long) newData[DetectInfo.STATUSCHANGTIME])) : null,
								id,	
								newData[DetectInfo.CHECKTIME],
								newData[DetectInfo.ARRIVETIME],
								newData[DetectInfo.URGENTLEVEL],
								newData[DetectInfo.SETINFOID],
								newData[DetectInfo.SEQID]
						};
						addRecordToStatement(stmt, params);
					}
					stmt.executeBatch();
					
					logger.info("info_new table update success! size : "+ dataList.size());
				} catch (SQLException e) {
					logger.error("update info to info_new table error"+e.getMessage());
				}
			}
		}
		dataList.clear();
	}
	public  void addRecordToStatement(PreparedStatement stmt, Object[] params) throws SQLException {
		if (params != null) {
			logger.debug(" params " + Arrays.toString(params));
			for (int i = 0; i < params.length; i++) {
				stmt.setObject(i + 1, params[i]);
			}
			stmt.addBatch();
		}
	}
	public static void main(String[] args) {
		System.out.println(StringUtils.isNumeric("1245463"));
		System.out.println(StringUtils.isNumeric("1245.463"));
		System.out.println(StringUtils.isNumeric("1asd5463"));
	}

//	public Map<String,String[]> getNodeByIp(List<String> ipList) {
//		Map<String,String[]> ipNodeMap = new HashMap<String,String[]>();
//		if(ipList!=null &&ipList.size()>0){
//			StringBuffer strb = new StringBuffer();
//			for(int i=0;i<ipList.size();i++){
//				if(i!=0&&i%1000==0){
//					strb.deleteCharAt(strb.length() - 1);
//					strb.append(") or NODE_IP in ( '"+ ipList.get(i) + "',"); 
//				}else{
//					strb.append("'" + ipList.get(i) + "',");
//				}
//			}
//			if(strb.length()>0){
//				strb.deleteCharAt(strb.length() - 1);
//			}
//			strb.append(")");
//			String sql =  "select NODE_IP,NODE_USERNAME,NODE_PASSWORD from NODE_TABLE where NODE_IP in ("+strb.toString();
//			
//			ArrayList<String> fields = new ArrayList<String>();
//			fields.add("NODE_IP");
//			fields.add("NODE_USERNAME");
//			fields.add("NODE_PASSWORD");
//			try {
//				List<Map<String, String>> sid = dao.dbSelect(sql, fields);
//				if(sid!=null&&sid.size()>0){
//					BASE64Decoder decoder = new BASE64Decoder();
//					for(Map<String, String> map : sid){
//						String[] ipInfo = new String[2];
//						ipInfo[0] = map.get("NODE_USERNAME");
//						String passward = map.get("NODE_PASSWORD");
//						if(StringUtils.isNotBlank(passward)){
//							passward = new String(decoder.decodeBuffer(passward));
//							ipInfo[1] = passward;
//						}
//						ipNodeMap.put(map.get("NODE_IP"), ipInfo);
//					}
//				}
//			} catch (SQLException e) {
//				e.printStackTrace();
//				logger.error("查询失败",e);
//			} catch (IOException e) {
//				e.printStackTrace();
//			}finally{
//				if(dao != null){
//					dao.clearConn();//清空连接，但是不关闭
//				}
//			}
//		}
//		return ipNodeMap;
//	}
}
