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

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.compress.utils.FileNameUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.rms.common.context.MonitoringContext;
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.common.interceptor.InterceptorSkipController;
import com.eactive.eai.rms.common.util.CommonConstants;
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.FileWriteUtil;
import com.eactive.eai.rms.onl.common.util.SimpleFileUtils;
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.intf.deploy.ServiceMessageDeploy;
import com.eactive.eai.rms.onl.loader.intf.deploy.StandardMessageInfoDeploy;
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.service.RuleDeployJobService;
import com.eactive.eai.rms.onl.loader.service.TransactionLoaderService;
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.InterfaceDeployPack;
import com.eactive.eai.rms.onl.loader.vo.RuleDeployJobItemVo;
import com.eactive.eai.rms.onl.loader.vo.RuleDeployJobVo;
import com.eactive.eai.rms.onl.manage.rule.transform2.Transform2Service;
import com.eactive.eai.rms.onl.manage.rule.transform2.ui.TransformSourceResultUI;
import com.eactive.eai.rms.onl.manage.serviceinfo.eaimsg.EaiMsgManService;
import com.eactive.eai.rms.onl.transaction.apim.ApiInterfaceService;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

@Controller
@RequestMapping(value={"/loader.do","/loader.json"})
public class LoaderController implements InterceptorSkipController {

    private static final Logger logger = Logger.getLogger(LoaderController.class);
    private static final String resultView ="common/loadResult";
    
    @Autowired 
    @Qualifier("monitoringContext")
    private MonitoringContext monitoringContext;

    @Autowired
    @Qualifier("loaderService")
    private TransactionLoaderService loaderService;
    
    
    /** The agentUtil service. */
    @Autowired
    @Qualifier("onlAgentUtilService")
    public AgentUtilService agentUtilService;    
    
    @Autowired
	@Qualifier("ruleDeployJobService")
	public RuleDeployJobService ruleDeployJobService;

	@Autowired
	private EaiMsgManService eaiMessageService;

	@Autowired
	private Transform2Service transform2Service;

	@Autowired
	private ApiInterfaceService apiInterfaceService;


	@Autowired
	private InterfaceDeployService interfaceDeployService;

	@Autowired
	private LayoutDeployService layoutDeployService;

	@Autowired
	private TransformDeployService transformDeployService;


	/**
     * 형상관리에서 layout을 로딩한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=layout","control=upload"})
    public ModelAndView layoutLoad(HttpServletRequest request, HttpServletResponse response ,String method, String serviceType , String bzwkDstcd, String fileName ) throws Exception {
    	long sTotalTime = System.currentTimeMillis();
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
    	
        String iomapPath = "";
        if("aio".equals(method)){
        	iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_AIO_PATH);
        }else{
        	iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_PATH);
        }
        
        String savePath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_AFTER_UPLOAD_PATH);
        String subPath = serviceType + File.separator + bzwkDstcd + File.separator + FileWriteUtil.LAYOUT + File.separator;
        String path = iomapPath + subPath ;
        
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }
        try{
        	if (serviceType != null) {
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){ //취약점소스 수정 2020.08.27
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.insertLayoutLoading(dt,path , fileName );
        		}
        	}
        	
        	//logger.info("-----layout UpLoad Db Start-----");
        	long sTimeForDb = System.currentTimeMillis();
	        long eTimeForDb = System.currentTimeMillis();
	        long dbTime = eTimeForDb-sTimeForDb;
        	
	        
	        //logger.info("-----layout Upload Mem Start-----");
        	long sTimeForMem = System.currentTimeMillis();
        	HashMap result = syncResult(new CommonCommand("com.eactive.eai.agent.transformer.ReloadLayoutCommand") , fileName );
        	long eTimeForMem = System.currentTimeMillis();
        	long memTime = eTimeForMem-sTimeForMem;
        	//logger.info("2:Memory Processed Time : " + (eTimeForMem-sTimeForMem));
	        
        	//HashMap result = new HashMap();
	        //result.put("status", "success");
	        
	        long eTotalTime = System.currentTimeMillis();
	        long totTime = eTotalTime-sTotalTime;
        	//logger.info("           FILENAME                DB                MEM                 TOTAL" );
        	logger.info("LoaderLogging	Layout     "+fileName+"          "+dbTime+"         "+memTime+"          "+totTime);

        	//file move
        	if (!((String)result.get("status")).equals("error")){
	        	String today =DateUtil.getDateTime("yyyy-MM-dd");
	        	String newPath = savePath  + today + File.separator + subPath;
	        	try{
	        		Boolean isMoved = SimpleFileUtils.moveFile(path, newPath,fileName, fileName);
	        		if(isMoved){
	        			logger.info(fileName + " is moved to " + newPath);
	        		}else{
	        			logger.info(fileName + " is moved NOT to " + newPath);
	        		}
	        	}catch(Exception e){
	        		logger.info("Failed to move File");
	        	}
        	}
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
//	        return new ModelAndView(resultView, "result", result.toString());
	    }catch(Exception e){
	    	HashMap result = new HashMap();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("layout Load Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	    }  
	    
    }
    
    

  
    /**
     * 형상관리에서 transform을 로딩한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=transform","control=upload"})
    public ModelAndView transformLoad(HttpServletRequest request, HttpServletResponse response ,String method, String serviceType , String bzwkDstcd, String fileName ) throws Exception {
    	long sTotalTime = System.currentTimeMillis();
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        String iomapPath = "";
        if("aio".equals(method)){
        	iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_AIO_PATH);
        }else{
        	iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_PATH);
        }
        String savePath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_AFTER_UPLOAD_PATH);
        String subPath = serviceType + File.separator + bzwkDstcd + File.separator + FileWriteUtil.TRANSFORM + File.separator;
        String path = iomapPath + subPath ;

        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }        
        try{
        	if (serviceType != null) {
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		
        		if(dt != null){//취약점소스 수정 2020.08.27
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.insertTransformLoading(dt,path , fileName );
        		}
        		
        	}

        	//logger.info("-----transform UpLoad Db Start-----");
        	long sTimeForDb = System.currentTimeMillis();
        	long eTimeForDb = System.currentTimeMillis();
        	long dbTime = eTimeForDb-sTimeForDb;
        	//logger.info("Db Processed Time : " + (eTimeForDb-sTimeForDb));
        	
        	//logger.info("-----transform Upload Mem Start-----");
        	long sTimeForMem = System.currentTimeMillis();
        	HashMap result = syncResult(new CommonCommand("com.eactive.eai.agent.transformer.ReloadTransformCommand") , fileName );
        	long eTimeForMem = System.currentTimeMillis();
        	//logger.info("Memory Processed Time : " + (eTimeForMem-sTimeForMem));
	        
        	long memTime = eTimeForMem-sTimeForMem;
	        
	        long eTotalTime = System.currentTimeMillis();
	        long totTime = eTotalTime - sTotalTime;
	        logger.info("LoaderLogging	Transform     "+fileName+"          "+dbTime+"         "+memTime+"          "+totTime);

        	//file move
        	if (!((String)result.get("status")).equals("error")){
	        	String today =DateUtil.getDateTime("yyyy-MM-dd");
	        	String newPath = savePath  + today + File.separator + subPath;
	        	try{
	        		Boolean isMoved = SimpleFileUtils.moveFile(path, newPath,fileName, fileName);
	        		if(isMoved){
	        			logger.info(fileName + " is moved to " + newPath);
	        		}else{
	        			logger.info(fileName + " is moved NOT to " + newPath);
	        		}
	        	}catch(Exception e){
	        		logger.info("Failed to move File");
	        	}
        	}
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
//	        return new ModelAndView(resultView, "result", result.toString());
        }catch(Exception e){
	    	HashMap result = new HashMap();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("transform Load Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }
    }    
    /**
     * 형상관리에서 interface을 로딩한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=interface","control=upload"})
    public ModelAndView interfaceLoad(HttpServletRequest request, HttpServletResponse response ,String method, String serviceType , String bzwkDstcd, String fileName ) throws Exception {
    	long sTotalTime = System.currentTimeMillis();
    	//logger.info("------------- INTERFACE --------------");
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
    	
        String iomapPath = "";
        if("aio".equals(method)){
        	iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_AIO_PATH);
        }else{
        	iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_PATH);
        }
        String savePath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_AFTER_UPLOAD_PATH);
        String subPath = serviceType + File.separator + bzwkDstcd + File.separator + FileWriteUtil.INTERFACE + File.separator;
        String path = iomapPath + subPath ;
        
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }

        try{
        	if (serviceType != null) {
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){
        			//취약점소스 수정 2020.08.27
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.insertInterfaceLoading(dt,path , fileName );
        		}
        		
        	}

        	long sTimeForDb = System.currentTimeMillis();
        	long eTimeForDb = System.currentTimeMillis();
            long dbTime = eTimeForDb-sTimeForDb;
	        
       	//logger.info("-----interface Upload Mem Start-----");
        	long sTimeForMem = System.currentTimeMillis();
        	
	        //eaimessage reload 
        	//--EAI헤더 공통부 정보 (HE01)
        	//--EAI헤더 개별부 정보 (HE02)
        	//--조건부 라우팅 정보  (FR01)
        	//--참조정보            (MS02)         	
        	HashMap result = syncResult(new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageCommand") , fileName );
        	//eaimessage정상 reload 확인
        	if (((String)result.get("status")).equals("error")){
        		return new ModelAndView(resultView, "result", result.toString());
        	}
        	HashMap map = loaderService.parse(path + fileName);
        	ArrayList list = null;
       		//필드추출 정보
        	list = (ArrayList)map.get("TSEAIFR03");
        	if (list != null && list.size() > 0){
        		HashMap row = (HashMap)list.get(0);
            	//필드추출 정보 reload
            	result = new HashMap();
            	result = syncResult(new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand") , fileName );
            	if (((String)result.get("status")).equals("error")){
            		return new ModelAndView(resultView, "result", result.toString());
            	}
        	}
        	
        	//내부표준전문 키 추출
        	list = (ArrayList)map.get("TSEAIHS04");
        	
        	if (list != null && list.size() > 0){
        		HashMap row = (HashMap)list.get(0);
            	//내부표준message reload
        		String bzwkKey = row.get("BZWKSVCKEYNAME")+".txt";
            	result = new HashMap();
            	result = syncResult(new CommonCommand("com.ext.eai.agent.stdmessage.ReloadSTDMessageCommand") , bzwkKey );
            	if (((String)result.get("status")).equals("error")){
            		return new ModelAndView(resultView, "result", result.toString());
            	}
        	}
        	long eTimeForMem = System.currentTimeMillis();
        	long memTime = eTimeForMem - sTimeForMem;
        	//logger.info("Memory Processed Time : " + (eTimeForDb-sTimeForDb));
	        
	        long eTotalTime = System.currentTimeMillis();
	        long totTime = eTotalTime - sTotalTime;
	        

        	logger.info("LoaderLogging	Interface     "+fileName+"          "+dbTime+"         "+memTime+"          "+totTime);
        	
        	if (!((String)result.get("status")).equals("error")){
	        	String today =DateUtil.getDateTime("yyyy-MM-dd");
	        	String newPath = savePath  + today + File.separator + subPath;
	        	try{
	        		Boolean isMoved = SimpleFileUtils.moveFile(path, newPath,fileName, fileName);
	        		if(isMoved){
	        			logger.info(fileName + " is moved to " + newPath);
	        		}else{
	        			logger.info(fileName + " is moved NOT to " + newPath);
	        		}
	        	}catch(Exception e){
	        		logger.info("Failed to move File");
	        	}
        	}
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}        	
//	        return new ModelAndView(resultView, "result", result.toString());
        }catch(Exception e){
	    	HashMap result = new HashMap();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("interface Load Exception " +e.getMessage(),e);
	    	return new ModelAndView(resultView, "result", result);
        }
    } 
    /**
     * 형상관리에서 adapter을 로딩한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=adapter","control=upload"})
    public ModelAndView adapterLoad(HttpServletRequest request, HttpServletResponse response ,String serviceType , String fileName ) throws Exception {
        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_PATH);
        String path = iomapPath + serviceType + File.separator + "TST" + File.separator + FileWriteUtil.ADAPTER + File.separator ;
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }

        try{
        	if (serviceType != null) {
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){//취약점소스 수정 2020.08.27
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.insertAdapterLoading(dt, path, fileName);
        		}
        		
        	}
        	
        	//내부표준전문 키 추출
        	//HashMap map = loaderService.parse(path + fileName);
        	
        	HashMap result = new HashMap();
        	result.put("status", "success");
	    	result.put("message", "");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
//        	return new ModelAndView(resultView, "result", result.toString());
        }catch(Exception e){
	    	HashMap result = new HashMap();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("adapter Load Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }
    }     
    /**
     * 형상관리에서 adapter을 로딩한다. (메모리 동기화)
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=adapter","control=uploadSync"})
    public ModelAndView adapterLoadSync(HttpServletRequest request, HttpServletResponse response ,String serviceType , String fileName ) throws Exception {
    	String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_PATH);
    	String path = iomapPath + serviceType + File.separator + "TST" + File.separator + FileWriteUtil.ADAPTER + File.separator ;
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
    	if (!DataSourceTypeManager.isOnlineForName(serviceType)){
    		HashMap<String,String> result = new HashMap<String,String>();
    		result.put("status", "error");
    		result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
    	}
    	
    	try{
        	if (serviceType != null) {
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){ //취약점소스 수정 2020.08.27
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.insertAdapterLoadingSync(dt,path , fileName);
        		}
        		
        	}
    		
    		HashMap result = new HashMap();
    		//내부표준전문 키 추출
    		HashMap map = loaderService.parse(path + fileName);
    		ArrayList list = (ArrayList)map.get("TSEAIAD14");
    		if (list == null){
    			throw new Exception ("Cannot find the Property Group Name");
    		}
    		
    		for (int i=0;i<list.size();i++){
    			HashMap row = (HashMap)list.get(i);
    			//property group name reload
    			String prptyGroupName = row.get("PRPTYGROUPNAME")+".txt";
    			
    			result = syncResult(new CommonCommand("com.eactive.eai.agent.adapter.ReloadAdapterPropGroupCommand") , prptyGroupName );
    			if (((String)result.get("status")).equals("error")){
    		    	if (isJSONResult){
    		    		return new ModelAndView("jsonView", result);
    		    	}else{
    		    		return new ModelAndView(resultView, "result", result);
    		    	}
//    				return new ModelAndView(resultView, "result", result.toString());
    			}
    		}
    		
    		result = syncResult(new CommonCommand("com.eactive.eai.agent.adapter.ReloadAdapterGroupCommand") , fileName );
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}    		
//    		return new ModelAndView(resultView, "result", result.toString());
    	}catch(Exception e){
    		HashMap result = new HashMap();
    		result.put("status", "error");
    		result.put("message", e.getMessage());
    		logger.error("adapter Load Sync Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
    	}
    }     
    /**
     * 형상관리에서 adapter을 로딩한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=adapter","control=uploadall"})
    public ModelAndView adapterLoadAll(HttpServletRequest request, HttpServletResponse response ,String serviceType ) throws Exception {
        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_PATH);
        String path = iomapPath + serviceType + File.separator + "TST" + File.separator + FileWriteUtil.ADAPTER + File.separator ;
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }

        try{
        	if (serviceType != null) {
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){//취약점소스 수정 2020.08.27
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.insertAdapterLoadingAll(dt,path );
        		}
        		
        	}

        	HashMap result = new HashMap();
	    	result.put("status", "success");
	    	result.put("message", "");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
//	        return new ModelAndView(resultView, "result", result.toString());
        }catch(Exception e){
	    	HashMap result = new HashMap();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("adapter Load All Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }
    }   
    
    private HashMap syncResult(Command command ,String fileName ) throws Exception {
        //layout 동기화 service 에는 transaction 때문에 문제의 소지가 있음
        HashMap receive =new HashMap(); 
        HashMap result = new HashMap();
        
        if(fileName !=  null){
			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;
	        	}
	        }
	       
	        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;
    }    
    /**
     * 형상관리에서 layout을 download한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=layout","control=download"})
    public ModelAndView layoutDownLoad(HttpServletRequest request, HttpServletResponse response ,String serviceType , String bzwkDstcd, String fileName ) throws Exception {
        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DOWNLOAD_PATH);
        String path = iomapPath + serviceType + File.separator + bzwkDstcd + File.separator + FileWriteUtil.LAYOUT + File.separator ;
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }
        try{
        	if (fileName != null && serviceType != null) {
        		String[] temp = fileName.split("[.]");
        		String serviceName = temp[0];
        		
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.layoutDownLoading(dt,path , serviceName );
        		}
        	}

	        HashMap<String,String> result = new HashMap<String,String>();
	        String status = "success";
	        result.put("status", status);
	        result.put("message", "");
	        if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	        }else{
	        	return new ModelAndView(resultView, "result", result.toString());
	        }
	    }catch(Exception e){
	    	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("layout DownLoad Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	        }else{
	        	return new ModelAndView(resultView, "result", result);
	        }
	    }  
	    
    }
    /**
     * 형상관리에서 layout 전체를 download한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=layout","control=downloadall"})
    public ModelAndView layoutDownLoadAll(HttpServletRequest request, HttpServletResponse response ,String serviceType ) throws Exception {
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }

        try{
        	if (serviceType != null) {
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.layoutDownLoadingAll( dt ,serviceType);
        		}
        	}

	        HashMap<String,String> result = new HashMap<String,String>();
	        String status = "success";
	        result.put("status", status);
	        result.put("message", "");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	        //return new ModelAndView(resultView, "result", result.toString());
	    }catch(Exception e){
	    	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("layout DownLoad All Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	    }  
	    
    }    
    
    
    
    /**
     * 형상관리에서 transform을 download한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=transform","control=download"})
    public ModelAndView transformDownLoad(HttpServletRequest request, HttpServletResponse response ,String serviceType , String bzwkDstcd, String fileName ) throws Exception {
        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DOWNLOAD_PATH);
        String path = iomapPath + serviceType + File.separator + bzwkDstcd + File.separator + FileWriteUtil.TRANSFORM + File.separator ;
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }
        try{
        	if (fileName != null && serviceType != null) {
        		String[] temp = fileName.split("[.]");
        		String serviceName = temp[0]; 
        		
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.transformDownLoading(dt,path , serviceName );
        		}
        	}
        	
	        HashMap<String,String> result = new HashMap<String,String>();
	        String status = "success";
	        result.put("status", status);
	        result.put("message", "");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	        //return new ModelAndView(resultView, "result", result.toString());
        }catch(Exception e){
	    	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("transform DownLoad Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }
    }    
    
    /**
     * 형상관리에서 transform 전체를 download한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=transform","control=downloadall"})
    public ModelAndView transformDownLoadAll(HttpServletRequest request, HttpServletResponse response ,String serviceType ) throws Exception {
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }

        try{
        	if (serviceType != null) {
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.transformDownLoadingAll( dt ,serviceType);
        		}
        	}

	        HashMap<String,String> result = new HashMap<String,String>();
	        String status = "success";
	        result.put("status", status);
	        result.put("message", "");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	        //return new ModelAndView(resultView, "result", result.toString());
	    }catch(Exception e){
	    	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("transform DownLoad All Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	    }  
	    
    }      
    /**
     * 형상관리에서 interface을 download한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=interface","control=download"})
    public ModelAndView interfaceDownLoad(HttpServletRequest request, HttpServletResponse response ,String serviceType , String bzwkDstcd, String fileName ) throws Exception {
        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DOWNLOAD_PATH);
        String path = iomapPath + serviceType + File.separator + bzwkDstcd + File.separator + FileWriteUtil.INTERFACE + File.separator ;
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }

        try{
        	if (fileName != null && serviceType != null) {
        		String[] temp = fileName.split("[.]");
        		String serviceName = temp[0]; 
        		
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.interfaceDownLoading(dt,path , serviceName );
        		}
        	}
        	
	        HashMap<String,String> result = new HashMap<String,String>();
	        String status = "success";
	        result.put("status", status);
	        result.put("message", "");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	        //return new ModelAndView(resultView, "result", result.toString());
        }catch(Exception e){
	    	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("interface DownLoad Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }
    }    
    /**
     * 형상관리에서 interface 전체를 download한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=interface","control=downloadall"})
    public ModelAndView interfaceDownLoadAll(HttpServletRequest request, HttpServletResponse response ,String serviceType ) throws Exception {
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }

        try{
        	if (serviceType != null) {
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.interfaceDownLoadingAll( dt ,serviceType);
        		}
        		
        	}

	        HashMap<String,String> result = new HashMap<String,String>();
	        String status = "success";
	        result.put("status", status);
	        result.put("message", "");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	        //return new ModelAndView(resultView, "result", result.toString());
	    }catch(Exception e){
	    	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("interface DownLoad All Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	    }  
	    
    }        
    /**
     * 형상관리에서 adapter을 download한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=adapter","control=download"})
    public ModelAndView adapterDownLoad(HttpServletRequest request, HttpServletResponse response ,String serviceType , String bzwkDstcd, String fileName ) throws Exception {

        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DOWNLOAD_PATH);
        String path = iomapPath + serviceType + File.separator + "TST" + File.separator + FileWriteUtil.ADAPTER + File.separator ;
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }

        try{
        	
        	if (fileName != null && serviceType != null) {
        		String[] temp = fileName.split("[.]");
        		String serviceName = temp[0];
        		
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.adapterDownLoading(dt, path, serviceName);
        		}
        	}
        	
	        HashMap<String,String> result = new HashMap<String,String>();
	        String status = "success";
	        result.put("status", status);
	        result.put("message", "");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}	        
	        //return new ModelAndView(resultView, "result", result.toString());
        }catch(Exception e){
	    	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("adapter DownLoad Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }
    }    
    /**
     * 형상관리에서 adapter을 download한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=adapter","control=downloadall"})
    public ModelAndView adapterDownLoadAll(HttpServletRequest request, HttpServletResponse response ,String serviceType ,String like ) throws Exception {

        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DOWNLOAD_PATH);
        String path = iomapPath + serviceType + File.separator + "TST" + File.separator + FileWriteUtil.ADAPTER + File.separator ;
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }

        try{
        	if (like == null || "".equals(like) ){
        		like ="%";
        	}else{
        		like = "%"+like +"%";
        	}
        	
        	if (serviceType != null) {
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.adapterDownLoadingAll( dt, path, like);
        		}
        	}

	        HashMap<String,String> result = new HashMap<String,String>();
	        String status = "success";
	        result.put("status", status);
	        result.put("message", "");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}	        
	        //return new ModelAndView(resultView, "result", result.toString());
        }catch(Exception e){
	    	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("adapter DownLoad All Exception " +e.getMessage(),e);
	    	return new ModelAndView(resultView, "result", result);
        }
    }   
    
    /**
     * 형상관리에서 table을 로딩한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=admin","control=upload"})
    public ModelAndView adminLoad(HttpServletRequest request, HttpServletResponse response ,String serviceType , String bzwkDstcd, String fileName ) throws Exception {

        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_PATH);
        String path = iomapPath + serviceType + File.separator + bzwkDstcd + File.separator + FileWriteUtil.ADMIN + File.separator ;
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (serviceType != null && !DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }
        try{
        	if (serviceType != null) {
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null ){//취약점소스 수정 2020.08.25
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.insertTableLoading(dt,path , fileName );
        		}
        		
        	}
        	
	        HashMap result = new HashMap();
	    	result.put("status", "success");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	    	//return new ModelAndView(resultView, "result", result.toString());
	    }catch(Exception e){
	    	HashMap result = new HashMap();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("admin Load Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	    }  
    }     
    /**
     * 형상관리에서 table을 download한다.
     * *
     * @param request
     * @param response
     * @param schema
     * @return
     * @throws Exception
     */
    @RequestMapping( params ={"cmd=admin","control=download"})
    public ModelAndView adminDownLoad(HttpServletRequest request, HttpServletResponse response ,String serviceType , String bzwkDstcd, String fileName ) throws Exception {

        String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DOWNLOAD_PATH);
        String path = iomapPath + serviceType + File.separator + bzwkDstcd + File.separator + FileWriteUtil.ADMIN + File.separator ;
        boolean isJSONResult=false;
        if (request.getRequestURI().endsWith("json")){
        	isJSONResult = true;
        }
        if (!DataSourceTypeManager.isOnlineForName(serviceType)){
        	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
        }
        try{
        	
        	if (fileName != null && serviceType != null) {
        		String[] temp = fileName.split("[.]");
        		String tableName = temp[0];
        		
        		request.getSession().setAttribute(CommonConstants.SERVICE_TYPE_KEY, serviceType);
        		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
        		if(dt != null){
        			DataSourceContextHolder.setDataSourceType(dt);
        			loaderService.tableDownLoading(dt,path , tableName );
        		}
        		
        	}

	        HashMap<String,String> result = new HashMap<String,String>();
	        String status = "success";
	        result.put("status", status);
	        result.put("message", "");
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	        //return new ModelAndView(resultView, "result", result.toString());
	    }catch(Exception e){
	    	HashMap<String,String> result = new HashMap<String,String>();
	    	result.put("status", "error");
	    	result.put("message", e.getMessage());
	    	logger.error("admin DownLoad Exception " +e.getMessage(),e);
	    	if (isJSONResult){
	    		return new ModelAndView("jsonView", result);
	    	}else{
	    		return new ModelAndView(resultView, "result", result);
	    	}
	    }  
	    
    }    
    
    @RequestMapping(params ={"cmd=interface","control=file-upload"}, method = RequestMethod.POST)
	public ModelAndView uploadInterfaceFile(@RequestParam("file") MultipartFile multipartFile,
			String serviceType, String bzwkDstcd, String cmd) throws Exception {
		return uploadeFile(multipartFile, serviceType, bzwkDstcd, cmd);
	}
    
    @RequestMapping(params ={"cmd=layout","control=file-upload"}, method = RequestMethod.POST)
    public ModelAndView uploadLayoutFile(@RequestParam("file") MultipartFile multipartFile,
    		String serviceType, String bzwkDstcd, String cmd) throws Exception {
    	return uploadeFile(multipartFile, serviceType, bzwkDstcd, cmd);
    }
    
    @RequestMapping(params ={"cmd=transform","control=file-upload"}, method = RequestMethod.POST)
    public ModelAndView uploadTransformFile(@RequestParam("file") MultipartFile multipartFile,
    		String serviceType, String bzwkDstcd, String cmd) throws Exception {
    	return uploadeFile(multipartFile, serviceType, bzwkDstcd, cmd);
    }
    
    @RequestMapping(params ={"cmd=adapter","control=file-upload"}, method = RequestMethod.POST)
    public ModelAndView uploadAdapterFile(@RequestParam("file") MultipartFile multipartFile,
    		String serviceType, String bzwkDstcd, String cmd) throws Exception {
    	return uploadeFile(multipartFile, serviceType, bzwkDstcd, cmd);
    }
    
    private ModelAndView uploadeFile(MultipartFile multipartFile, String serviceType, String bzwkDstcd, String dataType) throws IOException {
		logger.info("### " + dataType + " upload start");

		String iomapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_PATH);
		String subPath = serviceType + File.separator + bzwkDstcd + File.separator + dataType + File.separator;
		String path = iomapPath + subPath ;

		String fullyFileName = FilenameUtils.concat(path, multipartFile.getOriginalFilename());
		File targetFile = new File(fullyFileName);
		try {
			InputStream fileStream = multipartFile.getInputStream();
			FileUtils.copyInputStreamToFile(fileStream, targetFile);
		} catch (IOException e) {
			FileUtils.deleteQuietly(targetFile);
			logger.error(e);
			throw e;
		}

		logger.info("### success " + dataType + " file upload - " + path);
		HashMap<String,String> result = new HashMap<String,String>();
		String status = "success";
		result.put("status", status);
		result.put("message", "");

		return new ModelAndView(resultView, "result", result.toString());
	}
    
    /**
	 * 배포된 데이터의 로딩 스케쥴을 등록한다.
	 * @param request
	 * @param response
	 * @param method
	 * @param serviceType
	 * @param bzwkDstcd
	 * @param fileName
	 * @param onlyDB
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(params = { "cmd=schedule", "control=upload" })
	public ModelAndView scheduleDeployDataApply(HttpServletRequest request, HttpServletResponse response, String userId,
			String userIp, String serviceType, String cmTitle, String cmDate, String cmTime, String items)
			throws Exception {
		try {
			if (StringUtils.isBlank(items)) {
				throw new Exception("No have datas");
			}

			RuleDeployJobVo jobVo = new RuleDeployJobVo();
			jobVo.setJobId(DatetimeUtil.getCurrentTimeMillis());
			jobVo.setFailedCnt(0);
			jobVo.setScheduledDateTime(cmDate + cmTime);
			jobVo.setJobTitle(URLDecoder.decode(cmTitle));
			jobVo.setServiceType(serviceType);
			jobVo.setStatus("standby"); // working, finished, failed
			jobVo.setUserId(userId);
			jobVo.setUserIp(userIp);
			jobVo.setItemList(new ArrayList<RuleDeployJobItemVo>());

			String itemArr[] = items.split("\n");
			for (String itemStr : itemArr) {
				// COP|219036|COP_OPB0210300000_CBS.txt|FEP/COP/layout|layout|
				String item[] = itemStr.split("\\|");
				if (item.length >= 5) {
					RuleDeployJobItemVo itemVo = new RuleDeployJobItemVo();
					itemVo.setBizCode(item[0]);
					itemVo.setFileName(item[2]);
					itemVo.setJobId(jobVo.getJobId());
					itemVo.setRuleType(item[4]);
					jobVo.getItemList().add(itemVo);
				}
			}

			boolean result = true;
			if (System.currentTimeMillis() >= DatetimeUtil.getLongTimeFormat("yyyyMMddHHmmss", cmDate + cmTime)) {
				// 룰정보 적재 및 메모리 로딩
				result = loaderService.ruleDataSaveAndLoading(jobVo);
				if (result) {
					jobVo.setStatus("finished");
				} else {
					jobVo.setFailedCnt(jobVo.getFailedCnt() + 1);
				}

				jobVo.setLastJobTime(DatetimeUtil.getCurrentDateTime());
			}

			logger.debug("jobVo=" + jobVo.toString());

			ruleDeployJobService.insert(jobVo);

			if (!result) {
				throw new Exception("Job failed");
			}
		} catch (Exception e) {
			throw new Exception("Job failed:" + e.getMessage());
		}

		return new ModelAndView(resultView, "result", "Rule Data Load Success");
	}

	/**
	 * 대상 INTERFACE ID 기준으로 INTERFACE, LAYOUT, TRANSFORM을 모두 포함한 JSON DEPLOY 파일을 다운로드(서버) 한다.
	 * @param serviceType
	 * @param interfaceId
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping( params ={"cmd=interface","control=downloadfull"})
	public ModelAndView interfaceDownLoadFully(String serviceType, String interfaceId) throws Exception {
		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
		DataSourceContextHolder.setDataSourceType(dt);

		// 1. interface 데이터 다운로드
		InterfaceDeployPack interfaceDeployPack = new InterfaceDeployPack();

		EAIMessageDeploy eaiMessageDeploy = interfaceDeployService.selectDeploy(interfaceId);
		eaiMessageDeploy.setEailastamndyms(null);

		interfaceDeployPack.setEaiMessageDeploy(eaiMessageDeploy);

		for(StandardMessageInfoDeploy standardMessageInfoDeploy : eaiMessageDeploy.getStandardMessageInfoDeploys()){
			standardMessageInfoDeploy.setEailastamndyms(null);
		}

		for (ServiceMessageDeploy serviceMessageDeploy : eaiMessageDeploy.getServiceMessages()){
			String[] transformNames = {serviceMessageDeploy.getChngmsgidname(), serviceMessageDeploy.getBascrspnschngmsgidname()};
			// 2. Layout 데이터 생성
			for(String transformName: transformNames){
				if(StringUtils.isBlank(transformName)){
					continue;
				}
				
				for(TransformSourceResultUI transformSourceResultUI : transform2Service.selectTransformSourceResult(transformName)){
					String loutName = transformSourceResultUI.getLoutName();
					if(StringUtils.isBlank(loutName)){
						continue;
					}
					LayoutDeploy layoutDeploy = layoutDeployService.selectDeploy(loutName);
					layoutDeploy.setLastamndhms(null);
					interfaceDeployPack.getLayoutDeployList().add(layoutDeploy);
				}

				// 3. Transform 데이터 생성
				TransformDeploy transformDeploy = transformDeployService.selectDeploy(transformName);
				transformDeploy.setLastamndhms(null);
				interfaceDeployPack.getTransformDeployList().add(transformDeploy);
			}
		}

		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.registerModule(new JavaTimeModule());
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
		String bizCode = eaiMessageDeploy.getEaibzwkdstcd();
		String ioMapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DOWNLOAD_PATH);
		String fileDir = FilenameUtils.concat(ioMapPath, bizCode);
		String fileFullPath = FilenameUtils.concat(fileDir, interfaceId+".json");

		FileWriteUtil.makeDirWithGroupPermission(fileDir);
		File file = new File(fileFullPath);
		writer.writeValue(file, interfaceDeployPack);

		Map<String,String> result = new HashMap<>();
		String status = "success";
		result.put("status", status);
		result.put("message", fileFullPath+" write done.");

		return new ModelAndView(resultView, "result", result);
	}

	/**
	 * 대상 INTERFACE ID 기준으로 INTERFACE, LAYOUT, TRANSFORM을 모두 포함한 JSON DEPLOY 파일을 로드(서버) 및 배포 한다.
	 * @param serviceType
	 * @param bizCode
	 * @param interfaceId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping( params ={"cmd=interface","control=uploadfull"})
	public ModelAndView interfaceLoadFully(String serviceType, String filePath) throws Exception {
		DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
		DataSourceContextHolder.setDataSourceType(dt);

		String ioMapPath = monitoringContext.getStringProperty(MonitoringContext.IOMAP_UPLOAD_PATH);
		String fileFullPath ;
		if(StringUtils.isBlank(ioMapPath)) {
			fileFullPath = filePath;
		} else {
			fileFullPath = FilenameUtils.concat(ioMapPath, filePath);
		}
		
		File file = new File(fileFullPath);
		InputStream inputStream = new FileInputStream(file);
		// ObjectMapper 생성 및 설정
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.registerModule(new JavaTimeModule());
		InterfaceDeployPack interfaceDeployPack = objectMapper.readValue(inputStream, InterfaceDeployPack.class);

		EAIMessageDeploy eaiMessageDeploy = interfaceDeployPack.getEaiMessageDeploy();

		interfaceDeployService.saveDeploy(eaiMessageDeploy);
		agentUtilService.broadcast(new CommonCommand("com.ext.eai.agent.stdmessage.ReloadSTDMessageCommand", "ALL"));
		agentUtilService.broadcast(new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageCommand", eaiMessageDeploy.getEaisvcname()));

		for(LayoutDeploy layoutDeploy: interfaceDeployPack.getLayoutDeployList()){
			layoutDeployService.saveDeploy(layoutDeploy);
			agentUtilService.broadcast(new CommonCommand( "com.eactive.eai.agent.transformer.ReloadLayoutCommand", layoutDeploy.getLoutname()));
		}

		for(TransformDeploy transformDeploy : interfaceDeployPack.getTransformDeployList()){
			transformDeployService.saveDeploy(transformDeploy);
			agentUtilService.broadcast(new CommonCommand( "com.eactive.eai.agent.transformer.ReloadTransformCommand", transformDeploy.getCnvsnname()));
		}
		
		Map<String,String> result = new HashMap<String,String>();
		String status = "success";
		result.put("status", status);
		result.put("message", fileFullPath+" deploy done.");

		return new ModelAndView(resultView, "result", result);
	}

}
