package com.eactive.eai.rms.onl.loader.service;

import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.converter.ElinkObjectMapper;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.onl.common.service.AgentUtilService;
import com.eactive.eai.rms.onl.common.util.DateUtil;
import com.eactive.eai.rms.onl.common.util.FileUtils;
import com.eactive.eai.rms.onl.common.util.FileWriteUtil;
import com.eactive.eai.rms.onl.loader.dao.LoaderDao;
import com.eactive.eai.rms.onl.loader.intf.InterfaceDeployService;
import com.eactive.eai.rms.onl.loader.intf.deploy.EAIMessageDeploy;
import com.eactive.eai.rms.onl.loader.layout.LayoutDeployService;
import com.eactive.eai.rms.onl.loader.layout.deploy.LayoutDeploy;
import com.eactive.eai.rms.onl.loader.transform.TransformDeployService;
import com.eactive.eai.rms.onl.loader.transform.deploy.TransformDeploy;
import com.eactive.eai.rms.onl.loader.vo.RuleDeployJobItemVo;
import com.eactive.eai.rms.onl.loader.vo.RuleDeployJobVo;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;


@Service("loaderService")
public class TransactionLoaderServiceImpl extends BaseService implements TransactionLoaderService {

    /** The monitoring context. */
    @Autowired
    @Qualifier("monitoringContext")
    private transient MonitoringContext monitoringContext;

    @Autowired
    @Qualifier("loaderDao")
    private LoaderDao dao;
    
    @Autowired
	@Qualifier("onlAgentUtilService")
	public AgentUtilService agentUtilService;

   @Autowired
   private InterfaceDeployService interfaceDeployService;

   @Autowired
   private LayoutDeployService layoutDeployService;

   @Autowired
   private TransformDeployService transformDeployService;

   private ElinkObjectMapper mapper;

   @PostConstruct
   public void startup() {
      mapper = new ElinkObjectMapper();
      mapper.enable(SerializationFeature.WRITE_SELF_REFERENCES_AS_NULL);
      mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
      mapper.enable(SerializationFeature.INDENT_OUTPUT);
      mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
      mapper.writerWithDefaultPrettyPrinter();
   }

    public TransactionLoaderServiceImpl() { 
        super();
    }

   public void insertLayoutLoading(DataSourceType dt, String path, String fileName)
         throws Exception {
      String json = load(path + fileName, "UTF-8");
//      mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
      LayoutDeploy deploy = mapper.readValue(json, LayoutDeploy.class);
      layoutDeployService.saveDeploy(deploy);
   }

   public void insertTransformLoading(DataSourceType dt, String path, String fileName)
         throws Exception {
      String json = load(path + fileName, "UTF-8");
      TransformDeploy transformDeploy = mapper.readValue(json, TransformDeploy.class);
      transformDeployService.saveDeploy(transformDeploy);
   }

   public void insertInterfaceLoading(DataSourceType dt, String path, String fileName)
         throws Exception {
      String json = load(path + fileName, "UTF-8");
      EAIMessageDeploy eaiMessageDeploy = mapper.readValue(json, EAIMessageDeploy.class);
      interfaceDeployService.saveDeploy(eaiMessageDeploy);
   }

    /**
     * b2b loading
     */
    public void insertB2BLoading(DataSourceType dt, String path,String fileName)
    		throws Exception {
    	String[] tables = {"TSEAIHE03"}; 
		HashMap map = parse(path + fileName);
		if(map !=null) {
			ArrayList list = null;
			for (String table : tables){
				list = (ArrayList)map.get(table);
				if(list != null){
					//HashMap hm = (HashMap)list.get(0);
					adapterGroupValid(dt, map, "TSEAIHE03");
					dao.load( dt , table , list);
				}
				
			}
		}
    }       
    /**
     * c2r loading
     */
    public void insertC2RLoading(DataSourceType dt, String path,String fileName)
    		throws Exception {
    	String[] tables = {"TSEAIHE04"}; 
    	HashMap map = parse(path + fileName);
    	if(map !=null) {
    		ArrayList list = null;
    		for (String table : tables){
    			list = (ArrayList)map.get(table);
    			if(list != null){
    				//HashMap hm = (HashMap)list.get(0);
    				adapterGroupValid(dt, map, "TSEAIHE04");
    				dao.load( dt , table , list);
    			}
    			
    		}
    	}
    }
    /**
     * b2b ext loading
     */
    public void insertB2BExtLoading(DataSourceType dt, String path,String fileName)
    		throws Exception {
    	String[] tables = {"TSEAIFR06"}; 
    	HashMap map = parse(path + fileName);
    	if(map !=null) {
    		ArrayList list = null;
    		for (String table : tables){
    			list = (ArrayList) map.get(table);
    			if(list != null){
    				dao.load(dt, table, list);
    			}
    		}
    	}
    }
    /**
     * adapter loading
     */
    public void insertAdapterLoading(DataSourceType dt, String path,String fileName)
    		throws Exception {
    	HashMap map = parse(path + fileName);
		//TSEAIAD15 삭제 어댑터명 기준
	    //TSEAIAD14 삭제 어댑터명 기준
    	//TSEAIAD02 삭제
		//TSEAIAD01 삭제
		//TSEAIFR04 삭제
    	String[] tables = {"TSEAIAD15","TSEAIAD14","TSEAIAD02","TSEAIAD01","TSEAIFR04"}; 
		if(map !=null) {
			ArrayList list = null;
			for (String table : tables){
				list = (ArrayList)map.get(table);
				if(list != null) 
					dao.load( dt , table , list);
			}
		}		
    }
    
    /**
     * adapter loading Sync
     */
    public void insertAdapterLoadingSync(DataSourceType dt, String path,String fileName)
    		throws Exception {
    	
    	if(path == null || fileName == null) {
    		throw new Exception("path filname is null");
    	}
    	HashMap map = parse(path + fileName);
    	//TSEAIAD15 삭제 어댑터명 기준
    	//TSEAIAD14 삭제 어댑터명 기준
    	//TSEAIAD02 삭제
    	//TSEAIAD01 삭제
    	//TSEAIFR04 삭제
    	String[] tables = {"TSEAIAD15","TSEAIAD14","TSEAIAD02","TSEAIAD01","TSEAIFR04"}; 
    	if(map !=null) {
    		ArrayList list = null;
    		for (String table : tables){
    			list = (ArrayList)map.get(table);
    			if(list != null) 
    				dao.adapterLoadSync( dt , table , list);
    		}
    	}		
    }
    
    /**
     * adapter loading
     */
    public void insertAdapterLoadingAll(DataSourceType dt, String path)
    throws Exception {
    	
    	File dir = new File(path);
    	for ( File file  : dir.listFiles() ){
    		if (file.isFile() && file.getName().endsWith(".txt")){
		    	HashMap map = parse(path + file.getName());
				//TSEAIAD15 삭제 어댑터명 기준
			    //TSEAIAD14 삭제 어댑터명 기준
				//TSEAIAD01 삭제
				//TSEAIAD02 삭제
				//TSEAIFR04 삭제
		    	String[] tables = {"TSEAIAD15","TSEAIAD14","TSEAIAD01","TSEAIAD02","TSEAIFR04"}; 
				if(map !=null) {
					ArrayList list = null;
					for (String table : tables){
						list = (ArrayList)map.get(table);
						if(list != null) 
							dao.load( dt , table , list);
					}
				}		
    		}
    	}
    }    
    
    /**
     * messageKey loading
     */
    public void insertMessageKeyLoading(DataSourceType dt, String path,String fileName)
    throws Exception {
    	HashMap map = parse(path + fileName);
		//TSEAIFR04 삭제
    	String[] tables = {"TSEAIFR04"}; 
		if(map !=null) {
			ArrayList list = null;
			for (String table : tables){
				list = (ArrayList)map.get(table);
				if(list != null) {
					//HashMap hm = (HashMap)list.get(0);
					adapterGroupValid(dt, map, "TSEAIFR04");
					
					dao.load( dt , table , list);
				}
			}
		}		
    }
    
    
    /**
     * layout downloading
     */
    public void layoutDownLoadingForOrg(DataSourceType dt, String path,String loutName)   throws Exception {
        //inboundErrorInfoDao.selectTable(dt,"TSEAITR07", "LoutName", loutName); 
        List<LinkedHashMap> listTR07 = dao.selectTableData(dt,"TSEAITR07", "LoutName", loutName);  
        if (listTR07 == null || listTR07.size() == 0){
        	throw new Exception ("layout data is empty  layoutName =["+loutName+"]") ;
        }
        
        List<LinkedHashMap> listTR08 = dao.selectDataForTableName(dt,"TSEAITR08", "LoutName", loutName);  
        
        if( listTR08 == null || listTR08.size() == 0) {
        	throw new Exception ("layout data is empty  layoutName =["+loutName+"]") ;
        } 

        LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
        tables.put("TSEAITR07",listTR07);
        tables.put("TSEAITR08",listTR08);
        FileWriteUtil.FileWrite(path , loutName+".txt", tables);

		
    } 
    @Transactional
    public void layoutDownLoading(DataSourceType dt, String path,String loutName)   throws Exception {
       LayoutDeploy layoutDeploy = layoutDeployService.selectDeploy(loutName);
       if (layoutDeploy == null) {
          throw new Exception ("layout data is empty  layoutName =["+loutName+"]") ;
       }

      mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
      String json = mapper.writeValueAsString(layoutDeploy);

       FileWriteUtil.FileWrite(path , loutName+".txt", json, "UTF-8");
    }
    
    /**
     * transform downloading
     */
    public void transformDownLoading(DataSourceType dt, String path,String cnvsnName)
    throws Exception {
        List<LinkedHashMap> listTR01 = dao.selectTableData(dt,"TSEAITR01", "CnvsnName", cnvsnName);  
        if( listTR01 == null || listTR01.size() == 0) {
        	throw new Exception ("transform data is empty  transformName =["+cnvsnName+"]") ;
        } 
        
        List<LinkedHashMap> listTR02 = dao.selectTableData(dt,"TSEAITR02", "CnvsnName", cnvsnName);  
        if( listTR02 == null || listTR02.size() == 0) {
        	throw new Exception ("transform data is empty  transformName =["+cnvsnName+"]") ;
        } 
        
        List<LinkedHashMap> listTR03 = dao.selectDataForTableName(dt,"TSEAITR03", "CnvsnName", cnvsnName);
        if( listTR03 == null || listTR03.size() == 0) {
        	throw new Exception ("transform data is empty  transformName =["+cnvsnName+"]") ;
        } 
        LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
        tables.put("TSEAITR01",listTR01);
        tables.put("TSEAITR02",listTR02);
        tables.put("TSEAITR03",listTR03);
        FileWriteUtil.FileWrite(path , cnvsnName+".txt", tables);
	
    }     
    public LinkedHashMap<String,List> transformDownLoadingForData(DataSourceType dt, String path,String cnvsnName)
    		throws Exception {
    	List<LinkedHashMap> listTR01 = dao.selectTableData(dt,"TSEAITR01", "CnvsnName", cnvsnName);  
    	if( listTR01 == null || listTR01.size() == 0) {
    		throw new Exception ("transform data is empty  transformName =["+cnvsnName+"]") ;
    	} 
    	
    	List<LinkedHashMap> listTR02 = dao.selectTableData(dt,"TSEAITR02", "CnvsnName", cnvsnName);  
    	if( listTR02 == null || listTR02.size() == 0) {
    		throw new Exception ("transform data is empty  transformName =["+cnvsnName+"]") ;
    	} 
    	
    	List<LinkedHashMap> listTR03 = dao.selectDataForTableName(dt,"TSEAITR03", "CnvsnName", cnvsnName);  
    	if( listTR03 == null || listTR03.size() == 0) {
    		throw new Exception ("transform data is empty  transformName =["+cnvsnName+"]") ;
    	} 
    	LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
    	tables.put("TSEAITR01",listTR01);
    	tables.put("TSEAITR02",listTR02);
    	tables.put("TSEAITR03",listTR03);
    	return tables;
    }     
    
    
    /**
     * interface downloading
     */
    public void interfaceDownLoading(DataSourceType dt, String path,String eaiSvcName)   throws Exception {

        List<LinkedHashMap> listHE01 = dao.selectTableData(dt,"TSEAIHE01", "EAISvcName", eaiSvcName);  
        if( listHE01 == null || listHE01.size() == 0) {
        	throw new Exception ("interface data is empty  interfaceName =["+eaiSvcName+"]") ;
        }
        
        //TAS거래 > 일반거래로 복사 2020.05.06 추가
        for( LinkedHashMap m : listHE01 ) {
    		if("T".equals((String)m.get("TRANTYPE"))){  
    			m.put("TRANTYPE", "R");
    		}
        }    
        
        List<LinkedHashMap> listHE02 = dao.selectTableData(dt,"TSEAIHE02", "EAISvcName", eaiSvcName);
        if( listHE02 == null || listHE02.size() == 0) {
        	throw new Exception ("interface data is empty  interfaceName =["+eaiSvcName+"]") ;
        } 
        
        List<LinkedHashMap> listMS02 = dao.selectTableData(dt,"TSEAIMS02", "EAISvcName", eaiSvcName);
        
        List<LinkedHashMap> listFR01 = dao.selectTableData(dt,"TSEAIFR01", "EAISvcName", eaiSvcName);
        
        List<LinkedHashMap> listFR03 = dao.selectTableData(dt,"TSEAIFR03", "EAISvcName", eaiSvcName);

        List<LinkedHashMap> listHS04 = dao.selectTableData(dt,"TSEAIHS04", "EAISvcName", eaiSvcName);
        List<LinkedHashMap> listHS05 = new ArrayList<LinkedHashMap>();
        if( listHS04 != null ) {      
            for( LinkedHashMap m : listHS04 ) {
            	String bzwkSvcKeyName = (String)m.get("BZWKSVCKEYNAME");
            	List<LinkedHashMap> list = dao.selectTableData(dt,"TSEAIHS05", "BZWKSVCKEYNAME", bzwkSvcKeyName);
            	listHS05.addAll(list);
            }        	
        }
        List<LinkedHashMap> listFR06 = dao.selectTableData(dt,"TSEAIFR06", "EAISvcName", eaiSvcName);
        
        
        LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
        tables.put("TSEAIHE01",listHE01);
        tables.put("TSEAIHE02",listHE02);
        tables.put("TSEAIMS02",listMS02);
        tables.put("TSEAIFR01",listFR01);
        tables.put("TSEAIFR03",listFR03);
        tables.put("TSEAIHS04",listHS04);
        tables.put("TSEAIHS05",listHS05);
        tables.put("TSEAIFR06",listFR06);
        FileWriteUtil.FileWrite(path , eaiSvcName+".txt", tables);
    }         
    /**
     * b2b downloading
     */
    public void b2bDownLoading(DataSourceType dt, String path,String extnlInstiIdnfiName)
    throws Exception {
        List<LinkedHashMap> listHE03 = dao.selectTableData(dt,"TSEAIHE03", "extnlInstiIdnfiName", extnlInstiIdnfiName);  
        if( listHE03 == null || listHE03.size() == 0) {
        	throw new Exception ("b2b extractor data is empty  extnlInstiIdnfiName =["+extnlInstiIdnfiName+"]") ;
        } 

        LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
        tables.put("TSEAIHE03",listHE03);
        FileWriteUtil.FileWrite(path , extnlInstiIdnfiName+".txt", tables);
	
    }
    /**
     * c2r downloading
     */
	public void c2rDownLoading(DataSourceType dt, String path, String extnlInstiIdnfiName) throws Exception {
		List<LinkedHashMap> listHE04 = dao.selectTableData(dt,"TSEAIHE04", "extnlInstiIdnfiName", extnlInstiIdnfiName);  
        if( listHE04 == null || listHE04.size() == 0) {
        	throw new Exception ("c2r extractor data is empty  extnlInstiIdnfiName =["+extnlInstiIdnfiName+"]") ;
        } 

        LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
        tables.put("TSEAIHE04",listHE04);
        FileWriteUtil.FileWrite(path , extnlInstiIdnfiName+".txt", tables);
	}
	/**
	 * b2bext downloading
	 */
	public void b2bExtDownLoading(DataSourceType dt, String path, String eaiSvcName) throws Exception {
		List<LinkedHashMap> listFR06 = dao.selectTableData(dt, "TSEAIFR06", "eaiSvcName", eaiSvcName);  
		if(listFR06 == null || listFR06.size() == 0) {
			throw new Exception ("b2bExt extractor data is empty  eaiSvcName =["+eaiSvcName+"]") ;
		} 
		LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
		tables.put("TSEAIFR06", listFR06);
		FileWriteUtil.FileWrite(path , eaiSvcName+".txt", tables);
	}
    /**
     * adapter downloading
     */
    public void adapterDownLoading(DataSourceType dt, String path,String adapterName)   throws Exception {

        List<LinkedHashMap> listAD01 = dao.selectTableData(dt,"TSEAIAD01", "AdptrBzwkGroupName", adapterName);  
        if( listAD01 == null || listAD01.size() == 0) {
        	throw new Exception ("adapter data is empty  adapterName =["+adapterName+"]") ;
        }
        List<LinkedHashMap> listAD02 = dao.selectTableData(dt,"TSEAIAD02", "AdptrBzwkGroupName", adapterName);
        if( listAD02 == null || listAD02.size() == 0) {
        	throw new Exception ("adapter data is empty  adapterName =["+adapterName+"]") ;
        } 
        
        List<LinkedHashMap> listAD14 = new ArrayList();
        for(LinkedHashMap lhm : listAD02){
        	List<LinkedHashMap> mlistAD14 = dao.selectTableData(dt,"TSEAIAD14", "prptyGroupName", (String)lhm.get("PRPTYGROUPNAME"));
            if( mlistAD14 == null || mlistAD14.size() == 0) {
            	throw new Exception ("adapter propertyGroup data(TSEAIAD14) is empty  prptyGroupName =["+lhm.get("PRPTYGROUPNAME")+"]") ;
            } 
            if( mlistAD14 != null ) {                        
            	for( LinkedHashMap m : mlistAD14 ) {
            		m.put("ADPTRBZWKGROUPNAME", adapterName);
          		}
            	listAD14.addAll(mlistAD14);
            }
            
          
        }
               
        List<LinkedHashMap> listAD15 = new ArrayList();
        for(LinkedHashMap lhm : listAD02){
        	List<LinkedHashMap> mlistAD15 = dao.selectTableData(dt,"TSEAIAD15", "prptyGroupName", (String)lhm.get("PRPTYGROUPNAME"));
            if( mlistAD15 == null || mlistAD15.size() == 0) {
            	throw new Exception ("adapter propertyGroup data(TSEAIAD15) is empty  prptyGroupName =["+lhm.get("PRPTYGROUPNAME")+"]") ;
            } 
            if( mlistAD15 != null ) {                        
            	for( LinkedHashMap m : mlistAD15 ) {
            		m.put("ADPTRBZWKGROUPNAME", adapterName);
          		}
            	listAD15.addAll(mlistAD15);
            }
            
          
        }       
  
        
        List<LinkedHashMap> listFR04 = dao.selectTableData(dt,"TSEAIFR04", "AdptrBzwkGroupName", adapterName);
        
        
        LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
        tables.put("TSEAIAD01",listAD01);
        tables.put("TSEAIAD02",listAD02);
        tables.put("TSEAIAD14",listAD14);
        tables.put("TSEAIAD15",listAD15);
        tables.put("TSEAIFR04",listFR04);
        FileWriteUtil.FileWrite(path , adapterName+".txt", tables);

		
    }  
    /**
     * adapter downloading
     */
    public void adapterDownLoading(DataSourceType dt, String path,String adapterName, String prefix)   throws Exception {
    	
    	List<LinkedHashMap> listAD01 = dao.selectTableData(dt,"TSEAIAD01", "AdptrBzwkGroupName", adapterName);  
    	if( listAD01 == null || listAD01.size() == 0) {
    		throw new Exception ("adapter data is empty  adapterName =["+adapterName+"]") ;
    	}
    	List<LinkedHashMap> listAD02 = dao.selectTableData(dt,"TSEAIAD02", "AdptrBzwkGroupName", adapterName);
    	if( listAD02 == null || listAD02.size() == 0) {
    		throw new Exception ("adapter data is empty  adapterName =["+adapterName+"]") ;
    	} 
    	for(LinkedHashMap ad02 : listAD02){
    		String instance =(String)ad02.get("EAISEVRINSTNCNAME");
    		if (instance != null && instance.length() >5 && prefix != null){
    			String replace = prefix + instance.substring(5);
    			ad02.put("EAISEVRINSTNCNAME",replace);
    		}
    	}
    	
    	List<LinkedHashMap> listAD14 = new ArrayList();
    	for(LinkedHashMap lhm : listAD02){
    		List<LinkedHashMap> mlistAD14 = dao.selectTableData(dt,"TSEAIAD14", "prptyGroupName", (String)lhm.get("PRPTYGROUPNAME"));
    		if( mlistAD14 == null || mlistAD14.size() == 0) {
    			throw new Exception ("adapter propertyGroup data(TSEAIAD14) is empty  prptyGroupName =["+lhm.get("PRPTYGROUPNAME")+"]") ;
    		} 
    		if( mlistAD14 != null ) {                        
    			for( LinkedHashMap m : mlistAD14 ) {
    				m.put("ADPTRBZWKGROUPNAME", adapterName);
    			}
    			listAD14.addAll(mlistAD14);
    		}
    		
    		
    	}
    	
    	List<LinkedHashMap> listAD15 = new ArrayList();
    	for(LinkedHashMap lhm : listAD02){
    		List<LinkedHashMap> mlistAD15 = dao.selectTableData(dt,"TSEAIAD15", "prptyGroupName", (String)lhm.get("PRPTYGROUPNAME"));
    		if( mlistAD15 == null || mlistAD15.size() == 0) {
    			throw new Exception ("adapter propertyGroup data(TSEAIAD15) is empty  prptyGroupName =["+lhm.get("PRPTYGROUPNAME")+"]") ;
    		} 
    		if( mlistAD15 != null ) {                        
    			for( LinkedHashMap m : mlistAD15 ) {
    				m.put("ADPTRBZWKGROUPNAME", adapterName);
    			}
    			listAD15.addAll(mlistAD15);
    		}
    		
    		
    	}       
    	
    	
    	List<LinkedHashMap> listFR04 = dao.selectTableData(dt,"TSEAIFR04", "AdptrBzwkGroupName", adapterName);
    	
    	
    	LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
    	tables.put("TSEAIAD01",listAD01);
    	tables.put("TSEAIAD02",listAD02);
    	tables.put("TSEAIAD14",listAD14);
    	tables.put("TSEAIAD15",listAD15);
    	tables.put("TSEAIFR04",listFR04);
    	FileWriteUtil.FileWrite(path , adapterName+".txt", tables);
    	
    	
    }  
    
    /**
     * adapter downloading
     */
    public void adapterDownLoadingAll(DataSourceType dt, String path, String like)   throws Exception {

        List<LinkedHashMap> listAD01All = dao.selectTableDataLike(dt,"TSEAIAD01", "AdptrBzwkGroupName",like);
        
        for( LinkedHashMap all : listAD01All ) {
    		String adapterName = (String)all.get("ADPTRBZWKGROUPNAME");
    	
	        List<LinkedHashMap> listAD01 = dao.selectTableData(dt,"TSEAIAD01", "AdptrBzwkGroupName", adapterName);  
	        if( listAD01 == null || listAD01.size() == 0) {
	        	throw new Exception ("adapter data(TSEAIAD01) is empty  adapterName =["+adapterName+"]") ;
	        }
	        List<LinkedHashMap> listAD02 = dao.selectTableData(dt,"TSEAIAD02", "AdptrBzwkGroupName", adapterName);
	        if( listAD02 == null || listAD02.size() == 0) {
	        	throw new Exception ("adapter data(TSEAIAD02) is empty  adapterName =["+adapterName+"]") ;
	        } 
	        
	        List<LinkedHashMap> listAD14 = dao.selectTableData(dt,"TSEAIAD14", "prptyGroupName", (String) listAD02.get(0).get("PRPTYGROUPNAME"));
	        if( listAD14 == null || listAD14.size() == 0) {
	        	throw new Exception ("adapter propertyGroup data(TSEAIAD14) is empty  prptyGroupName =["+listAD02.get(0).get("PRPTYGROUPNAME")+"]") ;
	        } 
	        if( listAD14 != null ) {                        
	        	for( LinkedHashMap m : listAD14 ) {
	        		m.put("ADPTRBZWKGROUPNAME", adapterName);
	      		}
	        }         
	        
	        List<LinkedHashMap> listAD15 = dao.selectTableData(dt,"TSEAIAD15", "prptyGroupName", (String)listAD14.get(0).get("PRPTYGROUPNAME"));
	        if( listAD15 == null || listAD15.size() == 0) {
	        	throw new Exception ("adapter propertyGroup data(TSEAIAD15) is empty  prptyGroupName =["+listAD14.get(0).get("PRPTYGROUPNAME")+"]") ;
	        } 
	        if( listAD15 != null ) {                        
	        	for( LinkedHashMap m : listAD15 ) {
	        		m.put("ADPTRBZWKGROUPNAME", adapterName);
	      		}
	        }         
	        
	        List<LinkedHashMap> listFR04 = dao.selectTableData(dt,"TSEAIFR04", "AdptrBzwkGroupName", adapterName);
        
	        LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
	        tables.put("TSEAIAD01",listAD01);
	        tables.put("TSEAIAD02",listAD02);
	        tables.put("TSEAIAD14",listAD14);
	        tables.put("TSEAIAD15",listAD15);
	        tables.put("TSEAIFR04",listFR04);
	        FileWriteUtil.FileWrite(path , adapterName+".txt", tables);
  		}


		
    }    
    
    /**
     * layout download list all
     */
    public void layoutDownLoadingAll(DataSourceType dt, String serviceType)   throws Exception {
        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DOWNLOAD_PATH);
        String path = "";
        List elist = new ArrayList();
    	List<LinkedHashMap> list =  dao.selectTableDataLike(dt,"TSEAITR07", "LoutName", "%");
    	for (int i=0;i<list.size();i++){
    		LinkedHashMap lm = list.get(i);
    		String loutName = (String)lm.get("LOUTNAME");
    		String bzwkDstcd = ((String)lm.get("EAIBZWKDSTCD")).trim();
    		path = iomapPath + serviceType + File.separator + bzwkDstcd + File.separator + FileWriteUtil.LAYOUT + File.separator ;
    	    try{
    	    	layoutDownLoading( dt,  path, loutName);
       		}catch(Exception e){
    			
    			elist.add(loutName);
    			//logger.error(error);
    		}
    	}
    	if(elist.size() > 0){
    		StringBuffer sb = new StringBuffer();
    		sb.append("layout data is empty  loutName =[");
    		for(int i = 0; i< elist.size(); i++){
    			sb.append(elist.get(i)+ ", ");
    		}
    		sb.append("]");
    		throw new Exception(sb.toString());
    	}
    }     
    /**
     * transform download all
     */
    public void transformDownLoadingAll(DataSourceType dt, String serviceType) throws Exception {
        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DOWNLOAD_PATH);
        String path = "";
        
    	List<LinkedHashMap> list =  dao.selectTableDataLike(dt,"TSEAITR01", "CnvsnName", "%");
    	List elist = new ArrayList();
    	for (int i=0;i<list.size();i++){
    		LinkedHashMap lm = list.get(i);
    		String cnvsnName = (String)lm.get("CNVSNNAME");
    		String bzwkDstcd = cnvsnName.substring(10,13);
    		path = iomapPath + serviceType + File.separator + bzwkDstcd + File.separator + FileWriteUtil.TRANSFORM + File.separator ;
    		try{
    			transformDownLoading( dt,  path, cnvsnName);
    		}catch(Exception e){
    			
    			elist.add(cnvsnName);
    			//logger.error(error);
    		}
    	}
    	if(elist.size() > 0){
    		StringBuffer sb = new StringBuffer();
    		sb.append("transform data is empty  cnvsnName =[");
    		for(int i = 0; i< elist.size(); i++){
    			sb.append(elist.get(i)+ ", ");
    		}
    		sb.append("]");
    		throw new Exception(sb.toString());
    	}
    	
    }     
    
    /**
     * interface download all
     */
    public void interfaceDownLoadingAll(DataSourceType dt, String serviceType) throws Exception {
        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DOWNLOAD_PATH);
        String path = "";
        List elist = new ArrayList();
    	List<LinkedHashMap> list =  dao.selectTableDataLike(dt,"TSEAIHE01", "EAISvcName", "%");
    	for (int i=0;i<list.size();i++){
    		LinkedHashMap lm = list.get(i);
    		String eaiSvcName = (String)lm.get("EAISVCNAME");
    		String bzwkDstcd = ((String)lm.get("EAIBZWKDSTCD")).trim();
    		path = iomapPath + serviceType + File.separator + bzwkDstcd + File.separator + FileWriteUtil.INTERFACE + File.separator ;
    		try{
    			interfaceDownLoading( dt,  path, eaiSvcName);
    		}catch(Exception e){
    			
    			elist.add(eaiSvcName);
    			//logger.error(error);
    		}
    	}
    	if(elist.size() > 0){
    		StringBuffer sb = new StringBuffer();
    		sb.append("interface data is empty  eaiSvcName =[");
    		for(int i = 0; i< elist.size(); i++){
    			sb.append(elist.get(i)+ ", ");
    		}
    		sb.append("]");
    		throw new Exception(sb.toString());
    	}
    } 
    
    /**
     * table loading
     */
    public void insertTableLoading(DataSourceType dt, String path,String fileName) throws Exception {
    	String[] temp = null;
    	if(fileName != null){ //취약점소스 수정 2020.08.27
    		temp = fileName.split("[.]");
    		String tableName = temp[0];         	
        	
        	String[] tables = {tableName}; 
    		HashMap map = parse(path + fileName);
    		if(map !=null) {
    			ArrayList list = null;
    			for (String table : tables){
    				list = (ArrayList)map.get(table);
    				if(list != null){ 
    					
    					dao.insertTable( dt , table , list);
    				}
    			}
    		}
    	}
	}      
   
    /**
     * table downloading
     */
    public void tableDownLoading(DataSourceType dt, String path,String tableName) throws Exception {
        
        List<LinkedHashMap> table = dao.selectTable(dt, tableName, "1", "1");  

        if (table == null || table.size() == 0){
        	throw new Exception ("table data is empty  tableName =["+tableName+"]") ;
        }

        LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
        tables.put(tableName,table);
        FileWriteUtil.FileWrite(path , tableName+".txt", tables);
		
    }     
    /**
     * messageKey downloading
     */
    public void messageKeyDownLoading(DataSourceType dt, String path,String adapterName)   throws Exception {
        List<LinkedHashMap> listFR04 = dao.selectTableData(dt,"TSEAIFR04", "AdptrBzwkGroupName", adapterName);
        LinkedHashMap<String,List> tables= new LinkedHashMap<String,List>();
        tables.put("TSEAIFR04",listFR04);
        FileWriteUtil.FileWrite(path , adapterName+".txt", tables);
    }  
    
    /**
     * tran block
     */
    public void tranBlock(DataSourceType dt, String cmd, String type, String value) throws Exception {
    	if ("NODE".equals(cmd)){
//    		loaderDao.updateNode(dt,value);
    	}else if ("INST".equals(cmd)){
    		dao.updateInst(dt,type,value);
    	}
    }     
	public HashMap parse(String filePath) throws Exception {
		String delimeter = ";";
		HashMap map = new HashMap();
		ArrayList list = null;
		
		FileReader fr = new FileReader(filePath);
		if(fr == null) {
			return map;
		}
		BufferedReader br = null;
        String lbuff = null;
        String[] header = null;
        
        try {
        	br = new BufferedReader(fr);
			while ((lbuff = br.readLine()) != null) {
				if(lbuff.indexOf(delimeter) < 0) {
		        	list = new ArrayList();
		        	map.put(lbuff.toUpperCase(), list);
		        	if((lbuff = br.readLine()) == null) {	        		
		        		throw new Exception("File Header parsing Error : "+ filePath);
		        	}	
		        	header = lbuff.split(delimeter);
		        	continue;
				}
				if(header == null) continue;
				LinkedHashMap codes = split(header,lbuff, delimeter, header.length);
				list.add(codes);
	        }
        }catch(Exception ex) {
			logger.error("parse error", ex);
		}
		finally {
			if(br != null){
			  br.close();
			 }
		}
		return map;
	}
   public String load(String filePath, String encoding) {
      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      File file = new File(filePath);
      byte[] data = null;
      FileInputStream fis = null;
      try {
         fis = new FileInputStream(file);
         
         int c = -1;
         byte[] bytes = new byte[1024];

         while ((c = fis.read(bytes, 0, bytes.length)) != -1) {
            outStream.write(bytes, 0, c);
         }
         data = new byte[outStream.toByteArray().length];
         data = outStream.toByteArray();
      }catch(Exception e) {
         
      }finally {
         try{fis.close();}catch(Exception e ) {}
         try{outStream.close();}catch(Exception e ) {}
      }
      try {
         return new String(data,encoding);
      } catch (UnsupportedEncodingException e) {
         return new String(data);
      }
   }
   
   
   public String load(String filePath) throws Exception {
      return  load( filePath, Charset.defaultCharset().name());
   }   
	private LinkedHashMap split(String[] header, String data, String deli, int size) {
		LinkedHashMap array = new LinkedHashMap();
		String data2 = data + " " +deli;//마지막 에 ";;" 될경우 length 차이가 나서 보정해주는 로직 
		String[] s = data2.split(deli);
		for(int i=0; i<s.length-1;i++){
			array.put(header[i], s[i]);
		}
		return array;
	}
    public HashSet<String> getFileInterfaceAdapterList(HashMap map) throws Exception{
    	HashSet<String> adapterList = new HashSet<String>();

		String eaiSvcName = "";
		String srcType   = "";
		String tgtType   = "";

		String sndRecvType = "";
		
		ArrayList he01 = (ArrayList)map.get("TSEAIHE01");
		if (he01 == null || he01.size() == 0){
			throw new Exception("EAI 메시지가 없습니다.");
		}
		HashMap he01row0 = (HashMap)he01.get(0);
		String src = (String)he01row0.get("GSTATSYSADPTRBZWKGROUPNAME");						//기동어댑터명
		srcType    = (String)he01row0.get("SVCMOTIVUSEDSTCD");									//기동인터페이스 유형
		
		if (StringUtils.isBlank(src)){
			throw new Exception("기동 어댑터가 없습니다.");
		}
		adapterList.add(src);

		ArrayList he02 = (ArrayList)map.get("TSEAIHE02");
		if (he02 == null || he02.size() == 0){
			throw new Exception("EAI 서비스처리정보가 없습니다.");
		}
		HashMap he02row0 = (HashMap)he02.get(0);
		String tgt  = (String)he02row0.get("PSVSYSADPTRBZWKGROUPNAME");						//수동어댑터명
		tgtType     = (String)he02row0.get("PSVINTFACDSTICNAME");							//수동인터페이스 유형
		eaiSvcName  = (String)he02row0.get("EAISVCNAME");									//인터페이스명
		sndRecvType = eaiSvcName.substring(eaiSvcName.length()-2, eaiSvcName.length()-1);	//인터페이스 송수신구분
		
		//S-A 응답일때 빼고 수동어댑터 체크
		if(srcType.equals("SYNC") && tgtType.equals("ASYN") && sndRecvType.equals("R")){
			;
		}else{
			if(StringUtils.isBlank(tgt)){
				throw new Exception("수동 어댑터가 없습니다.");
			}
			adapterList.add(tgt);
		}
		// A-S > HE01의 인터페이스유형 ASYN이고 HE02의 첫번째 수동인터페이스가 SYNC일 때 -> 수동인터페이스 2개
		if(srcType.equals("ASYN") && tgtType.equals("SYNC")){
			if(he02.size()==1){
				throw new Exception("기동 응답 서비스가 존재하지 않습니다.");
			}
			HashMap he02row1 = (HashMap)he02.get(1);
			tgt = (String)he02row1.get("PSVSYSADPTRBZWKGROUPNAME");
			if(StringUtils.isBlank(tgt)){
				throw new Exception("기동 응답 어댑터가 없습니다.");
			}
			adapterList.add(tgt);
		}
		return adapterList;
    }	
    public List<LinkedHashMap> selectTableDataForListValue(DataSourceType dataSourceType, String tableName, String key1, List<String> param1) throws Exception{
        return dao.selectTableDataForListValue( dataSourceType, tableName, key1, param1 );
    }
    public void adptInstValid(DataSourceType dataSourceType, HashMap map) throws Exception{
    	boolean ret = true;
    	ArrayList he01 = (ArrayList)map.get("TSEAIHE01");
		if (he01 == null || he01.size() == 0){
			ret = false;
			throw new Exception("EAI 메시지가 없습니다.");
		}
		HashMap he01row0 = (HashMap)he01.get(0);
		String eaiSvcName  = (String)he01row0.get("EAISVCNAME");	
		String srcType     = (String)he01row0.get("SVCMOTIVUSEDSTCD");
		String srcAdpt	   = (String)he01row0.get("GSTATSYSADPTRBZWKGROUPNAME");						//기동어댑터명
		
		ArrayList he02 = (ArrayList)map.get("TSEAIHE02");
		if (he02 == null || he02.size() == 0){
			throw new Exception("[EAI서비스코드 : "+eaiSvcName+"] EAI 서비스처리정보가 없습니다.");
		}
		HashMap he02row0 = (HashMap)he02.get(0);
		String tgtAdpt   = (String)he02row0.get("PSVSYSADPTRBZWKGROUPNAME");						//수동어댑터명
		String tgtType   = (String)he02row0.get("PSVINTFACDSTICNAME");
		
		String sndRecvType = eaiSvcName.substring(eaiSvcName.length()-2, eaiSvcName.length()-1);	//인터페이스 송수신구분
		
		
		List<LinkedHashMap> ouAdptInstList = dao.selectTableData(dataSourceType, "TSEAIAD02", "ADPTRBZWKGROUPNAME", tgtAdpt);
		//outBound 어댑터 정보가 없고 그룹명만 있을 때 ____ 비교 X
		if(ouAdptInstList.size()==0){
			return ;
		}
		
		//기동어댑터와 관계없이 수동어댑터 바인딩된 인스턴스가 ALL일때 우선적으로 PASS (A_S 패턴 포함 - 처리순서1인 어댑터로 비교)
		if("ALL".equals(ouAdptInstList.get(0).get("EAISEVRINSTNCNAME"))){
			return ;
		}
		
		List<LinkedHashMap> inAdptInstList = dao.selectTableData(dataSourceType, "TSEAIAD02", "ADPTRBZWKGROUPNAME", srcAdpt);
		//inBound 어댑터 정보가 없고 그룹명만 있을 때 ____ 비교 X
		if(inAdptInstList.size()==0){
			return ;
		}
		List<LinkedHashMap> ouAdptInstList2 = new ArrayList<>();
		
		//S_A 패턴 응답 ___ 비교 X
		if(srcType.equals("SYNC") && tgtType.equals("ASYN") && sndRecvType.equals("R")){
			return ;
		}
		//A_S 패턴 
		if(srcType.equals("ASYN") && tgtType.equals("SYNC")){
			if(he02.size()==1){
				throw new Exception("[EAI서비스코드 : "+eaiSvcName+"] 기동 응답 서비스가 존재하지 않습니다.");
			}
			HashMap he02row1 = (HashMap)he02.get(1);
			tgtAdpt = (String)he02row1.get("PSVSYSADPTRBZWKGROUPNAME");
			ouAdptInstList2 = dao.selectTableData(dataSourceType, "TSEAIAD02", "ADPTRBZWKGROUPNAME", tgtAdpt);
		}
		/**
		 * 아래는 SNA 체크임 우체국에서는 안쓰임 시작
		 */
		/*
		//IN 어댑터 List의 ADPTRCD는 다 같음.
		//String adptrName = (String)inAdptInstList.get(0).get("ADPTRBZWKNAME");
		String adptrGrpName = (String)inAdptInstList.get(0).get("ADPTRBZWKGROUPNAME");
		//IN 어댑터가 SNA일때
		boolean flag = false;
		if(adptrGrpName.indexOf("SNA")>=0){
			inAdptInstList.clear();
			List<LinkedHashMap> snaApList = inboundErrorInfoDao.selectSnaAdpApList(dataSourceType, adptrGrpName);
			String svcApCd = eaiSvcName.substring(0,3);	//서비스코드 앞 3자리
			for(LinkedHashMap m : snaApList){
				String apList = (String)m.get("PRPTY2VAL");
				int chk = apList.indexOf(svcApCd);
				if(chk>=0){
					inAdptInstList.add(m);
					flag = true;
				}
			}
			if(!flag){
				ret = false;
				throw new Exception("[EAI서비스코드 : "+eaiSvcName+"] AP코드("+svcApCd+")가 SNA어댑터["+adptrGrpName+"]에 존재하지 않습니다");
			}
		}
		//in out 불일치 
		int cnt = inAdptInstList.size();
		String srcAdptName = "";
		String tgtAdptName = "";
		for(HashMap om : ouAdptInstList){
			String ouInst = (String)om.get("EAISEVRINSTNCNAME");
			tgtAdptName = (String)om.get("ADPTRBZWKGROUPNAME");
			if("ALL".equals(ouInst)){
				cnt=0;
				break;
			}
			for(HashMap im : inAdptInstList){
				String inInst =(String)im.get("EAISEVRINSTNCNAME");
				srcAdptName = (String)im.get("ADPTRBZWKGROUPNAME");
				if(ouInst.equals(inInst)){
					cnt--;
					continue;
				}
			}
		}
		if(cnt>0){
			ret = false;
			throw new Exception("[EAI서비스코드 : "+eaiSvcName+"] 기동어댑터와 수동어댑터의 인스턴스가 일치하지 않습니다 [기동 : "+srcAdptName+" / 수동 : "+tgtAdptName+"]");
		}
		if(ouAdptInstList2.size()>0){	//A-S 패턴 수동인터페이스 어댑터2 번째꺼 
			int cnt2 = inAdptInstList.size();
			for(HashMap om : ouAdptInstList2){
				String ouInst = (String)om.get("EAISEVRINSTNCNAME");
				tgtAdptName = (String)om.get("ADPTRBZWKGROUPNAME");
				if("ALL".equals(ouInst)){
					cnt2=0;
					break;
				}
				for(HashMap im : inAdptInstList){
					String inInst =(String)im.get("EAISEVRINSTNCNAME");
					srcAdptName = (String)im.get("ADPTRBZWKGROUPNAME");
					if(ouInst.equals(inInst)){
						cnt2--;
						continue;
					}
				}
			}
			if(cnt2>0){
				ret = false;
				throw new Exception("[EAI서비스코드 : "+eaiSvcName+"] 기동어댑터와 수동어댑터의 인스턴스가 일치하지 않습니다 [기동 : "+srcAdptName+" / 수동 : "+tgtAdptName+"]");
			}
		}
		*/
		/**
		 * 아래는 SNA 체크임 우체국에서는 안쓰임 종료
		 */
    }	
    public void adapterGroupValid(DataSourceType dt, HashMap map, String table) throws Exception{
    	
    	if(map!=null){
    		if("TSEAIFR04".equals(table)){
    			ArrayList list = (ArrayList)map.get(table);
    			if(list != null){
					HashMap hm = (HashMap)list.get(0);
					String adapterGroupName=(String)hm.get("ADPTRBZWKGROUPNAME");
					List adptList = dao.selectTableData(dt, "TSEAIAD01", "ADPTRBZWKGROUPNAME", adapterGroupName);
					if(adptList.size()==0){
						String ioDstcd = (String)hm.get("IODSTCD");
						throw new Exception("메시지 키 관리 [어댑터명 : "+adapterGroupName+" / 기능구분 : "+ioDstcd+"] 에 대한 어댑터가 해당서버에 존재하지 않습니다.");
					}
    			}
    		}else if("TSEAIHE03".equals(table) || "TSEAIHE04".equals(table)){
    			ArrayList list = (ArrayList)map.get(table);
    			if(list != null){
					HashMap hm = (HashMap)list.get(0);
					String adapterGroupName=(String)hm.get("PSVSYSADPTRBZWKGROUPNAME");
					List adptList = dao.selectTableData(dt, "TSEAIAD01", "ADPTRBZWKGROUPNAME", adapterGroupName);
					if(adptList.size()==0){
						String extnlInstiIdfiName=(String)hm.get("EXTNLINSTIIDNFINAME");
						String svcPrcssNo = (String)hm.get("SVCPRCSSNO");
						throw new Exception("B2B or C2R 기관 정보 관리 [기관코드 : "+extnlInstiIdfiName+" / 서비스처리순서 : "+svcPrcssNo+"] 에 대한 수동 어댑터가 해당서버에 존재하지 않습니다. ["+adapterGroupName+"]");
					}
    			}
			}
    	}
    }

    public void makeDataFiles(DataSourceType dt, String downloadPath,
			HashMap<String, ArrayList<HashMap<String, String>>> listMap) throws Exception {

		// 1. interface 데이터 다운로드
		if (listMap.get(FileWriteUtil.INTERFACE) != null && listMap.get(FileWriteUtil.INTERFACE).size() > 0) {
			for (HashMap<String, String> data : listMap.get(FileWriteUtil.INTERFACE)) {
				String path = downloadPath + File.separator + data.get("bizCode") + File.separator
						+ FileWriteUtil.INTERFACE + File.separator;
				interfaceDownLoading(dt, path, StringUtils.removeEnd(data.get("programNm"), ".txt"));
			}
		}

		// 2. Layout 데이터 생성
		if (listMap.get(FileWriteUtil.LAYOUT) != null && listMap.get(FileWriteUtil.LAYOUT).size() > 0) {
			for (HashMap<String, String> data : listMap.get(FileWriteUtil.LAYOUT)) {
				String path = downloadPath + File.separator + data.get("bizCode") + File.separator
						+ FileWriteUtil.LAYOUT + File.separator;
				layoutDownLoading(dt, path, StringUtils.removeEnd(data.get("programNm"), ".txt"));
			}
		}

		// 3. LayoutMapping 데이터 생성
		if (listMap.get(FileWriteUtil.TRANSFORM) != null && listMap.get(FileWriteUtil.TRANSFORM).size() > 0) {
			for (HashMap<String, String> data : listMap.get(FileWriteUtil.TRANSFORM)) {
				String path = downloadPath + File.separator + data.get("bizCode") + File.separator
						+ FileWriteUtil.TRANSFORM + File.separator;
				transformDownLoading(dt, path, StringUtils.removeEnd(data.get("programNm"), ".txt"));
			}
		}
		
		// 4. Adapter 데이터 생성
		if (listMap.get(FileWriteUtil.ADAPTER) != null && listMap.get(FileWriteUtil.ADAPTER).size() > 0) {
			for (HashMap<String, String> data : listMap.get(FileWriteUtil.ADAPTER)) {
				String path = downloadPath + File.separator + data.get("bizCode") + File.separator
						+ FileWriteUtil.ADAPTER + File.separator;
				adapterDownLoading(dt, path, StringUtils.removeEnd(data.get("programNm"), ".txt"));
			}
		}
	}
	
	public void deployDataToTargetSystem(String url, String downloadPath,
			HashMap<String, ArrayList<HashMap<String, String>>> listMap, String serviceType) throws Exception {

		// 1. interface 배포
		if (listMap.get(FileWriteUtil.INTERFACE) != null && listMap.get(FileWriteUtil.INTERFACE).size() > 0) {
			for (HashMap<String, String> data : listMap.get(FileWriteUtil.INTERFACE)) {
				String filePath = downloadPath + data.get("bizCode") + File.separator + FileWriteUtil.INTERFACE
						+ File.separator + data.get("programNm");
				uploadDeployFile(url, filePath, FileWriteUtil.INTERFACE, serviceType, data.get("bizCode"));
			}
		}

		// 2. layout 배포
		if (listMap.get(FileWriteUtil.LAYOUT) != null && listMap.get(FileWriteUtil.LAYOUT).size() > 0) {
			for (HashMap<String, String> data : listMap.get(FileWriteUtil.LAYOUT)) {
				String filePath = downloadPath + data.get("bizCode") + File.separator + FileWriteUtil.LAYOUT
						+ File.separator + data.get("programNm");
				uploadDeployFile(url, filePath, FileWriteUtil.LAYOUT, serviceType, data.get("bizCode"));
			}
		}

		// 3. LayoutMapping 배포
		if (listMap.get(FileWriteUtil.TRANSFORM) != null && listMap.get(FileWriteUtil.TRANSFORM).size() > 0) {
			for (HashMap<String, String> data : listMap.get(FileWriteUtil.TRANSFORM)) {
				String filePath = downloadPath + data.get("bizCode") + File.separator + FileWriteUtil.TRANSFORM
						+ File.separator + data.get("programNm");
				uploadDeployFile(url, filePath, FileWriteUtil.TRANSFORM, serviceType, data.get("bizCode"));
			}
		}
		
		// 4. Adapter 배포
		if (listMap.get(FileWriteUtil.ADAPTER) != null && listMap.get(FileWriteUtil.ADAPTER).size() > 0) {
			for (HashMap<String, String> data : listMap.get(FileWriteUtil.ADAPTER)) {
				String filePath = downloadPath + data.get("bizCode") + File.separator + FileWriteUtil.ADAPTER
						+ File.separator + data.get("programNm");
				uploadDeployFile(url, filePath, FileWriteUtil.ADAPTER, serviceType, data.get("bizCode"));
			}
		}
	}
	
	public void uploadDeployFile(String url, String localFile, String cmd, String serviceType, String bzwkDstcd)
			throws Exception {
		File file = new File(localFile);
		if (file == null || file.isDirectory()) {
			throw new Exception("No file found" + localFile);
		}

		PostMethod filePost = new PostMethod(url);
		HttpClient client = new HttpClient();
		String encoding = "UTF-8";

		try {
			Part[] parts = new Part[5];
			parts[0] = new StringPart("cmd", cmd, encoding);
			parts[1] = new StringPart("control", "file-upload", encoding);
			parts[2] = new StringPart("serviceType", serviceType, encoding);
			parts[3] = new StringPart("bzwkDstcd", bzwkDstcd, encoding);
			parts[4] = new FilePart("file", file, "application/octet-stream", encoding);
			
			filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

			int status = client.executeMethod(filePost);
			if (status == HttpStatus.SC_OK) {
				logger.info("Uploaded successfully-" + localFile);
			} else {
				throw new Exception(String.format("Upload failed, HttpStatus=%d, file=%s", status, localFile));
			}
		} catch (Exception e) {
			logger.error("Upload faild-" + localFile);
			logger.error(e.getMessage());
			throw e;
		} finally {
			filePost.releaseConnection();
		}
	}
	
	/**
	 * 룰정보 등록 및 메모리 적재 요청
	 * Source 시스템에서 사용
	 */
	public void scheduleDeployDataApply(String url, String userId, String userIp, String serviceType, String cmTitle, String cmDate,
			String cmTime, String items) throws Exception {
		PostMethod post = new PostMethod(url);
		HttpClient client = new HttpClient();
		String encoding = "UTF-8";

		try {
			post.setParameter("cmd", "schedule");
			post.setParameter("control", "upload");
			post.setParameter("userId", userId);
			post.setParameter("userIp", userIp);
			post.setParameter("serviceType", serviceType);
			post.setParameter("cmTitle", URLEncoder.encode(cmTitle, encoding));
			post.setParameter("cmDate", cmDate);
			post.setParameter("cmTime", cmTime);
			post.setParameter("items", items);

			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

			int status = client.executeMethod(post);
			if (status == HttpStatus.SC_OK) {
				logger.info("Apply Uploaded Data successfully");
			} else {
				throw new Exception("Apply Uploaded Data failed= Check to target System");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw e;
		} finally {
			post.releaseConnection();
		}
	}
	
	/**
	 * 룰정보 등록 및 메모리 적재 작업 수행
	 * Target 시스템에서 사용
	 */
	public boolean ruleDataSaveAndLoading(RuleDeployJobVo jobVo) throws Exception {
		if (jobVo == null || jobVo.getItemList() == null || jobVo.getItemList().size() == 0) {
			throw new Exception("No have rule datas");
		}

		if (!DataSourceTypeManager.isDynamicByName(jobVo.getServiceType())) {
			throw new Exception("Undefined service type. Received service type=" + jobVo.getServiceType());
		}

		String uploadPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_PATH);
		uploadPath = StringUtils.removeEnd(uploadPath, File.separator) + File.separator + jobVo.getServiceType()
				+ File.separator;
		String savePath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_AFTER_UPLOAD_PATH);

		DataSourceType dt = DataSourceTypeManager.getDataSourceType(jobVo.getServiceType());
		if (dt != null) {
			DataSourceContextHolder.setDataSourceType(dt);
		}

		for (RuleDeployJobItemVo itemVo : jobVo.getItemList()) {
			logger.debug("itemVo=" + itemVo.toString());
			HashMap result = null;
			String path = uploadPath + itemVo.getBizCode() + File.separator + itemVo.getRuleType() + File.separator;
			if (FileWriteUtil.INTERFACE.equals(itemVo.getRuleType())) {
				insertInterfaceLoading(dt, path, itemVo.getFileName());

				// 1. eaimessage reload(HE01,HE02,FR01,MS02)
				result = syncResult(new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageCommand"),
						itemVo.getFileName());
				if (((String) result.get("status")).equals("error")) {
					throw new Exception(result.toString());
				}

				// 2. 필드추출 정보 reload
				result = syncResultForBizKey(new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand"),
						itemVo.getFileName(), "TR");
				if (((String) result.get("status")).equals("error")) {
					throw new Exception(result.toString());
				}
				
				result = syncResultForBizKey(new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand"),
						itemVo.getFileName(), "AK");
				if (((String) result.get("status")).equals("error")) {
					throw new Exception(result.toString());
				}

				// 3. 내부표준message reload
				// 내부표준전문 키 추출
				HashMap map = parse(path + itemVo.getFileName());
				ArrayList list = (ArrayList) map.get("TSEAIHS04");
				if (list != null && list.size() > 0) {
					HashMap row = (HashMap) list.get(0);
					String bzwkKey = (String) row.get("BZWKSVCKEYNAME");
					result = syncResultForSTDMessage(new CommonCommand("com.ext.eai.agent.stdmessage.ReloadSTDMessageCommand"),
							bzwkKey);
				}
			} else if (FileWriteUtil.LAYOUT.equals(itemVo.getRuleType())) {
				insertLayoutLoading(dt, path, itemVo.getFileName());
				result = syncResult(new CommonCommand("com.eactive.eai.agent.transformer.ReloadLayoutCommand"),
						itemVo.getFileName());
			} else if (FileWriteUtil.TRANSFORM.equals(itemVo.getRuleType())) {
				insertTransformLoading(dt, path, itemVo.getFileName());
				result = syncResult(new CommonCommand("com.eactive.eai.agent.transformer.ReloadTransformCommand"),
						itemVo.getFileName());
			} else if (FileWriteUtil.ADAPTER.equals(itemVo.getRuleType())) {
				insertAdapterLoading(dt, path, itemVo.getFileName());

				// 1. adapter properties reload
				HashMap map = parse(path + itemVo.getFileName());
				ArrayList list = (ArrayList) map.get("TSEAIAD14");
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {
						HashMap row = (HashMap) list.get(i);
						String prptyGroupName = row.get("PRPTYGROUPNAME") + ".txt";
						result = syncResult(
								new CommonCommand("com.eactive.eai.agent.adapter.ReloadAdapterPropGroupCommand"),
								prptyGroupName);
					}
				}

				// 2. adapter reload
				result = syncResult(new CommonCommand("com.eactive.eai.agent.adapter.ReloadAdapterGroupCommand"),
						itemVo.getFileName());

				// 3. message key reload
				result = syncResultForVector(
						new CommonCommand("com.eactive.eai.agent.messagekey.ReloadMessageKeyListCommand"),
						itemVo.getFileName());
			}

			if (result == null || ("error").equals((String) result.get("status"))) {
				throw new Exception(result.toString());
			} else {
				String today = DateUtil.getDateTime("yyyy-MM-dd");
				String newPath = savePath + today + File.separator + jobVo.getServiceType() + File.separator
						+ itemVo.getBizCode() + File.separator + itemVo.getRuleType() + File.separator;
				try {
					Boolean isMoved = FileUtils.moveFile(path, newPath, itemVo.getFileName(), itemVo.getFileName());
					if (isMoved) {
						logger.info(itemVo.getFileName() + " is moved to " + newPath);
					} else {
						logger.info(itemVo.getFileName() + " is moved NOT to " + newPath);
					}
				} catch (Exception e) {
					logger.info("Failed to move File");
				}
			}
		}

		return true;
	}
	
	public HashMap syncResult(Command command ,String fileName ) throws Exception {
		//layout 동기화 service 에는 transaction 때문에 문제의 소지가 있음
		HashMap receive =new HashMap();
		/**
		 * 20230906 HS04 서비스 key 동기화 시 url등에 .jsp등의 .문자가 있을 시 문제가 있어 마지막 확장자만 제거하도록 임시 수정
		 * TODO: 추후 내부표준 서비스키 동기화 로직 자체를 분리 할 필요가 있어보임(오류메시지 발생시에도 .txt가 같이 출력되어 오해의 소지가 있음)
		 */
		if(org.apache.commons.lang.StringUtils.contains(fileName, ".")){
			String paramWithoutExt = org.apache.commons.lang.StringUtils.substringBeforeLast(fileName, ".");
			command.setArgs(paramWithoutExt);
			receive = agentUtilService.broadcast(command);
		}
//		String[] name = fileName.split("\\.");
//		if (name.length > 0 &&  name[0] != null){
//			command.setArgs(name[0]);
//			receive = agentUtilService.broadcast(command);
//		}

		String status = "success";
		for (Object o : receive.keySet()){
			String key = (String)o;
			if (receive.get(key) == null || !"success".equals(receive.get(key)) ){
				status = "error";
				break;
			}
		}
		HashMap result = new HashMap();
		result.put("status", status);
		result.put("message", receive.toString());

		if (logger.isInfoEnabled()){
			logger.info(this.getClass().toString()+"] command = "+command.getClass().toString()+ " fileName="+fileName + " status = " + status + " message = " + receive.toString());
		}

		return result;
	}
	
	public HashMap syncResultForSTDMessage(Command command, String bzwkKey) throws Exception {
		// layout 동기화 service 에는 transaction 때문에 문제의 소지가 있음
		HashMap receive = new HashMap();
		command.setArgs(bzwkKey);
		receive = agentUtilService.broadcast(command);

		String status = "success";
		for (Object o : receive.keySet()) {
			String key = (String) o;
			if (receive.get(key) == null || !"success".equals(receive.get(key))) {
				status = "error";
				break;
			}
		}
		HashMap result = new HashMap();
		result.put("status", status);
		result.put("message", receive.toString());

		if (logger.isInfoEnabled()) {
			logger.info(this.getClass().toString() + "] command = " + command.getClass().toString() + " bzwkKey="
					+ bzwkKey + " status = " + status + " message = " + receive.toString());
		}

		return result;
	}
	
	public HashMap syncResultForBizKey(Command command, String fileName, String cls ) throws Exception {
		HashMap receive =new HashMap();
		String[] name = fileName.split("\\.");
		if (name.length > 0 &&  name[0] != null){
			command.setArgs(name[0] + "," + cls);
			receive = agentUtilService.broadcast(command);
		}

		String status = "success";
		for (Object o : receive.keySet()){
			String key = (String)o;
			if (receive.get(key) == null || !"success".equals(receive.get(key)) ){
				status = "error";
				break;
			}
		}
		HashMap result = new HashMap();
		result.put("status", status);
		result.put("message", receive.toString());

		if (logger.isInfoEnabled()){
			logger.info(this.getClass().toString()+"] command = "+command.getClass().toString()+ " fileName="+fileName + " status = " + status + " message = " + receive.toString());
		}

		return result;
	}
	
	public HashMap syncResultForVector(Command command, String fileName) throws Exception {
		HashMap receive = new HashMap();
		String[] name = fileName.split("\\.");
		if (name.length > 0 && name[0] != null) {
			Vector vector = new Vector();
			vector.add(name[0]);
			command.setArgs(vector);
			receive = agentUtilService.broadcast(command);
		}

		String status = "success";
		for (Object o : receive.keySet()) {
			String key = (String) o;
			if (receive.get(key) == null || !"success".equals(receive.get(key))) {
				status = "error";
				break;
			}
		}
		HashMap result = new HashMap();
		result.put("status", status);
		result.put("message", receive.toString());

		if (logger.isInfoEnabled()) {
			logger.info(this.getClass().toString() + "] command = " + command.getClass().toString() + " fileName="
					+ fileName + " status = " + status + " message = " + receive.toString());
		}

		return result;
	}

	@Override
	public void appendToListfile(String bizCode, String interfaceId) throws Exception {
		String listFilePath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_LISTFILE_PATH);
		if(StringUtils.isBlank(listFilePath)) {
			logger.error(MonitoringContext.IOMAP_LISTFILE_PATH+" is null or empty!!");
		}
		File listFile = new File(listFilePath);
		String targetLine = bizCode+"|"+interfaceId+System.lineSeparator();
		org.apache.commons.io.FileUtils.writeStringToFile(listFile, targetLine, Charset.defaultCharset(), true);
	}
}