proxy사용으로 변경

This commit is contained in:
zoomk
2025-11-12 16:05:52 +09:00
parent d7957c9478
commit e8f0cce9ef
17 changed files with 32 additions and 5421 deletions
-274
View File
@@ -1,274 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Properties;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
//KIS 제공 자료 정보계 ( FTP )
//IP : 203.234.219.30 PORT : 21
//ID : kjbank PWD: kjbank0409
//파일명 kjb_YYYYMMDD[_HH].tar.gz
/**
* 데이터 수신에 시간이 오래 걸리는 경우에 KeepAliveTimeout을 설정하여 NOOP 를 Control Connection으로
* 전송하도록 TCP 연결을 유지하도록 수정
*
*/
public class FTP01 extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
private static final String REQ_FILE_NAME = "req.file.name";
private static final String POST_FIX = "post.fix";
private static final String FLAG_FILE_NAME = "flag.file.name";
public void sendFile(BatchDoc batchDoc) throws Exception {
throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다.");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTP01] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//2. System FTP Shell 명령어를 Runtime 으로 실행
try {
// 기관 프라퍼티에서 keepAliveTimeout 읽음
// 설정이 없는 경우 0으로 설정하여 disable
String instPropName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
int keepAliveTimeout = 0;
int keepAliveReplyTimeout = 1;
try {
Properties instProperties = PropManager.getInstance().getProperties(instPropName);
keepAliveTimeout = Integer.parseInt(instProperties.getProperty("keep.alive.timeout", "0"));
keepAliveReplyTimeout = Integer.parseInt(instProperties.getProperty("keep.alive.reply.timeout", "1"));
} catch (Exception e) {
logger.info(e.getLocalizedMessage());
}
logger.info("keepAliveTimeout = {} seconds", keepAliveTimeout);
logger.info("keepAliveReplyTimeout = {} seconds", keepAliveReplyTimeout);
String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP();
String port = batchDoc.getBatchMsg().getHeader().getPort();
String userid = batchDoc.getBatchMsg().getHeader().getUserID();
String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword();
if (ftpClient == null || !ftpClient.isConnected()) this.connect(ipaddress, Integer.parseInt(port) );
ftpClient.login(userid, passwd);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
setLastActivity();
logger.debug( "[FTP01]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String baseDate = DatetimeUtil.getCurrentDate();
if ( reqFileName != null && reqFileName.length() > 8 ){
if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){
baseDate = reqFileName.substring(reqFileName.length() - 8 );
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
}
}
String postFix = "";
String flagFileName = "";
reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode();
try{
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getBizCode() + "}";
PropManager pmanager = PropManager.getInstance();
postFix = pmanager.getProperties(propName).getProperty(POST_FIX);
if ( postFix == null ){
postFix = "";
}
flagFileName = pmanager.getProperties(propName).getProperty(FLAG_FILE_NAME);
reqFileName = pmanager.getProperties(propName).getProperty(REQ_FILE_NAME);
}catch ( Exception e){}
reqFileName = reqFileName + "_" + baseDate + postFix.trim() + ".tar.gz";
ftpClient.setDataTimeout(600*1000);
ftpClient.setConnectTimeout(300);
// Keep Alive 설정
ftpClient.setControlKeepAliveTimeout(keepAliveTimeout);
ftpClient.setControlKeepAliveReplyTimeout(keepAliveReplyTimeout * 1000);
String remoteDir = "pub/" + baseDate + postFix.trim();
logger.debug("[FTP01] ■ VAN사 remoteDir["+remoteDir+"]");
if ( !ftpClient.changeWorkingDirectory(remoteDir)){
logger.info("[FTP01] ■ VAN사 → FEP 수신 파일 없음.["+remoteDir+"]");
return;
}
FTPFile[] files = ftpClient.listFiles();
setLastActivity();
if ( !flagFileName.equals("")){
boolean find = false;
for (int inx = 0; inx < files.length; inx++) {
if ( files[inx].getName().equals(flagFileName) ){
find = true;
break;
}
}
if ( !find ){
logger.info("[FTP01] ■ VAN사 → FEP 수신 지표 파일이 없음.["+flagFileName+"]");
return;
}
}
for (int inx = 0; inx < files.length; inx++) {
if ( !files[inx].isFile() || !files[inx].getName().equals(reqFileName) ) continue;
FileOutputStream fos = null;
batchDoc.getBatchMsg().getHeader().setFileName(reqFileName);
batchDoc.getBatchMsg().getHeader().setFileSize(files[inx].getSize());
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + reqFileName;
File rcvRealFile = new File( recvFile );
File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) );
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileStart(batchDoc);
try {
fos = new FileOutputStream( rcvRealFile );
ftpClient.retrieveFile(reqFileName, fos);
setLastActivity();
} catch (Exception e) {
setLastActivity();
logger.error(e.getMessage(), e);
throw new Exception("파일수신에 실패하였습니다. -" + e.getMessage());
} finally {
fos.close();
}
try {
File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) );
if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
rcvRealFile.renameTo(rcvArchFile);
rcvChkFile.createNewFile();
}else{
throw new Exception("파일수신에 실패하였습니다.");
}
} catch (Exception e) {
throw e;
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
break;
}
} 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);
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setErrorLog(batchDoc, ex.getMessage());
logger.error( errMsg, ex );
throw ex;
} finally {
this.disconnect();
}
logger.info("[FTPCC] ■ VAN사 → FEP 파일 수신 완료.");
}
@Override
public void shutdown() {
disconnect();
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-243
View File
@@ -1,243 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Properties;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
//KIS 제공 자료 정보계 ( FTP )
//IP : 203.234.219.30 PORT : 21
//ID : kjbank PWD: kjbank0409
//파일명 kjfb_YYYYMMDD.tar.gz
//매월 첫주 화요일에 수신
/**
* 데이터 수신에 시간이 오래 걸리는 경우에 KeepAliveTimeout을 설정하여 NOOP 를 Control Connection으로
* 전송하도록 TCP 연결을 유지하도록 수정
*
*/
public class FTP03 extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
public void sendFile(BatchDoc batchDoc) throws Exception {
throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다.");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTP03] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//2. System FTP Shell 명령어를 Runtime 으로 실행
try {
// 기관 프라퍼티에서 keepAliveTimeout 읽음
// 설정이 없는 경우 0으로 설정하여 disable
String instPropName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
int keepAliveTimeout = 0;
int keepAliveReplyTimeout = 1;
try {
Properties instProperties = PropManager.getInstance().getProperties(instPropName);
keepAliveTimeout = Integer.parseInt(instProperties.getProperty("keep.alive.timeout", "0"));
keepAliveReplyTimeout = Integer.parseInt(instProperties.getProperty("keep.alive.reply.timeout", "1"));
} catch (Exception e) {
logger.info(e.getLocalizedMessage());
}
logger.info("keepAliveTimeout = {} seconds", keepAliveTimeout);
logger.info("keepAliveReplyTimeout = {} seconds", keepAliveReplyTimeout);
String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP();
String port = batchDoc.getBatchMsg().getHeader().getPort();
String userid = batchDoc.getBatchMsg().getHeader().getUserID();
String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword();
if (ftpClient == null || !ftpClient.isConnected()) this.connect(ipaddress, Integer.parseInt(port) );
ftpClient.login(userid, passwd);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
setLastActivity();
logger.debug( "[FTPC3]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String baseDate = DatetimeUtil.getCurrentDate();
if ( reqFileName != null && reqFileName.length() > 8 ){
if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){
baseDate = reqFileName.substring(reqFileName.length() - 8 );
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
}
}
reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode() + "_" + baseDate + ".tar.gz";
ftpClient.setDataTimeout(600*1000);
ftpClient.setConnectTimeout(300);
// Keep Alive 설정
ftpClient.setControlKeepAliveTimeout(keepAliveTimeout);
ftpClient.setControlKeepAliveReplyTimeout(keepAliveReplyTimeout * 1000);
String remoteDir = "pub/" + baseDate;
logger.debug( "[FTPC3]remoteDir:" + remoteDir);
logger.debug( "[FTPC3]reqFileName:" + reqFileName);
if ( !ftpClient.changeWorkingDirectory(remoteDir)){
logger.info("[FTP03] ■ VAN사 → FEP 수신 파일 없음.["+remoteDir+"]");
return;
}
FTPFile[] files = ftpClient.listFiles();
setLastActivity();
for (int inx = 0; inx < files.length; inx++) {
if ( !files[inx].isFile() || !files[inx].getName().equals(reqFileName) ) continue;
FileOutputStream fos = null;
batchDoc.getBatchMsg().getHeader().setFileName(reqFileName);
batchDoc.getBatchMsg().getHeader().setFileSize(files[inx].getSize());
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + reqFileName;
File rcvRealFile = new File( recvFile );
File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) );
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileStart(batchDoc);
try {
fos = new FileOutputStream( rcvRealFile );
ftpClient.retrieveFile(reqFileName, fos);
setLastActivity();
} catch (Exception e) {
setLastActivity();
logger.error(e.getMessage(), e);
throw new Exception("파일수신에 실패하였습니다. -" + e.getMessage());
} finally {
fos.close();
}
try {
File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) );
if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
rcvRealFile.renameTo(rcvArchFile);
rcvChkFile.createNewFile();
}else{
throw new Exception("파일수신에 실패하였습니다.");
}
} catch (Exception e) {
throw e;
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
break;
}
} 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);
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setErrorLog(batchDoc, ex.getMessage());
logger.error( errMsg, ex );
throw ex;
} finally {
this.disconnect();
}
logger.info("[FTPCC] ■ VAN사 → FEP 파일 수신 완료.");
}
@Override
public void shutdown() {
disconnect();
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
@@ -27,13 +27,13 @@ import com.eactive.eai.common.util.Logger;
/**
* 우체국 공융 ftp 전송을 위함 SFTP
* 광주은행 apim 공융 ftp 전송을 위함 SFTP proxy사용
*
* 파일명 : FTP00
* 파일명 : FTPAP
*
*/
public class FTP00 extends Transfer implements SocketService {
public class FTPAP extends Transfer implements SocketService {
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
@@ -42,6 +42,7 @@ public class FTP00 extends Transfer implements SocketService {
private static final String EXT_NAME = "ext.name";
private static final String FTP_FILE_TYPE = "ftp.file.type";// ftp ASCII 경우만 default BINARY
private static final String BASE_DATE_OVER_YN = "basedate.over.yn"; // 기준일 이후 파일전송여부
private static final String PROXY_SERVER = "proxy.server"; // 프록시 서버
/** ftp 0 , 인증 방법 1 = id, 2 = key 방식 */
private static final String AUTH_TYPE = "sftp.auth.type";
@@ -52,7 +53,7 @@ public class FTP00 extends Transfer implements SocketService {
public void sendFile(BatchDoc batchDoc) throws Exception {
// TODO Auto-generated method stub
if(logger.isInfoEnabled())
logger.info("[FTP00] ■ 대외기관→FEP 파일 송신 시작...... ");
logger.info("[FTPAP] ■ 대외기관→FEP 파일 송신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
@@ -75,8 +76,8 @@ public class FTP00 extends Transfer implements SocketService {
remotePath = remotePath + "/";
String ftpgb = pmanager.getProperties(propName).getProperty(AUTH_TYPE, "1");
String proxyServer = pmanager.getProperties(propName).getProperty(PROXY_SERVER, "");// 20251112
//baseDate 추출
String baseDate = DatetimeUtil.getCurrentDate();
String reqFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName();
@@ -116,10 +117,10 @@ public class FTP00 extends Transfer implements SocketService {
+ batchDoc.getBatchMsg().getHeader().getRenamedFileName();
String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName();
//logger.debug( "[FTP00]sendFileName:" + orgFileName);
//logger.debug( "[FTPAP]sendFileName:" + orgFileName);
if(logger.isDebugEnabled())
logger.debug( "[FTP00]remotePath:" + remotePath);
logger.debug( "[FTPAP]remotePath:" + remotePath);
//File 시작시간 설정
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
@@ -144,10 +145,10 @@ public class FTP00 extends Transfer implements SocketService {
FTPUtil.store(batchDoc, ipaddress, port, userid,
passwd, remotePath, batchDoc.getBatchMsg().getHeader().getFileName(),
sendFileName,
connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), ftpgb);
connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), ftpgb, proxyServer);
}
} catch (Exception e) {
logger.error("[FTP00]파일송신에 실패하였습니다.", e);
logger.error("[FTPAP]파일송신에 실패하였습니다.", e);
throw e;
}
@@ -170,13 +171,13 @@ public class FTP00 extends Transfer implements SocketService {
this.disconnect();
}
if(logger.isDebugEnabled())
logger.info("[FTP00] ■ FEP → VAN사 파일 송신 완료.");
logger.info("[FTPAP] ■ FEP → VAN사 파일 송신 완료.");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
if(logger.isInfoEnabled())
logger.info("@@@@@@@FTP00] ■ 대외기관→FEP 파일 수신 시작...... ");
logger.info("@@@@@@@FTPAP] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this,
@@ -190,8 +191,8 @@ public class FTP00 extends Transfer implements SocketService {
String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword();
if(logger.isDebugEnabled())
logger.debug("@@@@FTP00]userid:" + userid);
//logger.debug("@@@@FTP00]passwd:" + passwd);
logger.debug("@@@@FTPAP]userid:" + userid);
//logger.debug("@@@@FTPAP]passwd:" + passwd);
String propName = PROP_GROUP_NAME_PREFIX + "{" + batchDoc.getBatchMsg().getHeader().getProcessCode() + "_"
+ batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
@@ -204,13 +205,13 @@ public class FTP00 extends Transfer implements SocketService {
//SFTP방식
String ftpgb = pmanager.getProperties(propName).getProperty(AUTH_TYPE, "1");
String proxyServer = pmanager.getProperties(propName).getProperty(PROXY_SERVER, "");// 20251112
// FTP_FILE_TYPE
String ftpFileType = pmanager.getProperties(propName).getProperty(FTP_FILE_TYPE, "BINARY");
if(logger.isDebugEnabled())
logger.debug("[FTP00]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
logger.debug("[FTPAP]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
//baseDate 추출
String baseDate = DatetimeUtil.getCurrentDate();
@@ -311,18 +312,18 @@ public class FTP00 extends Transfer implements SocketService {
}catch(Exception e) {
}
FTPFileObject[] list = FTPUtil.listFilesJSCH(ipaddress, port, userid, passwd, remotePath, true, batchDoc.getLogger(),ftpgb);
FTPFileObject[] list = FTPUtil.listFilesJSCH(ipaddress, port, userid, passwd, remotePath, true, batchDoc.getLogger(),ftpgb, proxyServer);
if(list == null) {// 파일 경로가 없는경우 20231025
if(logger.isDebugEnabled())
logger.debug("[FTP00]remotePath:"+remotePath +" path is none");
logger.debug("[FTPAP]remotePath:"+remotePath +" path is none");
return;
}
setLastActivity();
String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode();
if(logger.isDebugEnabled())
logger.debug("[FTP00] ■ baseDate[" + baseDate + "] bizCode[" + bizCode + "]");
logger.debug("[FTPAP] ■ baseDate[" + baseDate + "] bizCode[" + bizCode + "]");
for (int inx = 0; inx < list.length; inx++) {
FTPFileObject file = list[inx];
@@ -335,12 +336,12 @@ public class FTP00 extends Transfer implements SocketService {
if(isFileNameSet && fileName.contains(reqFileName)){
if(logger.isDebugEnabled())
logger.debug("[FTP00]reqFileName=isFileNameSet["+isFileNameSet + "] fileName[" + fileName + "] reqFileName[" + reqFileName +"]");
logger.debug("[FTPAP]reqFileName=isFileNameSet["+isFileNameSet + "] fileName[" + fileName + "] reqFileName[" + reqFileName +"]");
fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType
, connTimeout, setTimeout, bandWidth);
, connTimeout, setTimeout, bandWidth, proxyServer);
}else if (!isFileNameSet && fileName.contains(bizCode)) {
if(logger.isDebugEnabled())
logger.debug("[FTP00]reqFileName=isFileNameSet["+isFileNameSet + "] fileName[" + fileName + "] bizCode[" + bizCode +"]");
logger.debug("[FTPAP]reqFileName=isFileNameSet["+isFileNameSet + "] fileName[" + fileName + "] bizCode[" + bizCode +"]");
Matcher matcher = Pattern.compile("(20[0-9]{6})").matcher(fileName.trim());
if (matcher.find()) {
@@ -350,19 +351,19 @@ public class FTP00 extends Transfer implements SocketService {
int bday = Integer.parseInt(baseDate);
if (iday >= bday && !selectDate) { //스케줄러를 통한 파일 수신, 오늘 날짜 이상
if(logger.isDebugEnabled())
logger.debug("[FTP00]ALL OVER DATE OK-fileName[" + fileName + "]");
logger.debug("[FTPAP]ALL OVER DATE OK-fileName[" + fileName + "]");
fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType
, connTimeout, setTimeout, bandWidth);
, connTimeout, setTimeout, bandWidth, proxyServer);
} else if (iday == bday && selectDate) { //파일날짜 선택하여 파일 수신, 해당 날짜만 수신
if(logger.isDebugEnabled())
logger.debug("[FTP00]SELECT_DATE-fileName[" + fileName + "]");
logger.debug("[FTPAP]SELECT_DATE-fileName[" + fileName + "]");
fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType
, connTimeout, setTimeout, bandWidth);
, connTimeout, setTimeout, bandWidth, proxyServer);
}
}else{
if(logger.isDebugEnabled())
logger.debug("[FTP00]No SELECT_DATE-fileName[" + fileName + "]");
logger.debug("[FTPAP]No SELECT_DATE-fileName[" + fileName + "]");
try {
OutsideVO organInfo = OutsideManager.getInstance().getOutsideInfo(batchDoc.getBatchMsg().getHeader().getProcessCode()
@@ -372,7 +373,7 @@ public class FTP00 extends Transfer implements SocketService {
if (fileName.length() > bizCodeEndIndex && bizCode.equals(fileName.substring(bizCodeStartIndex, bizCodeEndIndex))){
fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType
, connTimeout, setTimeout, bandWidth);
, connTimeout, setTimeout, bandWidth, proxyServer);
}
}catch(Exception e) {
//
@@ -396,12 +397,12 @@ public class FTP00 extends Transfer implements SocketService {
this.disconnect();
}
if(logger.isInfoEnabled())
logger.info("[FTP00] ■ VAN사 → FEP 파일 수신 완료.");
logger.info("[FTPAP] ■ VAN사 → FEP 파일 수신 완료.");
}
private void fileDownProcess(BatchDoc batchDoc, String fileName, long fileSize, String ipaddress, int port,
String userid, String passwd, String remotePath, String sftpmode, String ftpFileType
, int connTimeout, int setTimeout, int bandWidth) throws Exception {
, int connTimeout, int setTimeout, int bandWidth, String proxyServer) throws Exception {
FileOutputStream fos = null;
batchDoc.getBatchMsg().getHeader().setFileName(fileName);
@@ -425,7 +426,7 @@ public class FTP00 extends Transfer implements SocketService {
logger.debug("@@@@@@@@" + this.getClass().getName() + ".fileName[" + fileName + "]");
FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath , fileName, batchDoc.getBatchMsg().getHeader().getFilePath(),
connTimeout, setTimeout, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), sftpmode, ftpFileType);
connTimeout, setTimeout, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), sftpmode, ftpFileType, proxyServer);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + fileName;
-213
View File
@@ -1,213 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
public class FTPBG extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
private static final String SEND_SHELL = "send.shell";
private static final String RECV_SHELL = "recv.shell";
public void sendFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPSH] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//Shell 명령어를 Runtime 으로 실행
try {
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String shellCommand = pmanager.getProperties(propName).getProperty(SEND_SHELL);
if ( shellCommand == null ){
throw new Exception("해당 기관에 송신 스크립트가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_SHELL);
}
String[] command = new String[4];
command[0] = shellCommand;
command[1] = batchDoc.getBatchMsg().getHeader().getFilePath();
command[2] = batchDoc.getBatchMsg().getHeader().getRenamedFileName();
command[3] = batchDoc.getBatchMsg().getHeader().getFileName();
setFileHeaderAndTrailer(batchDoc, new File(batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName()));
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileStart(batchDoc);
runSystemScript( command );
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);
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setErrorLog(batchDoc, ex.getMessage());
logger.error( errMsg, ex );
throw ex;
} finally {
BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID());
this.disconnect();
}
logger.info("[FTPSH] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPSH] ■ 대외기관→FEP 파일 수신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
String fileName = batchDoc.getBatchMsg().getHeader().getBizCode();
//Shell 명령어를 Runtime 으로 실행
try {
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String shellCommand = pmanager.getProperties(propName).getProperty(RECV_SHELL);
if ( shellCommand == null ){
throw new Exception("해당 기관에 수신 스크립트가 지정되어 있지 않습니다. -propName:" + propName + "," + RECV_SHELL);
}
String[] command = new String[3];
command[0] = shellCommand;
command[1] = batchDoc.getBatchMsg().getHeader().getFilePath();
command[2] = fileName;
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
runSystemScript( command );
File recvDir = new File(batchDoc.getBatchMsg().getHeader().getFilePath());
File[] recvFiles = recvDir.listFiles();
for( int inx = 0; inx < recvFiles.length; inx++){
File recvFile = recvFiles[inx];
if ( recvFile.getName().startsWith(fileName)){
File rcvRootFile = new File( StringUtil.realToRootDir(batchDoc.getBatchMsg().getHeader().getFilePath()) + "/" + recvFile.getName() );
File rcvArchFile = new File( StringUtil.realToArchDir(batchDoc.getBatchMsg().getHeader().getFilePath()) + "/" + recvFile.getName());
batchDoc.getBatchMsg().getHeader().setFileName(recvFile.getName());
LogUtil.setLogFileStart(batchDoc);
batchDoc.getBatchMsg().getHeader().setFileSize(recvFile.length());
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
setFileHeaderAndTrailer(batchDoc, recvFile);
recvFile.renameTo(rcvArchFile);
rcvRootFile.createNewFile();
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
}
}
} catch(Exception ex) {
String noFileMessage = fileName + " NOT EXIST";
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);
if ( ex.getMessage().indexOf(noFileMessage) < 0 ){
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setErrorLog(batchDoc, ex.getMessage());
logger.error( errMsg, ex );
throw ex;
}
} finally {
BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID());
this.disconnect();
}
logger.info("[FTPSH] ■ 대외기관→FEP 파일 수신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-203
View File
@@ -1,203 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.DatetimeUtil;
// 신용회복 위원회 파일 수신 ( FTP )
// IP : 114.108.166.14 PORT : 21 PASSIVE 방식
// ID : kjbk_ccrs PWD: ccrskjbk!@#
// 파일명: SNTFTP.${YYYYMMDD}.tar.gz
public class FTPCC extends Transfer implements SocketService{
public void sendFile(BatchDoc batchDoc) throws Exception {
throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다.");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPCC] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//2. System FTP Shell 명령어를 Runtime 으로 실행
try {
String ipaddress = batchDoc.getBatchMsg().getHeader().getRemoteIP();
String port = batchDoc.getBatchMsg().getHeader().getPort();
String userid = batchDoc.getBatchMsg().getHeader().getUserID();
String passwd = batchDoc.getBatchMsg().getHeader().getUserPassword();
if (ftpClient == null || !ftpClient.isConnected()) this.connect(ipaddress, Integer.parseInt(port) );
ftpClient.login(userid, passwd);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
setLastActivity();
logger.debug( "[FTPCC]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String baseDate = DatetimeUtil.getCurrentDate();
if ( reqFileName != null && reqFileName.length() > 8 ){
if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){
baseDate = reqFileName.substring(reqFileName.length() - 8 );
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
}
}
reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode() + "." + baseDate + ".tar.gz";
ftpClient.setDataTimeout(600*1000);
ftpClient.setConnectTimeout(300);
FTPFile[] files = ftpClient.listFiles();
setLastActivity();
for (int inx = 0; inx < files.length; inx++) {
if ( !files[inx].isFile() || !files[inx].getName().equals(reqFileName) ) continue;
FileOutputStream fos = null;
batchDoc.getBatchMsg().getHeader().setFileName(reqFileName);
batchDoc.getBatchMsg().getHeader().setFileSize(files[inx].getSize());
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + reqFileName;
File rcvRealFile = new File( recvFile );
File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) );
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileStart(batchDoc);
try {
fos = new FileOutputStream( rcvRealFile );
ftpClient.retrieveFile(reqFileName, fos);
setLastActivity();
} catch (Exception e) {
setLastActivity();
logger.error(e.getMessage(), e);
throw new Exception("파일수신에 실패하였습니다. -" + e.getMessage());
} finally {
fos.close();
}
try {
File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) );
if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
rcvRealFile.renameTo(rcvArchFile);
rcvChkFile.createNewFile();
}else{
throw new Exception("파일수신에 실패하였습니다.");
}
} catch (Exception e) {
throw e;
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
break;
}
} 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);
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setErrorLog(batchDoc, ex.getMessage());
logger.error( errMsg, ex );
throw ex;
} finally {
this.disconnect();
}
logger.info("[FTPCC] ■ VAN사 → FEP 파일 수신 완료.");
}
@Override
public void shutdown() {
disconnect();
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-357
View File
@@ -1,357 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.nio.file.Files;
import org.apache.commons.lang3.StringUtils;
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.FTPUtil;
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.property.PropManager;
import com.eactive.eai.common.util.Logger;
/**
* chk 파일(check.file.suffix)이 있는 파일 송수신
*
*/
public class FTPCH extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
/** 송신 폴더 */
private static final String SEND_REMOTE_PATH = "send.remote.path";
/** 수신 폴더 */
private static final String RECV_REMOTE_PATH = "recv.remote.path";
/** 체크 파일 확장자 */
private static final String CHECK_FILE_SUFFIX = "check.file.suffix";
/** 큐에서 가져오는 최대 갯수 */
private static final String MAX_ITERATION = "max.iteration";
public final static String PHASECODE_NORMAL_END = "END";
public void sendFile(BatchDoc batchDoc) throws Exception {
internalSendFile(batchDoc);
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
int iteration = 100;
String maxIteration = pmanager.getProperties(propName).getProperty(MAX_ITERATION);
if (maxIteration != null) {
try {
iteration = Integer.parseInt(maxIteration);
} catch(Exception e) {
logger.error(maxIteration, e);
}
}
// 만일의 경우 대비해서 100번만 돈다.
for (int i = 0; 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(newDoc);
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);
}
}
}
/**
* 실제로 파일을 전송한다.
* @param batchDoc 전송할 배치 작업
*/
private void internalSendFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPCH] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
String checkFileName = 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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(SEND_REMOTE_PATH);
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
String checkFileSuffix = pmanager.getProperties(propName).getProperty(CHECK_FILE_SUFFIX);
if ( checkFileSuffix == null ){
throw new Exception("체크 파일 접미어가 지정되어 있지 않습니다. -propName:" + propName + "," + CHECK_FILE_SUFFIX);
}
String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName();
String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName();
setFileHeaderAndTrailer(batchDoc, new File(sendFileName));
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileStart(batchDoc);
FTPUtil.store(ipaddress, port, userid, passwd, remoteFileName, sendFileName, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
// check 파일 이름
checkFileName = sendFileName + checkFileSuffix;
// 체크 파일을 지우기 이전에 생성한 체크 파일 삭제
Files.deleteIfExists(new File(checkFileName).toPath());
// check 파일 생성
if (new File(checkFileName).createNewFile() == false) {
throw new Exception("체크 파일을 생성하지 못했습니다. checkFileName = " + checkFileName);
};
String remoteCheckfileName = remoteFileName + checkFileSuffix;
FTPUtil.store(ipaddress, port, userid, passwd, remoteCheckfileName, checkFileName, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
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);
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setErrorLog(batchDoc, ex.getMessage());
logger.error( errMsg, ex );
throw ex;
} finally {
BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID());
this.disconnect();
// 체크 파일 삭제
// 재전송할 때 오류 발생 방지
if (checkFileName != null) {
Files.deleteIfExists(new File(checkFileName).toPath());
}
}
logger.info("[FTPCHK] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
}
/**
* 같은 업무, 기관 코드의 작업이 큐에 있는지 확인한다.
*
* @param batchDoc
* @return 큐에서 가져온 배치 잡
*/
private BatchDoc checkMoreFile(BatchDoc batchDoc) {
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 ? "null" : newDoc.toString(), e);
return null;
}
return newDoc;
}
/**
* 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 ("FTPCH");
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 ("");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다.");
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-319
View File
@@ -1,319 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.ftp.FTPUtil;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
// 이제너두
// 파일명
// 송신:
// KJ13_YYYYMMDD.in
// KJ15_YYYYMMDD.in
// 수신:
// KJ12_YYYYMMDD.out
// KJ14_YYYYMMDD.out
public class FTPET extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
/** 원격지 경로 */
private static final String REMOTE_PATH = "remote.path";
/** 파일 수신시 접미어 */
private static final String POSTFIX = "post.fix";
/** sftp 사용 여부 */
private static final String SFTP_YN = "sftp";
public void sendFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPET] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH);
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String sftpYn = pmanager.getProperties(propName).getProperty(SFTP_YN);
boolean isSftp = "Y".equalsIgnoreCase(sftpYn);
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
//20220712
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10");
int connTimeout = Integer.parseInt(connTimeoutStr);
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10");
int setTimeout = Integer.parseInt(setTimeoutStr);
String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName();
//String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName();
String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName();
setFileHeaderAndTrailer(batchDoc, new File(sendFileName));
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileStart(batchDoc);
//FTPUtil.store(ipaddress, port, userid, passwd, remoteFileName, sendFileName, isSftp, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
FTPUtil.store(batchDoc, ipaddress, port, userid, passwd, remotePath, remoteFileName, sendFileName,
connTimeout, setTimeout, isSftp, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
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);
logger.error( errMsg, ex );
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setErrorLog(batchDoc, ex.getMessage());
throw ex;
} finally {
BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID());
this.disconnect();
}
logger.info("[FTPET] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPET] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//2. System FTP Shell 명령어를 Runtime 으로 실행
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
String jobName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getBizCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH);
String sftpYn = pmanager.getProperties(propName).getProperty(SFTP_YN);
boolean isSftp = "Y".equalsIgnoreCase(sftpYn);
String postfix = null;
try{
postfix = pmanager.getProperties(jobName).getProperty(POSTFIX);
logger.debug( "[FTPET]postfix: {}", postfix);
}catch( Exception e ){}
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
//20220712
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10");
int connTimeout = Integer.parseInt(connTimeoutStr);
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10");
int setTimeout = Integer.parseInt(setTimeoutStr);
String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
logger.debug( "[FTPET]FileName: {}", batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String baseDate = DatetimeUtil.getCurrentDate();
if ( reqFileName != null && reqFileName.length() > 8 ){
if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){
baseDate = reqFileName.substring(reqFileName.length() - 8 );
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
}
}
reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode() + "_" + baseDate;
if ( postfix != null && !postfix.equals("")){
reqFileName = reqFileName + postfix;
}
logger.debug( "[FTPET]reqFileName:" + reqFileName );
try {
FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, isSftp, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
for ( int inx = 0 ; inx < list.length; inx++){
FTPFile file = list[inx];
if ( file.getName().equals(reqFileName) ){
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);
//FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), isSftp, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(),
connTimeout, setTimeout, isSftp, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
//batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName();
File rcvRealFile = new File( recvFile );
File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) );
try {
File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) );
if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
//setFileHeaderAndTrailer(batchDoc, rcvRealFile);
rcvRealFile.renameTo(rcvArchFile);
rcvChkFile.createNewFile();
}else{
throw new Exception("파일수신에 실패하였습니다.");
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
} catch (Exception e) {
throw e;
}
}
}
}catch ( Exception e ){
if ( !e.getMessage().contains("No such file"))
throw e;
}
} 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);
logger.error( errMsg, ex );
String errorMessage = ex.getMessage();
if (StringUtils.isEmpty(errorMessage)) {
errorMessage = "No Exception ErrorMessage";
}
LogUtil.setErrorLog(batchDoc, errorMessage);
throw ex;
} finally {
this.disconnect();
}
logger.info("[FTPET] ■ VAN사 → FEP 파일 수신 완료.");
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-270
View File
@@ -1,270 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.ftp.FTPUtil;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
/**
* 금용결제원 SFTP
* 빅데이터 기반의 금융의심거래정보 분석 공유 서비스[FAS]
*
* 이름은 KS(Kftc Sftp)가 사용 중이라 FAS에 따옴
*
* 거래일자 확인: 전일자 YYYYMMDD 파일
* 파일명 : FS0001
*
* 오류
* 1. 거래일자 파일이 없는 경우에 오류 발생
*/
public class FTPFA extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
/** 원격지 경로 */
private static final String REMOTE_PATH = "remote.path";
/** 파일 수신시 접미어 */
private static final String POSTFIX = "post.fix";
/** sftp 사용 여부 */
private static final String SFTP_YN = "sftp";
public void sendFile(BatchDoc batchDoc) throws Exception {
throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다.");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPFA] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
String jobName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getBizCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH);
String sftpYn = pmanager.getProperties(propName).getProperty(SFTP_YN);
boolean isSftp = "Y".equalsIgnoreCase(sftpYn);
String postfix = null;
try{
postfix = pmanager.getProperties(jobName).getProperty(POSTFIX);
if (logger.isDebugEnabled()) {
logger.debug( "[FTPFA]postfix:" + postfix);
}
}catch( Exception e ){}
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
//20220712
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10");
int connTimeout = Integer.parseInt(connTimeoutStr);
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10");
int setTimeout = Integer.parseInt(setTimeoutStr);
String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
if (logger.isDebugEnabled()) {
logger.debug( "[FTPFA]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
}
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String baseDate = DatetimeUtil.getCurrentDate();
if ( reqFileName != null && reqFileName.length() > 8 ){
if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){
baseDate = reqFileName.substring(reqFileName.length() - 8 );
}
}
// 전일자
baseDate = DatetimeUtil.getDayAddedDate(baseDate, -1);
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode();
if ( postfix != null && !postfix.equals("")) {
reqFileName = reqFileName + postfix;
}
logger.debug( "[FTPFA]reqFileName:" + reqFileName );
try {
FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, isSftp, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
// 전일자 파일 확인
boolean dateFileExist = false;
FTPFile remoteFile = null;
for (FTPFile file : list){
if (file.getName().equals(baseDate)) {
dateFileExist = true;
}
if (file.getName().equals(reqFileName)) {
remoteFile = file;
}
}
if (dateFileExist == false) {
throw new Exception("거래일자 파일(" + baseDate + ")이 없습니다.");
}
if (remoteFile != null) {
batchDoc.getBatchMsg().getHeader().setFileSize(remoteFile.getSize());
batchDoc.getBatchMsg().getBody().setRecCnt(1);
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
batchDoc.getBatchMsg().getHeader().setFileName(remoteFile.getName());
LogUtil.setLogFileStart(batchDoc);
//FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + remoteFile.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), isSftp, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, remoteFile.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(),
connTimeout, setTimeout, isSftp, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
//batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + remoteFile.getName();
File rcvRealFile = new File( recvFile );
File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) );
try {
File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) );
if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
//setFileHeaderAndTrailer(batchDoc, rcvRealFile);
rcvRealFile.renameTo(rcvArchFile);
rcvChkFile.createNewFile();
}else{
throw new Exception("파일수신에 실패하였습니다.");
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
} catch (Exception e) {
throw e;
}
}
}catch ( Exception e ){
if ( !e.getMessage().contains("No such file"))
throw e;
}
} 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 {
this.disconnect();
}
logger.info("[FTPFA] ■ VAN사 → FEP 파일 수신 완료.");
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-535
View File
@@ -1,535 +0,0 @@
package com.eactive.eai.adapter.ftp;
import static com.eactive.eai.adapter.ftp.SFTPConstants.RECV_REMOTE_PATH;
import static com.eactive.eai.adapter.ftp.SFTPConstants.SEND_REMOTE_PATH;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.ftp.FTPUtil;
import com.eactive.eai.batch.logger.LogManager;
import com.eactive.eai.batch.osd.OutsideManager;
import com.eactive.eai.batch.osd.OutsideVO;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
/**
* 금용결제원 SFTP
* 빅데이터 기반의 금융의심거래정보 분석 공유 서비스[FAS]
*
* 이름은 KS(Kftc Sftp)가 사용 중이라 FAS에 따옴
*
* 파일명 : FS0001
*
*/
public class FTPFS extends Transfer implements SocketService {
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
// 파일경로 관련 프로퍼티
private static final String REMOTE_PATH = "remote.path";
private static final String REMOTE_PATH_BASEDATE_YN = "remote.path.basedate.yn";
/** 임시 파일 확장자 .FILEPART. 해당 파일 무시 */
private static final String REMOTE_FILE_WORKING_POSTFIX = "remote.file.working.postfix";
// 파일관련 프로퍼티
private static final String REMOTE_FILE_BASEDATE_DELIM = "remote.file.basedate.delim";
/** 현재일 기준 일자 변경: -1 인경우 전일자 */
private static final String REMOTE_FILE_BASEDATE_ADDDAYS = "remote.file.basedate.adddays";
private static final String REMOTE_FILE_BASEDATE_YN = "remote.file.basedate.yn";
private static final String REMOTE_FILE_BASETIME_DELIM = "remote.file.basetime.delim";
private static final String REMOTE_FILE_BASETIME_YN = "remote.file.basetime.yn";
private static final String REMOTE_FILE_BASETIME = "remote.file.basetime";
/** 인증 방법 1 = id, 2 = key 방식 */
private static final String AUTH_TYPE = "sftp.auth.type";
@Override
public void sendFile(BatchDoc batchDoc) throws Exception {
// TODO Auto-generated method stub
logger.info("[FTPFS] ■ 대외기관→FEP 파일 송신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH);
if ( remotePath == null ) {
remotePath = "";
}
String sendRemotePath = pmanager.getProperties(propName).getProperty(SEND_REMOTE_PATH);
if ( sendRemotePath != null && sendRemotePath.trim().length() > 0) {
remotePath = sendRemotePath;
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = "1"; // id
}
// 업로드 서버가 일자별 경로 생성 시, 경로에 일자정보 추가.
String remotePathBasedateYn = pmanager.getProperties(propName).getProperty(REMOTE_PATH_BASEDATE_YN);
if ( remotePathBasedateYn == null || !remotePathBasedateYn.equalsIgnoreCase("y") ) {
remotePathBasedateYn = "n";
}
else {
remotePathBasedateYn = "y";
}
String baseDate = DatetimeUtil.getCurrentDate();
if ( remotePathBasedateYn == "y" )
remotePath = remotePath + baseDate + "/";
// 실제 파일이름
String orgFileName = batchDoc.getBatchMsg().getHeader().getFileName();
// FEP 에서 Rename(송신Real->송신Arch)한 파일이름
String sendFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName();
logger.debug( "[FTPFS]sendFileName:" + orgFileName);
logger.debug( "[FTPFS]remotePath:" + remotePath);
//File 시작시간 설정
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileStart(batchDoc);
String sendFilePath = batchDoc.getBatchMsg().getHeader().getFilePath();
try {
FTPUtil.store(ipaddress, port, userid, passwd, remotePath + orgFileName, sendFilePath + File.separator + sendFileName, true, batchDoc.getLogger(), authType);
} catch (Exception e) {
logger.error("[FTPFS]파일송신에 실패하였습니다.", e);
throw e;
}
//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("[FTPFS] ■ FEP → VAN사 파일 송신 완료.");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPFS] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
try {
int bizCodeStartIndex = 0; // 거래시작인덱스
int bizCodeEndIndex = 0; // 거래종료인덱스
String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode();
String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode();
ArrayList<OutsideVO> organList = OutsideManager.getInstance().getOutsideInfo(processCode);
for (int i=0; organList!=null && i<organList.size(); i++) {
OutsideVO organInfo = organList.get(i);
if ( institutionCode.equals(organInfo.getOsdCode()) ) {
bizCodeStartIndex = organInfo.getBizCdStartIdx();
bizCodeEndIndex = organInfo.getBizCdEndIdx();
break;
}
}
PropManager pmanager = PropManager.getInstance();
// 기관 프로퍼티그룹 명
String propName = PROP_GROUP_NAME_PREFIX + "{" +
processCode +
"_" +
institutionCode + "}";
String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH);
if ( remotePath == null ) {
remotePath = "";
}
String recvRemotePath = pmanager.getProperties(propName).getProperty(RECV_REMOTE_PATH);
if ( recvRemotePath != null && recvRemotePath.trim().length() > 0) {
remotePath = recvRemotePath;
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
//20220712
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10");
int connTimeout = Integer.parseInt(connTimeoutStr);
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10");
int setTimeout = Integer.parseInt(setTimeoutStr);
String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
// 1. 파일 경로에 일자 디렉토리 포함 여부 확인
String remotePathBasedateYn = pmanager.getProperties(propName).getProperty(REMOTE_PATH_BASEDATE_YN);
if ( remotePathBasedateYn == null || !remotePathBasedateYn.equalsIgnoreCase("y") ) {
remotePathBasedateYn = "n";
}
else {
remotePathBasedateYn = "y";
}
// 2. 파일 이름에 일자 포함 여부 확인
String remoteFileBasedateYn = pmanager.getProperties(propName).getProperty(REMOTE_FILE_BASEDATE_YN);
if ( remoteFileBasedateYn == null || !remoteFileBasedateYn.equalsIgnoreCase("y") ) {
remoteFileBasedateYn = "n";
}
else {
remoteFileBasedateYn = "y";
}
// 2-1. 2 에 해당 시 구분자
String remoteFileBasedateDelim = pmanager.getProperties(propName).getProperty(REMOTE_FILE_BASEDATE_DELIM);
if ( remoteFileBasedateDelim == null )
remoteFileBasedateDelim = "";
// 3. 임시파일 확장자
String remoteFileWorkingPostfix = pmanager.getProperties(propName).getProperty(REMOTE_FILE_WORKING_POSTFIX);
if ( remoteFileWorkingPostfix == null )
remoteFileWorkingPostfix = "";
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();
// 특정일자 파일을 수기로 수신요청 시, 해당 일자의 경로 설정
logger.debug( "[FTPFS]recvFileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String baseDate = DatetimeUtil.getCurrentDate();
boolean isManualRcv = false;
if ( reqFileName != null && reqFileName.length() > 8 ){
if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){
baseDate = reqFileName.substring(reqFileName.length() - 8 );
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
isManualRcv = true;
}else{
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
}
}else{
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
}
// 다운로드 서버가 일자별 경로 생성 시, 경로에 일자정보 추가.
if ("y".equalsIgnoreCase(remotePathBasedateYn))
remotePath = remotePath + baseDate;
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
FTPFile[] list = new FTPFile[0];
try {
list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(), authType);
} catch ( Exception e ){
if ( !e.getMessage().contains("No such file") )
throw e;
}
for ( int inx = 0 ; inx < list.length; inx++ ){
FTPFile file = list[inx];
String remoteFileName = file.getName();
try {
if (remoteFileWorkingPostfix.length() > 0 && remoteFileName.endsWith(remoteFileWorkingPostfix)) {
logger.debug( "[FTPFS]임시파일은 무시 " + remoteFileName + ", 임시파일 확장자 = " + remoteFileWorkingPostfix);
continue;
}
// 파일이름으로부터 등록된 파일명을 구함
if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= remoteFileName.length()) bizCodeStartIndex = 0;
if (bizCodeEndIndex <= 0 || bizCodeEndIndex > remoteFileName.length()) bizCodeEndIndex = remoteFileName.length();
String bizCode = remoteFileName.substring(bizCodeStartIndex, bizCodeEndIndex);
reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
// 수기요청 파일명은 아래 로직에서 기관 프로퍼티값에 따라 재설정.
if ( reqFileName != null && reqFileName.length() > 8 ) {
reqFileName = reqFileName.substring(bizCodeStartIndex, bizCodeEndIndex);
}
// 파일 프로퍼티그룹 명
String propJobName = PROP_GROUP_NAME_PREFIX + "{" +
processCode +
"_" +
bizCode + "}";
// 3. 시간대별 수신이 필요한 파일여부 확인
String remoteFileBasetimeYn = pmanager.getProperties(propJobName).getProperty(REMOTE_FILE_BASETIME_YN);
if ( remoteFileBasetimeYn == null || !remoteFileBasetimeYn.equalsIgnoreCase("y") ) {
remoteFileBasetimeYn = "n";
}
else {
remoteFileBasetimeYn = "y";
}
// 3-1. 3 에 해당 시 구분자
String remoteFileBasetimeDelim = pmanager.getProperties(propJobName).getProperty(REMOTE_FILE_BASETIME_DELIM);
if ( remoteFileBasetimeDelim == null )
remoteFileBasetimeDelim = "";
// 3-2. 3 에 해당 시 기준시 추출
String baseTime = "";
if ("y".equalsIgnoreCase(remoteFileBasetimeYn)) {
baseTime = pmanager.getProperties(propJobName).getProperty(REMOTE_FILE_BASETIME);
// 기준시 설정이 DEFAULT(99)일 경우 현재 시간(24HH)으로 설정
if ( baseTime.equals("99") ) {
baseTime = DatetimeUtil.getTimeString().substring(0,2);
}
}
// 파일이름에 날짜를 포함하는 경우, 특정일자 파일을 수신요청 시 요청일자의 파일명 설정
if ("y".equalsIgnoreCase(remoteFileBasedateYn)) {
// 전일자 등 날짜 추가
String addDays = pmanager.getProperties(propJobName).getProperty(REMOTE_FILE_BASEDATE_ADDDAYS, "0");
String tempBaseDate = baseDate;
if (!StringUtils.equals(addDays, "0")) {
try {
int days = Integer.parseInt(addDays);
tempBaseDate = DatetimeUtil.addDays(tempBaseDate, days);
} catch (Exception e) {
// ignore
logger.error(e.getMessage());
}
}
reqFileName = reqFileName + remoteFileBasedateDelim + tempBaseDate;
}
logger.debug( "[FTPFS]reqFileName: {}", reqFileName );
logger.debug( "[FTPFS]remotePath: {}", remotePath);
logger.debug( "[FTPFS]remoteFileName: {}", remoteFileName);
boolean balreadyRcv = false;
// 수기요청이 아닐때,
if ( isManualRcv == false ) {
String compareFileName = bizCode + reqFileName;
// 특정시점(24HH)수신 파일인 경우, 자동요청시점과의 일치여부 검증
if ( "y".equalsIgnoreCase(remoteFileBasetimeYn) ) {
// 시간만 비교하면 이전 일짜도 가져올 수 있기 때문에 년월일시까지 비교함
compareFileName = bizCode + reqFileName + remoteFileBasetimeDelim + baseTime;
}
if (!remoteFileName.startsWith(compareFileName)) {
logger.debug( "[FTPFS]basetime not equal.. receive skipped : "+remoteFileName+" / "+compareFileName);
continue;
}
// 기수신여부 확인
balreadyRcv = LogManager.getInstance().getFileLogSuccessCheck(processCode, institutionCode, bizCode, remoteFileName);
}
// 수기 요청 시,
else {
if ( remoteFileName.startsWith(reqFileName) ) {
String compareFileName = reqFileName;
// 특정시점(24HH)수신 파일인 경우, 수기요청시점과의 일치여부 검증
if ( "y".equalsIgnoreCase(remoteFileBasetimeYn) ) {
// 시각을 붙여서 같은 시각인지 확인
compareFileName = reqFileName + remoteFileBasetimeDelim + baseTime;
}
if (!remoteFileName.startsWith(compareFileName)) {
logger.debug( "[FTPFS]basetime not equal.. receive skipped : " + remoteFileName + "/" + compareFileName);
continue;
}
}
else {
continue;
}
}
if ( balreadyRcv == false ) {
batchDoc.getBatchMsg().getHeader().setBizCode(bizCode);
batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize());
batchDoc.getBatchMsg().getBody().setRecCnt(1);
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
// 반복 실행을 위해서 FileName을 원복
String restoreFileName = batchDoc.getBatchMsg().getHeader().getFileName();
batchDoc.getBatchMsg().getHeader().setFileName(remoteFileName);
LogUtil.setLogFileStart(batchDoc);
// FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + remoteFileName, batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(), authType);
FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(),
connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + remoteFileName;
File rcvRealFile = new File( recvFile );
try {
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("[FTPFS]파일수신에 실패하였습니다.");
}
//File 종료시간 설정
// setLastActivity();
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
} catch (Exception e) {
LogUtil.setErrorLog(batchDoc, e.getMessage());
throw e;
} finally {
batchDoc.getBatchMsg().getHeader().setFileName(restoreFileName);
}
}
else {
logger.info( "[FTPFS] " + remoteFileName + " 은 기수신되었으므로 수신하지 않습니다.");
}
} catch (Exception e) {
logger.error(remoteFileName + " 파일 처리 중 오류, 다음 파일 처리는 계속 진행함", e);
}
}
} 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("[FTPFS] ■ VAN사 → FEP 파일 수신 완료.");
}
@Override
public void shutdown() {
// TODO Auto-generated method stub
}
@Override
public Socket getCurrentSocket() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean connect() {
// TODO Auto-generated method stub
return false;
}
@Override
public ConfigurationContext getContext() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setControl(Object control) {
// TODO Auto-generated method stub
}
@Override
public void notifyMessage() {
// TODO Auto-generated method stub
}
@Override
public boolean idle(long timeout) {
// TODO Auto-generated method stub
return false;
}
@Override
public int getCurrentState() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isConnected() throws IOException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isActive() {
// TODO Auto-generated method stub
return false;
}
@Override
public void checkActivity() {
// TODO Auto-generated method stub
}
@Override
public String getRemoteIPAddress() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setLastActivity() {
// TODO Auto-generated method stub
lastActivity = System.currentTimeMillis();
}
@Override
public long getFirstActivity() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getLastActivity() {
// TODO Auto-generated method stub
return 0;
}
}
-555
View File
@@ -1,555 +0,0 @@
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);
}
}
}
}
-284
View File
@@ -1,284 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.ftp.FTPUtil;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
// KED Findsystem 파일수신 ( SFTP )
// IP : 10.0.249.35 PORT : 22
// ID : kjbank PWD: kjbank2015
// 수신디렉터리 : /ftp_user/kjbank/test/senddata/findsystem
// 백업디렉터리 : ?
// 파일명:
// KED_20191015142047_20191015_H01_1_35766653888617_1_1_1058675080000.TIF
// KEDFS_20191015142047_20191015_H06_1_35766653888617_1_1_1058675080000.TIF
public class FTPKF extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
private static final String REMOTE_PATH = "remote.path";
private static final String BACKUP_PATH = "backup.path";
private static final String FIN_EXT = "fin.ext";
private static final String FILE_EXT = "file.ext";
public void sendFile(BatchDoc batchDoc) throws Exception {
throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다.");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPKF] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH);
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String backupPath = pmanager.getProperties(propName).getProperty(BACKUP_PATH);
if ( backupPath == null ){
throw new Exception("해당 기관에 백업 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + BACKUP_PATH);
}
String finExt = pmanager.getProperties(propName).getProperty(FIN_EXT);
if (finExt == null){
finExt = ".fin";
}
String fileExt = pmanager.getProperties(propName).getProperty(FILE_EXT);
if (fileExt == null) {
fileExt = ".tif";
}
logger.debug( "[FTPKF]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String baseDate = DatetimeUtil.getCurrentDate();
if ( reqFileName != null && reqFileName.length() > 8 ){
if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){
baseDate = reqFileName.substring(reqFileName.length() - 8 );
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
}
}
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
remotePath = remotePath.replaceAll("#YYYYMMDD#", baseDate );
// if ( !remotePath.endsWith("/") )
// remotePath = remotePath + "/";
backupPath = backupPath.replaceAll("#YYYYMMDD#", baseDate );
if ( !backupPath.endsWith("/") )
backupPath = backupPath + "/";
//20220712
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10");
int connTimeout = Integer.parseInt(connTimeoutStr);
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10");
int setTimeout = Integer.parseInt(setTimeoutStr);
String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
FTPFile[] list = null;
try {
list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
// .fin 파일에서 원본 파일을 찾기 위해서
Map<String, FTPFile> fileMap = new HashMap<String, FTPFile>();
for (int i = 0; i < list.length; i++) {
fileMap.put(list[i].getName(), list[i]);
}
for (int i = 0 ; i < list.length; i++){
FTPFile file = list[i];
if ( file.getName().endsWith(finExt) ){
String finFileName = file.getName();
// a.fin을 a.tif로 변경
String recvFileName = finFileName.substring(0, finFileName.length() - finExt.length());
recvFileName += fileExt;
FTPFile recvFtpFile = fileMap.get(recvFileName);
if (recvFtpFile == null) {
throw new Exception(file.getName() + " 파일에 해당하는 원본 파일 [" + recvFileName + "] 이 없습니다.");
}
batchDoc.getBatchMsg().getHeader().setFileSize(recvFtpFile.getSize());
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
batchDoc.getBatchMsg().getHeader().setFileName(recvFtpFile.getName());
LogUtil.setLogFileStart(batchDoc);
//FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + recvFileName, batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, recvFileName, batchDoc.getBatchMsg().getHeader().getFilePath(),
connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
//batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + recvFileName;
File rcvRealFile = new File( recvFile );
File rcvChkFile = new File(StringUtil.realToRootDir(recvFile));
try {
File rcvArchFile = new File(StringUtil.realToArchDir(recvFile));
if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
//setFileHeaderAndTrailer(batchDoc, rcvRealFile);
rcvRealFile.renameTo(rcvArchFile);
rcvChkFile.createNewFile();
} else {
throw new Exception("파일수신에 실패하였습니다." + recvFileName);
}
// 원본 파일 백업
try {
FTPUtil.renameWithMkdirs(ipaddress, port, userid, passwd, remotePath + recvFileName, backupPath, recvFileName, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
} catch (Exception e) {
logger.error("파일 백업에 실패하였습니다." + recvFileName, e);
throw new Exception("파일 백업에 실패하였습니다.");
}
// .fin 파일 백업
try {
FTPUtil.rename(ipaddress, port, userid, passwd, remotePath + file.getName(), backupPath + file.getName(), true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
} catch (Exception e) {
logger.error(".fin 파일 백업에 실패하였습니다." + file.getName(), e);
throw new Exception(".fin 파일 백업에 실패하였습니다.");
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
} catch (Exception e) {
throw e;
}
}
}
}catch ( Exception e ){
if ( e.getMessage() != null && !e.getMessage().contains("No such file"))
throw e;
}
} 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 {
this.disconnect();
}
logger.info("[FTPKF] ■ VAN사 → FEP 파일 수신 완료.");
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-277
View File
@@ -1,277 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.ftp.FTPUtil;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
/**
* 한국조폐공사(KMS) 연동
* Java 1.7에서 jsch로 연동 불가하여 sshj 사용
* Bandwith 삭제함
* SFTP 송수신 중단 안됨
*/
public class FTPKM extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
private static final String SEND_REMOTE_PATH = "send.remote.path";
private static final String SEND_DELAY_SEC = "send.delay.sec";
private static final String RECV_REMOTE_PATH = "recv.remote.path";
private static final String REQ_FILE_NAME = "req.file.name";
public void sendFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPKM] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//Shell 명령어를 Runtime 으로 실행
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
String remotePath = pmanager.getProperties(propName).getProperty(SEND_REMOTE_PATH);
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
long delaySec = 60 * 1000;
try {
delaySec = Long.parseLong(pmanager.getProperties(propName).getProperty(SEND_DELAY_SEC));
Thread.sleep(delaySec * 1000);
}catch ( Exception e){}
String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName();
//String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName();
String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName();
setFileHeaderAndTrailer(batchDoc, new File(sendFileName));
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileStart(batchDoc);
FTPUtil.store(ipaddress, port, userid, passwd, remotePath + remoteFileName, sendFileName, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
// FTPUtil.store(batchDoc, ipaddress, port, userid, passwd, remotePath, remoteFileName, sendFileName,
// connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER), authType);
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);
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setErrorLog(batchDoc, ex.getMessage());
logger.error( errMsg, ex );
throw ex;
} finally {
BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID());
this.disconnect();
}
logger.info("[FTPKM] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPKM] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//2. System FTP Shell 명령어를 Runtime 으로 실행
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(RECV_REMOTE_PATH);
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + RECV_REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
logger.debug( "[FTPKM]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode();
if ( DatetimeUtil.isRightDate(reqFileName.substring(bizCode.length()))){
reqFileName = pmanager.getProperties(propName).getProperty(REQ_FILE_NAME);
batchDoc.getBatchMsg().getHeader().setFileName(reqFileName);
}
logger.debug( "[FTPKM]reqFileName:" + reqFileName );
try {
FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
for ( int inx = 0 ; inx < list.length; inx++){
FTPFile file = list[inx];
if ( file.getName().equals(reqFileName) ){
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);
FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), true,
batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName();
File rcvRealFile = new File( recvFile );
File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) );
try {
File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) );
if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
rcvRealFile.renameTo(rcvArchFile);
rcvChkFile.createNewFile();
}else{
throw new Exception("파일수신에 실패하였습니다.");
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
} catch (Exception e) {
throw e;
}
}
}
}catch ( Exception e ){
if ( !e.getMessage().contains("No such file"))
throw e;
}
} 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 {
this.disconnect();
}
logger.info("[FTPKM] ■ VAN사 → FEP 파일 수신 완료.");
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-303
View File
@@ -1,303 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.ftp.FTPUtil;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
// KT-NET 자료 송수신 ( SFTP )
// IP : 10.0.249.28 (R), 10.0.249.29 (T) PORT : 30022
// ASIS -- ID : kjbsftp PWD: sftpKjb
// 파일명
//송신시 /recv/doc
//수신시 /send/doc
// KJ[연도네자리][신청번호].pdf
// 차세대
// ID : gjbsftp PW: sftpGjb
//송신시 /recv/doc
//수신시 /send/doc
public class FTPKN extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
private static final String SEND_REMOTE_PATH = "send.remote.path";
private static final String SEND_DELAY_SEC = "send.delay.sec";
private static final String RECV_REMOTE_PATH = "recv.remote.path";
private static final String REQ_FILE_NAME = "req.file.name";
public void sendFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPKN] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//Shell 명령어를 Runtime 으로 실행
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
String remotePath = pmanager.getProperties(propName).getProperty(SEND_REMOTE_PATH);
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_REMOTE_PATH);
}
long delaySec = 60 * 1000;
try {
delaySec = Long.parseLong(pmanager.getProperties(propName).getProperty(SEND_DELAY_SEC));
Thread.sleep(delaySec * 1000);
}catch ( Exception e){}
//20220712
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10");
int connTimeout = Integer.parseInt(connTimeoutStr);
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10");
int setTimeout = Integer.parseInt(setTimeoutStr);
String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName();
//String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName();
String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName();
setFileHeaderAndTrailer(batchDoc, new File(sendFileName));
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileStart(batchDoc);
//FTPUtil.store(ipaddress, port, userid, passwd, remoteFileName, sendFileName, true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
FTPUtil.store(batchDoc, ipaddress, port, userid, passwd, remotePath, remoteFileName, sendFileName,
connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
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);
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setErrorLog(batchDoc, ex.getMessage());
logger.error( errMsg, ex );
throw ex;
} finally {
BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID());
this.disconnect();
}
logger.info("[FTPKN] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPKN] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//2. System FTP Shell 명령어를 Runtime 으로 실행
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(RECV_REMOTE_PATH);
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + RECV_REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
//20220712
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10");
int connTimeout = Integer.parseInt(connTimeoutStr);
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10");
int setTimeout = Integer.parseInt(setTimeoutStr);
String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
logger.debug( "[FTPKN]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode();
if ( DatetimeUtil.isRightDate(reqFileName.substring(bizCode.length()))){
reqFileName = pmanager.getProperties(propName).getProperty(REQ_FILE_NAME);
batchDoc.getBatchMsg().getHeader().setFileName(reqFileName);
}
logger.debug( "[FTPKN]reqFileName:" + reqFileName );
try {
FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
for ( int inx = 0 ; inx < list.length; inx++){
FTPFile file = list[inx];
if ( file.getName().equals(reqFileName) ){
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);
//FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(),
connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
//batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName();
File rcvRealFile = new File( recvFile );
File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) );
try {
File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) );
if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
//setFileHeaderAndTrailer(batchDoc, rcvRealFile);
rcvRealFile.renameTo(rcvArchFile);
rcvChkFile.createNewFile();
}else{
throw new Exception("파일수신에 실패하였습니다.");
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
} catch (Exception e) {
throw e;
}
}
}
}catch ( Exception e ){
if ( !e.getMessage().contains("No such file"))
throw e;
}
} 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 {
this.disconnect();
}
logger.info("[FTPKN] ■ VAN사 → FEP 파일 수신 완료.");
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-235
View File
@@ -1,235 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.ftp.FTPUtil;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
// KED 파일 수신 ( SFTP )
// IP : 10.0.249.35 PORT : 22
// ID : kjbank PWD: kjbank2015
// 파일명: test/YYYYMMDD/kjbank_YYYYMMDD.jar (TEST)
// prod/YYYYMMDD/kjbank_YYYYMMDD.jar (PROD)
public class FTPKS extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
private static final String REMOTE_PATH = "remote.path";
public void sendFile(BatchDoc batchDoc) throws Exception {
throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다.");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPKS] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//2. System FTP Shell 명령어를 Runtime 으로 실행
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH);
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH);
}
//20220712
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10");
int connTimeout = Integer.parseInt(connTimeoutStr);
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10");
int setTimeout = Integer.parseInt(setTimeoutStr);
String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
logger.debug( "[FTPKS]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String baseDate = DatetimeUtil.getCurrentDate();
if ( reqFileName != null && reqFileName.length() > 8 ){
if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){
baseDate = reqFileName.substring(reqFileName.length() - 8 );
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
}
}
remotePath = remotePath.replaceAll("#YYYYMMDD#", baseDate );
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode() + "_" + baseDate + ".jar";
logger.debug( "[FTPKS]reqFileName:" + reqFileName );
boolean isFileInTheServer = false;
try {
FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
//FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, false, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
for ( int inx = 0 ; inx < list.length; inx++){
FTPFile file = list[inx];
if ( file.getName().equals(reqFileName) ){
isFileInTheServer = true;
batchDoc.getBatchMsg().getHeader().setFileSize(file.getSize());
batchDoc.getBatchMsg().getBody().setRecCnt(1);
file.isFile();
break;
}
}
}catch ( Exception e ){
if ( !e.getMessage().contains("No such file"))
throw e;
}
if ( isFileInTheServer ){
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
batchDoc.getBatchMsg().getHeader().setFileName(reqFileName);
LogUtil.setLogFileStart(batchDoc);
//FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + reqFileName, batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, reqFileName, batchDoc.getBatchMsg().getHeader().getFilePath(),
connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
//FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath + reqFileName, batchDoc.getBatchMsg().getHeader().getFilePath(),
// connTimeout, setTimeout, false, bandWidth, logger);
//batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + reqFileName;
File rcvRealFile = new File( recvFile );
File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) );
try {
File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) );
if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
//setFileHeaderAndTrailer(batchDoc, rcvRealFile);
rcvRealFile.renameTo(rcvArchFile);
rcvChkFile.createNewFile();
}else{
throw new Exception("파일수신에 실패하였습니다.");
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
} catch (Exception e) {
throw e;
}
}
} 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 {
this.disconnect();
}
logger.info("[FTPKS] ■ VAN사 → FEP 파일 수신 완료.");
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-234
View File
@@ -1,234 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.ftp.FTPUtil;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
// 여신 메타 자료 수신 ( SFTP )
// IP : 10.0.249.68 PORT : 22
// ID : kjbankftp PWD: !@$#kjbank@mcgFTP
// 수신:
// 파일명 META_YYYYMMDDHH.jar
// TEST / PROD 별도 서버 구성
// 접속후 send 폴더에 파일이 존재 함.
// 파일 수신 후 send/send.done 폴더 아래로 파일 이동 바람.
public class FTPMC extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
private static final String REMOTE_PATH = "remote.path";
private static final String REMOTE_BACKUP_PATH = "remote.backup.path";
public void sendFile(BatchDoc batchDoc) throws Exception {
throw new Exception("해당 Component 에 의한 FTP 송신이 구현되지 않았습니다.");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPMC] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//2. System FTP Shell 명령어를 Runtime 으로 실행
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH);
String remote_backup_Path = pmanager.getProperties(propName).getProperty(REMOTE_BACKUP_PATH);
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
//20220712
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10");
int connTimeout = Integer.parseInt(connTimeoutStr);
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10");
int setTimeout = Integer.parseInt(setTimeoutStr);
String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
logger.debug( "[FTPMC]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String baseDate = DatetimeUtil.getCurrentDate();
if ( reqFileName != null && reqFileName.length() > 8 ){
if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){
baseDate = reqFileName.substring(reqFileName.length() - 8 );
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
}
}
reqFileName = batchDoc.getBatchMsg().getHeader().getBizCode() + "_" + baseDate;
logger.debug( "[FTPMC]reqFileName:" + reqFileName );
try {
FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
for ( int inx = 0 ; inx < list.length; inx++){
FTPFile file = list[inx];
if ( file.getName().startsWith(reqFileName) ){
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);
//FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(),
connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
//batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName();
File rcvRealFile = new File( recvFile );
File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) );
try {
File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) );
if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
//setFileHeaderAndTrailer(batchDoc, rcvRealFile);
rcvRealFile.renameTo(rcvArchFile);
rcvChkFile.createNewFile();
}else{
throw new Exception("파일수신에 실패하였습니다.");
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
} catch (Exception e) {
throw e;
}
try {
FTPUtil.rename(ipaddress, port, userid, passwd,remotePath + file.getName(), remotePath +remote_backup_Path +"/" + file.getName(), true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
} catch (Exception e){
throw new Exception("파일수신후 백업디렉토리로 RENAME 실패하였습니다.");
}
}
}
}catch ( Exception e ){
if ( !e.getMessage().contains("No such file"))
throw e;
}
} 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 {
this.disconnect();
}
logger.info("[FTPMC] ■ VAN사 → FEP 파일 수신 완료.");
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-322
View File
@@ -1,322 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
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.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.ftp.FTPUtil;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
// NICE CB 자료 송수신 ( SFTP )
// IP : 10.94.50.207 PORT : 22
// ID : kjb01 PWD: kjb1111
// 파일명
// 송신:
// F13_MXALINF 90 당행CB정보송신
// F13_CSALINB 90 당행CB정보송신
// 1A9_REWOINF 90 당행조기경보회원등록(부동산)
// 수신:
// NICE_MXALINF_F13 Y 90 나이스CB정보수신
// NICE_CSALINB_F13 Y 90 나이스CB정보수신
// NICE_MXALINF_F13_CARD N 90 나이스CB정보수신
// NICE_REWORLT_1A9 N 90 나이스부동산권리정보(정상분)
// NICE_REWOERR_1A9 N 90 나이스부동산권리정보(오류분)
// NICE_EWRECHG_1A9 N 90 나이스부동산권리정보(변경분)
// TEST / PROD 구분이 없음, TEST파일의 경우 파일명 어딘가에 TEST라는 표시가 있으면 됨.
// 김효희 과장. 02-2122-4033
public class FTPNC extends Transfer implements SocketService{
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
private static final String REMOTE_PATH = "remote.path";
private static final String POSTFIX = "post.fix";
public void sendFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPNC] ■ FEP → 대외기관파일 송신 시작...... [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//Shell 명령어를 Runtime 으로 실행
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH);
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH);
}
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
//20220712
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10");
int connTimeout = Integer.parseInt(connTimeoutStr);
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10");
int setTimeout = Integer.parseInt(setTimeoutStr);
String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + batchDoc.getBatchMsg().getHeader().getRenamedFileName();
//String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName();
String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName();
setFileHeaderAndTrailer(batchDoc, new File(sendFileName));
//나이스 테스트 파일명 "TEST_" 운영path는 반드시 "/"로 끝나야 한다.
String fullPath = remotePath+remoteFileName;
String [] arr = fullPath.split("/");
remoteFileName = arr[arr.length-1];
remotePath = fullPath.replace(remoteFileName, "");
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileStart(batchDoc);
//FTPUtil.store(ipaddress, port, userid, passwd, remoteFileName, sendFileName, true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
FTPUtil.store(batchDoc, ipaddress, port, userid, passwd, remotePath, remoteFileName, sendFileName,
connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
//FTPUtil.store(batchDoc, ipaddress, port, userid, passwd, remoteFileName, sendFileName,
// connTimeout, setTimeout, false, bandWidth, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
logger.debug("guid ["+batchDoc.getBatchMsg().getHeader().getUUID()+"]"+"FTPUtil.store finish<<<<<<<<<<<<<<<<<<<<<<<");
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);
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setErrorLog(batchDoc, ex.getMessage());
logger.error( errMsg, ex );
throw ex;
} finally {
BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID());
this.disconnect();
}
logger.info("[FTPNC] ■ FEP → 대외기관 파일 송신 완료. [" + batchDoc.getBatchMsg().getHeader().getUUID()+ "]");
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger.info("[FTPNC] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
//2. System FTP Shell 명령어를 Runtime 으로 실행
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();
String propName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
String jobName = PROP_GROUP_NAME_PREFIX + "{" +
batchDoc.getBatchMsg().getHeader().getBizCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
PropManager pmanager = PropManager.getInstance();
String remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH);
String postfix = null;
try{
postfix = pmanager.getProperties(jobName).getProperty(POSTFIX);
}catch( Exception e ){}
if ( remotePath == null ){
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String authType = pmanager.getProperties(propName).getProperty(AUTH_TYPE);
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_ID; // id
}
//20220712
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "10");
int connTimeout = Integer.parseInt(connTimeoutStr);
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "10");
int setTimeout = Integer.parseInt(setTimeoutStr);
String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
logger.debug( "[FTPNC]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String baseDate = DatetimeUtil.getCurrentDate();
if ( reqFileName != null && reqFileName.length() > 8 ){
if ( DatetimeUtil.isRightDate(reqFileName.substring(reqFileName.length() - 8 )) ){
baseDate = reqFileName.substring(reqFileName.length() - 8 );
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
}
}
reqFileName = "NICE_" + batchDoc.getBatchMsg().getHeader().getBizCode() + "." + baseDate.substring(2);
if ( postfix != null && !!postfix.equals("")){
reqFileName = reqFileName + postfix;
}
logger.debug( "[FTPNC]reqFileName:" + reqFileName );
try {
FTPFile[] list = FTPUtil.listFiles(ipaddress, port, userid, passwd, remotePath, null, true, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
for ( int inx = 0 ; inx < list.length; inx++){
FTPFile file = list[inx];
if ( file.getName().equals(reqFileName) ){
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);
//FTPUtil.retrieve(ipaddress, port, userid, passwd, remotePath + "/" + file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), true, batchDoc.getLogger(ElinkLogger.LOGGER_ADAPTER));
FTPUtil.retrieve(batchDoc, ipaddress, port, userid, passwd, remotePath, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(),
connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), authType);
//batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName();
File rcvRealFile = new File( recvFile );
File rcvChkFile = new File( StringUtil.realToRootDir(recvFile) );
try {
File rcvArchFile = new File( StringUtil.realToArchDir(recvFile) );
if (rcvRealFile.exists() && rcvRealFile.length() == batchDoc.getBatchMsg().getHeader().getFileSize() ) {
//setFileHeaderAndTrailer(batchDoc, rcvRealFile);
rcvRealFile.renameTo(rcvArchFile);
rcvChkFile.createNewFile();
}else{
throw new Exception("파일수신에 실패하였습니다.");
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
} catch (Exception e) {
throw e;
}
}
}
}catch ( Exception e ){
if ( !e.getMessage().contains("No such file"))
throw e;
}
} 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 {
this.disconnect();
}
logger.info("[FTPNC] ■ VAN사 → FEP 파일 수신 완료.");
}
@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 firstActivity;
}
@Override
public long getLastActivity() {
return lastActivity;
}
}
-766
View File
@@ -1,766 +0,0 @@
package com.eactive.eai.adapter.ftp;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.nio.file.Files;
import java.util.Properties;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.util.Timeout;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.core5.http.ContentType;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.impl.matchers.GroupMatcher;
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.agent.web.FepFileSupport;
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.doc.Header;
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.property.PropManager;
import com.eactive.eai.common.scheduler.Scheduler;
import com.eactive.eai.common.scheduler.SchedulerKeys;
import com.eactive.eai.common.scheduler.SchedulerManager;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
/**
* 차세대 지방세입 자동이체를 지원한다.
*
* 1. SFTPClient를 하나 만들어서 사용한다.
* 2. 전송할 파일이 검사한 후 계속 전송한다.(send.max.iteration 기관 프로퍼티: 없으면 하나만 전송)
*
*/
public class FTPNT extends Transfer implements SocketService {
/** 송신 폴더 */
private static final String SEND_REMOTE_PATH = "send.remote.path";
/** 수신 폴더 */
private static final String RECV_REMOTE_PATH = "recv.remote.path";
// 송신완료파일 생성관련 프로퍼티
private static final String SEND_COMPLETE_CREATE_YN = "send.complete.create.yn";
private static final String SEND_COMPLETE_FILE_EXT = "send.complete.file.ext";
/** 인증 방법 1 = id, 2 = key 방식 */
private static final String AUTH_TYPE = "sftp.auth.type";
/** 큐에서 가져오는 최대 갯수. 없으면 하나만 전송 */
private static final String SEND_MAX_ITERATION = "send.max.iteration";
public final static String PHASECODE_NORMAL_END = "END";
/** 송신 완료 전송 */
private static final String SEND_NOTIFY_YN = "send.notify.yn";
/** 송신 완료을 알릴 송신 파일 이름 Regular Expression */
private static final String SEND_NOTIFY_FILENAME_PATTERN = "send.notify.filename.pattern";
/** , 로 구분한 송신 완료 전송 URL */
private static final String SEND_NOTITY_URLS = "send.notify.urls";
private static final String SEND_NOTITY_CONNECTION_TIMEOUT = "send.notify.connection.timeout";
private static final String SEND_NOTITY_READ_TIMEOUT = "send.notify.read.timeout";
/** 수신 완료 전송 여부 */
private static final String RECV_NOTIFY_YN = "recv.notify.yn";
/** 파일 수신 후 계정계로 파일 전송 Job 실행 */
private static final String RECV_ROOT_JOB_NAME = "EF003";
@Override
public void sendFile(BatchDoc batchDoc) throws Exception {
ChannelSftp channelSftp = null;
Session session = null;
try {
logger = (com.eactive.eai.common.util.Logger) batchDoc.getLogger();
String propName = FtpSupport.getInstitutionPropertyName(batchDoc);
Properties institutionProperties = PropManager.getInstance().getProperties(propName);
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 = institutionProperties.getProperty(AUTH_TYPE, AUTH_TYPE_ID);
// 설정이 없으면 기존 처럼 한 번만 돈다.
int iteration = FtpSupport.getIntProperty(institutionProperties, SEND_MAX_ITERATION, 1, (Logger) logger);
int connTimeout = FtpSupport.getIntProperty(institutionProperties, CONNECTION_TIMEOUT, 10, (Logger) logger);
int setTimeout = FtpSupport.getIntProperty(institutionProperties, READ_TIMEOUT, 10, (Logger) logger);
String bandWidthLimit = institutionProperties.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) logger);
internalSendFile(session, batchDoc, bandWidth, (Logger) 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("[FTPNT] ■ 대외기관→FEP 파일 송신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
// 전송 성공 여부
boolean result = false;
// 계정계 통보
String notifyCBSFilename = null;
String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String sendNotifyYn = "N";
try {
String propName = FtpSupport.getInstitutionPropertyName(batchDoc);
Properties institutionProperties = PropManager.getInstance().getProperties(propName);
String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName();
String hdrfileName = hdrInfo.substring(19, hdrInfo.length() - 2).trim();
String remotePath = null;
if (hdrfileName.contains("/")) {
int position = hdrfileName.lastIndexOf("/");
remotePath = hdrfileName.substring(0, position);
remoteFileName = hdrfileName.substring(position + 1);
}
if (remotePath == null) {
remotePath = institutionProperties.getProperty(SEND_REMOTE_PATH);
}
if (remotePath == null) {
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + SEND_REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String sendCompleteCreateYn = institutionProperties.getProperty(SEND_COMPLETE_CREATE_YN, "n");
String sendCompleteFileExt = "";
if (!sendCompleteCreateYn.equalsIgnoreCase("y") ) {
sendCompleteCreateYn = "n";
}
else {
sendCompleteCreateYn = "y";
sendCompleteFileExt = institutionProperties.getProperty(SEND_COMPLETE_FILE_EXT, "done");
}
notifyCBSFilename = institutionProperties.getProperty(SEND_NOTIFY_FILENAME_PATTERN);
sendNotifyYn = institutionProperties.getProperty(SEND_NOTIFY_YN, "N");
// 실제 파일이름
// String orgFileName = batchDoc.getBatchMsg().getHeader().getFileName();
// FEP 에서 Rename(송신Real->송신Arch)한 파일이름
String sendFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName();
logger.debug( "[FTPNT]sendFileName:" + remoteFileName);
logger.debug( "[FTPNT]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 + File.separator + sendFileName, bandWidthLimit, logger);
// 송신완료파일 생성 및 업로드
if ( sendCompleteCreateYn == "y" ) {
String completeFileName = remoteFileName + "." + sendCompleteFileExt;
File completeFile = new File(sendFilePath + File.separatorChar + completeFileName);
completeFile.createNewFile();
SFTPAdaptor.storeJSCH(batchDoc, channelSftp, remotePath, completeFileName, sendFilePath + File.separator + completeFileName, bandWidthLimit, logger);
Files.delete(completeFile.toPath());
}
} catch (Exception e) {
logger.error("[SFTP1]파일송신에 실패하였습니다.", e);
throw e;
} finally {
if (channelSftp != null) {
channelSftp.disconnect();
}
}
//File 종료시간 설정
setLastActivity();
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
result = true;
} 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 {
BatchRunningJobManager.getInstance().removeRunningJobInfo( batchDoc.getBatchMsg().getHeader().getUUID());
// SFTP는 실제 disconnect는 FTPUtil-SFTPAdaptor에서 하지만, 연결해제 로그를 찍어주기 위해 호출.
this.disconnect();
// 파일 이름 패턴이 통보하는 이름과 매칭되면
if ("y".equalsIgnoreCase(sendNotifyYn) && StringUtils.isNotBlank(notifyCBSFilename) && remoteFileName.matches(notifyCBSFilename)) {
sendResult("S", result, batchDoc, "", "", 1, remoteFileName);
}
}
logger.info("[FTPNT] ■ FEP → VAN사 파일 송신 완료.");
}
/**
* 송신 결과를 계정계로 알려준다.
*
* @param sendOrReceive 송수신 구분. S: 송신, R: 수신
* @param batchDoc
* @param remoteFileName
* @param result
*/
private void sendResult(String sendOrReceive, boolean resultCode, BatchDoc batchDoc, String listFileName, String listFileYn, int fileCount, String remoteFilename) {
logger = batchDoc.getLogger();
String propName = FtpSupport.getInstitutionPropertyName(batchDoc);
Properties institutionProperties = PropManager.getInstance().getProperties(propName);
String notifyUrls = institutionProperties.getProperty(SEND_NOTITY_URLS);
int connectionTimeout = FtpSupport.getIntProperty(institutionProperties, SEND_NOTITY_CONNECTION_TIMEOUT, 10, logger);
int readTimeout = FtpSupport.getIntProperty(institutionProperties, SEND_NOTITY_READ_TIMEOUT, 10, logger);
//PostMethod method = null;
if (StringUtils.isBlank(notifyUrls)) {
logger.error("notifyUrls is blank");
return;
}
notifyUrls = notifyUrls.trim();
String message = FepFileSupport.getNotifyMessage(sendOrReceive, resultCode, batchDoc, listFileName, listFileYn, fileCount, remoteFilename);
for (String notifyUrl : notifyUrls.split("\\s*,\\s*")) {
try {
HttpPost post = new HttpPost(notifyUrl);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(Timeout.ofSeconds(connectionTimeout))
.setResponseTimeout(Timeout.ofSeconds(readTimeout))
.build();
post.setConfig(requestConfig);
StringEntity entity = new StringEntity(
"msg=" + message,
ContentType.create("application/x-www-form-urlencoded", "EUC-KR")
);
post.setEntity(entity);
try (CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(post)) {
int status = response.getCode();
if (status != HttpStatus.SC_OK) {
logger.error("http status error {" + status + "}, url = {" + notifyUrl + "}");
}
// 응답 읽기
String responseMessage = EntityUtils.toString(response.getEntity(), "EUC-KR");
logger.info("Url {" + notifyUrl + "} response = {" + responseMessage + "}");
}
break;
} catch (Exception e) {
logger.error("url = {"+notifyUrl+"}, msg={"+message+"}");
logger.error(e.getLocalizedMessage(), e);
}
}
}
/**
* 수신 결과를 계정계로 알려준다.
* 수신 이벤트 job을 trigger한다.
*
* @param batchDoc
* @param remoteFileName
* @param result
* @throws SchedulerException
*/
private void sendReceiveResult(boolean resultCode, BatchDoc batchDoc, String listFileName, String listFileYn, int fileCount, String remoteFilename) throws SchedulerException {
logger = batchDoc.getLogger();
SchedulerManager schedulerManager = SchedulerManager.getInstance();
Scheduler scheduler = schedulerManager.getScheduler(SchedulerKeys.DEFAULT_SCHEDULER_ID);
org.quartz.Scheduler quartzScheduler = scheduler.getQuartzScheduler();
for (String groupName : quartzScheduler.getJobGroupNames()) {
// get jobkey
for (JobKey jobKey : quartzScheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
String jobName = jobKey.getName();
String jobGroup = jobKey.getGroup();
if (jobName.equals(RECV_ROOT_JOB_NAME)) {
logger.info("triggering jobName = {"+jobName+"}, jogGroup = {"+jobGroup+"}");
quartzScheduler.triggerJob(jobKey);
break;
}
}
}
sendResult("R", resultCode, batchDoc, listFileName, listFileYn, fileCount, remoteFilename);
}
public void recvFile(BatchDoc batchDoc) throws Exception {
logger = batchDoc.getLogger();
logger.info("[FTPNT] ■ 대외기관→FEP 파일 수신 시작...... ");
firstActivity = System.currentTimeMillis();
setLastActivity();
BatchRunningJobManager.getInstance().addRunningJobInfo(batchDoc.getBatchMsg().getHeader().getUUID(), this, batchDoc);
ChannelSftp channelSftp = null;
Session session = null;
String recvNotifyYn = "N";
int fileCount = 0;
boolean resultCode = false;
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();
String propName = FtpSupport.getInstitutionPropertyName(batchDoc);
Properties institutionProperties = PropManager.getInstance().getProperties(propName);
String hdrInfo = batchDoc.getBatchMsg().getHeader().getHdrInfoName();
String hdrFileName = hdrInfo.substring(19, hdrInfo.length() - 2).trim();
String remoteFileName = batchDoc.getBatchMsg().getHeader().getFileName();
String requestFileName = remoteFileName;
String remotePath = null;
if (hdrFileName.contains("/")) {
requestFileName = hdrFileName;
int position = hdrFileName.lastIndexOf("/");
remotePath = hdrFileName.substring(0, position);
remoteFileName = hdrFileName.substring(position + 1);
}
if (remotePath == null) {
remotePath = institutionProperties.getProperty(RECV_REMOTE_PATH);
}
if (remotePath == null) {
throw new Exception("해당 기관에 전송 경로가 지정되어 있지 않습니다. -propName:" + propName + "," + RECV_REMOTE_PATH);
}
if ( !remotePath.endsWith("/") )
remotePath = remotePath + "/";
String authType = institutionProperties.getProperty(AUTH_TYPE, AUTH_TYPE_ID);
recvNotifyYn = institutionProperties.getProperty(RECV_NOTIFY_YN, "N");
int connTimeout = FtpSupport.getIntProperty(institutionProperties, CONNECTION_TIMEOUT, 10, logger);
int setTimeout = FtpSupport.getIntProperty(institutionProperties, READ_TIMEOUT, 10, logger);
String bandWidthLimit = institutionProperties.getProperty(BADNWIDTH, "0");
bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replaceAll(",", "");
int bandWidth = Integer.parseInt(bandWidthLimit);
String listFileName = ""; // 수신한 LIST 파일:EBG00_EBGR_LISTTR 형식
String listFileYn = "N"; // LIST 파일 수신 여부
logger.debug( "[FTPNT]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
try {
session = SFTPAdaptor.getSessionJSCH(ipaddress, port, userid, passwd, authType, connTimeout, setTimeout, logger);
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
// 파일을 가져올지 디렉터리를 가져올지
boolean oneFile = false;
if (!FtpSupport.hasWildcard(remoteFileName)) {
SftpATTRS sa = SFTPAdaptor.lstatJSCH(channelSftp, remotePath, remoteFileName);
if (sa.isReg()) {
oneFile = true;
}
}
// 파일 하나만 수신한다.
if (oneFile) {
LogUtil.setLogFileStart(batchDoc);
batchDoc.getBatchMsg().getBody().setRecCnt(1);
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
batchDoc.getBatchMsg().getHeader().setFileName(remoteFileName);
SFTPAdaptor.cdJSCH(channelSftp, remotePath);
SFTPAdaptor.retrieveJSCH(batchDoc, channelSftp, remoteFileName, batchDoc.getBatchMsg().getHeader().getFilePath(), bandWidth, logger);
File file = new File(batchDoc.getBatchMsg().getHeader().getFilePath() + "/" + remoteFileName);
batchDoc.getBatchMsg().getHeader().setFileSize(file.length());
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + remoteFileName;
File rcvRealFile = new File( recvFile );
try {
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();
// LIST 파일이면 통보 내용으로 설정한다.
if (remoteFileName.toUpperCase().startsWith("LIST")) {
listFileYn = "Y";
Header header = batchDoc.getBatchMsg().getHeader();
listFileName = header.getProcessCode() + "_" + header.getInstitutionCode() + "_" + remoteFileName;
}
} else {
throw new Exception("[FTPNT]파일수신에 실패하였습니다.");
}
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
resultCode = true;
} catch (Exception e) {
throw e;
}
} else {
FTPFile[] list = SFTPAdaptor.lsJSCH(channelSftp, remotePath, remoteFileName, logger);
SFTPAdaptor.cdJSCH(channelSftp, remotePath);
for ( int inx = 0 ; inx < list.length; inx++ ){
//강제중지 설정시
if (batchDoc.isUserCancel()){
throw new Exception("사용자가 전송을 중지 했습니다.");
}
FTPFile file = list[inx];
if (!file.isFile()) {
continue;
}
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.retrieveJSCH(batchDoc, channelSftp, file.getName(), batchDoc.getBatchMsg().getHeader().getFilePath(), bandWidth, logger);
String recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + file.getName();
File rcvRealFile = new File( recvFile );
try {
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();
// LIST 파일이면 통보 내용으로 설정한다.
if (file.getName().toUpperCase().startsWith("LIST")) {
listFileYn = "Y";
Header header = batchDoc.getBatchMsg().getHeader();
listFileName = header.getProcessCode() + "_" + header.getInstitutionCode() + "_" + file.getName();
}
} else {
throw new Exception("[FTPNT]파일수신에 실패하였습니다.");
}
fileCount++;
//File 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLogFileEnd(batchDoc);
resultCode = true;
} catch (Exception e) {
throw e;
}
}
}
} catch ( Exception e ){
if ( !e.getMessage().contains("No such file") ) {
resultCode = false;
throw e;
}
} finally {
closeJsch(logger, session, channelSftp);
if ("y".equalsIgnoreCase(recvNotifyYn)) {
sendReceiveResult(resultCode, batchDoc, listFileName, listFileYn, fileCount, requestFileName);
}
}
} 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 {
batchDoc.setSftpChannel(null);
this.disconnect();
}
logger.info("[FTPNT] ■ VAN사 → FEP 파일 수신 완료.");
}
@Override
public void shutdown() {
// TODO Auto-generated method stub
}
@Override
public Socket getCurrentSocket() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean connect() {
// TODO Auto-generated method stub
return false;
}
@Override
public ConfigurationContext getContext() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setControl(Object control) {
// TODO Auto-generated method stub
}
@Override
public void notifyMessage() {
// TODO Auto-generated method stub
}
@Override
public boolean idle(long timeout) {
// TODO Auto-generated method stub
return false;
}
@Override
public int getCurrentState() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isConnected() throws IOException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isActive() {
// TODO Auto-generated method stub
return false;
}
@Override
public void checkActivity() {
// TODO Auto-generated method stub
}
@Override
public String getRemoteIPAddress() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setLastActivity() {
// TODO Auto-generated method stub
}
@Override
public long getFirstActivity() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getLastActivity() {
// TODO Auto-generated method stub
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);
}
}
}
}