package com.eactive.eai.rms.bap.manage.mmi;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

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

import org.apache.log4j.Logger;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
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.servlet.View;

import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.common.util.NullControl;
import com.eactive.eai.common.util.StringUtil;
import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.rms.common.base.BapBaseAnnotationController;
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.logging.UserAccessLogger;
import com.eactive.eai.rms.common.mmilog.MMILogDao;
import com.eactive.eai.rms.onl.common.util.DateUtil;

@Controller
public class MMIBAPSyncController extends BapBaseAnnotationController implements InterceptorSkipController {

	private static final Logger logger = Logger.getLogger(MMIBAPSyncController.class);

	@Autowired
	@Qualifier("mmiBapSyncService")
	private MMIBAPSyncService service;

	@Autowired
	private MonitoringContext monitoringContext;

	@Autowired
	@Qualifier("mmiLogDao")
	private MMILogDao mmiLogDao;

	@RequestMapping(value= "/mmiBapSync.file",params = "cmd=delete", method=RequestMethod.POST)
	public View messageDelete(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String encoding = request.getHeader("encoding");
		if (encoding != null) {
			request.setCharacterEncoding(encoding);
			response.setCharacterEncoding(encoding);
		}

		HashMap<String,Object> map = new HashMap<String,Object>();
		ServletInputStream sis = null;
		StringBuilder sb = new StringBuilder();
		StringBuilder frame = new StringBuilder();

		try {
			sis = request.getInputStream();
			String data = streamToString(sis,encoding);
			logger.info("### received XML : "+data);

			map = MMIBAPParser.parseDelete(data);

			service.delete(map);

			//일괄 인터페이스 동기화
			CommonCommand command = new CommonCommand("com.eactive.eai.agent.rule.dirInfo.RefreshAllJobCommand");
			if (!validate(agentUtilService.broadcast(command)))	throw new Exception("일괄 인터페이스 동기화 오류");

			sb.append(resultInterface(map.get(MMIBAPParserKey.MMI_INTF_ID).toString(), map.get(MMIBAPParserKey.VERSION).toString(), "SUCCESS", ""));
		} catch(Exception e){
			logger.error("MMIBAPSyncController error="+e.getMessage(),e);
			sb.append(resultInterfaceDelete(map.get(MMIBAPParserKey.MMI_INTF_ID).toString(), map.get(MMIBAPParserKey.INTF_ID).toString(), "FAIL",e.getMessage()));	        
		}

      frame.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		frame.append("<Deploy>");
		frame.append(sb.toString());
		frame.append("</Deploy>");

		ServletOutputStream sos = null;
		try {
			sos = response.getOutputStream();
			sos.write(frame.toString().getBytes());
		} catch( Exception e ) {
			//취약점소스 수정 2020.08.24
			logger.error(" error", e); 
		} finally {
			if( sos != null ) sos.close();
		}
		return null;
	}


	/**
	 * 통합인터페이스 시스템(EIMS)에서 일괄전송 파일송수신 전문 레이아웃에 대한 INSERT, UPDATE 요청
	 * *
	 * @param request
	 * @param response
	 * @param schema
	 * @return
	 * @throws Exception
	 */
	//    @RequestMapping(value= "/eimsbapcall.file", method=RequestMethod.POST)
	public View fileSndRevMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {

		UserAccessLogger.log(request, "메시지", "L", "cmd=Message");
		HashMap<String,Object> map = new HashMap<String,Object>();
		HashMap<String,Object> info = new HashMap<String,Object>();
		StringBuilder sb = new StringBuilder();
		StringBuilder frame = new StringBuilder();
		String userId        = "";
		String sysId = "";
		String fileName = "";
		String sndst = "";

		String serverType = monitoringContext.getStringProperty(MonitoringContext.MMI_SYNC_BAP_SERVERTYPE, "BAP");
		DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(serverType));

		logger.debug("parseMessage content-Type="+request.getContentType());
		logger.debug("parseMessage content-Values="+request.getParameterMap().values());		

		HashMap<String,Object> mmiLogMap = new HashMap<String,Object>();
		StringBuffer buffer = new StringBuffer();
		try{
			if (!SystemUtil.isDevServer()){
				throw new Exception("only support dev server ");
			}

			//			for (String key : request.getParameterMap().keySet()){
			//				String [] datas= request.getParameterValues(key);
			//				StringBuffer resultS = new StringBuffer();
			//				for(String data : datas){
			//					resultS.append(data);
			//				}
			//				buffer.append(resultS.toString()).append("\n");
			//				map.put(key, resultS);
			//			}
			//			logger.info("### New received XML : "+map);
			//
			//			if (key.startsWith("INTERFACE")){
			//				buffer.append(resultS.toString()).append("\n");
			//			}

			for (String key : request.getParameterMap().keySet()){
				String [] datas= request.getParameterValues(key);
				StringBuffer resultS = new StringBuffer();
				for(String data : datas){
					resultS.append(data);
				}
				if (key.startsWith("INTERFACE")){
					buffer.append(resultS.toString()).append("\n");
				}

				logger.info("New receive Data "+key+"="+resultS.toString());
				if(key.startsWith("INTERFACE")) {
					map.put(key, resultS.toString());
				}    
			}


			for(String key : map.keySet()){
				if (key.startsWith("INTERFACE") ){
					info = MMIBAPParser.parseInfoNew(map.get(key).toString());
				}
			}

			if (info == null){
				throw new Exception("인터페이스 정보가 존재하지 않습니다.");
			}

			logger.info("[ORG0]New map-->" + map);
			logger.info("[ORG0]New info-->" + info);
			for(String key : info.keySet()){
				logger.info("[ORG]New info-->" + (key == null ? " " : key) + ":" + (key == null ? " " : info.get(key)));
			}

			userId = (String)info.get(MMIBAPParserKey.THISMSGCHRGIDS); //당메시지담당자ID
			sysId = info.get(MMIBAPParserKey.SYSCD).toString();  //송신시스템

			//*********************************************************	        
			//** 임시 우케국 시스템코드 동기화 후 아래 거 풀어줘야 함 2021.07.20 장권진
			//*********************************************************
			//			List<Map<String, Object>> sysMapList = service.selectSysGbCd(sysId);
			//			if ( sysMapList == null || sysMapList.size() != 1 )
			//				throw new Exception("대외 시스템ID를 특정할 수 없습니다.");

			// validate data type & size
			String checkresult = service.checkFieldLength(info);
			if (checkresult != null) throw new Exception(checkresult);

			//            Map<String, Object> sysMap = sysMapList.get(0);
			for(String key : info.keySet()){
				logger.info("New info-->" + (key == null ? " " : key) + ":" + (key == null ? " " : info.get(key)));
			}

			//			for(String key : sysMap.keySet()){
			//				logger.info("New sysMap-->" + (key == null ? " " : key) + ":" + (key == null ? " " : sysMap.get(key)));
			//			}

			//			String eaiFileRecvUseYn = (String)info.get(MMIBAPSyncField.eaiFileRecvUseYn.name());
			//			if ( eaiFileRecvUseYn.equals("1") ){
			//				String rmtNodeName = service.getNdmNodeBySysId(info.get(MMIBAPSyncField.rmtNodeName.name()).toString());
			//				//System.out.println("info.get(MMIBAPSyncField.rmtNodeName.name()).toString()-->" + info.get(MMIBAPSyncField.rmtNodeName.name()).toString());
			//				//System.out.println("rmtNodeName-->" + rmtNodeName);
			//				info.put(MMIBAPSyncField.rmtNodeName.name(), rmtNodeName );
			//			}else{
			//				info.put(MMIBAPSyncField.rmtNodeName.name(), "" );
			//			}

			//** BjobBzwkDstcd, OsidInstiDstcd
			//			info.put(MMIBAPSyncField.bjobBzwkDstcd.name(), sysMap.get("BJOBBZWKDSTCD"));
			//			info.put(MMIBAPSyncField.osidInstiDstcd.name(), sysMap.get("OSIDINSTIDSTCD"));   //**대외기관구분코드 (사용안함)

			//			service.merge(info);

			logger.info("New sysId-->" + sysId );

			//*********************************************************
			//** 일괄 동기화 작업 보류함 --- 확인 후 조치 해야 함  2021.07.20 장권진
			//** IFBPKG.TSEAIBA07 테이블에 아무정보 없음 (참고사항)
			//*********************************************************
			//	        logger.info("New sysId2-->" + sysId.substring(4, 5) );
			//	        if ( sysId.substring(4, 5).equals("E")){
			//일괄 인터페이스 동기화
			//				CommonCommand command = new CommonCommand("com.eactive.eai.agent.rule.dirInfo.RefreshAllJobCommand");
			//				if (!validate(agentUtilService.broadcast(command)))	throw new Exception("일괄 인터페이스 동기화 오류");

			//	        	logger.info("New 일괄 인터페이스 동기화-->" + sysId);
			//	        }else{
			//	        	logger.info("New 일괄 인터페이스 동기화 안함 -->" + sysId);
			//	        }

			sb.append(resultInterface(info.get(MMIBAPParserKey.BJOBMSGDSTCD).toString(), "V0.1", "SUCCESS", "일괄전송 배포 성공하였습니다."));
		} catch(Exception e){
			logger.error("MMIBAPSyncController error="+e.getMessage(),e);
			sb.append(resultInterfaceDelete(info.get(MMIBAPParserKey.BJOBMSGDSTCD).toString(), "V0.1", "FAIL",e.getMessage()));
		} finally {
			//
		}

      frame.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		frame.append("<Deploy>");
		frame.append(sb.toString());
		frame.append("</Deploy>");

		//MMI Log data
		String schemaId = "";
		DataSourceType dt = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING);

		if(dt != null){//취약점소스 수정 2020.08.25
			DataSourceContextHolder.setDataSourceType(dt);
			schemaId =DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING).getSchema();
		}else{
			logger.error("DataSourceType is null");
			return null;
		}

		mmiLogMap.put("schemaId"     , schemaId);
		mmiLogMap.put("msgDpstHMS"   , DateUtil.getDateTimeMilliSecound());
		mmiLogMap.put("eaiSvcName"   , NullControl.addSpace(sysId + "_" + fileName));
		mmiLogMap.put("eaiSevrDstcd" , "0");
		mmiLogMap.put("cnvsnName"    , " " );
		mmiLogMap.put("loutName"     , " " );
		mmiLogMap.put("reqDstcd"     , NullControl.addSpace(buffer.toString()));
		mmiLogMap.put("resDstcd"     , NullControl.addSpace(frame.toString()));
		mmiLogMap.put("interfaceId"  , NullControl.addSpace(info.get(MMIBAPParserKey.BJOBMSGDSTCD).toString() ));
		mmiLogMap.put("deployId"     , NullControl.addSpace(userId));

		try{
			mmiLogDao.insert(mmiLogMap);
		}catch(Exception e){
			logger.error("db insert error : " + mmiLogMap.toString(),e);
		}

		ServletOutputStream sos = null;
		try {
			sos = response.getOutputStream();
			sos.write(frame.toString().getBytes());
		} catch( Exception e ) {
			//취약점소스 수정 2020.08.24
			logger.error(" error", e); 
		} finally {
			if( sos != null ) sos.close();
		}
		return null;
	}


	private boolean validate(HashMap<String,Object> map ){
		for(String key : map.keySet()){
			Object o = map.get(key);
			if (o instanceof String){
				if("sucess".equals((String)o)){
					;
				}else{
					return false;
				}
			}else{
				return false;
			}
		}
		return true;
	}

	private String resultInterface(String mmiIfId, String ver, String returnCode, String returnMessage){
		return "<Result> mmi_if_id=\""+mmiIfId+"\" ver=\""+ver+"\" return_code=\""+returnCode+"\" return_message=\""+returnMessage+"\" />";
	}
	private String resultInterfaceDelete(String mmiIfId, String id, String returnCode, String returnMessage){
		return "<Interface mmi_if_id=\""+mmiIfId+"\" id=\""+id+"\" return_code=\""+returnCode+"\" return_message=\""+returnMessage+"\" />";
	}

	private static String streamToString(InputStream is,String encoding) throws UnsupportedEncodingException{
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		int r;
		byte[] data = new byte[1024];
		try {
			while((r = is.read(data)) != -1){
				buffer.write(data,0,r);

			}
			buffer.flush();
		} catch (IOException e) {
			//e.printStackTrace();
			return "";
		}
		String s = new String(buffer.toByteArray(),encoding);

		return s;
	}


	/**
	 * 통합인터페이스 시스템(EIMS)에서 일괄전송 파일송수신 인터페이스에 대해 BJ10 테이블에 저장
	 * *
	 * @param request
	 * @param response
	 * @param schema
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value= "/eimsbapcall.file", method=RequestMethod.POST)
	public View deployBapInterface(HttpServletRequest request, HttpServletResponse response) throws Exception {

		UserAccessLogger.log(request, "메시지", "L", "cmd=Message");
		String intfId = "";

		String serverType = monitoringContext.getStringProperty(MonitoringContext.MMI_SYNC_BAP_SERVERTYPE, "BAP");
		DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(serverType));

		logger.debug("parseMessage content-Type="+request.getContentType());
		logger.debug("parseMessage content-Values="+request.getParameterMap().values());		

		String resultBody = "";
		try {
			if (!SystemUtil.isDevServer()) {
				logger.error("개발서버가 아니여서 배포처리 안함.");
				resultBody = resultInterface("False", "배포 요청을 받은 환경이 개발서버가 아님.");
			} else {
				StringBuffer rcvXml = new StringBuffer();
				for (String key : request.getParameterMap().keySet()) {
					if (key.startsWith("INTERFACE")) {
						String[] datas = request.getParameterValues(key);
						for (String data : datas) {
							rcvXml.append(data);
						}
					}
				}

				//ORG Start
				BapDeploy bapDeploy = parseDeployXml(rcvXml.toString());
				//ORG End

				//HD추가 Start
//				String tmpRcvXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><Interface><Header appCd=\"ADA\" authorId=\"admin\" etcDesc=\"aaa\" fileCode=\"SSSS0011\" infDesc=\"bbb\" infDstCd=\"OUT\" infId=\"XAIBFEP90010035\" inftName=\"cccc\" osidInstiCd=\"01001\" outBizCd=\"03031BQ1\" recSize=\"100\" runType=\"E\" snDst=\"S\" srcBzSystemCd=\"AIB\" srcFileNm=\"*.*\" srcFilePath=\"/test2/file/\" tgtFileNm=\"aaa.txt\" trnsmsnCycle=\"ddd\"/></Interface>";
//				BapDeploy bapDeploy = parseDeployXml(tmpRcvXml);
				//HD추가 End

				bapDeploy.setSchemaId(DataSourceContextHolder.getDataSourceType().getSchema());
				bapDeploy.setCreateYmd(DateUtil.getDateTime());
				intfId = bapDeploy.getInfId();
				// validate data type & size
				service.saveBapDeploy(bapDeploy);  //EIMS 전달데이타 저장
				service.mergeData(bapDeploy);
				CommonCommand command = new CommonCommand("com.eactive.eai.agent.rule.dirInfo.RefreshAllJobCommand");
				if (!validate(agentUtilService.broadcast(command)))	throw new Exception("일괄 인터페이스 동기화 오류");

				resultBody = resultInterface("True", "일괄전송 배포 성공하였습니다.");
			}
		} catch (Exception e) {
			logger.error("배포 처리 실패=" + e.getMessage(), e);
			resultBody = resultInterface("False", e.getMessage());
		}

		StringBuilder frame = new StringBuilder();
		frame.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		frame.append("<Results sysInfId=\""+intfId+"\" ver=\"1.0\">");
		frame.append(resultBody.toString());
		frame.append("</Results>");
		logger.debug("result XML="+frame.toString());		

		ServletOutputStream sos = null;
		try {
			sos = response.getOutputStream();
			sos.write(frame.toString().getBytes("UTF-8"));
		} catch( Exception e ) {
			logger.error("배포 응답 송신 실패", e); 
		} finally {
			if( sos != null ) sos.close();
		}
		return null;
	}

	private String resultInterface(String returnCode, String returnMessage){
		return "<Result>"+returnCode+"</Result><ResultMessage>"+returnMessage+"</ResultMessage>";
	}

	public static class BapDeploy {
		String appCd = "";
		String authorId = "";
		String etcDesc = "";
		String fileCode = "";
		String infDesc = "";
		String infDstCd = "";
		String infId = "";
		String inftName = "";
		String osidInstiCd = "";
		String outBizCd = "";
		String recSize = "";
		String runType = "";
		String snDst = "";
		String srcBzSystemCd = "";
		String srcFileNm = "";
		String srcFilePath = "";
		String tgtFileNm = "";
		String trnsmsnCycle = "";
		String createBy = "";
		String createYmd = "";
		String schemaId = "";
		String bzwkDstCd = "";
		String bjobMsgDstcd = "";
		String fileSendUseYN = "";
		String fileRecvUseYN = "";
		String encYN		 ="N";
		
		public String getEncYN() {
			return encYN;
		}
		public void setEncYN(String encYN) {
			this.encYN = encYN;
		}
		public String getAppCd() {
			return appCd;
		}
		public void setAppCd(String appCd) {
			this.appCd = appCd;
		}
		public String getAuthorId() {
			return authorId;
		}
		public void setAuthorId(String authorId) {
			this.authorId = authorId;
		}
		public String getEtcDesc() {
			return etcDesc;
		}
		public void setEtcDesc(String etcDesc) {
			this.etcDesc = etcDesc;
		}
		public String getFileCode() {
			return fileCode;
		}
		public void setFileCode(String fileCode) {
			this.fileCode = fileCode;
		}
		public String getInfDesc() {
			return infDesc;
		}
		public void setInfDesc(String infDesc) {
			this.infDesc = infDesc;
		}
		public String getInfDstCd() {
			return infDstCd;
		}
		public void setInfDstCd(String infDstCd) {
			this.infDstCd = infDstCd;
		}
		public String getInfId() {
			return infId;
		}
		public void setInfId(String infId) {
			this.infId = infId;
		}
		public String getInftName() {
			return inftName;
		}
		public void setInftName(String inftName) {
			this.inftName = inftName;
		}
		public String getOsidInstiCd() {
			return osidInstiCd;
		}
		public void setOsidInstiCd(String osidInstiCd) {
			this.osidInstiCd = osidInstiCd;
		}
		public String getOutBizCd() {
			return outBizCd;
		}
		public void setOutBizCd(String outBizCd) {
			this.outBizCd = outBizCd;
		}
		public String getRecSize() {
			return recSize;
		}
		public void setRecSize(String recSize) {
			this.recSize = recSize;
		}
		public String getRunType() {
			return runType;
		}
		public void setRunType(String runType) {
			this.runType = runType;
		}
		public String getSnDst() {
			return snDst;
		}
		public void setSnDst(String snDst) {
			this.snDst = snDst;
		}
		public String getSrcBzSystemCd() {
			return srcBzSystemCd;
		}
		public void setSrcBzSystemCd(String srcBzSystemCd) {
			this.srcBzSystemCd = srcBzSystemCd;
		}
		public String getSrcFileNm() {
			return srcFileNm;
		}
		public void setSrcFileNm(String srcFileNm) {
			this.srcFileNm = srcFileNm;
		}
		public String getSrcFilePath() {
			return srcFilePath;
		}
		public void setSrcFilePath(String srcFilePath) {
			this.srcFilePath = srcFilePath;
		}
		public String getTgtFileNm() {
			return tgtFileNm;
		}
		public void setTgtFileNm(String tgtFileNm) {
			this.tgtFileNm = tgtFileNm;
		}
		public String getTrnsmsnCycle() {
			return trnsmsnCycle;
		}
		public void setTrnsmsnCycle(String trnsmsnCycle) {
			this.trnsmsnCycle = trnsmsnCycle;
		}
		public String getCreateBy() {
			return createBy;
		}
		public void setCreateBy(String createBy) {
			this.createBy = createBy;
		}
		public String getCreateYmd() {
			return createYmd;
		}
		public void setCreateYmd(String createYmd) {
			this.createYmd = createYmd;
		}
		public String getSchemaId() {
			return schemaId;
		}
		public void setSchemaId(String schemaId) {
			this.schemaId = schemaId;
		}

		public String getBjobMsgDstcd() {
			return bjobMsgDstcd;
		}
		public void setBjobMsgDstcd(String bjobMsgDstcd) {
			this.bjobMsgDstcd = bjobMsgDstcd;
		}		

		public String getBzwkDstCd() {
			return bzwkDstCd;
		}
		public void setBzwkDstCd(String bzwkDstCd) {
			this.bzwkDstCd = bzwkDstCd;
		}		

		public String getFileSendUseYN() {
			return fileSendUseYN;
		}
		public void setFileSendUseYN(String fileSendUseYN) {
			this.fileSendUseYN = fileSendUseYN;
		}

		public String getFileRecvUseYN() {
			return fileRecvUseYN;
		}
		public void setfileRecvUseYN(String fileRecvUseYN) {
			this.fileRecvUseYN = fileRecvUseYN;
		}

		@Override
		public String toString() {
			return "BapDeploy [appCd=" + appCd + ", authorId=" + authorId +  ", encYn=" + encYN + ", etcDesc=" + etcDesc + ", fileCode="
					+ fileCode + ", infDesc=" + infDesc + ", infDstCd=" + infDstCd + ", infId=" + infId + ", inftName="
					+ inftName + ", osidInstiCd=" + osidInstiCd + ", outBizCd=" + outBizCd + ", recSize=" + recSize
					+ ", runType=" + runType + ", snDst=" + snDst + ", srcBzSystemCd=" + srcBzSystemCd + ", srcFileNm="
					+ srcFileNm + ", srcFilePath=" + srcFilePath + ", tgtFileNm=" + tgtFileNm + ", trnsmsnCycle="
					+ trnsmsnCycle + ", createBy=" + createBy + ", createYmd=" + createYmd + ", schemaId=" + schemaId
					+ ", bzwkDstCd=" + bzwkDstCd + ", bjobMsgDstcd=" + bjobMsgDstcd + ", fileSendUseYN=" + fileSendUseYN
					+ ", fileRecvUseYN=" + fileRecvUseYN + "]";
		}
	}

	public static BapDeploy parseDeployXml(String data) throws Exception {
		BapDeploy bapDeploy = new BapDeploy();
		HashMap<String, String> result = new HashMap<>();
		InputStream is = null;
		try {
			is = new ByteArrayInputStream(data.getBytes("UTF-8"));
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(is);

			Element inter = doc.getRootElement();

			result.putAll(getAttr(doc.getRootElement()));
			result.putAll(getAttr(inter.getChild("Header")));

			bapDeploy.setAppCd(result.get("appCd"));
			bapDeploy.setAuthorId(result.get("authorId"));
			bapDeploy.setEncYN(StringUtil.nvlTrim(result.get("encYn"), "N"));
			bapDeploy.setEtcDesc(result.get("etcDesc"));
			bapDeploy.setFileCode(result.get("fileCode"));
			bapDeploy.setInfDesc(result.get("infDesc"));
			bapDeploy.setInfDstCd(result.get("infDstCd"));
			bapDeploy.setInfId(result.get("infId"));
			bapDeploy.setInftName(result.get("inftName"));
			bapDeploy.setOsidInstiCd(result.get("osidInstiCd"));
			bapDeploy.setOutBizCd(result.get("outBizCd"));
			bapDeploy.setRecSize(result.get("recSize"));
			bapDeploy.setRunType(result.get("runType"));
			bapDeploy.setSnDst(result.get("snDst"));
			bapDeploy.setSrcBzSystemCd(result.get("srcBzSystemCd"));
			bapDeploy.setSrcFileNm(result.get("srcFileNm"));
			bapDeploy.setSrcFilePath(result.get("srcFilePath"));
			bapDeploy.setTgtFileNm(result.get("tgtFileNm"));
			bapDeploy.setTrnsmsnCycle(result.get("trnsmsnCycle"));

		} catch (Exception e) {
			throw new Exception("배포 요청 XML parsing error " + e.getMessage(), e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
				}
			}
		}
		return bapDeploy;
	}

	public static HashMap<String,String> getAttr(Element doc){
		if (doc == null) return  new HashMap<String,String>();
		HashMap<String,String> map = new HashMap<String,String>();
		for(Object obj : doc.getAttributes()){
			if (obj instanceof Attribute){
				Attribute attr = (Attribute)obj;
				map.put(attr.getName(), attr.getValue());
			}
		}
		return map;
	}
}
