package com.eactive.eai.adapter.ftp;

import static com.eactive.eai.adapter.ftp.SFTPConstants.DATE_PATTERN;
import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_ADD_DAY;
import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_ADD_MONTH;
import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_ADD_PATH;
import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_ADD_YEAR;
import static com.eactive.eai.adapter.ftp.SFTPConstants.PHASECODE_NORMAL_END;
import static com.eactive.eai.adapter.ftp.SFTPConstants.RECV_REMOTE_PATH;
import static com.eactive.eai.adapter.ftp.SFTPConstants.SEND_COMPLETE_CREATE_YN;
import static com.eactive.eai.adapter.ftp.SFTPConstants.SEND_COMPLETE_FILE_EXT;
import static com.eactive.eai.adapter.ftp.SFTPConstants.SEND_MAX_ITERATION;
import static com.eactive.eai.adapter.ftp.SFTPConstants.SEND_REMOTE_PATH;
import static com.eactive.eai.adapter.ftp.SFTPConstants.SFTP_AUTH_TYPE;
import static com.eactive.eai.adapter.ftp.SFTPConstants.SFTP_AUTH_TYPE_ID;
import static com.eactive.eai.adapter.ftp.SFTPConstants.YES;
import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_AUTO_FILENAME;
import static com.eactive.eai.adapter.ftp.SFTPConstants.FILE_RECV_MANUAL_FILENAME;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.net.ftp.FTPFile;

import com.eactive.eai.common.util.Logger;
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
import com.eactive.eai.adapter.socket.service.SocketService;
import com.eactive.eai.batch.common.CalendarUtil;
import com.eactive.eai.batch.common.CommonKeys;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.ftp.SFTPAdaptor;
import com.eactive.eai.batch.message.EAIBatchMsgManager;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageVO;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.DatetimeUtil;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;

/**
 * 은행 연합회 SFTP 파일 송수신
 * 
 * 자동 수신시 해당 폴더에 있는 모든 파일을 받아온다.
 * 수동 수신시 정해진 파일 이름의 파일을 받아온다.  
 *
 */
public class FTPKB extends Transfer implements SocketService {
	String moduleName = this.getClass().getSimpleName();

	/** 경로에 있는 날짜 패턴를 찾는 패턴 */
	static Pattern PATH_DATE_PATTERN = Pattern.compile(DATE_PATTERN);

	@Override
	public void sendFile(BatchDoc batchDoc) throws Exception {
		ChannelSftp channelSftp = null;
		Session session = null;
		try {
			logger = batchDoc.getLogger();
			Properties instProperties = FtpSupport.getInstProperties(batchDoc);
	        
			String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP();
			int    port      = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort());
			String userid    = batchDoc.getBatchMsg().getHeader().getUserID();
			String passwd    = batchDoc.getBatchMsg().getHeader().getUserPassword();
			
	        String authType = instProperties.getProperty(AUTH_TYPE, AUTH_TYPE_ID);
	    	// 설정이 없으면 기존 처럼 한 번만 돈다.
	        int iteration = FtpSupport.getIntProperty(instProperties, SEND_MAX_ITERATION, 1, logger);
	        int connTimeout = FtpSupport.getIntProperty(instProperties, CONNECTION_TIMEOUT, 10, logger);
	        int setTimeout = FtpSupport.getIntProperty(instProperties, READ_TIMEOUT, 10, logger);
			String bandWidthLimit = instProperties.getProperty(BADNWIDTH, "0");
			bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
			int bandWidth = Integer.parseInt(bandWidthLimit);		
			
			session = SFTPAdaptor.getSessionJSCH(ipaddress, port, userid, passwd, authType, connTimeout, setTimeout, logger);

	    	internalSendFile(session, batchDoc, bandWidth, logger);
	    	
	    	for (int i = 1; i < iteration; i++) {
	    		// Queue에 있는 지 확인한다.
	    		BatchDoc newDoc = checkMoreFile(batchDoc);
	    		if (newDoc == null) {
	    			break;
	    		}
	    		String uuid = newDoc.getBatchMsg().getHeader().getUUID();
	    		String subUuid = newDoc.getBatchMsg().getBody().getSubUUID();
	    		try {
		    		internalSendFile(session, newDoc, bandWidth, logger);
	
		    		newDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
		    		setDefaultEndStage(newDoc);
		    		// FlowController Log
		    		LogUtil.setLog(newDoc);
		    		// master 정보
		    		LogUtil.updateLogMaster(newDoc);
		    		// master 작업상태 정보: 정상 종료
		    		LogUtil.setEndLog(newDoc);
	    		} finally {
		    		// 진행중에서 삭제. 반드시 삭제되어야 함
		    		SchedulerMessageManager.getInstance().deleteJobFromProcessing(uuid, subUuid);
	    		}
	    	}	
        } finally {
        	closeJsch(logger, session, channelSftp);
        }
	}	
	/**
	 * 파일 하나를 전송한다.
	 */
	protected void internalSendFile(Session session, BatchDoc batchDoc, int bandWidthLimit, Logger logger) throws Exception {
		logger.info("[{}] ■ 대외기관→FEP 파일 송신 시작...... ", moduleName);
		firstActivity = System.currentTimeMillis();
		setLastActivity();
		BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this,
				batchDoc);

		String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName();
		try {
			Properties instProperties = FtpSupport.getInstProperties(batchDoc);
			
			String remotePath = instProperties.getProperty(SEND_REMOTE_PATH);
			if (remotePath == null) {
		        String propName = FtpSupport.getInstitutionPropertyName(batchDoc);
				throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_REMOTE_PATH);
			}

	        if ( !remotePath.endsWith("/") )
				remotePath = remotePath + "/";
	        
	        String sendCompleteCreateYn = instProperties.getProperty(SEND_COMPLETE_CREATE_YN, "n");
	        String sendCompleteFileExt = "";
	        if (sendCompleteCreateYn.equalsIgnoreCase(YES) ) {
	        	sendCompleteFileExt = instProperties.getProperty(SEND_COMPLETE_FILE_EXT, "done");
	        }

			// 실제 파일이름
			String sendFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName();

			logger.debug("["+moduleName+"]sendFileName:{"+remoteFileName+"}");
			logger.debug("["+moduleName+"]remotePath:{"+remotePath+"}");

			// File 시작시간 설정
			batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
			LogUtil.setLogFileStart(batchDoc);

			String sendFilePath = batchDoc.getBatchMsg().getHeader().getFilePath();

	        ChannelSftp channelSftp = null;
			try {
				channelSftp = (ChannelSftp) session.openChannel("sftp");
				channelSftp.connect();
	        	SFTPAdaptor.storeJSCH(batchDoc, channelSftp, remotePath, remoteFileName, sendFilePath + "/" + sendFileName, bandWidthLimit, logger);
				
	        	// 송신완료파일 생성 및 업로드
	        	if ( sendCompleteCreateYn.equalsIgnoreCase(YES) ) {
	        		String completeFileName = remoteFileName + "." + sendCompleteFileExt;
	                File completeFile = new File(sendFilePath + "/" + completeFileName);
	                completeFile.createNewFile();
	                
	                SFTPAdaptor.storeJSCH(batchDoc, channelSftp, remotePath, completeFileName, sendFilePath + "/" + completeFileName, bandWidthLimit, logger);
	                Files.delete(completeFile.toPath());
	        	}
			} catch (Exception e) {
				logger.error("[{}]파일송신에 실패하였습니다.", moduleName, e);
				throw e;
			} finally {
	        	if (channelSftp != null) {
	        		channelSftp.disconnect();
	        	}
	        }

			// File 종료시간 설정
			setLastActivity();
			batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
			LogUtil.setLogFileEnd(batchDoc);

		} catch (Exception ex) {
			String[] msgArgs = new String[1];
			msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode();
			String errCode = "BECEAIFJI002";
			String errMsg = ExceptionUtil.getErrorCode(ex, errCode, msgArgs);
			batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
			LogUtil.setErrorLog(batchDoc, ex.getMessage());
			logger.error(errMsg, ex);
			throw ex;
		} finally {
			// SFTP는 실제 disconnect는 FTPUtil-SFTPAdaptor에서 하지만, 연결해제 로그를 찍어주기 위해 호출.
			this.disconnect();
		}

		logger.info("[{}] ■ FEP → VAN사 파일 송신 완료.", moduleName);

	}

	/**
	 * 자동 스케줄은 해당 폴더의 파일을 모두 수신하고, 수동 스케줄은 해당 일자(파일 프라터티)의 파일만 수신한다.
	 */
	public void recvFile(BatchDoc batchDoc) throws Exception {
		logger = batchDoc.getLogger();
		logger.info("[{}] ■ 대외기관→FEP 파일 수신 시작...... ", moduleName);
		firstActivity = System.currentTimeMillis();
		setLastActivity();
		BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this,
				batchDoc);
		ChannelSftp channelSftp = null;
		Session session = null;
		try {
			String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP();
			int port = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort());
			String userid = batchDoc.getBatchMsg().getHeader().getUserID();
			String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword();

			Properties instProperties = FtpSupport.getInstProperties(batchDoc);
			Properties fileProperties = FtpSupport.getFileProperties(batchDoc);

			String remotePath = instProperties.getProperty(RECV_REMOTE_PATH);
			String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName();
			
			if (remotePath == null) {
		        String propName = FtpSupport.getInstitutionPropertyName(batchDoc);
				throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + RECV_REMOTE_PATH);
			}

	        if ( !remotePath.endsWith("/") )
				remotePath = remotePath + "/";
	        
	        int connTimeout = FtpSupport.getIntProperty(instProperties, CONNECTION_TIMEOUT, 10, logger);
	        int setTimeout = FtpSupport.getIntProperty(instProperties, READ_TIMEOUT, 10, logger);
			String bandWidthLimit = instProperties.getProperty(BADNWIDTH, "0");
			bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
			int bandWidth = Integer.parseInt(bandWidthLimit);

			logger.debug("["+moduleName+"]recvFileName:{"+remoteFileName+"}");

			// 특정일자 파일을 수신요청 시, 해당 일자의 경로 설정
			String reqFileName = remoteFileName;
			boolean isManualReceive = FtpSupport.isManaulRecive(batchDoc);
			// isManualReceive에서 변경한 기준일자
			String baseDate = batchDoc.getBatchMsg().getHeader().getBaseDate();

			// 경로에 있는 접수 일자 조정.
			int addYear = FtpSupport.getIntProperty(fileProperties, FILE_RECV_ADD_YEAR, 0, logger);
			int addMonth = FtpSupport.getIntProperty(fileProperties, FILE_RECV_ADD_MONTH, 0, logger);
			int addDay = FtpSupport.getIntProperty(fileProperties, FILE_RECV_ADD_DAY, 0, logger);
			if (addYear != 0 || addMonth != 0 || addDay != 0) {
				baseDate = DatetimeUtil.getDateAddedDate(baseDate, addYear, addMonth, addDay);
			}

			// 경로에 있는 TAX/<yyyyMMdd>/01/send 날짜를 패턴에 따라 변경
			String fileRecvAddPath = fileProperties.getProperty(FILE_RECV_ADD_PATH, "");
			
			// 파일별 추가 경로
			remotePath += fileRecvAddPath;
			if (!remotePath.endsWith("/"))
				remotePath = remotePath + "/";
			
			Matcher matcher = PATH_DATE_PATTERN.matcher(remotePath);
			
			if (matcher.find()) {
				String datePattern = matcher.group(1);
				DateFormat dateFormatter = new SimpleDateFormat(datePattern);
				Date replaceDate = new SimpleDateFormat("yyyyMMdd").parse(baseDate);
				remotePath = remotePath.replaceFirst(DATE_PATTERN, dateFormatter.format(replaceDate));
			}

			String authType = instProperties.getProperty(SFTP_AUTH_TYPE, SFTP_AUTH_TYPE_ID);

			try {
				if (isManualReceive == false) {
					// 자동 스케줄 *.gz 모든 파일 수신.
					reqFileName = fileProperties.getProperty(FILE_RECV_AUTO_FILENAME, "*.gz");
				} else {
					// 수동 스케줄: 정해진 파일 수신
					reqFileName = fileProperties.getProperty(FILE_RECV_MANUAL_FILENAME, "*.gz");
				}
				logger.debug("["+moduleName+"]remotePath:{"+remotePath+"}");
				logger.debug("["+moduleName+"]reqFileName:{"+reqFileName+"}");
				
				// SFTP 연결을 하나 만들어서 ls, get 을 실행한다.
				session = SFTPAdaptor.getSessionJSCH(ipaddress, port, userid, passwd, authType, connTimeout, setTimeout, logger);
				channelSftp = (ChannelSftp) session.openChannel("sftp");
				channelSftp.connect();

				FTPFile[] list = SFTPAdaptor.lsJSCH(channelSftp, remotePath, reqFileName, logger);
				for (FTPFile file : list) {
					receiveOneFile(channelSftp, batchDoc, file, remotePath, bandWidth);
				}
			} catch (Exception e) {
				if (!e.getMessage().contains("No such file"))
					throw e;
            } finally {
            	closeJsch(logger, session, channelSftp);
            }
		} catch (Exception ex) {
			String[] msgArgs = new String[1];
			msgArgs[0] = batchDoc.getBatchMsg().getHeader().getProcessCode();
			String errCode = "BECEAIFJI002";
			String errMsg = ExceptionUtil.getErrorCode(ex, errCode, msgArgs);
			batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
			LogUtil.setErrorLog(batchDoc, ex.getMessage());
			logger.error(errMsg, ex);
			throw ex;
		} finally {
			// SFTP는 실제 disconnect는 FTPUtil-SFTPAdaptor에서 하지만, 연결해제 로그를 찍어주기 위해 호출.
			this.disconnect();
		}

		logger.info("[{}] ■ VAN사 → FEP 파일 수신 완료.", moduleName);
	}

	/**
	 * 파일 하나를 수신한다.
	 * 
	 * @param sftpClient SFTP 연결
	 * @param file       수신할 파일
	 * @param remotePath 원격 디렉토리
	 */
	protected void receiveOneFile(ChannelSftp channelSftp, BatchDoc batchDoc, FTPFile file, String remotePath, int bandWidth)
			throws Exception {
		// 파일만 처리
		if (!file.isFile()) {
			return;
		}
		batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize());
		batchDoc.getBatchMsg().getBody().setRecCnt(1);
		batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
        batchDoc.getBatchMsg().getHeader().setFileName(file.getName());
		LogUtil.setLogFileStart(batchDoc);
		
		SFTPAdaptor.cdJSCH(channelSftp, remotePath);
		SFTPAdaptor.retrieveJSCH(batchDoc, channelSftp, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), bandWidth, logger);
		
		String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" +  file.getName();
		File rcvRealFile = new File( recvFile );  					

		File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) );
		if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
			rcvRealFile.renameTo(rcvArchFile);
			File rcvRootFile = new File( StringUtil.realToRootDir(recvFile) );
			rcvRootFile.createNewFile();
		} else {
			throw new Exception("[" + moduleName + "]파일수신에 실패하였습니다.");
		}
		//File 종료시간 설정
		batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
		LogUtil.setLogFileEnd(batchDoc);
	}

	@Override
	public void shutdown() {
	}

	@Override
	public Socket getCurrentSocket() {
		return null;
	}

	@Override
	public boolean connect() {
		return false;
	}

	@Override
	public ConfigurationContext getContext() {
		return null;
	}

	@Override
	public void setControl(Object control) {
	}

	@Override
	public void notifyMessage() {

	}

	@Override
	public boolean idle(long timeout) {
		return false;
	}

	@Override
	public int getCurrentState() {
		return 0;
	}

	@Override
	public boolean isConnected() throws IOException {
		return false;
	}

	@Override
	public boolean isActive() {
		return false;
	}

	@Override
	public void checkActivity() {

	}

	@Override
	public String getRemoteIPAddress() {
		return null;
	}

	@Override
	public void setLastActivity() {
		lastActivity = System.currentTimeMillis();
	}

	@Override
	public long getFirstActivity() {
		return 0;
	}

	@Override
	public long getLastActivity() {
		return 0;
	}

	   /** 
     * FlowController END를 위한 값으로 설정한다.
     * @param batchDoc 설정 값을 변경할 배치 작업
     */
	private void setDefaultEndStage(BatchDoc batchDoc) {
        batchDoc.getBatchMsg().getBody().setFlowPhaseCode(PHASECODE_NORMAL_END);
        batchDoc.getBatchMsg().getBody().setPhaseType(PHASECODE_NORMAL_END);
        //Phase 쪽 단계정보 설정
		batchDoc.getBatchMsg().getPhaseinfo().setRuleCode          (this.getClass().getSimpleName());
		batchDoc.getBatchMsg().getPhaseinfo().setPhaseCode         (PHASECODE_NORMAL_END);
		batchDoc.getBatchMsg().getPhaseinfo().setPhaseType         (PHASECODE_NORMAL_END);
		batchDoc.getBatchMsg().getPhaseinfo().setFlowClassName     ("com.eactive.eai.batch.job.jobModule.Component.END");
		batchDoc.getBatchMsg().getPhaseinfo().setLengthFieldIndex  (0);
		batchDoc.getBatchMsg().getPhaseinfo().setLengthTelegramID  ("");
		batchDoc.getBatchMsg().getPhaseinfo().setLengthClassName   ("");
		batchDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode     ("");
		batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq          ("1");
		batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID   ("");
		batchDoc.getBatchMsg().getPhaseinfo().setPhaseClassName    ("");
		batchDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode      ("");
		batchDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue ("");
		batchDoc.getBatchMsg().getPhaseinfo().setBizCodeValue      ("");
		batchDoc.getBatchMsg().getPhaseinfo().setControlCodeValue  ("");
		batchDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue ("");	
	}
	
	/**
	 * 같은 업무, 기관 코드의 작업이 큐에 있는지 확인한다.
	 * 
	 * @param batchDoc
	 * @return 큐에서 가져온 배치 잡 
	 */
    private BatchDoc checkMoreFile(BatchDoc batchDoc) {
		logger = batchDoc.getLogger();

		BatchDoc newDoc = null;
    	String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode(); 
    	String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode();
    	SchedulerMessageVO info;
    	try{
    		info = SchedulerMessageManager.getInstance().getSendJobFromQueue(processCode, institutionCode );
    		if ( info == null ) {
    			return null;
    		}
    		newDoc = EAIBatchMsgManager.createBatchMsg(true);

			//해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동
    		SchedulerMessageManager.getInstance().moveJobQueueToHandle(info);
    		//BatchMsgDoc Layer, SubLayer, StartTime 설정
    		EAIBatchMsgManager.updateBatchMsgWithStageTime(newDoc, CommonKeys.LAYER_FLOW_CONTROLLER, CommonKeys.SUB_LAYER_FLOW_CONTROLLER);

    		//BatchMsgDoc 값 설정
    		newDoc.getBatchMsg().getHeader().setUUID(info.getUUID());
    		newDoc.getBatchMsg().getBody().setSubUUID(info.getSubUUID());
    		newDoc.getBatchMsg().getHeader().setProcessCode(info.getProcessCode());
    		newDoc.getBatchMsg().getHeader().setProcessName(info.getProcessName());
    		newDoc.getBatchMsg().getHeader().setProcessType(info.getProcessType());
    		newDoc.getBatchMsg().getHeader().setInstitutionCode(info.getInstitutionCode());
    		newDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName());
    		newDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode());
    		newDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime());
    		newDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime());
    		newDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath());
    		newDoc.getBatchMsg().getHeader().setFileName(info.getFileName());
    		newDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName());
    		newDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode());
    		newDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode());
    		newDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode());
    		newDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode());
    		newDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize());
    		newDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize());
    		newDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize());
    		newDoc.getBatchMsg().getHeader().setUserID(batchDoc.getBatchMsg().getHeader().getUserID());
    		newDoc.getBatchMsg().getHeader().setUserPassword(batchDoc.getBatchMsg().getHeader().getUserPassword());
    		newDoc.getBatchMsg().getHeader().setPort(batchDoc.getBatchMsg().getHeader().getPort());
    		newDoc.getBatchMsg().getHeader().setSystemConnCode(info.getSystemConnCode());
    		newDoc.getBatchMsg().getHeader().setRequestResponse(info.getRqstRspnsDstcd());
    		newDoc.getBatchMsg().getHeader().setRemoteIP(batchDoc.getBatchMsg().getHeader().getRemoteIP());

			// 다음 파일의 체크 파일 가져오기
			if (info.getProcessType().equals(CommonKeys.PROCESS_REQUEST_SEND)
					|| info.getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND)) {
				String hdrInfoName = info.getHdrInfoName();
				newDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName);
				newDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName));
				newDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName));

				String dirPath = newDoc.getBatchMsg().getHeader().getFilePath();
				String renamedFileName = newDoc.getBatchMsg().getHeader().getRenamedFileName();
				File file = new File(dirPath + File.separatorChar + renamedFileName);
				if (!file.exists()) {
					throw new Exception();
				}
				long fileLen = file.length();

				newDoc.getBatchMsg().getHeader().setFileSize(fileLen);
			}
    	} catch ( Exception e){
    		logger.error(newDoc == null ? "batchDoc is null" : newDoc.toString(), e);
    		return null;
    	}
    	
    	return newDoc;
    }
    
    private void closeJsch(Logger logger, Session session, ChannelSftp channelSftp) {
		if (channelSftp != null && channelSftp.isConnected()) {
			try {
				channelSftp.disconnect();
			} catch (Exception e) {
				logger.error(e.getLocalizedMessage(), e);
			}
		}
		if (session != null) {
			try {
				session.disconnect();
			} catch (Exception e) {
				logger.error(e.getLocalizedMessage(), e);
			}

		}
    }
}
