init
This commit is contained in:
@@ -0,0 +1,223 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Vector;
|
||||
|
||||
import com.eactive.eai.common.dao.BaseDAO;
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.NullControl;
|
||||
|
||||
/**
|
||||
* 1. 기능 : 업무데이터로 부터 아래와 같은 특정 필드를 추출하기 위한 어댑터 정보 테이블에
|
||||
* 대한 Data Access Object 이다.
|
||||
* 2. 처리 개요 : 어댑터 정보 테이블에 대한 Create, Read, Update, Delete 를 처리한다.
|
||||
*
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : AdapterQuery.java
|
||||
* @since :
|
||||
*/
|
||||
public class AdapterDAO extends BaseDAO implements AdapterQuery
|
||||
{
|
||||
|
||||
/**
|
||||
* Default Logger
|
||||
*/
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 그룹 정보 전체를 메모리에 로딩하기 위해 테이블 전체 내용을 SELECT해서
|
||||
* AdapterGroupVO 객체 리스트로 생성 반환하는 메서드.
|
||||
* 2. 처리 개요 : 어댑터 그룹 정보 전체를 SELECT해서 한 레코드를 AdapterGroupVO로 생성 ArrayList에
|
||||
* 저장하여 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return ArrayList 어댑터 그룹 정보 전체데이터로 AdapterGroupVO Collection
|
||||
* @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 어댑터 그룹 정보를 가져오다 발생되는 모든 에러
|
||||
**/
|
||||
public ArrayList<AdapterGroupVO> getAllAdapterGroups() throws DAOException {
|
||||
ArrayList<AdapterGroupVO> al = new ArrayList<AdapterGroupVO>();
|
||||
ResultSet rs = null;
|
||||
AdapterGroupVO vo = null;
|
||||
try {
|
||||
this.connect(SELECT_ALL_GROUPS);
|
||||
//logger.debug("SELECT_ALL_GROUPS: "+ SELECT_ALL_GROUPS);
|
||||
|
||||
rs = this.executeQuery();
|
||||
while(rs.next()) {
|
||||
vo = new AdapterGroupVO();
|
||||
vo.setName (rs.getString(1));
|
||||
vo.setType (rs.getString(2));
|
||||
vo.setUsedFlag ("1".equals(rs.getString(3)));
|
||||
vo.setDescription (NullControl.trimSpace(rs.getString(4)));
|
||||
vo.setBatchProcessCode (rs.getString(5)); //TSEAIBJ06테이블 PK 값
|
||||
vo.setBatchInstitutionCode(rs.getString(6)); //TSEAIBJ06테이블 PK 값
|
||||
al.add(vo);
|
||||
}
|
||||
|
||||
return al;
|
||||
} catch(Exception e) {
|
||||
throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMAD001"));
|
||||
} finally {
|
||||
this.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보 전체를 메모리에 로딩하기 위해 테이블 전체 내용을 SELECT해서
|
||||
* AdapterGroupVO 객체 리스트로 생성 반환하는 메서드.
|
||||
* 2. 처리 개요 : 어댑터 정보 전체를 SELECT해서 한 레코드를 AdapterGroupVO로 생성 ArrayList에
|
||||
* 저장하여 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param adapterGroupName 어댑터 그룹 이름
|
||||
* @return ArrayList 어댑터 정보 전체데이터로 AdapterGroupVO Collection
|
||||
* @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 어댑터 정보를 가져오다 발생되는 모든 에러
|
||||
**/
|
||||
public ArrayList<AdapterVO> getAllAdapters(String adapterGroupName) throws DAOException {
|
||||
ArrayList<AdapterVO> al = new ArrayList<AdapterVO>();
|
||||
ResultSet rs = null;
|
||||
AdapterVO vo = null;
|
||||
try {
|
||||
this.connect(SELECT_ADAPTERS_BY_GROUP);
|
||||
//logger.debug("[AdapterDAO:getAllAdapters]SELECT_ADAPTERS_BY_GROUP: "+ SELECT_ADAPTERS_BY_GROUP);
|
||||
|
||||
this.preparedStatement.setString(1, adapterGroupName);
|
||||
logger.debug("바인드[1]: "+ adapterGroupName);
|
||||
|
||||
|
||||
|
||||
rs = this.executeQuery();
|
||||
while(rs.next()) {
|
||||
vo = new AdapterVO();
|
||||
vo.setAdapterGroupName (rs.getString("AdptrBzwkGroupName"));
|
||||
vo.setName (rs.getString("AdptrBzwkName"));
|
||||
vo.setListenerClass (NullControl.trimSpace(rs.getString("LstnerClsName")));
|
||||
vo.setPropGroupName (NullControl.trimSpace(rs.getString("PrptyGroupName")));
|
||||
vo.setDescription (NullControl.trimSpace(rs.getString("AdptrDesc")));
|
||||
vo.setBatchSystemConnCode (rs.getString("SysLnkgDstcd"));
|
||||
vo.setBatchProcessCode (rs.getString("BjobBzwkDstcd"));
|
||||
vo.setBatchInstitutionCode(rs.getString("OsidInstiDstcd"));
|
||||
vo.setBatchServerIP (rs.getString("LnkgIPInfoName"));
|
||||
vo.setBatchServerPortNo (rs.getString("LnkgPortInfoName"));
|
||||
vo.setBatchInterMsgTimeout(rs.getInt ("ToutVal"));
|
||||
vo.setBatchRcvFlowRuleCode(rs.getString("RecvPrcssRuleCd"));
|
||||
vo.setBatchInstitutionName(rs.getString("OsidInstiName"));
|
||||
vo.setLnkID(rs.getString ("LnkgID"));
|
||||
vo.setLnkPwd(rs.getString ("LnkgPwd"));
|
||||
vo.setPacketSize (rs.getInt("TelgmPcketSize"));
|
||||
vo.setRqstRspnsDstcd (rs.getString("RqstRspnsDstcd"));
|
||||
vo.setBatchProcessName (rs.getString("BjobBzwkName"));
|
||||
al.add(vo);
|
||||
}
|
||||
|
||||
return al;
|
||||
} catch(Exception e) {
|
||||
throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMAD002"));
|
||||
} finally {
|
||||
this.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 그룹 및 그룹에 속한 어댑터 정보 리스트에 대한 상세 조회를 하는
|
||||
* 메서드. by 전홍성
|
||||
* 2. 처리 개요 :
|
||||
*
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param adapterGroupName 어댑터 그룹 이름
|
||||
* @param serverName 서버 이름
|
||||
* @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 어댑터 그룹 정보를 가져오다 발생되는 모든 에러
|
||||
**/
|
||||
public AdapterGroupVO getAdapterGroup(String adapterGroupName) throws DAOException {
|
||||
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
this.connect(GET_ADAPTER_GROUP);
|
||||
this.preparedStatement.setString(1, adapterGroupName);
|
||||
rs = this.executeQuery();
|
||||
|
||||
if(!rs.next()) {
|
||||
String code = "BECEAIMAD008";
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = adapterGroupName;
|
||||
String errText = ExceptionUtil.make(code, msgArgs);
|
||||
if (logger.isError()) logger.error(errText);
|
||||
throw new DAOException(errText);
|
||||
}
|
||||
|
||||
AdapterGroupVO gvo = new AdapterGroupVO();
|
||||
gvo.setName(adapterGroupName);
|
||||
gvo.setType(rs.getString("AdptrCd"));
|
||||
try {
|
||||
gvo.setUsedFlag(rs.getString("AdptrUseYn").equals("1"));
|
||||
} catch(NullPointerException e) {}
|
||||
gvo.setDescription(NullControl.trimSpace(rs.getString("AdptrBzwkGroupDesc")));
|
||||
gvo.setBatchProcessCode(rs.getString("BjobBzwkDstcd"));
|
||||
gvo.setBatchInstitutionCode(rs.getString("OsidInstiDstcd"));
|
||||
|
||||
rs.close();
|
||||
|
||||
this.prepareStatement(GET_ADAPTERS);
|
||||
this.preparedStatement.setString(1,adapterGroupName);
|
||||
rs = this.executeQuery();
|
||||
|
||||
while(rs.next()) {
|
||||
AdapterVO vo = new AdapterVO();
|
||||
vo.setAdapterGroupName(adapterGroupName);
|
||||
vo.setName(rs.getString("AdptrBzwkName"));
|
||||
vo.setListenerClass(NullControl.trimSpace(rs.getString("LstnerClsName")));
|
||||
vo.setPropGroupName(NullControl.trimSpace(rs.getString("PrptyGroupName")));
|
||||
vo.setDescription(NullControl.trimSpace(rs.getString("AdptrDesc")));
|
||||
vo.setPropGroupDesc(NullControl.trimSpace(rs.getString("PrptyGroupDesc")));
|
||||
gvo.addAdapterVO(vo);
|
||||
}
|
||||
|
||||
|
||||
return gvo;
|
||||
} catch(Exception e) {
|
||||
throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMAD009"));
|
||||
} finally {
|
||||
this.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 그룹 정보 테이블 전체 내용을 SELECT해서
|
||||
* AdapterGroupVO 객체 Vector로 생성 반환하는 메서드.
|
||||
* 2. 처리 개요 : 어댑터 그룹 정보 전체를 SELECT해서 한 레코드를 AdapterGroupVO로 생성 Vector에
|
||||
* 저장하여 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return Vector 어댑터 그룹 정보 전체데이터로 AdapterGroupVO Collection
|
||||
* @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 어댑터 그룹 정보를 가져오다 발생되는 모든 에러
|
||||
**/
|
||||
public Vector<AdapterGroupVO> getAdptGroupNM() throws DAOException {
|
||||
Vector<AdapterGroupVO> all = new Vector<AdapterGroupVO>();
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
this.connect(SELECT_ADPT_GROUP_NAMES);
|
||||
rs = executeQuery();
|
||||
AdapterGroupVO vo = null;
|
||||
|
||||
while(rs.next()) {
|
||||
vo = new AdapterGroupVO();
|
||||
vo.setName(rs.getString(1));
|
||||
all.addElement(vo);
|
||||
}
|
||||
|
||||
} catch(Exception e) {
|
||||
throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMAD014"));
|
||||
} finally {
|
||||
this.disconnect();
|
||||
}
|
||||
|
||||
return all;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Vector;
|
||||
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.lifecycle.Lifecycle;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleException;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleListener;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleSupport;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 그룹 정보를 표현하는 Java Value Object 클래스.
|
||||
* 2. 처리 개요 : 어댑터 그룹 정보를 정의한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : 관련 기능을 참조
|
||||
* @since :
|
||||
*/
|
||||
public class AdapterGroupVO implements Serializable, Lifecycle
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Default Logger
|
||||
*/
|
||||
static Logger logger = (Logger) Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
private String name; //어뎁터업무그룹명[TSEAIAD01.AdptrBzwkGroupName]
|
||||
private String type; //어댑터코드[TSEAIAD01.AdptrCd]
|
||||
private boolean usedFlag; //어댑터사용여부[TSEAIAD01.AdptrUseYn]
|
||||
private String description; //어댑터업무그룹설명[TSEAIAD01.AdptrBzwkGroupDesc]
|
||||
private String batchProcessCode; //BATCH작업업무구분코드[TSEAIBJ06.BjobBzwkDstcd]
|
||||
private String batchInstitutionCode; //BATCH작업업무구분코드[TSEAIBJ06.OsidInstiDstCd]
|
||||
|
||||
/**
|
||||
* 어댑터 collection
|
||||
*/
|
||||
private HashMap<String,AdapterVO> adapters;
|
||||
|
||||
private Vector<AdapterVO> actives;
|
||||
// private Vector<AdapterVO> disables;
|
||||
|
||||
/**
|
||||
* 어댑터 이름 리스트
|
||||
*/
|
||||
private ArrayList<String> adapterNames;
|
||||
|
||||
/**
|
||||
* index
|
||||
*/
|
||||
private int idx;
|
||||
|
||||
/**
|
||||
* 기동 여부
|
||||
*/
|
||||
private boolean started;
|
||||
/**
|
||||
* LifecycleSupport instance
|
||||
*/
|
||||
private LifecycleSupport lifecycle = new LifecycleSupport(this);
|
||||
|
||||
/**
|
||||
* current transaction
|
||||
*/
|
||||
private int currentTx;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Defualt Constructor
|
||||
* 2. 처리 개요 :
|
||||
* -
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public AdapterGroupVO() {
|
||||
this("");
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 그룹명을 초기화하는 생성자 함수
|
||||
* 2. 처리 개요 : 어댑터 그룹명을 초기화한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param name 어댑터 그룹명
|
||||
**/
|
||||
public AdapterGroupVO(String name) {
|
||||
this.name = name;
|
||||
this.adapters = new HashMap<String,AdapterVO>();
|
||||
this.actives = new Vector<AdapterVO>();
|
||||
// this.disables = new Vector<AdapterVO>();
|
||||
this.adapterNames = new ArrayList<String>();
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
public void setUsedFlag(boolean usedFlag) {
|
||||
this.usedFlag = usedFlag;
|
||||
}
|
||||
|
||||
public boolean isUsedFlag() {
|
||||
return this.usedFlag;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return this.description;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보를 추가하는 메서드
|
||||
* 2. 처리 개요 : 어댑터 정보를 추가 한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param avo AdapterVO 객체
|
||||
*
|
||||
**/
|
||||
public void addAdapterVO(AdapterVO avo) {
|
||||
this.adapters.put(avo.getName(),avo);
|
||||
this.adapterNames.add(avo.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보를 반환하는 메서드
|
||||
* 2. 처리 개요 : 어댑터 정보를 반환 한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return AdapterVO AdapterVO 객체
|
||||
*
|
||||
**/
|
||||
public AdapterVO getAdapterVO(String adapterName) {
|
||||
return (AdapterVO)adapters.get(adapterName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : currentTx를 증가시키는 메서드
|
||||
* 2. 처리 개요 : currentTx를 증가시킨다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public synchronized void increase() {
|
||||
++currentTx;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : currentTx를 감소시키는 메서드
|
||||
* 2. 처리 개요 : currentTx를 감소 시킨다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public synchronized void decrease() {
|
||||
--currentTx;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : currentTx getter 메서드
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return int currentTx
|
||||
**/
|
||||
public int currentTx() {
|
||||
return this.currentTx;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : Lifecycle의 start 메서드로 AdapterGroupVO 초기화하는 메서드
|
||||
* 2. 처리 개요 : AdapterVO를 초기화한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception LifecycleException 이미 시작되었거나, AdapterVO를 통해 Rule 정보를 가져오다 DAOExcepiton이 발생될 경우
|
||||
*
|
||||
**/
|
||||
public void start() throws LifecycleException {
|
||||
|
||||
if (started)
|
||||
throw new LifecycleException("BECEAIMAD030");
|
||||
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
|
||||
|
||||
if(!this.usedFlag){
|
||||
String code = "BECEAIMAD040";
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = name;
|
||||
String errText = ExceptionUtil.make(code, msgArgs);
|
||||
if (logger.isError()) logger.error(errText);
|
||||
throw new LifecycleException(errText);
|
||||
}
|
||||
|
||||
AdapterVO avo = null;
|
||||
Iterator<AdapterVO> it = adapters.values().iterator();
|
||||
while(it.hasNext()) {
|
||||
avo = it.next();
|
||||
if(avo instanceof Lifecycle) {
|
||||
try {
|
||||
LifecycleListener []listeners = this.lifecycle.findLifecycleListeners();
|
||||
if(listeners != null) {
|
||||
for(int j=0;j<listeners.length;j++) {
|
||||
avo.addLifecycleListener(listeners[j]);
|
||||
}
|
||||
}
|
||||
avo.setAdapterGroupVO(this);
|
||||
avo.start();
|
||||
active(avo);
|
||||
} catch(Exception e) {
|
||||
disable(avo);
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD031")); }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
started = true;
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : Lifecycle의 stop 메서드로 어댑터 정보를 clear 하는 메서드
|
||||
* 2. 처리 개요 : 멤버에 캐싱한 어댑터 정보를 clear한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception LifecycleException 이미 종료된 경우 발생
|
||||
**/
|
||||
public void stop() throws LifecycleException {
|
||||
// Validate and update our current component state
|
||||
if (!started)
|
||||
throw new LifecycleException("BECEAIMAD032");
|
||||
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
|
||||
|
||||
|
||||
AdapterVO avo = null;
|
||||
Iterator<AdapterVO> it = adapters.values().iterator();
|
||||
while(it.hasNext()) {
|
||||
avo = it.next();
|
||||
if(!avo.isStarted()) continue;
|
||||
if(avo instanceof Lifecycle) {
|
||||
try {
|
||||
avo.stop();
|
||||
} catch(Exception e) {
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD033"));
|
||||
}
|
||||
}
|
||||
}
|
||||
started = false;
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 초기화 여부를 반환하는 getter 메서드
|
||||
* 2. 처리 개요 : 초기화 여부를 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return 초기화 여부
|
||||
**/
|
||||
public boolean isStarted() {
|
||||
return this.started;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 해당 어댑터를 active 그룹으로 변경한다.
|
||||
* 2. 처리 개요 : 해당 어댑터를 disble 그룹에서 삭제하고, active 그룹에 추가한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param vo 상태변경할 어댑터
|
||||
*/
|
||||
public void active(AdapterVO vo) {
|
||||
// this.disables.remove(vo);
|
||||
if (!actives.contains(vo) && vo.isStatus()) {
|
||||
this.actives.add(vo);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 해당 어댑터를 disble 그룹으로 변경한다.
|
||||
* 2. 처리 개요 : 해당 어댑터를 active 그룹에서 삭제하고, disble 그룹에 추가한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param vo 상태변경할 어댑터
|
||||
*/
|
||||
public void disable(AdapterVO vo) {
|
||||
this.actives.remove(vo);
|
||||
// this.disables.add(vo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 그룹에 속한 가용한 어댑터가 있는지 여부를 반환하는 메서드
|
||||
* 2. 처리 개요 : Active 그룹에 속한 어댑터가 있으면 true, 그렇지 않으면 false를 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return 어댑터 그룹에 속한 가용한 어댑터가 있는지 여부
|
||||
*/
|
||||
public boolean isAlive() {
|
||||
if(this.actives.size()>0) return true;
|
||||
else return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 1. 기능 : LifecycleListener를 등록하는 메서드
|
||||
* 2. 처리 개요 : LifecycleListener를 등록한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param listener LifecycleEvent를 수신한 LifecycleListener
|
||||
**/
|
||||
public void addLifecycleListener(LifecycleListener listener)
|
||||
{
|
||||
lifecycle.addLifecycleListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드
|
||||
* 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return 등록된 LifecycleListener 리스트
|
||||
**/
|
||||
public LifecycleListener[] findLifecycleListeners()
|
||||
{
|
||||
return lifecycle.findLifecycleListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드
|
||||
* 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param listener 삭제할 LifecycleListener
|
||||
**/
|
||||
public void removeLifecycleListener(LifecycleListener listener)
|
||||
{
|
||||
lifecycle.removeLifecycleListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보 Iteration 객체를 반환
|
||||
* 2. 처리 개요 : 어댑터 정보 Iteration 객체를 반환 한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return Iterator 어댑터 정보 Iteration 객체
|
||||
**/
|
||||
public Iterator<AdapterVO> getAdapters() {
|
||||
return this.adapters.values().iterator();
|
||||
}
|
||||
|
||||
public HashMap<String,AdapterVO> getAllAdapters() {
|
||||
return this.adapters;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터명 array를 반환
|
||||
* 2. 처리 개요 : 어댑터명 array를 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return String[] 어댑터명 array
|
||||
**/
|
||||
public String[] getAdapterNames() {
|
||||
String[] names = new String[this.adapterNames.size()];
|
||||
for(int i=0;i<names.length;i++) {
|
||||
names[i] = (String)this.adapterNames.get(i);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 다음 인덱스의 어댑터 정보를 반환
|
||||
* 2. 처리 개요 : 다음 인덱스의 어댑터 정보를 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return AdapterVO 어댑터 정보
|
||||
**/
|
||||
public synchronized AdapterVO nextAdapterVO() {
|
||||
if(this.actives.size()==0) return null;
|
||||
try {
|
||||
if(idx>=this.actives.size()) idx=0;
|
||||
AdapterVO vo = this.actives.get(idx++);
|
||||
return vo;
|
||||
} catch(Exception e) {
|
||||
if(this.actives.size()==0) return null;
|
||||
idx = 0;
|
||||
return this.actives.get(idx++);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보를 삭제하는 메서드
|
||||
* 2. 처리 개요 : 어댑터 정보를 삭제 한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param name 어댑터그룹명
|
||||
**/
|
||||
public void removeAdapterVO(String name){
|
||||
adapters.remove(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보를 String 형태로 반환하는 메서드
|
||||
* 2. 처리 개요 : String 형태로 어댑터 정보를 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return String 어댑터 정보
|
||||
**/
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append("\nAdapterGroupVO [ name=").append(name);
|
||||
sb.append(", type=").append(type);
|
||||
sb.append(", usedFlag=").append(usedFlag);
|
||||
sb.append(", description=").append(description);
|
||||
sb.append(", batchProcessCode=").append(batchProcessCode);
|
||||
sb.append(", batchInstitutionCode=").append(batchInstitutionCode);
|
||||
sb.append(", AdapterList=").append(adapters);
|
||||
sb.append(" ]");
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void setBatchProcessCode(String batchProcessCode) {
|
||||
this.batchProcessCode = batchProcessCode;
|
||||
}
|
||||
|
||||
public String getBatchProcessCode() {
|
||||
return this.batchProcessCode;
|
||||
}
|
||||
|
||||
public void setBatchInstitutionCode(String batchInstitutionCode) {
|
||||
this.batchInstitutionCode = batchInstitutionCode;
|
||||
}
|
||||
|
||||
public String getBatchInstitutionCode() {
|
||||
return this.batchInstitutionCode;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.dao.DAOFactory;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.lifecycle.Lifecycle;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleException;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleListener;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleSupport;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보를 DB로 부터 로딩해 메모리에 관리하는 Manager 클래스
|
||||
* 2. 처리 개요 : 어댑터 정보에 저장된 정보를 메모리에 로딩 관리한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : Lifecycle
|
||||
* @since :
|
||||
*/
|
||||
public class AdapterManager implements Lifecycle
|
||||
{
|
||||
/**
|
||||
* Default Logger
|
||||
*/
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
/**
|
||||
* AdapterManager Single Instance
|
||||
*/
|
||||
private static AdapterManager instance = new AdapterManager();
|
||||
/**
|
||||
* 기동 여부
|
||||
*/
|
||||
private boolean started;
|
||||
/**
|
||||
* 어댑터 정보를 저장하는 collection
|
||||
*/
|
||||
private HashMap<String, AdapterGroupVO> adapterGroups = new HashMap<String, AdapterGroupVO>();
|
||||
/**
|
||||
* LifeccyleSupport object
|
||||
*/
|
||||
private LifecycleSupport lifecycle = new LifecycleSupport(this);
|
||||
|
||||
/**
|
||||
* 1. 기능 : Default Constructor
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
private AdapterManager() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : AdapterManager Singleton Object를 반환하는 getter method
|
||||
* 2. 처리 개요 : AdapterManager Singleton Object를 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return AdapterManager Singleton object
|
||||
**/
|
||||
public static AdapterManager getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : Lifecycle의 start 메서드로 AdapterManager를 초기화하는 메서드
|
||||
* 2. 처리 개요 : AdapterDAO를 이용해 추출 Rule 정보 모두를 가져와 초기화한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception LifecycleException 이미 시작되었거나, AdapterDAO를 통해 Rule 정보를 가져오다 DAOExcepiton이 발생될 경우
|
||||
*
|
||||
**/
|
||||
public void start() throws LifecycleException {
|
||||
if (started)
|
||||
throw new LifecycleException("BECEAIMAD015");
|
||||
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
|
||||
|
||||
this.adapterGroups.clear();
|
||||
|
||||
ArrayList<AdapterGroupVO> groups = null;
|
||||
AdapterDAO dao = null;
|
||||
try {
|
||||
dao = (AdapterDAO)DAOFactory.newInstance().create(AdapterDAO.class);
|
||||
groups = dao.getAllAdapterGroups();
|
||||
|
||||
} catch(DAOException e) {
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD016"));
|
||||
}
|
||||
|
||||
AdapterGroupVO gvo = null;
|
||||
//AdapterVO avo = null;
|
||||
for(int i=0;i<groups.size();i++) {
|
||||
gvo = (AdapterGroupVO)groups.get(i);
|
||||
ArrayList<AdapterVO> all = null;
|
||||
try {
|
||||
all = dao.getAllAdapters(gvo.getName());
|
||||
for(int j=0;j<all.size();j++) {
|
||||
AdapterVO vo = all.get(j);
|
||||
gvo.addAdapterVO(vo);
|
||||
}
|
||||
} catch(DAOException e) {
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD017"));
|
||||
}
|
||||
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = gvo.toString();
|
||||
if (logger.isDebugEnabled()) logger.debug(ExceptionUtil.make("BDCEAIMAD018", msgArgs));
|
||||
addAdapterGroupVO(gvo);
|
||||
|
||||
|
||||
|
||||
if(gvo instanceof Lifecycle) {
|
||||
try {
|
||||
LifecycleListener listeners[] = this.lifecycle.findLifecycleListeners();
|
||||
if(listeners!=null) {
|
||||
for(int j=0;j<listeners.length;j++) {
|
||||
gvo.addLifecycleListener(listeners[j]);
|
||||
}
|
||||
}
|
||||
|
||||
if(!gvo.isUsedFlag()) {
|
||||
if (logger.isDebugEnabled()) logger.debug("Not Used Adapter>> "+gvo);
|
||||
continue;
|
||||
}
|
||||
gvo.start();
|
||||
} catch(Exception e) {
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD019"));
|
||||
}
|
||||
}
|
||||
}
|
||||
started = true;
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : Lifecycle의 stop 메서드로 AdapterManager를 종료하는 메서드
|
||||
* 2. 처리 개요 : 멤버에 캐싱한 어댑터 정보를 clear한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception LifecycleException 이미 종료된 경우 발생
|
||||
**/
|
||||
public void stop() throws LifecycleException {
|
||||
// Validate and update our current component state
|
||||
if (!started)
|
||||
throw new LifecycleException("BECEAIMAD020");
|
||||
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
|
||||
|
||||
for(Iterator<AdapterGroupVO> it = this.adapterGroups.values().iterator();it.hasNext();) {
|
||||
AdapterGroupVO vo = it.next();
|
||||
try {
|
||||
if(!vo.isStarted()) continue;
|
||||
if(vo instanceof Lifecycle) {
|
||||
vo.stop();
|
||||
}
|
||||
} catch(LifecycleException e) {
|
||||
String msgArgs[] = new String[1];
|
||||
msgArgs[0] = vo.toString();
|
||||
String errText = ExceptionUtil.make("BECEAIMAD021", msgArgs);
|
||||
if (logger.isError()) logger.error(errText);
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, errText));
|
||||
}
|
||||
}
|
||||
|
||||
started = false;
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : AdapterManager의 초기화 여부를 반환하는 getter 메서드
|
||||
* 2. 처리 개요 : AdapterManager의 초기화 여부를 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return 초기화 여부
|
||||
**/
|
||||
public boolean isStarted() {
|
||||
return this.started;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : LifecycleListener를 등록하는 메서드
|
||||
* 2. 처리 개요 : LifecycleListener를 등록한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param listener LifecycleEvent를 수신한 LifecycleListener
|
||||
**/
|
||||
public void addLifecycleListener(LifecycleListener listener)
|
||||
{
|
||||
lifecycle.addLifecycleListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드
|
||||
* 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return 등록된 LifecycleListener 리스트
|
||||
**/
|
||||
public LifecycleListener[] findLifecycleListeners()
|
||||
{
|
||||
return lifecycle.findLifecycleListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드
|
||||
* 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param listener 삭제할 LifecycleListener
|
||||
**/
|
||||
public void removeLifecycleListener(LifecycleListener listener)
|
||||
{
|
||||
lifecycle.removeLifecycleListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보를 찾아 반환하는 메서드
|
||||
* 2. 처리 개요 : 어댑터 정보를 찾아 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param adapterGroupName 어댑터그룹명
|
||||
* @param adapterName 어댑터명
|
||||
* @return 어댑터 정보 VO 객체
|
||||
**/
|
||||
public AdapterVO getAdapterVO(String adapterGroupName, String adapterName) {
|
||||
AdapterGroupVO gvo = (AdapterGroupVO)adapterGroups.get(adapterGroupName);
|
||||
if(gvo==null) return null;
|
||||
|
||||
return (AdapterVO)gvo.getAdapterVO(adapterName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 그룹 정보를 찾아 반환하는 메서드
|
||||
* 2. 처리 개요 : 어댑터 그룹 정보를 찾아 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param adapterGroupName 어댑터그룹명
|
||||
* @return 어댑터 그룹 정보 VO 객체
|
||||
**/
|
||||
public AdapterGroupVO getAdapterGroupVO(String adapterGroupName) {
|
||||
return (AdapterGroupVO)adapterGroups.get(adapterGroupName);
|
||||
}
|
||||
|
||||
public AdapterGroupVO getAdapterGroupInDB(String adapterGroupName) {
|
||||
try {
|
||||
AdapterDAO dao = (AdapterDAO)DAOFactory.newInstance().create(AdapterDAO.class);
|
||||
AdapterGroupVO vo = dao.getAdapterGroup(adapterGroupName);
|
||||
ArrayList<AdapterVO> all = null;
|
||||
|
||||
all = dao.getAllAdapters(adapterGroupName);
|
||||
for(int j=0;j<all.size();j++) {
|
||||
AdapterVO avo = all.get(j);
|
||||
vo.addAdapterVO(avo);
|
||||
}
|
||||
|
||||
return vo;
|
||||
|
||||
} catch(DAOException e) {
|
||||
logger.error( e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 그룹 정보를 추가하는 메서드
|
||||
* 2. 처리 개요 : 어댑터 그룹 정보를 추가한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param vo 어댑터그룹 VO
|
||||
**/
|
||||
public void addAdapterGroupVO(AdapterGroupVO vo) {
|
||||
if(vo!=null)
|
||||
adapterGroups.put(vo.getName(),vo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 모든 어댑터 그룹 정보를 찾아 반환하는 메서드
|
||||
* 2. 처리 개요 : 모든 어댑터 그룹 정보를 찾아 HashMap 객체로반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return 어댑터 그룹 정보 VO 객체 Collection
|
||||
**/
|
||||
public HashMap<String, AdapterGroupVO> getAllAdapterGroupVO() {
|
||||
return adapterGroups;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 모든 어댑터 그룹명을 찾아 반환하는 메서드
|
||||
* 2. 처리 개요 : 모든 어댑터 그룹명을 찾아 List 객체로 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return 어댑터 그룹명 리스트
|
||||
**/
|
||||
public List<String> getAllAdapterGroupNames() {
|
||||
ArrayList<String> al = new ArrayList<String>();
|
||||
Iterator<String> it = this.adapterGroups.keySet().iterator();
|
||||
while(it.hasNext()) {
|
||||
al.add(it.next());
|
||||
}
|
||||
Collections.sort(al);
|
||||
return al;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 그룹정보를 갱신하는 메서드
|
||||
* 2. 처리 개요 : 어댑터 그룹정보를 갱신한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param vo 어댑터 그룹 VO 객체
|
||||
**/
|
||||
//db update code 필요!!
|
||||
public void updateAdapterGroupVO(AdapterGroupVO vo) {
|
||||
if(vo!=null)
|
||||
adapterGroups.put(vo.getName(),vo);
|
||||
//db update code 넣을것..
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 그룹정보를 삭제하는 메서드
|
||||
* 2. 처리 개요 : 어댑터 그룹정보를 삭제한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param vo 어댑터 그룹명
|
||||
**/
|
||||
public void removeAdapterGroupVO(String name){
|
||||
adapterGroups.remove(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : debug String을 리턴하는 메서드
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public void print() {
|
||||
if (logger.isDebugEnabled()) logger.debug("AdapterManager] All Adapter List>> "+this.adapterGroups);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import com.eactive.eai.common.dao.BaseDAO;
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.NullControl;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 유형 별 프라퍼키 정보를 추출하기 위한 Data Access Object
|
||||
* 2. 처리 개요 : 어댑터유형, 어댑터프라퍼티정보 테이블에 대한 Create, Read, Update, Delete 를 처리한다.
|
||||
* * -
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : 관련 기능을 참조
|
||||
* @since :
|
||||
*/
|
||||
public class AdapterPropDAO extends BaseDAO implements AdapterPropQuery
|
||||
{
|
||||
/**
|
||||
* EAI FRAMEWORK DEFAULT FILE LOGGER
|
||||
*/
|
||||
//private static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_ADAPTER);
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 유형 별 모든 프라퍼티 정보 조회하여 AdapterTypeVO Collection으로 반환
|
||||
* 2. 처리 개요 : 어댑터 유형 별 모든 프라퍼티 정보를 SELECT해서 AdapterTypeVO로 생성 HashMap에
|
||||
* 저장하여 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return Returns AdapterTypeVO Collection
|
||||
* @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 어댑터 유형 별 모든 프라퍼티 정보를 가져오다 발생되는 모든 에러
|
||||
*/
|
||||
public HashMap<String, AdapterTypeVO> getAllAdapterPropInfo() throws DAOException {
|
||||
|
||||
HashMap<String, AdapterTypeVO> adptPropInfo = new HashMap<String, AdapterTypeVO>();
|
||||
ResultSet rs = null;
|
||||
|
||||
try {
|
||||
|
||||
this.connect(GET_ALL_ADPT_PROP_INFO);
|
||||
rs = executeQuery();
|
||||
|
||||
String current = null, previous = null;
|
||||
AdapterTypeVO adptTp = null;
|
||||
|
||||
while(rs.next()) {
|
||||
current = rs.getString(1);
|
||||
|
||||
if(!current.equals(previous)) {
|
||||
adptTp = new AdapterTypeVO(current, rs.getString(2));
|
||||
adptPropInfo.put(current, adptTp);
|
||||
previous = current;
|
||||
}
|
||||
|
||||
adptTp.addAdapterPropInfo(current, rs.getString(3), rs.getString(4), NullControl.trimSpace(rs.getString(5)));
|
||||
}
|
||||
|
||||
return adptPropInfo;
|
||||
} catch(Exception e) {
|
||||
throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMAD041"));
|
||||
} finally {
|
||||
this.disconnect();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 특정 어댑터 유형의 프라퍼티 정보 조회하여 AdapterTypeVO로 반환
|
||||
* 2. 처리 개요 : 특정 어댑터 유형의 프라퍼티 정보를 SELECT해서 AdapterTypeVO로 생성, 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return Returns AdapterTypeVO
|
||||
* @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 프라퍼티 정보를 가져오다 발생되는 모든 에러
|
||||
*/
|
||||
public AdapterTypeVO getAdapterPropInfo(String adptrCd) throws DAOException {
|
||||
|
||||
ResultSet rs = null;
|
||||
|
||||
try {
|
||||
|
||||
this.connect(GET_ADPT_PROP_INFO);
|
||||
this.preparedStatement.setString(1, adptrCd);
|
||||
rs = executeQuery();
|
||||
|
||||
String current = null, previous = null;
|
||||
AdapterTypeVO adptTp = null;
|
||||
|
||||
while(rs.next()) {
|
||||
current = rs.getString(1);
|
||||
|
||||
if(!current.equals(previous)) {
|
||||
adptTp = new AdapterTypeVO(current, rs.getString(2));
|
||||
previous = current;
|
||||
}
|
||||
|
||||
adptTp.addAdapterPropInfo(current, rs.getString(3), rs.getString(4), NullControl.trimSpace(rs.getString(5)));
|
||||
}
|
||||
|
||||
return adptTp;
|
||||
} catch(Exception e) {
|
||||
throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMAD042"));
|
||||
} finally {
|
||||
this.disconnect();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터유형 정보를 등록하는 메서드
|
||||
* 2. 처리 개요 : 어댑터유형 정보를 DB 테이블에 INSERT한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param adptrCd 어댑터코드
|
||||
* @param adptrName 어댑터명
|
||||
* @exception DAOException DB INSERT 시 발생하는 SQLException을 포함한 추출정보 저장시 발생되는 모든 에러
|
||||
*/
|
||||
public void addAdapterType(String adptrCd, String adptrName) throws DAOException {
|
||||
|
||||
try {
|
||||
this.connect(ADD_ADPT_TP);
|
||||
|
||||
this.preparedStatement.setString(1,adptrCd);
|
||||
this.preparedStatement.setString(2,adptrName);
|
||||
|
||||
executeUpdate();
|
||||
|
||||
} catch(Exception e) {
|
||||
throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMAD043"));
|
||||
} finally {
|
||||
this.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터프라퍼티정보를 등록하는 메서드
|
||||
* 2. 처리 개요 : 어댑터프라퍼티정보를 DB 테이블에 INSERT한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param adptrCd 어댑터코드
|
||||
* @param adptrIODstcd 어댑터입출력구분코드
|
||||
* @param adptrPrptyName 어댑터프라퍼티명
|
||||
* @param adptrPrptyDesc 어댑터프라퍼티설명
|
||||
* @exception DAOException DB INSERT 시 발생하는 SQLException을 포함한 추출정보 저장시 발생되는 모든 에러
|
||||
*/
|
||||
public void addAdapterPropInfo(String adptrCd, String adptrIODstcd, String adptrPrptyName, String adptrPrptyDesc)
|
||||
throws DAOException {
|
||||
|
||||
try {
|
||||
this.connect(ADD_ADPT_PROP_INFO);
|
||||
|
||||
this.preparedStatement.setString(1,adptrCd);
|
||||
this.preparedStatement.setString(2,adptrIODstcd);
|
||||
this.preparedStatement.setString(3,adptrPrptyName);
|
||||
this.preparedStatement.setString(4,NullControl.addSpace(adptrPrptyDesc));
|
||||
|
||||
executeUpdate();
|
||||
|
||||
} catch(Exception e) {
|
||||
throw new DAOException(ExceptionUtil.getErrorCode(e,"BECEAIMAD044"));
|
||||
} finally {
|
||||
this.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 프라퍼티 정보를 정의한 Java Value Object 클래스
|
||||
* 2. 처리 개요 : 어댑터 프라퍼티 정보를 정의한다.
|
||||
* * -
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : 관련 기능을 참조
|
||||
* @since :
|
||||
*/
|
||||
public class AdapterPropInfoVO implements Serializable
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
private String adptrCd; //어댑터코드[TSEAIAD04.AdptrCd]
|
||||
private String adptrIODstcd; //어댑터입출력구분코드[TSEAIAD04.AdptrIODstcd]
|
||||
private String adptrPrptyName; //어댑터프라퍼티명[TSEAIAD04.AdptrPrptyName]
|
||||
private String adptrPrptyDesc; //어댑터프라퍼티설명[TSEAIAD04.AdptrPrptyDesc]
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public AdapterPropInfoVO(String adptrCd, String adptrIODstcd, String adptrPrptyName, String adptrPrptyDesc) {
|
||||
this.adptrCd = adptrCd;
|
||||
this.adptrIODstcd = adptrIODstcd;
|
||||
this.adptrPrptyName = adptrPrptyName;
|
||||
this.adptrPrptyDesc = adptrPrptyDesc;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the adptrCd.
|
||||
*/
|
||||
public String getAdptrCd() {
|
||||
return adptrCd;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param adptrCd The adptrCd to set.
|
||||
*/
|
||||
public void setAdptrCd(String adptrCd) {
|
||||
this.adptrCd = adptrCd;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the adptrIODstcd.
|
||||
*/
|
||||
public String getAdptrIODstcd() {
|
||||
return adptrIODstcd;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param adptrIODstcd The adptrIODstcd to set.
|
||||
*/
|
||||
public void setAdptrIODstcd(String adptrIODstcd) {
|
||||
this.adptrIODstcd = adptrIODstcd;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the adptrPrptyDesc.
|
||||
*/
|
||||
public String getAdptrPrptyDesc() {
|
||||
return adptrPrptyDesc;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param adptrPrptyDesc The adptrPrptyDesc to set.
|
||||
*/
|
||||
public void setAdptrPrptyDesc(String adptrPrptyDesc) {
|
||||
this.adptrPrptyDesc = adptrPrptyDesc;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the adptrPrptyName.
|
||||
*/
|
||||
public String getAdptrPrptyName() {
|
||||
return adptrPrptyName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param adptrPrptyName The adptrPrptyName to set.
|
||||
*/
|
||||
public void setAdptrPrptyName(String adptrPrptyName) {
|
||||
this.adptrPrptyName = adptrPrptyName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import com.eactive.eai.common.dao.Keys;
|
||||
/**
|
||||
* 1. 기능 : AdapterPropDAO에서 사용하는 SQL Query문을 정의한 상수 인터페이스
|
||||
* 2. 처리 개요 : AdapterPropDAO에서 사용하는 SQL Query문을 상수로 정의한다.
|
||||
* * -
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : 관련 기능을 참조
|
||||
* @since :
|
||||
*/
|
||||
public interface AdapterPropQuery
|
||||
{
|
||||
/**
|
||||
* 어댑터 유형 별 모든 프라퍼티 정보 조회
|
||||
*/
|
||||
public static final String GET_ALL_ADPT_PROP_INFO =
|
||||
//AdptrCd, AdptrName
|
||||
//AdptrPrptyName, AdptrPrptyDesc, AdptrCd, AdptrIODstcd
|
||||
" SELECT a.AdptrCd, a.AdptrName, b.AdptrIODstcd, b.AdptrPrptyName, b.AdptrPrptyDesc \n"
|
||||
+ " FROM " + Keys.TABLE_OWNER + "TSEAIAD03 a, " + Keys.TABLE_OWNER + "TSEAIAD04 b \n"
|
||||
+ " WHERE a.AdptrCd = b.AdptrCd \n"
|
||||
+ " ORDER BY a.AdptrCd ";
|
||||
|
||||
/**
|
||||
* 특정 어댑터 유형에 해당하는 프라퍼티 정보 조회
|
||||
*/
|
||||
public static final String GET_ADPT_PROP_INFO =
|
||||
" SELECT a.AdptrCd, a.AdptrName, b.AdptrIODstcd, b.AdptrPrptyName, b.AdptrPrptyDesc \n"
|
||||
+ " FROM " + Keys.TABLE_OWNER + "TSEAIAD03 a, " + Keys.TABLE_OWNER + "TSEAIAD04 b \n"
|
||||
+ " WHERE a.AdptrCd = b.AdptrCd \n"
|
||||
+ " AND a.AdptrCd = ? ";
|
||||
|
||||
/**
|
||||
* 어댑터 유형 추가
|
||||
*/
|
||||
public static final String ADD_ADPT_TP =
|
||||
" INSERT INTO " + Keys.TABLE_OWNER + "TSEAIAD03 ( AdptrCd, AdptrName ) VALUES ( ?, ? ) ";
|
||||
|
||||
/**
|
||||
* 어댑터 프라퍼티 정보 추가
|
||||
*/
|
||||
public static final String ADD_ADPT_PROP_INFO =
|
||||
" INSERT INTO " + Keys.TABLE_OWNER + "TSEAIAD04 ( AdptrCd, AdptrIODstcd, AdptrPrptyName, AdptrPrptyDesc ) \n"
|
||||
+ " VALUES ( ?, ?, ?, ? ) ";
|
||||
|
||||
/**
|
||||
* 어댑터 유형 수정
|
||||
* 어댑터명만 수정 가능
|
||||
*/
|
||||
public static final String UPDATE_ADPT_TP =
|
||||
" UPDATE " + Keys.TABLE_OWNER + "TSEAIAD03 SET AdptrName = ? WHERE AdptrCd = ? ";
|
||||
|
||||
/**
|
||||
* 어댑터 프라퍼티 정보 수정
|
||||
*/
|
||||
public static final String UPDATE_ADPT_PROP_INFO =
|
||||
" UPDATE " + Keys.TABLE_OWNER + "TSEAIAD04 SET AdptrPrptyDesc = ? \n"
|
||||
+ " WHERE AdptrCd = ? AND AdptrIODstcd = ? AND AdptrPrptyName = ? ";
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import com.eactive.eai.common.dao.Keys;
|
||||
/**
|
||||
* 1. 기능 : AdapterDAO에서 사용하는 SQL Query문을 정의한 상수 인터페이스
|
||||
* 2. 처리 개요 : AdapterDAO에서 사용하는 SQL Query문을 상수로 정의한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : 관련 기능을 참조
|
||||
* @since :
|
||||
*/
|
||||
public interface AdapterQuery
|
||||
{
|
||||
|
||||
/**
|
||||
* 모든 어댑터그룹 정보를 SELECT하는 QUERY
|
||||
* 어댑터 사용여부 = '1'
|
||||
*/
|
||||
public static final String SELECT_ALL_GROUPS =
|
||||
"SELECT A.AdptrBzwkGroupName ,\n" +
|
||||
" A.AdptrCd ,\n" +
|
||||
" A.AdptrUseYn ,\n" +
|
||||
" A.AdptrBzwkGroupDesc ,\n" +
|
||||
" B.BjobBzwkDstcd ,\n" +
|
||||
" LTRIM(RTRIM(B.OsidInstiDstcd)) AS OsidInstiDstcd \n" +
|
||||
"FROM " + Keys.TABLE_OWNER + "TSEAIBA01 A, \n" +
|
||||
" " + Keys.TABLE_OWNER + "TSEAIBJ06 B \n" +
|
||||
"WHERE A.AdptrBzwkGroupName = B.AdptrBzwkGroupName \n" +
|
||||
"AND A.AdptrUseYn = '1' \n" +
|
||||
"AND B.ThisMsgUseYn = '1' ";
|
||||
|
||||
|
||||
/**
|
||||
* 어댑터그룹에 해당되는 어댑터 정보를 SELECT하는 QUERY
|
||||
*/
|
||||
public static final String SELECT_ADAPTERS_BY_GROUP =
|
||||
"SELECT A.AdptrBzwkGroupName ,\n" +
|
||||
" A.AdptrBzwkName ,\n" +
|
||||
" A.LstnerClsName ,\n" +
|
||||
" A.PrptyGroupName ,\n" +
|
||||
" A.AdptrDesc ,\n" +
|
||||
" B.SysLnkgDstcd ,\n" +
|
||||
" B.BjobBzwkDstcd ,\n" +
|
||||
" LTRIM(RTRIM(B.OsidInstiDstcd)) AS OsidInstiDstcd,\n" +
|
||||
" B.LnkgIPInfoName ,\n" +
|
||||
" B.LnkgPortInfoName ,\n" +
|
||||
" B.ToutVal ,\n" +
|
||||
" C.RecvPrcssRuleCd ,\n" +
|
||||
" C.OsidInstiName ,\n" +
|
||||
" B.LnkgID ,\n" +
|
||||
" B.LnkgPwd ,\n" +
|
||||
" C.TelgmPcketSize ,\n" +
|
||||
" B.RqstRspnsDstcd ,\n" +
|
||||
" D.BjobBzwkName \n" +
|
||||
"FROM " + Keys.TABLE_OWNER + "TSEAIBA02 A, \n" +
|
||||
" " + Keys.TABLE_OWNER + "TSEAIBJ05 B, \n" +
|
||||
" " + Keys.TABLE_OWNER + "TSEAIBJ06 C \n" +
|
||||
" LEFT OUTER JOIN " + Keys.TABLE_OWNER + "TSEAIBJ02 D \n" +
|
||||
" on C.BjobBzwkDstcd = D.BjobBzwkDstcd \n" +
|
||||
"WHERE A.AdptrBzwkGroupName = B.AdptrBzwkGroupName \n" +
|
||||
"AND A.AdptrBzwkName = B.AdptrBzwkName \n" +
|
||||
"AND B.BjobBzwkDstcd = C.BjobBzwkDstcd \n" +
|
||||
"AND LTRIM(RTRIM(B.OsidInstiDstcd)) = LTRIM(RTRIM( C.OsidInstiDstcd))\n" +
|
||||
"AND A.AdptrBzwkGroupName = ? \n" +
|
||||
"AND B.ThisMsgUseYn = '1' \n" +
|
||||
"AND B.RqstRspnsDstcd in ('A', 'C') \n" +
|
||||
"AND C.ThisMsgUseYn = '1' ";
|
||||
|
||||
/**
|
||||
* 어댑터 그룹 정보 상세조회
|
||||
*/
|
||||
public static final String GET_ADAPTER_GROUP =
|
||||
"SELECT A.AdptrBzwkGroupName ,\n" +
|
||||
" A.AdptrCd ,\n" +
|
||||
" A.AdptrUseYn ,\n" +
|
||||
" A.AdptrBzwkGroupDesc ,\n" +
|
||||
" B.BjobBzwkDstcd ,\n" +
|
||||
" LTRIM(RTRIM(B.OsidInstiDstcd)) AS OsidInstiDstcd \n" +
|
||||
"FROM " + Keys.TABLE_OWNER + "TSEAIBA01 A, \n" +
|
||||
" " + Keys.TABLE_OWNER + "TSEAIBJ06 B \n" +
|
||||
"WHERE A.AdptrBzwkGroupName = B.AdptrBzwkGroupName \n" +
|
||||
"AND A.AdptrBzwkGroupName = ? ";
|
||||
|
||||
|
||||
/**
|
||||
* 어댑터 정보 상세조회
|
||||
*/
|
||||
public static final String GET_ADAPTERS =
|
||||
"SELECT a.AdptrBzwkGroupName,\n"
|
||||
+ " a.AdptrBzwkName ,\n"
|
||||
+ " a.LstnerClsName ,\n"
|
||||
+ " a.PrptyGroupName ,\n"
|
||||
+ " a.AdptrDesc ,\n"
|
||||
+ " b.PrptyGroupDesc \n"
|
||||
+ "FROM " + Keys.TABLE_OWNER + "TSEAIBA02 a LEFT OUTER JOIN\n"
|
||||
+ Keys.TABLE_OWNER + "TSEAIBP01 b \n"
|
||||
+ " ON a.PrptyGroupName = b.PrptyGroupName \n"
|
||||
+ "WHERE a.AdptrBzwkGroupName = ? ";
|
||||
|
||||
/**
|
||||
* 어댑터 그룹명 조회
|
||||
*/
|
||||
public static final String SELECT_ADPT_GROUP_NAMES =
|
||||
"SELECT AdptrBzwkGroupName \n"
|
||||
+ "FROM " + Keys.TABLE_OWNER + "TSEAIBA01\n"
|
||||
+ "ORDER BY AdptrBzwkGroupName ";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터유형을 정의한 Java Value Object 클래스
|
||||
* 2. 처리 개요 : 어댑터유형을 정의한다.
|
||||
* * -
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : 관련 기능을 참조
|
||||
* @since :
|
||||
*/
|
||||
public class AdapterTypeVO implements Serializable
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
private String adptrCd;
|
||||
private String adptrName;
|
||||
|
||||
private ArrayList<AdapterPropInfoVO> propInfo;
|
||||
|
||||
public AdapterTypeVO() {
|
||||
this("", "");
|
||||
}
|
||||
|
||||
public AdapterTypeVO(String adptrCd, String adptrName) {
|
||||
this.adptrCd = adptrCd;
|
||||
this.adptrName = adptrName;
|
||||
this.propInfo = new ArrayList<AdapterPropInfoVO>();
|
||||
}
|
||||
|
||||
public String getAdptrCd() {
|
||||
return adptrCd;
|
||||
}
|
||||
|
||||
public void setAdptrCd(String adptrCd) {
|
||||
this.adptrCd = adptrCd;
|
||||
}
|
||||
|
||||
public String getAdptrName() {
|
||||
return adptrName;
|
||||
}
|
||||
|
||||
public void setAdptrName(String adptrName) {
|
||||
this.adptrName = adptrName;
|
||||
}
|
||||
|
||||
public ArrayList<AdapterPropInfoVO> getPropInfo() {
|
||||
return propInfo;
|
||||
}
|
||||
|
||||
public void setPropInfo(ArrayList<AdapterPropInfoVO> propInfo) {
|
||||
this.propInfo = propInfo;
|
||||
}
|
||||
|
||||
public void addAdapterPropInfo(String adptrCd, String adptrIODstcd, String adptrPrptyName, String adptrPrptyDesc) {
|
||||
AdapterPropInfoVO vo = new AdapterPropInfoVO(adptrCd, adptrIODstcd, adptrPrptyName, adptrPrptyDesc);
|
||||
this.propInfo.add(vo);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.eactive.eai.adapter.listener.AdapterException;
|
||||
import com.eactive.eai.adapter.listener.AdapterListener;
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.lifecycle.Lifecycle;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleException;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleListener;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleSupport;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보를 표현하는 Java Value Object 클래스.
|
||||
* 2. 처리 개요 : 어댑터 정보를 정의한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : Serializable, Lifecycle
|
||||
* @since :
|
||||
*/
|
||||
public class AdapterVO implements Serializable, Lifecycle
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Default Logger
|
||||
*/
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
private AdapterGroupVO adapterGroupVO; //어댑터 그룹
|
||||
|
||||
private String adapterGroupName; //어뎁터업무그룹명[TSEAIAD02.AdptrBzwkGroupName]
|
||||
private String name; //어뎁터업무명[TSEAIAD02.AdptrBzwkName]
|
||||
// private String eaiSevrInstncName; //서버인스탄스명[TSEAIAD02.EAISevrInstncName] - migration added.
|
||||
private String listenerClass; //리스너클래스명[TSEAIAD02.LstnerClsName]
|
||||
// private String testCallClass; //테스터클래스명[TSEAIAD02.TestClsName]
|
||||
private String propGroupName; //프라퍼티그룹명[TSEAIAD02.PrptyGroupName]
|
||||
private String description; //어댑터설명[TSEAIAD02.AdptrDesc]
|
||||
private String propGroupDesc; //프라퍼티그룹설명
|
||||
|
||||
private String batchSystemConnCode; //BATCH작업업무구분코드[TSEAIBJ05.SysLnkgDstCd] [JUNGFUX] 추가 2006/02/20
|
||||
private String batchProcessCode; //BATCH작업업무구분코드[TSEAIBJ05.BjobBzwkDstcd] [JUNGFUX] 추가 2006/02/20
|
||||
private String batchProcessName; //BATCH작업업무구분코드[TSEAIBJ05.BjobBzwkName] [JUNGFUX] 추가 2006/11/17
|
||||
private String batchInstitutionCode; //BATCH작업업무구분코드[TSEAIBJ05.OsidInstiDstCd] [JUNGFUX] 추가 2006/02/20
|
||||
private String batchServerIP; //BATCH작업업무구분코드[TSEAIBJ05.LnkgIPInfoName] [JUNGFUX] 추가 2006/02/20
|
||||
private String batchServerPortNo; //BATCH작업업무구분코드[TSEAIBJ05.LnkgPortInfoName] [JUNGFUX] 추가 2006/02/20
|
||||
private int batchInterMsgTimeout; //BATCH소켓서버전문간Timeout[TSEAIBJ05.ToutVal] [JUNGFUX] 추가 2006/02/20
|
||||
private String batchRcvFlowRuleCode; //BATCH수신처리규칙코드[TSEAIBJ02.SysLnkgPortNo] [JUNGFUX] 추가 2006/02/20
|
||||
//20060328 add by khs
|
||||
private String batchInstitutionName; // 대외기관 이름
|
||||
//20060329 add by khs
|
||||
private String lnkID;
|
||||
private String lnkPwd;
|
||||
//20060331 add by khs
|
||||
// private String batchInstitutionType; // 퇴직연금 전문조립에 사용되는 대외기관 구분 : 1, 2,3,4,5 등 가능
|
||||
//20060411 add by khs
|
||||
private int batchPacketSize;
|
||||
//20060425 add by khs
|
||||
private String rqstRspnsDstcd; // 응답수신('A'), 응답송신('C'), 요구('R') 구분
|
||||
|
||||
private ConfigurationContext context;
|
||||
|
||||
/**
|
||||
* 어댑터 상태
|
||||
*/
|
||||
private boolean status;
|
||||
|
||||
/**
|
||||
* AdapterListener instance
|
||||
*/
|
||||
transient private AdapterListener adapterListener;
|
||||
//private AdapterListener adapterListener;
|
||||
|
||||
|
||||
/**
|
||||
* 기동여부
|
||||
*/
|
||||
private boolean started;
|
||||
/**
|
||||
* LifecycleSupport instance
|
||||
*/
|
||||
private LifecycleSupport lifecycle = new LifecycleSupport(this);
|
||||
|
||||
/**
|
||||
* 1. 기능 : Defualt Constructor
|
||||
* 2. 처리 개요 :
|
||||
* -
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public AdapterVO() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터를 초기화하는 생성자 함수
|
||||
* 2. 처리 개요 : 어댑터를 초기화한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param name 어뎁터업무 이름
|
||||
**/
|
||||
public AdapterVO(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 초기화 여부를 반환하는 getter 메서드
|
||||
* 2. 처리 개요 : 초기화 여부를 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return 초기화 여부
|
||||
**/
|
||||
public boolean isStarted() {
|
||||
return this.started;
|
||||
}
|
||||
|
||||
public void setAdapterGroupName(String adapterGroupName) {
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
}
|
||||
|
||||
public String getAdapterGroupName() {
|
||||
return this.adapterGroupName;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public void setListenerClass(String listenerClass) {
|
||||
this.listenerClass = listenerClass;
|
||||
}
|
||||
|
||||
public String getListenerClass() {
|
||||
return this.listenerClass;
|
||||
}
|
||||
|
||||
// public void setTestCallClass(String testCallClass) {
|
||||
// this.testCallClass = testCallClass;
|
||||
// }
|
||||
//
|
||||
// public String getTestCallClass() {
|
||||
// return this.testCallClass;
|
||||
// }
|
||||
|
||||
public void setPropGroupName(String propGroupName) {
|
||||
this.propGroupName = propGroupName;
|
||||
}
|
||||
|
||||
public String getPropGroupName() {
|
||||
return this.propGroupName;
|
||||
}
|
||||
|
||||
public void setAdapterGroupVO(AdapterGroupVO group) {
|
||||
this.adapterGroupVO = group;
|
||||
}
|
||||
|
||||
public AdapterGroupVO getAdapterGroupVO() {
|
||||
return this.adapterGroupVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : TestCallManager에 어댑터 정보를 설정하는 메서드
|
||||
* 2. 처리 개요 : 어댑터 상태 설정
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param status 어댑터 상태
|
||||
*
|
||||
**/
|
||||
public synchronized void setStatus(boolean status) {
|
||||
this.status = status;
|
||||
|
||||
// if (this.status==false && this.testCallClass!=null && !this.testCallClass.equals("")) {
|
||||
// TestCallManager tmanager = TestCallManager.getInstance();
|
||||
// try {
|
||||
// tmanager.addTester(this);
|
||||
// logger.info(ExceptionUtil.make("BICEAIMAD034", new String[] {this.toString()}));
|
||||
//
|
||||
// } catch(Exception e) {
|
||||
// throw new RuntimeException(ExceptionUtil.getErrorCode(e, "BICEAIMAD035"));
|
||||
// }
|
||||
// }
|
||||
|
||||
if(this.status) {
|
||||
this.adapterGroupVO.active(this);
|
||||
} else {
|
||||
this.adapterGroupVO.disable(this);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isStatus() {
|
||||
return this.status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : Lifecycle의 start 메서드로 AdapterVO 초기화하는 메서드
|
||||
* 2. 처리 개요 : AdapterVO를 초기화한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception LifecycleException 이미 시작되었을 경우
|
||||
*
|
||||
**/
|
||||
public void start() throws LifecycleException {
|
||||
if (started)
|
||||
throw new LifecycleException("BECEAIMAD036");
|
||||
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
|
||||
|
||||
if(listenerClass!=null && !"".equals(listenerClass)) {
|
||||
try {
|
||||
adapterListener = (AdapterListener)Class.forName(listenerClass).newInstance();
|
||||
adapterListener.setAdapterInfo(this);
|
||||
adapterListener.start();
|
||||
} catch(Exception e) {
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD037"));
|
||||
}
|
||||
}
|
||||
|
||||
started = true;
|
||||
status = true;
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : Lifecycle의 stop 메서드로 어댑터 정보를 clear 하는 메서드
|
||||
* 2. 처리 개요 : 멤버에 캐싱한 어댑터 정보를 clear한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception LifecycleException 이미 종료된 경우 발생
|
||||
**/
|
||||
public void stop() throws LifecycleException {
|
||||
// Validate and update our current component state
|
||||
if (!started)
|
||||
throw new LifecycleException("BECEAIMAD038");
|
||||
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
|
||||
|
||||
try {
|
||||
if(adapterListener!=null) adapterListener.stop();
|
||||
} catch(AdapterException e) {
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMAD039"));
|
||||
}
|
||||
|
||||
started = false;
|
||||
status = false;
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : LifecycleListener를 등록하는 메서드
|
||||
* 2. 처리 개요 : LifecycleListener를 등록한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param listener LifecycleEvent를 수신한 LifecycleListener
|
||||
**/
|
||||
public void addLifecycleListener(LifecycleListener listener)
|
||||
{
|
||||
lifecycle.addLifecycleListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 등록된 LifecycleListener 리스트를 반환하는 메서드
|
||||
* 2. 처리 개요 : 등록된 LifecycleListener 리스트를 반환하다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return 등록된 LifecycleListener 리스트
|
||||
**/
|
||||
public LifecycleListener[] findLifecycleListeners()
|
||||
{
|
||||
return lifecycle.findLifecycleListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 등록된 LifecycleListener를 삭제하는 메서드
|
||||
* 2. 처리 개요 : 파라미터의 LifecycleListener를 삭제한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param listener 삭제할 LifecycleListener
|
||||
**/
|
||||
public void removeLifecycleListener(LifecycleListener listener)
|
||||
{
|
||||
lifecycle.removeLifecycleListener(listener);
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return this.description;
|
||||
}
|
||||
|
||||
// public void setEaiSevrInstncName(String eaiSevrInstncName) {
|
||||
// this.eaiSevrInstncName = eaiSevrInstncName;
|
||||
// }
|
||||
//
|
||||
// public String getEaiSevrInstncName() {
|
||||
// return this.eaiSevrInstncName;
|
||||
// }
|
||||
|
||||
public void setPropGroupDesc(String propGroupDesc) {
|
||||
this.propGroupDesc = propGroupDesc;
|
||||
}
|
||||
|
||||
public String getPropGroupDesc() {
|
||||
return this.propGroupDesc;
|
||||
}
|
||||
|
||||
public void setContext(ConfigurationContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public ConfigurationContext getContext() {
|
||||
return this.context;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보를 String 형태로 반환하는 메서드
|
||||
* 2. 처리 개요 : String 형태로 어댑터 정보를 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return String 어댑터 정보
|
||||
**/
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append("\n AdapterVO [ name=").append(name);
|
||||
sb.append(", adapterGroupName=").append(adapterGroupName);
|
||||
// sb.append(", eaiSevrInstncName=").append(eaiSevrInstncName);
|
||||
sb.append(", listenerClass=").append(listenerClass);
|
||||
// sb.append(", testCallClass=").append(testCallClass);
|
||||
sb.append(", propGroupName=").append(propGroupName);
|
||||
sb.append(", description=").append(description);
|
||||
sb.append(", status=").append(status);
|
||||
sb.append(", context=").append(context);
|
||||
sb.append(", batchSystemConnCode=").append(batchSystemConnCode);
|
||||
sb.append(", batchProcessCode=").append(batchProcessCode);
|
||||
sb.append(", batchProcessName=").append(batchProcessName);
|
||||
sb.append(", batchInstitutionCode=").append(batchInstitutionCode);
|
||||
sb.append(", batchServerIP=").append(batchServerIP);
|
||||
sb.append(", batchServerPortNo=").append(batchServerPortNo);
|
||||
sb.append(", batchInterMsgTimeout=").append(batchInterMsgTimeout);
|
||||
sb.append(", batchRcvFlowRuleCode=").append(batchRcvFlowRuleCode);
|
||||
sb.append(", batchInstitutionCode=").append(this.batchInstitutionName);
|
||||
// sb.append(", batchInstitutionType=").append(this.batchInstitutionType);
|
||||
sb.append(" ]");
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void setBatchSystemConnCode(String batchSystemConnCode) {
|
||||
this.batchSystemConnCode = batchSystemConnCode;
|
||||
}
|
||||
|
||||
public String getBatchSystemConnCode() {
|
||||
return this.batchSystemConnCode;
|
||||
}
|
||||
|
||||
public void setBatchProcessCode(String batchProcessCode) {
|
||||
this.batchProcessCode = batchProcessCode;
|
||||
}
|
||||
|
||||
public String getBatchProcessCode() {
|
||||
return this.batchProcessCode;
|
||||
}
|
||||
|
||||
public void setBatchProcessName(String batchProcessName) {
|
||||
this.batchProcessName = batchProcessName;
|
||||
}
|
||||
|
||||
public String getBatchProcessName() {
|
||||
return this.batchProcessName;
|
||||
}
|
||||
|
||||
public void setBatchInstitutionCode(String batchInstitutionCode) {
|
||||
this.batchInstitutionCode = batchInstitutionCode;
|
||||
}
|
||||
|
||||
public String getBatchInstitutionCode() {
|
||||
return this.batchInstitutionCode;
|
||||
}
|
||||
|
||||
public void setBatchInstitutionName(String batchInstitutionName) {
|
||||
this.batchInstitutionName = batchInstitutionName;
|
||||
}
|
||||
|
||||
public String getBatchInstitutionName() {
|
||||
return this.batchInstitutionName;
|
||||
}
|
||||
// public void setBatchInsitutionType(String batchInstitutionType) {
|
||||
// this.batchInstitutionType = batchInstitutionType;
|
||||
// }
|
||||
// public String getBatchInstitutionType() {
|
||||
// return this.batchInstitutionType;
|
||||
// }
|
||||
|
||||
|
||||
public void setBatchServerIP(String batchServerIP) {
|
||||
this.batchServerIP = batchServerIP;
|
||||
}
|
||||
|
||||
public String getBatchServerIP() {
|
||||
return this.batchServerIP;
|
||||
}
|
||||
|
||||
public void setBatchServerPortNo(String batchServerPortNo) {
|
||||
this.batchServerPortNo = batchServerPortNo;
|
||||
}
|
||||
|
||||
public String getBatchServerPortNo() {
|
||||
return this.batchServerPortNo;
|
||||
}
|
||||
|
||||
public void setBatchInterMsgTimeout(int batchInterMsgTimeout) {
|
||||
this.batchInterMsgTimeout = batchInterMsgTimeout;
|
||||
}
|
||||
|
||||
public int getBatchInterMsgTimeout() {
|
||||
return this.batchInterMsgTimeout;
|
||||
}
|
||||
|
||||
public void setBatchRcvFlowRuleCode(String batchRcvFlowRuleCode) {
|
||||
this.batchRcvFlowRuleCode = batchRcvFlowRuleCode;
|
||||
}
|
||||
|
||||
public String getBatchRcvFlowRuleCode() {
|
||||
return this.batchRcvFlowRuleCode;
|
||||
}
|
||||
|
||||
public void setLnkID(String lnkID) {
|
||||
this.lnkID = lnkID;
|
||||
}
|
||||
|
||||
public String getLnkID() {
|
||||
return this.lnkID;
|
||||
}
|
||||
|
||||
public void setLnkPwd(String lnkPwd) {
|
||||
this.lnkPwd = lnkPwd;
|
||||
}
|
||||
|
||||
public String getLnkPwd() {
|
||||
return this.lnkPwd;
|
||||
}
|
||||
|
||||
public int getPacketSize() {
|
||||
return this.batchPacketSize;
|
||||
}
|
||||
|
||||
public void setPacketSize(int packetSize) {
|
||||
this.batchPacketSize = packetSize;
|
||||
}
|
||||
|
||||
//20060425 add by khs for 응답송신
|
||||
public String getRqstRspnsDstcd() {
|
||||
return this.rqstRspnsDstcd;
|
||||
}
|
||||
//20060425 add by khs for 응답송신
|
||||
public void setRqstRspnsDstcd(String rqstRspnsDstcd) {
|
||||
this.rqstRspnsDstcd = rqstRspnsDstcd;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
/**
|
||||
* 1. 기능 : adapter 패키지에서 사용하는 상수를 정의한 Interface
|
||||
* 2. 처리 개요 :
|
||||
* - adapter 패키지에서 사용하는 상수를 정의한 Interface
|
||||
* 3. 주의사항
|
||||
*/
|
||||
public interface Keys
|
||||
{
|
||||
|
||||
/**
|
||||
* 어댑터 타입 - NET(Socket)
|
||||
*/
|
||||
public static final String TYPE_NET = "SOC";
|
||||
|
||||
/**
|
||||
* 어댑터 타입 - X25
|
||||
*/
|
||||
public static final String TYPE_X25 = "X25";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import com.eactive.eai.adapter.socket.service.InboundControl;
|
||||
import com.eactive.eai.batch.doc.BatchDoc;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.inbound.ResponseHandler;
|
||||
|
||||
/**
|
||||
* 1. 기능 : AdapterGroupVO와 AdapterVO 생성
|
||||
* 2. 처리 개요 :
|
||||
* - AdapterGroupVO와 AdapterVO 생성
|
||||
* - Adapter.isStatus()를 통해 어뎁터 상태 확인
|
||||
* - property에 어뎁터 그룹명, 어뎁터 명, 표준메시지여부, REQUESTACTION class 등록
|
||||
* - Processor 클래스의 execute(Object message, Properties prop) 호출
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : AdapterGroupVO, AdapterVO
|
||||
* @since :
|
||||
*/
|
||||
public class RequestDispatcher
|
||||
{
|
||||
/**
|
||||
* Default Logger
|
||||
*/
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
/**
|
||||
* RequestDispatcher HashMap
|
||||
*/
|
||||
private static HashMap<String, RequestDispatcher> dispatchers = new HashMap<String, RequestDispatcher>();
|
||||
|
||||
/**
|
||||
* 1. 기능 : RequestDispatcher HashMap 객체로 부터
|
||||
* 요청한 어탭터 그룹의 RequestDispatcher instance 획득
|
||||
* 2. 처리 개요 :
|
||||
* - RequestDispatcher HashMap 객체로 부터 요청한 어탭터 그룹의 RequestDispatcher instance 획득
|
||||
* - RequestDispatcher instance가 없으면 생성 한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param adapterGroupName 어댑터 그룹명
|
||||
* @return RequestDispatcher instance
|
||||
**/
|
||||
public static RequestDispatcher getRequestDispatcher(String adapterGroupName) {
|
||||
RequestDispatcher dispatcher = dispatchers.get(adapterGroupName);
|
||||
if(dispatcher==null) {
|
||||
dispatcher = new RequestDispatcher(adapterGroupName);
|
||||
dispatchers.put(adapterGroupName, dispatcher);
|
||||
}
|
||||
|
||||
return dispatcher;
|
||||
}
|
||||
|
||||
/**
|
||||
* 어댑터 그룹명
|
||||
*/
|
||||
private String adapterGroupName;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Default Constructor
|
||||
* 2. 처리 개요 :
|
||||
* - 어댑터 그룹명 초기화
|
||||
* - ProcessorFactory instance 생성
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param adapterGroupName 어댑터 그룹명
|
||||
**/
|
||||
private RequestDispatcher(String adapterGroupName) {
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 1. 기능 : Processor 클래스의 execute(Object message, Properties prop) 호출
|
||||
* 2. 처리 개요 :
|
||||
* - 어댑터 프라퍼티를 설정하고 Processor Class의
|
||||
* execute(Object message, Properties prop) method 호출
|
||||
* - 리턴된 메시지 객체를 반환
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param adapterName 어댑터명
|
||||
* @param message 요청 메시지
|
||||
* @param prop 어댑터 프라퍼티
|
||||
* @return Object Processor로 부터 리턴된 message Object
|
||||
* @exception Exception Adapter가 없거나 액티브 상태가 아닐때, 프라퍼티 설정 오류 시 발생
|
||||
**/
|
||||
//public BatchDoc handle(InboundControl control) throws Exception {
|
||||
public void handle(InboundControl control) throws Exception {
|
||||
|
||||
logger.debug("[ELINK]################ RequestDispatcher.handle() 호출됨.");
|
||||
|
||||
long srtTime = 0;
|
||||
srtTime = System.currentTimeMillis();
|
||||
|
||||
String adapterName = control.getAdapterName();
|
||||
AdapterManager manager = AdapterManager.getInstance();
|
||||
AdapterGroupVO group = manager.getAdapterGroupVO(this.adapterGroupName);
|
||||
if(group == null) {
|
||||
String code = "BECEAIMAD042";
|
||||
String[] msgArgs = new String[2];
|
||||
msgArgs[0] = adapterGroupName;
|
||||
msgArgs[1] = adapterName;
|
||||
String errText = ExceptionUtil.make(code, msgArgs);
|
||||
if (logger.isError()) logger.error(errText);
|
||||
throw new Exception(errText);
|
||||
}
|
||||
|
||||
AdapterVO adapter = group.getAdapterVO(adapterName);
|
||||
if(adapter==null) {
|
||||
String code = "BECEAIMAD022";
|
||||
String[] msgArgs = new String[3];
|
||||
msgArgs[0] = adapterGroupName;
|
||||
msgArgs[1] = adapterName;
|
||||
msgArgs[2] = group.toString();
|
||||
String errText = ExceptionUtil.make(code, msgArgs);
|
||||
if (logger.isError()) logger.error(errText);
|
||||
throw new Exception(errText);
|
||||
}
|
||||
|
||||
|
||||
if(!adapter.isStatus()) {
|
||||
String code = "BECEAIMAD023";
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = adapter.toString();
|
||||
String errText = ExceptionUtil.make(code, msgArgs);
|
||||
if (logger.isError()) logger.error(errText);
|
||||
throw new Exception(errText);
|
||||
}
|
||||
|
||||
//BatchDoc batchMsgDoc = null;
|
||||
try {
|
||||
group.increase();
|
||||
ResponseHandler handler = new ResponseHandler();
|
||||
BatchDoc batchMsgDoc = handler.execute(control.getBatchMsgDoc());
|
||||
control.setBatchMsgDoc(batchMsgDoc);
|
||||
////batchMsgDoc = handler.execute(control.getBatchMsgDoc());
|
||||
|
||||
} catch(Exception e) {
|
||||
throw new Exception(ExceptionUtil.getErrorCode(e, "BECEAIMAD025"));
|
||||
} finally {
|
||||
group.decrease();
|
||||
}
|
||||
|
||||
logger.debug("[ELINK]################ RequestDispatcher.handle() 종료. (수행 시간: "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec)");
|
||||
//return batchMsgDoc;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* 1. 기능 : EAI 엔진에서 어댑터을 common하게 접근하기 위한 Interface
|
||||
* 2. 처리 개요 :
|
||||
* - execute hookup method를 실행한다.
|
||||
* - 실재 어댑터를 통해 통신 한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : 관련 기능을 참조
|
||||
* @since :
|
||||
*/
|
||||
public interface WLIAdapter
|
||||
{
|
||||
/**
|
||||
* 1. 기능 : execute hookup method를 실행한다.
|
||||
* 2. 처리 개요 :
|
||||
* - execute hookup method를 실행한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param prop 어댑터 Property
|
||||
* @param message 전문 메시지
|
||||
**/
|
||||
//public Object callService(Properties prop, Object message) throws Exception;
|
||||
|
||||
/**
|
||||
* 1. 기능 : execute hookup method를 실행한다.
|
||||
* 2. 처리 개요 :
|
||||
* - execute hookup method를 실행한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param adapterGroupName 어댑터 그룹명
|
||||
* @param prop 어댑터 Property
|
||||
* @param message 전문 메시지
|
||||
**/
|
||||
public Object callService(String adapterGroupName, Properties prop, Object message) throws Exception;
|
||||
|
||||
/**
|
||||
* 1. 기능 : 실재 어댑터를 통해 통신하는 로직을 구현한다.
|
||||
* 2. 처리 개요 :
|
||||
* - 실재 어댑터를 통해 통신하는 로직을 구현한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param prop 어댑터 Property
|
||||
* @param message 전문 메시지
|
||||
**/
|
||||
public Object execute(Properties prop, Object message) throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//package com.eactive.eai.adapter;
|
||||
//
|
||||
//import java.util.HashMap;
|
||||
//import com.eactive.eai.adapter.socket.SocketAdapter;
|
||||
//
|
||||
///**
|
||||
//* 1. 기능 : 어댑터를 초기화 하기 위한 Factory Class
|
||||
//* 2. 처리 개요 :
|
||||
//* - 초기화 된 어댑터 인스턴스를 HashMap 객체에 담는다.
|
||||
//* - 해당 어댑터의 WLIAdapter 인스턴스를 반환 한다.
|
||||
//* 3. 주의사항
|
||||
//*
|
||||
//*/
|
||||
//public class WLIAdapterFactory
|
||||
//{
|
||||
//
|
||||
// private static final WLIAdapterFactory factory = new WLIAdapterFactory();
|
||||
//
|
||||
// private HashMap<String, WLIAdapter> adapterMap;
|
||||
//
|
||||
// /**
|
||||
// * 1. 기능 : Default Constructor
|
||||
// * 2. 처리 개요 :
|
||||
// * - 타입 별 어댑터 instance를 어댑터 HashMap에 담는다.
|
||||
// * 3. 주의사항
|
||||
// *
|
||||
// **/
|
||||
// private WLIAdapterFactory() {
|
||||
// // 초기화 코드는 여기에 넣어 주세요.
|
||||
// //try {
|
||||
// adapterMap = new HashMap<String, WLIAdapter>();
|
||||
// //adapterMap.put(Keys.TYPE_HTTP, new HttpClientAdapter());
|
||||
// //adapterMap.put(Keys.TYPE_SNA, new SNAAdapterClient());
|
||||
// //adapterMap.put(Keys.TYPE_NET, SocketAdapter.getInstance());
|
||||
//
|
||||
// //adapterMap.put(Keys.TYPE_IMS, new IMSAdapter());
|
||||
// //adapterMap.put(Keys.TYPE_IMS, IMSAdapter.getInstance());
|
||||
// //} catch(Exception e) {
|
||||
// // throw new RuntimeException(ExceptionUtil.getErrorCode(e, "RECEAIAAC026"));
|
||||
// //}
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 1. 기능 : WLIAdapterFactory Object를 반환하는 getter method
|
||||
// * 2. 처리 개요 : WLIAdapterFactory Object를 반환한다.
|
||||
// * 3. 주의사항
|
||||
// *
|
||||
// * @return WLIAdapterFactory object
|
||||
// **/
|
||||
// public static WLIAdapterFactory newInstance() {
|
||||
// return factory;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 1. 기능 : 해당 어댑터의 WLIAdapter Object를 반환
|
||||
// * 2. 처리 개요 :
|
||||
// * - WLIAdapter instance HashMap으로 부터 해당 어댑터의 WLIAdapter Object를 반환 한다.
|
||||
// * 3. 주의사항
|
||||
// *
|
||||
// * @param adapterName 어댑터명
|
||||
// * @return WLIAdapter object
|
||||
// **/
|
||||
// public WLIAdapter getWLIAdapter(String adapterName) {
|
||||
// WLIAdapter adapter = (WLIAdapter)adapterMap.get(adapterName);
|
||||
// if(adapter==null) {
|
||||
// adapter = createAdapter(adapterName);
|
||||
// }
|
||||
// if(adapter==null) {
|
||||
// throw new RuntimeException("등록된 어댑터를 찾을 수 없습니다. - "+adapterName);
|
||||
// }
|
||||
// return adapter;
|
||||
// }
|
||||
//
|
||||
// private synchronized WLIAdapter createAdapter(String adapterName) {
|
||||
// if(adapterName==null) return null;
|
||||
//
|
||||
// WLIAdapter adapter = null;
|
||||
// if(adapterName.equals(Keys.TYPE_HTTP)) {
|
||||
// //adapter = new HttpClientAdapter();
|
||||
// //adapterMap.put(Keys.TYPE_HTTP, adapter);
|
||||
// } else if(adapterName.equals(Keys.TYPE_SNA)) {
|
||||
// //adapter = new SNAAdapterClient();
|
||||
// //adapterMap.put(Keys.TYPE_SNA, adapter);
|
||||
// } else if(adapterName.equals(Keys.TYPE_NET)) {
|
||||
// adapter = SocketAdapter.getInstance();
|
||||
// adapterMap.put(Keys.TYPE_NET, adapter);
|
||||
// } else if(adapterName.equals(Keys.TYPE_IMS)) {
|
||||
// //adapter = IMSAdapter.getInstance();
|
||||
// //adapterMap.put(Keys.TYPE_IMS, adapter);
|
||||
// }
|
||||
//
|
||||
// return adapter;
|
||||
// }
|
||||
//}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.eactive.eai.adapter;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : WLIAdapter Interface를 implements 한 Default WLIAdapter
|
||||
* 2. 처리 개요 :
|
||||
* - execute hookup method를 실행한다.
|
||||
* - 실재 어댑터를 통해 통신 한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : WLIAdapter, AdapterManager
|
||||
* @since :
|
||||
*/
|
||||
public class WLIDefaultAdapter implements WLIAdapter
|
||||
{
|
||||
/**
|
||||
* Default Logger
|
||||
*/
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
/**
|
||||
* AdapterManager instance
|
||||
*/
|
||||
private AdapterManager manager;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Default Constructor
|
||||
* 2. 처리 개요 :
|
||||
* - AdapterManager instance를 생성한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public WLIDefaultAdapter() {
|
||||
this.manager = AdapterManager.getInstance();
|
||||
}
|
||||
/*
|
||||
public Object callService(Properties prop, Object message) throws Exception {
|
||||
return callService(null,prop,message);
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* 1. 기능 : execute hookup method를 실행한다.
|
||||
* 2. 처리 개요 :
|
||||
* - execute hookup method를 실행한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param adapterGroupName 어댑터 그룹명
|
||||
* @param prop 어댑터 Property
|
||||
* @param message 전문 메시지
|
||||
**/
|
||||
public Object callService(String adapterGroupName, Properties prop, Object message) throws Exception{
|
||||
AdapterGroupVO group = this.manager.getAdapterGroupVO(adapterGroupName);
|
||||
if(group==null) {
|
||||
String code = "BECEAIMAD027";
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = adapterGroupName;
|
||||
String errText = ExceptionUtil.make(code, msgArgs);
|
||||
if (logger.isError()) logger.error(errText);
|
||||
throw new Exception(errText);
|
||||
}
|
||||
|
||||
if(group!=null) group.increase();
|
||||
try {
|
||||
return execute(prop, message);
|
||||
} catch(Throwable e) {
|
||||
throw new Exception(ExceptionUtil.getErrorCode(e, "BECEAIMAD028"));
|
||||
} finally {
|
||||
if(group!=null) group.decrease();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 실재 어댑터를 통해 통신하는 로직을 구현한다.
|
||||
* 2. 처리 개요 :
|
||||
* - 실재 어댑터를 통해 통신하는 로직을 구현한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param prop 어댑터 Property
|
||||
* @param message 전문 메시지
|
||||
**/
|
||||
public Object execute(Properties prop, Object message) throws Exception {
|
||||
throw new java.lang.UnsupportedOperationException("BECEAIMAD029");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,578 @@
|
||||
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.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
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.FTPFileObject;
|
||||
import com.eactive.eai.batch.ftp.FTPUtil;
|
||||
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;
|
||||
|
||||
|
||||
/**
|
||||
* 우체국 공융 ftp 전송을 위함 SFTP
|
||||
*
|
||||
* 파일명 : FTP00
|
||||
*
|
||||
*/
|
||||
|
||||
public class FTP00 extends Transfer implements SocketService {
|
||||
|
||||
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
|
||||
|
||||
private static final String REMOTE_PATH = "remote.path";// 원격지 경로 #YYYYMMDD#
|
||||
private static final String FILENAME_PATTERN = "filename.pattern";// 기준일자 [YYYYMMDD] 당일이전일 [YYYYMMDD-1][YYYYMMDD-2][YYYYMMDD+1]
|
||||
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"; // 기준일 이후 파일전송여부
|
||||
|
||||
/** ftp 0 , 인증 방법 1 = id, 2 = key 방식 */
|
||||
private static final String AUTH_TYPE = "sftp.auth.type";
|
||||
|
||||
private static final String TRANS_LIB = "sftp.trans.lib";
|
||||
|
||||
@Override
|
||||
public void sendFile(BatchDoc batchDoc) throws Exception {
|
||||
// TODO Auto-generated method stub
|
||||
if(logger.isInfoEnabled())
|
||||
logger.info("[FTP00] ■ 대외기관→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.endsWith("/") )
|
||||
remotePath = remotePath + "/";
|
||||
|
||||
String ftpgb = pmanager.getProperties(propName).getProperty(AUTH_TYPE, "1");
|
||||
|
||||
|
||||
//baseDate 추출
|
||||
String baseDate = DatetimeUtil.getCurrentDate();
|
||||
String reqFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName();
|
||||
if (reqFileName != null && reqFileName.length() > 8) {
|
||||
String extName = pmanager.getProperties(propName).getProperty(EXT_NAME);
|
||||
if(extName != null && extName.trim().length() > 0){
|
||||
//String reqFileNameNoExt = reqFileName.replace(extName, "");
|
||||
String reqFileNameNoExt = reqFileName.substring(0, reqFileName.lastIndexOf(extName));// 20241230
|
||||
if (reqFileNameNoExt.length() >= 8 && DatetimeUtil.isRightDate(reqFileNameNoExt.substring(reqFileNameNoExt.length() - 8))) {
|
||||
baseDate = reqFileNameNoExt.substring(reqFileNameNoExt.length() - 8);
|
||||
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// remotePath = remotePath.replaceAll("#YYYYMMDD#", baseDate);
|
||||
if(remotePath.indexOf("#YYYYMMDD#") > -1){
|
||||
remotePath = remotePath.replace("#YYYYMMDD#", baseDate);
|
||||
}else if(remotePath.indexOf("#YYYYMMDD-1#") > -1) {
|
||||
baseDate = DatetimeUtil.addDays(baseDate, -1);
|
||||
remotePath = remotePath.replace("#YYYYMMDD-1#", baseDate);
|
||||
}else if(remotePath.indexOf("#YYYYMMDD-2#") > -1) {
|
||||
baseDate = DatetimeUtil.addDays(baseDate, -2);
|
||||
remotePath = remotePath.replace("#YYYYMMDD-2#", baseDate);
|
||||
}else if(remotePath.indexOf("#YYYYMMDD+1#") > -1) {
|
||||
baseDate = DatetimeUtil.addDays(baseDate, 1);
|
||||
remotePath = remotePath.replace("#YYYYMMDD+1#", baseDate);;
|
||||
}
|
||||
|
||||
if (!remotePath.endsWith("/"))
|
||||
remotePath = remotePath + "/";
|
||||
|
||||
// 실제 파일이름
|
||||
//String orgFileName = batchDoc.getBatchMsg().getHeader().getFileName();
|
||||
// FEP 에서 Rename(송신Real->송신Arch)한 파일이름
|
||||
String sendFileName = batchDoc.getBatchMsg().getHeader().getFilePath() + "/"
|
||||
+ batchDoc.getBatchMsg().getHeader().getRenamedFileName();
|
||||
String remoteFileName = remotePath + batchDoc.getBatchMsg().getHeader().getFileName();
|
||||
|
||||
//logger.debug( "[FTP00]sendFileName:" + orgFileName);
|
||||
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug( "[FTP00]remotePath:" + remotePath);
|
||||
|
||||
//File 시작시간 설정
|
||||
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
|
||||
LogUtil.setLogFileStart(batchDoc);
|
||||
|
||||
//String sendFilePath = batchDoc.getBatchMsg().getHeader().getFilePath();
|
||||
|
||||
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 transLib = pmanager.getProperties(propName).getProperty(TRANS_LIB, "JSCH");
|
||||
|
||||
try {
|
||||
if("SSH".equals(transLib)) {
|
||||
FTPUtil.store(ipaddress, port, userid, passwd, remoteFileName, sendFileName, true, batchDoc.getLogger(), ftpgb);
|
||||
}else {
|
||||
FTPUtil.store(batchDoc, ipaddress, port, userid,
|
||||
passwd, remotePath, batchDoc.getBatchMsg().getHeader().getFileName(),
|
||||
sendFileName,
|
||||
connTimeout, setTimeout, true, bandWidth, batchDoc.getLogger(Logger.LOGGER_ADAPTER), ftpgb);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("[FTP00]파일송신에 실패하였습니다.", 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();
|
||||
}
|
||||
if(logger.isDebugEnabled())
|
||||
logger.info("[FTP00] ■ FEP → VAN사 파일 송신 완료.");
|
||||
|
||||
}
|
||||
|
||||
public void recvFile(BatchDoc batchDoc) throws Exception {
|
||||
if(logger.isInfoEnabled())
|
||||
logger.info("@@@@@@@FTP00] ■ 대외기관→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();
|
||||
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("@@@@FTP00]userid:" + userid);
|
||||
//logger.debug("@@@@FTP00]passwd:" + passwd);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
//SFTP방식
|
||||
String ftpgb = pmanager.getProperties(propName).getProperty(AUTH_TYPE, "1");
|
||||
|
||||
|
||||
// FTP_FILE_TYPE
|
||||
String ftpFileType = pmanager.getProperties(propName).getProperty(FTP_FILE_TYPE, "BINARY");
|
||||
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("[FTP00]FileName:" + batchDoc.getBatchMsg().getHeader().getFileName());
|
||||
String reqFileName = batchDoc.getBatchMsg().getHeader().getFileName();
|
||||
//baseDate 추출
|
||||
String baseDate = DatetimeUtil.getCurrentDate();
|
||||
|
||||
String extName = "";
|
||||
String reqFileNameNoExt = reqFileName;
|
||||
try {
|
||||
extName = pmanager.getProperties(propName).getProperty(EXT_NAME);
|
||||
if(extName != null && extName.trim().length() > 0)
|
||||
reqFileNameNoExt = reqFileName.substring(0, reqFileName.lastIndexOf(extName));// 20241230
|
||||
}catch(Exception e) {
|
||||
}
|
||||
|
||||
if (reqFileNameNoExt != null && reqFileNameNoExt.length() > 8) {
|
||||
if (reqFileNameNoExt.length() >= 8 && DatetimeUtil.isRightDate(reqFileNameNoExt.substring(reqFileNameNoExt.length() - 8))) {
|
||||
baseDate = reqFileNameNoExt.substring(reqFileNameNoExt.length() - 8);
|
||||
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
|
||||
}
|
||||
}
|
||||
|
||||
//remotePath = remotePath.replaceAll("#YYYYMMDD#", baseDate);
|
||||
if(remotePath.indexOf("#YYYYMMDD#") > -1){
|
||||
remotePath = remotePath.replace("#YYYYMMDD#", baseDate);
|
||||
}else if(remotePath.indexOf("#YYYYMMDD-1#") > -1) {
|
||||
baseDate = DatetimeUtil.addDays(baseDate, -1);
|
||||
remotePath = remotePath.replace("#YYYYMMDD-1#", baseDate);
|
||||
}else if(remotePath.indexOf("#YYYYMMDD-2#") > -1) {
|
||||
baseDate = DatetimeUtil.addDays(baseDate, -2);
|
||||
remotePath = remotePath.replace("#YYYYMMDD-2#", baseDate);
|
||||
}else if(remotePath.indexOf("#YYYYMMDD+1#") > -1) {
|
||||
baseDate = DatetimeUtil.addDays(baseDate, 1);
|
||||
remotePath = remotePath.replace("#YYYYMMDD+1#", baseDate);;
|
||||
}
|
||||
if (!remotePath.endsWith("/"))
|
||||
remotePath = remotePath + "/";
|
||||
|
||||
boolean isFileNameSet = false;// 파일이름이 설정되는지 여부
|
||||
try{// 파일 프로퍼티
|
||||
String propFileName = PROP_GROUP_NAME_PREFIX + "{" + batchDoc.getBatchMsg().getHeader().getProcessCode() + "_"
|
||||
+ batchDoc.getBatchMsg().getHeader().getBizCode() + "}";
|
||||
|
||||
String filenamePattern = pmanager.getProperties(propFileName).getProperty(FILENAME_PATTERN, "");
|
||||
if(filenamePattern != null && filenamePattern.length() > 0) {
|
||||
isFileNameSet = true;
|
||||
reqFileName = filenamePattern;
|
||||
reqFileName = reqFileName.replace("[FILENAME]", batchDoc.getBatchMsg().getHeader().getBizCode());
|
||||
|
||||
if(reqFileName.indexOf("[YYYYMMDD]") > -1){
|
||||
reqFileName = reqFileName.replace("[YYYYMMDD]", baseDate);
|
||||
}else if(reqFileName.indexOf("[YYYYMMDD-1]") > -1) {
|
||||
String tmpbaseDate = DatetimeUtil.addDays(baseDate, -1);
|
||||
reqFileName = reqFileName.replace("[YYYYMMDD-1]", tmpbaseDate);
|
||||
}else if(reqFileName.indexOf("[YYYYMMDD-2]") > -1) {
|
||||
String tmpbaseDate = DatetimeUtil.addDays(baseDate,-2);
|
||||
reqFileName = reqFileName.replace("[YYYYMMDD-2]", tmpbaseDate);
|
||||
}else if(reqFileName.indexOf("[YYYYMMDD+1]") > -1){
|
||||
String tmpbaseDate = DatetimeUtil.addDays(baseDate, 1);
|
||||
reqFileName = reqFileName.replace("[YYYYMMDD+1]", tmpbaseDate);
|
||||
}
|
||||
|
||||
if(reqFileName.indexOf("[YYYYMM]") > -1){
|
||||
reqFileName = reqFileName.replace("[YYYYMM]", baseDate.substring(0,6));
|
||||
}
|
||||
|
||||
|
||||
if(reqFileName.indexOf("[MMDD]") > -1) {
|
||||
reqFileName = reqFileName.replace("[MMDD]", baseDate.substring(4));
|
||||
}else if(reqFileName.indexOf("[MMDD-1]") > -1) {
|
||||
String tmpbaseDate = DatetimeUtil.addDays(baseDate,-1);
|
||||
reqFileName = reqFileName.replace("[MMDD-1]", tmpbaseDate.substring(4));
|
||||
}if(reqFileName.indexOf("[MMDD-2]") > -1) {
|
||||
String tmpbaseDate = DatetimeUtil.addDays(baseDate,-2);
|
||||
reqFileName = reqFileName.replace("[MMDD-2]", tmpbaseDate.substring(4));
|
||||
}else if(reqFileName.indexOf("[MMDD+1]") > -1) {
|
||||
String tmpbaseDate = DatetimeUtil.addDays(baseDate, 1);
|
||||
reqFileName = reqFileName.replace("[MMDD+1]", tmpbaseDate.substring(4));
|
||||
}
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("trans reqFileName:"+reqFileName);
|
||||
}
|
||||
}catch(Exception ex) {
|
||||
// 파일프로퍼티 설정 없음
|
||||
}
|
||||
|
||||
String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "30");
|
||||
int connTimeout = Integer.parseInt(connTimeoutStr);
|
||||
String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "30");
|
||||
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);
|
||||
|
||||
boolean selectDate = true;
|
||||
try {
|
||||
if("Y".equals(pmanager.getProperties(propName).getProperty(BASE_DATE_OVER_YN, "N"))) {
|
||||
selectDate = false;
|
||||
}
|
||||
}catch(Exception e) {
|
||||
}
|
||||
|
||||
FTPFileObject[] list = FTPUtil.listFilesJSCH(ipaddress, port, userid, passwd, remotePath, true, batchDoc.getLogger(),ftpgb);
|
||||
|
||||
if(list == null) {// 파일 경로가 없는경우 20231025
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("[FTP00]remotePath:"+remotePath +" path is none");
|
||||
return;
|
||||
}
|
||||
setLastActivity();
|
||||
|
||||
String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode();
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("[FTP00] ■ baseDate[" + baseDate + "] bizCode[" + bizCode + "]");
|
||||
|
||||
for (int inx = 0; inx < list.length; inx++) {
|
||||
FTPFileObject file = list[inx];
|
||||
|
||||
if(!file.isFile())
|
||||
continue;
|
||||
|
||||
String fileName = file.getName().trim();
|
||||
long fileSize = file.getSize();
|
||||
|
||||
if(isFileNameSet && fileName.contains(reqFileName)){
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("[FTP00]reqFileName=isFileNameSet["+isFileNameSet + "] fileName[" + fileName + "] reqFileName[" + reqFileName +"]");
|
||||
fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType
|
||||
, connTimeout, setTimeout, bandWidth);
|
||||
}else if (!isFileNameSet && fileName.contains(bizCode)) {
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("[FTP00]reqFileName=isFileNameSet["+isFileNameSet + "] fileName[" + fileName + "] bizCode[" + bizCode +"]");
|
||||
|
||||
Matcher matcher = Pattern.compile("(20[0-9]{6})").matcher(fileName.trim());
|
||||
if (matcher.find()) {
|
||||
|
||||
String value = matcher.group(1).trim();
|
||||
int iday = Integer.parseInt(value);
|
||||
int bday = Integer.parseInt(baseDate);
|
||||
if (iday >= bday && !selectDate) { //스케줄러를 통한 파일 수신, 오늘 날짜 이상
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("[FTP00]ALL OVER DATE OK-fileName[" + fileName + "]");
|
||||
fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType
|
||||
, connTimeout, setTimeout, bandWidth);
|
||||
|
||||
} else if (iday == bday && selectDate) { //파일날짜 선택하여 파일 수신, 해당 날짜만 수신
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("[FTP00]SELECT_DATE-fileName[" + fileName + "]");
|
||||
fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType
|
||||
, connTimeout, setTimeout, bandWidth);
|
||||
}
|
||||
}else{
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("[FTP00]No SELECT_DATE-fileName[" + fileName + "]");
|
||||
|
||||
try {
|
||||
OutsideVO organInfo = OutsideManager.getInstance().getOutsideInfo(batchDoc.getBatchMsg().getHeader().getProcessCode()
|
||||
, batchDoc.getBatchMsg().getHeader().getInstitutionCode());
|
||||
int bizCodeStartIndex = organInfo.getBizCdStartIdx();
|
||||
int bizCodeEndIndex = organInfo.getBizCdEndIdx();
|
||||
|
||||
if (fileName.length() > bizCodeEndIndex && bizCode.equals(fileName.substring(bizCodeStartIndex, bizCodeEndIndex))){
|
||||
fileDownProcess(batchDoc, fileName, fileSize, ipaddress, port, userid, passwd, remotePath, ftpgb, ftpFileType
|
||||
, connTimeout, setTimeout, bandWidth);
|
||||
}
|
||||
}catch(Exception 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);
|
||||
batchDoc.getBatchMsg().getBody().setPhaseEndTime(DatetimeUtil.getCurrentTimeMillis());
|
||||
LogUtil.setErrorLog(batchDoc, ex.getMessage());
|
||||
logger.error(errMsg, ex);
|
||||
throw ex;
|
||||
} finally {
|
||||
this.disconnect();
|
||||
}
|
||||
if(logger.isInfoEnabled())
|
||||
logger.info("[FTP00] ■ 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 {
|
||||
FileOutputStream fos = null;
|
||||
|
||||
batchDoc.getBatchMsg().getHeader().setFileName(fileName);
|
||||
batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
|
||||
|
||||
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
|
||||
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("@@@@@@@@@batchDoc.getBatchMsg().getHeader().getJobCode()["
|
||||
+ batchDoc.getBatchMsg().getHeader().getJobCode() + "]");
|
||||
|
||||
String recvFile = "";
|
||||
File rcvRealFile = null;
|
||||
File rcvChkFile = null;
|
||||
|
||||
batchDoc.getBatchMsg().getBody().setPhaseStartTime(DatetimeUtil.getCurrentTimeMillis());
|
||||
LogUtil.setLogFileStart(batchDoc);
|
||||
try {
|
||||
|
||||
if(logger.isDebugEnabled())
|
||||
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);
|
||||
|
||||
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
|
||||
recvFile = batchDoc.getBatchMsg().getHeader().getFilePath() + File.separator + fileName;
|
||||
rcvRealFile = new File(recvFile);
|
||||
rcvChkFile = new File(StringUtil.realToRootDir(recvFile));
|
||||
} 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(logger.isDebugEnabled())
|
||||
logger.debug("@@@@@@@@@rcvArchFile[" + rcvArchFile.getName() + "]");
|
||||
batchDoc.getBatchMsg().getHeader().getJobCode();
|
||||
|
||||
if (rcvRealFile.exists()) {
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug("@@@@@@@@@rcvRealFile[" + rcvRealFile.getName() + "]");
|
||||
rcvRealFile.renameTo(rcvArchFile);
|
||||
rcvChkFile.createNewFile();
|
||||
} else {
|
||||
throw new Exception("파일수신에 실패하였습니다.");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
throw e;
|
||||
|
||||
}
|
||||
// File 종료시간 설정
|
||||
batchDoc.getBatchMsg().getBody().setPhaseEndTime(DatetimeUtil.getCurrentTimeMillis());
|
||||
LogUtil.setLogFileEnd(batchDoc);
|
||||
}
|
||||
|
||||
// 정상처리 20241025
|
||||
private void fileDownEndProcess(BatchDoc batchDoc, String fileName, String errMsg) throws Exception {
|
||||
FileOutputStream fos = null;
|
||||
|
||||
batchDoc.getBatchMsg().getHeader().setFileName(fileName);
|
||||
batchDoc.getBatchMsg().getHeader().setFileSize(0);
|
||||
|
||||
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
|
||||
logger.debug("@@@@@@@@@fileDownEndProcess batchDoc.getBatchMsg().getHeader().getFileName()["+ fileName + "]");
|
||||
|
||||
batchDoc.getBatchMsg().getBody().setPhaseStartTime(DatetimeUtil.getCurrentTimeMillis());
|
||||
|
||||
LogUtil.setLogFileStart(batchDoc);
|
||||
|
||||
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
|
||||
batchDoc.getBatchMsg().getHeader().getJobCode();
|
||||
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
|
||||
|
||||
// File 종료시간 설정
|
||||
batchDoc.getBatchMsg().getBody().setPhaseEndTime(DatetimeUtil.getCurrentTimeMillis());
|
||||
LogUtil.setLogFileEnd(batchDoc);
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,555 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,766 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.eactive.eai.adapter.ftp;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
import com.eactive.eai.batch.doc.BatchDoc;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
|
||||
public class FtpSupport {
|
||||
private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
|
||||
|
||||
/**
|
||||
* 기관 프라퍼티 이름을 얻는다.
|
||||
* @param batchDoc
|
||||
* @return
|
||||
*/
|
||||
public static String getInstitutionPropertyName(BatchDoc batchDoc) {
|
||||
return PROP_GROUP_NAME_PREFIX + "{" +
|
||||
batchDoc.getBatchMsg().getHeader().getProcessCode() +
|
||||
"_" +
|
||||
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
|
||||
}
|
||||
|
||||
/**
|
||||
* properties에서 propertyKey에 해당하는 정수 값을 얻는다.
|
||||
* 값이 없거나 오류가 발생하면 defaultValue를 얻는다.
|
||||
*
|
||||
* @param properties 프라퍼티
|
||||
* @param propertyKey 키
|
||||
* @param defaultValue 기본값
|
||||
* @param logger 로거
|
||||
* @return 프러퍼티 값의 정수 또는 기본값
|
||||
*/
|
||||
public static int getIntProperty(Properties properties, String propertyKey, int defaultValue, Logger logger) {
|
||||
int returnValue = defaultValue;
|
||||
String propertyValue = properties.getProperty(propertyKey);
|
||||
|
||||
if (propertyValue != null) {
|
||||
try {
|
||||
returnValue = Integer.parseInt(propertyValue);
|
||||
} catch(Exception e) {
|
||||
logger.error("{"+"propertyKey"+"} = {"+"propertyValue"+"}" +"["+ e.getMessage() +"]");
|
||||
}
|
||||
}
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* SFTP wild character *, ? 가 있는지 확인한다.
|
||||
* @param filename 검사할 파일 이름
|
||||
* @return *, ?가 있으면 true
|
||||
*/
|
||||
public static boolean hasWildcard(String filename) {
|
||||
return filename != null && (filename.contains("*") || filename.contains("?"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 기관 Properties 를 얻는다.
|
||||
* @param batchDoc 배치 정보
|
||||
* @return 기관 Properties
|
||||
*/
|
||||
public static Properties getInstProperties(BatchDoc batchDoc) {
|
||||
PropManager pmanager = PropManager.getInstance();
|
||||
|
||||
String propName = PROP_GROUP_NAME_PREFIX + "{" +
|
||||
batchDoc.getBatchMsg().getHeader().getProcessCode() +
|
||||
"_" +
|
||||
batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
|
||||
return pmanager.getProperties(propName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 파일 Properties 를 얻는다.
|
||||
* @param batchDoc 배치 정보
|
||||
* @return 파일 Properties
|
||||
*/
|
||||
public static Properties getFileProperties(BatchDoc batchDoc) {
|
||||
PropManager pmanager = PropManager.getInstance();
|
||||
|
||||
String propName = PROP_GROUP_NAME_PREFIX + "{" +
|
||||
batchDoc.getBatchMsg().getHeader().getProcessCode() +
|
||||
"_" +
|
||||
batchDoc.getBatchMsg().getHeader().getBizCode() + "}";
|
||||
return pmanager.getProperties(propName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 자동, 수동 스케줄을 판단하고, 수동인 경우 baseDate를 바꾼다.
|
||||
*
|
||||
* @param batchDoc
|
||||
* @return
|
||||
*/
|
||||
public static boolean isManaulRecive(BatchDoc batchDoc) {
|
||||
boolean isManualReceive = false;
|
||||
|
||||
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);
|
||||
isManualReceive = true;
|
||||
}
|
||||
}
|
||||
batchDoc.getBatchMsg().getHeader().setBaseDate(baseDate);
|
||||
return isManualReceive;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.eactive.eai.adapter.ftp;
|
||||
|
||||
/**
|
||||
* SFTP 프로퍼티 관련 상수
|
||||
*/
|
||||
public class SFTPConstants {
|
||||
/** 인증 방법 1 = id, 2 = key 방식 */
|
||||
public static final String SFTP_AUTH_TYPE = "sftp.auth.type";
|
||||
/** 인증 방법 id */
|
||||
public static final String SFTP_AUTH_TYPE_ID = "1";
|
||||
/** 인증 방법 key */
|
||||
public static final String SFTP_AUTH_TYPE_KEY = "2";
|
||||
|
||||
/** YN 의 Y */
|
||||
public static final String YES = "y";
|
||||
/** YN 의 N */
|
||||
public static final String NO = "n";
|
||||
|
||||
/** 파일이름에 치환할 날짜, 시간 포맷. -, _ 지원 */
|
||||
public static final String DATE_PATTERN = "\\{([yMdHms\\-_]+)\\}";
|
||||
|
||||
// 파일경로 관련 기관 프로퍼티
|
||||
public static final String SEND_REMOTE_PATH = "send.remote.path";
|
||||
public static final String RECV_REMOTE_PATH = "recv.remote.path";
|
||||
|
||||
// 송신완료파일 생성관련 기관 프로퍼티
|
||||
public static final String SEND_COMPLETE_CREATE_YN = "send.complete.create.yn";
|
||||
public static final String SEND_COMPLETE_FILE_EXT = "send.complete.file.ext";
|
||||
|
||||
// 파일 프러퍼티
|
||||
/** 접수일자 날짜 조정 */
|
||||
public static final String FILE_RECV_ADD_YEAR = "file.recv.add.year";
|
||||
public static final String FILE_RECV_ADD_MONTH = "file.recv.add.month";
|
||||
public static final String FILE_RECV_ADD_DAY = "file.recv.add.day";
|
||||
|
||||
/** 기본 수신 폴더에 파일 별 경로 추가. 파일접수일자 포함 */
|
||||
public static final String FILE_RECV_ADD_PATH = "file.recv.add.path";
|
||||
/** 자동 수신할 파일이름 패턴(*.gz) */
|
||||
public static final String FILE_RECV_AUTO_FILENAME = "file.recv.auto.filename";
|
||||
/** 스케줄 수신 파일 이름 */
|
||||
public static final String FILE_RECV_MANUAL_FILENAME = "file.recv.manual.filename";
|
||||
|
||||
/** 큐에서 가져오는 최대 갯수. 없으면 하나만 전송 */
|
||||
public static final String SEND_MAX_ITERATION = "send.max.iteration";
|
||||
|
||||
public final static String PHASECODE_NORMAL_END = "END";
|
||||
|
||||
private SFTPConstants() {
|
||||
// no construct
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package com.eactive.eai.adapter.ftp;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
import org.apache.commons.net.ftp.FTPClient;
|
||||
import org.apache.commons.net.ftp.FTPReply;
|
||||
|
||||
import com.eactive.eai.batch.doc.BatchDoc;
|
||||
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
|
||||
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
|
||||
//public abstract class Transfer extends Thread implements SocketService {
|
||||
public abstract class Transfer{
|
||||
|
||||
//리모트 전송 프라퍼티 정보
|
||||
public static final String DIRECTION_SEND = "송신"; //DB에 입력되는 값
|
||||
public static final String DIRECTION_RECEIVE = "수신"; //DB에 입력되는 값
|
||||
|
||||
public static final String SEND_SCRIPT_PATH = "script.send"; //VAN 송신 쉘스크립트 경로
|
||||
public static final String RECV_SCRIPT_PATH = "script.recv"; //VAN 수신 쉘스크립트 경로
|
||||
public static final String SEND_TITLE = "send.title"; //VAN 송신 TITLE
|
||||
public static final String RECV_TITLE = "recv.title"; //VAN 송신 TITLE
|
||||
public static final String ORG_ID = "org.id"; //상대방 ID
|
||||
|
||||
//sftp 20220713
|
||||
protected static final String CONNECTION_TIMEOUT = "connection.timeout";
|
||||
protected static final String READ_TIMEOUT = "read.timeout";
|
||||
protected static final String BADNWIDTH = "io.bandwidth";
|
||||
|
||||
protected long firstActivity;
|
||||
protected long lastActivity;
|
||||
|
||||
protected Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
protected String scriptErrorMsg = "";
|
||||
protected String scriptOutputMsg = "";
|
||||
protected FTPClient ftpClient = null;
|
||||
|
||||
/** 인증 방법 1 = id, 2 = key 방식 */
|
||||
public static final String AUTH_TYPE = "sftp.auth.type";
|
||||
public static final String AUTH_TYPE_ID = "1";
|
||||
public static final String AUTH_TYPE_KEY = "2";
|
||||
|
||||
//protected static EAIBatchMessageDocument batchDoc;
|
||||
|
||||
public static void sendFileByEvent(BatchDoc batchDoc) throws Exception {
|
||||
transferFileByEvent(DIRECTION_SEND, batchDoc);
|
||||
}
|
||||
|
||||
public static void recvFileByEvent(BatchDoc batchDoc) throws Exception {
|
||||
transferFileByEvent(DIRECTION_RECEIVE, batchDoc);
|
||||
}
|
||||
//-------------------------------------------------------------------------------------------
|
||||
//
|
||||
//-------------------------------------------------------------------------------------------
|
||||
public static void transferFileByEvent(String sendRecvType, BatchDoc batchDoc) throws Exception {
|
||||
Logger logger = (Logger) batchDoc.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer] ■ Event 송수신 시작......");
|
||||
|
||||
//파라미터 체크
|
||||
if (!sendRecvType.equals(DIRECTION_SEND) && !sendRecvType.equals(DIRECTION_RECEIVE)) throw new Exception("{송수신구분} 파라미터 오류");
|
||||
|
||||
String protocol = batchDoc.getBatchMsg().getHeader().getRuleCode();
|
||||
|
||||
String className = Transfer.class.getName();
|
||||
className = className.substring(0, className.lastIndexOf('.')+1) + protocol;
|
||||
// logger.debug("[Transfer]className-->" + className + "<--");
|
||||
@SuppressWarnings("rawtypes")
|
||||
Class cl = Class.forName(className);
|
||||
Transfer transfer = (Transfer)cl.newInstance();
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// 파일 송수신 수행
|
||||
transfer.transferFile(sendRecvType, batchDoc);
|
||||
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer] ■ VAN사 모듈 송수신 완료.");
|
||||
}
|
||||
|
||||
public void transferFile( String sendRecvType, BatchDoc batchDoc) throws Exception {
|
||||
logger = (Logger) batchDoc.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer] ■ 파일 송수신 수행 시작......");
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer] ⓟ 송수신구분 : ["+ sendRecvType +"] (송신: EAI→VAN사, 수신: VAN사→EAI)");
|
||||
|
||||
try {
|
||||
if (sendRecvType.equals(DIRECTION_SEND)) {
|
||||
//// =================================================================
|
||||
//// 송신 (EAI -> VAN)
|
||||
//// =================================================================
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer] ▶ 파일 송신...");
|
||||
sendFile(batchDoc);
|
||||
} else if (sendRecvType.equals(DIRECTION_RECEIVE)) {
|
||||
// =================================================================
|
||||
// 수신 (VAN -> EAI)
|
||||
// =================================================================
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer] ▶ 파일 수신...");
|
||||
recvFile(batchDoc);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new Exception("FTP 모듈 이용한 파일 송수신 실패!\n caused by..."+ ex.toString());
|
||||
}
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer] ■ 파일 송수신 수행 완료.");
|
||||
|
||||
}
|
||||
|
||||
protected void runSystemScript(String[] command) throws Exception {
|
||||
|
||||
String cmdLine = command[0];
|
||||
for ( int inx=1; inx < command.length; inx++)
|
||||
cmdLine += " " + command[inx];
|
||||
logger.info("[VAN송수신] [Runtime.Exec] ▶ System Command Runtime 수행 시작...");
|
||||
logger.info("[VAN송수신] [Runtime.Exec] ⓟ Command : ["+ cmdLine +"]");
|
||||
|
||||
//1. System Shell 명령어를 Runtime 으로 실행
|
||||
Process process = Runtime.getRuntime().exec(command);
|
||||
|
||||
//2. Runtime 실행 결과 저장
|
||||
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
|
||||
String errorLine = null;
|
||||
StringBuffer errorBuffer = new StringBuffer();
|
||||
try {
|
||||
while ((errorLine = errorReader.readLine()) != null) {
|
||||
if (errorBuffer.length() > 0) errorBuffer.append("\n");
|
||||
errorBuffer.append(errorLine);
|
||||
logger.debug("[VAN송수신] [Runtime.Exec] stderr> "+ errorLine);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error( e.getMessage(), e );
|
||||
}
|
||||
|
||||
BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
String outputLine = null;
|
||||
StringBuffer outputBuffer = new StringBuffer();
|
||||
|
||||
try {
|
||||
while ((outputLine = outputReader.readLine()) != null) {
|
||||
if (outputBuffer.length() > 0) outputBuffer.append("\n");
|
||||
outputBuffer.append(outputLine);
|
||||
logger.debug("[VAN송수신] [Runtime.Exec] stdout> "+ outputLine);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error( e.getMessage(), e );
|
||||
}
|
||||
|
||||
int exitVal = process.waitFor();
|
||||
|
||||
scriptErrorMsg = errorBuffer.toString();
|
||||
scriptOutputMsg = outputBuffer.toString();
|
||||
|
||||
logger.info("[VAN송수신] [Runtime.Exec] ☞ Exit Value : "+ exitVal);
|
||||
logger.info("[VAN송수신] [Runtime.Exec] ▶ System Command Runtime 수행 완료.");
|
||||
|
||||
String errMsg = "Runtime.Exec 으로 실행한 Command exit value ("+ exitVal +") 가 정상이 아닙니다. \n" +
|
||||
"(Command : "+ cmdLine +")\n" +
|
||||
"(STDOUT : "+ scriptErrorMsg +"\n" +
|
||||
"(STDERR : "+ scriptOutputMsg ;
|
||||
if (exitVal != 0) throw new Exception(errMsg);
|
||||
}
|
||||
|
||||
protected void connect(String ipaddress, int port) throws Exception {
|
||||
|
||||
try {
|
||||
|
||||
if (port < 1) {
|
||||
logger.warn("[com.eactive.eai.adapter.ftp.Transfer]해당 서버["+ port +"] 에 연결할 FTP 포트번호가 주어지지 않았습니다. 디폴트 포트번호 '21' 을 설정합니다.");
|
||||
port = 21;
|
||||
}
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer]▶ FTP 서버 연결 시도... " + ipaddress + ":" + port);
|
||||
|
||||
|
||||
if (ftpClient!=null && ftpClient.isConnected()) {
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer]▶ 해당 FTP 서버에 이미 연결되어 있습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
ftpClient = new FTPClient();
|
||||
ftpClient.setControlEncoding("EUC-KR");
|
||||
ftpClient.connect(ipaddress, port);
|
||||
|
||||
int reply = ftpClient.getReplyCode();
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer] ☞ 응답코드 : "+ reply);
|
||||
|
||||
if (!FTPReply.isPositiveCompletion(reply)) {
|
||||
try {
|
||||
logger.error("[com.eactive.eai.adapter.ftp.Transfer] FTP 서버 연결에 실패하였습니다.");
|
||||
ftpClient.disconnect();
|
||||
|
||||
} catch (Exception ex) {
|
||||
logger.error("[com.eactive.eai.adapter.ftp.Transfer] FTP 서버 연결에 실패후 에러 발생하였습니다.", ex);
|
||||
}
|
||||
throw new Exception("FTP 연결 응답코드("+ reply +") 가 비정상입니다.");
|
||||
}
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer] ▶ FTP 서버에 연결되었습니다.");
|
||||
|
||||
} catch (Exception ex) {
|
||||
String errMsg = "FTP 연결 오류!\n caused by..."+ ex.toString();
|
||||
logger.error(errMsg, ex);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
//-------------------------------------------------------------------------------------------
|
||||
//
|
||||
//-------------------------------------------------------------------------------------------
|
||||
public void disconnect() {
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer] ▶ FTP 서버 연결 해제 시도...");
|
||||
try {
|
||||
if (ftpClient!=null && ftpClient.isConnected()) ftpClient.disconnect();
|
||||
logger.info("[com.eactive.eai.adapter.ftp.Transfer] ▶ FTP 서버 연결이 해제 되었습니다.");
|
||||
} catch (Exception ex) {
|
||||
logger.error( ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
public abstract void sendFile( BatchDoc batchDoc) throws Exception;
|
||||
|
||||
public abstract void recvFile( BatchDoc batchDoc ) throws Exception;
|
||||
|
||||
//파일 송수신 시 파일의 헤더, 트레일러 값을 배치메시지에 설정
|
||||
public void setFileHeaderAndTrailer(BatchDoc batchDoc, File f) {
|
||||
|
||||
//파일이 존재하지 않거나 디렉토리면 리턴
|
||||
if (f == null || !f.exists() || f.isDirectory()) {
|
||||
logger.info( "["+ (f==null? "": f.getAbsolutePath()) +"]: 파일이 존재하지 않거나 디렉토리입니다. 파일헤더,트레일러 설정안함.");
|
||||
return;
|
||||
}
|
||||
|
||||
FileInputStream fin = null;
|
||||
try {
|
||||
long fileHeaderSize = 500; //파일헤더 로그 디폴트 사이즈
|
||||
long fileTrailerSize = 500; //파일트레일러 로그 디폴트 사이즈
|
||||
BatchJobInfoVO jobInfo = DirInfoManager.getInstance().getFileInfo(batchDoc.getBatchMsg().getHeader().getJobCode());
|
||||
if (jobInfo != null) {
|
||||
fileHeaderSize = jobInfo.getFileHeaderLogSize();
|
||||
fileTrailerSize = jobInfo.getFileTrailerLogSize();
|
||||
}
|
||||
|
||||
if (fileHeaderSize == 0 && fileTrailerSize == 0) return;
|
||||
|
||||
fin = new FileInputStream(f);
|
||||
long fileSize = f.length();
|
||||
|
||||
//DB값, 파일사이즈, 4000Byte(로그저장 varchar 최대값) 중 최소값 설정
|
||||
fileHeaderSize = Math.min(Math.min(fileHeaderSize , fileSize), 4000L);
|
||||
fileTrailerSize = Math.min(Math.min(fileTrailerSize, fileSize), 4000L);
|
||||
|
||||
byte[] bufHeader = new byte[(int)fileHeaderSize ];
|
||||
byte[] bufTrailer = new byte[(int)fileTrailerSize];
|
||||
int readSize = 0;
|
||||
|
||||
//파일 헤더 값 READ
|
||||
if (fileHeaderSize > 0) {
|
||||
readSize = fin.read(bufHeader, 0, bufHeader.length);
|
||||
}
|
||||
|
||||
//파일 트레일러 값 READ
|
||||
if (fileTrailerSize > 0 && readSize >= 0 && readSize <= fileSize) {
|
||||
int overlapSize = 0; //헤더와 트레일러의 겹치는 Byte 사이즈
|
||||
long skipSize = (fileSize - readSize) - fileTrailerSize;
|
||||
|
||||
if (skipSize > 0) { //헤더와 트레일러가 겹치지 않음 -> 트레일러까지 위치 이동
|
||||
fin.skip(skipSize);
|
||||
|
||||
} else if (skipSize < 0) { //헤더와 트레일러가 겹침 -> 오버랩핑되는 헤더의 뒷부분을 트레일러의 앞부분으로 카피
|
||||
overlapSize = Math.abs((int)skipSize);
|
||||
System.arraycopy(bufHeader, readSize - overlapSize, bufTrailer, 0, overlapSize);
|
||||
}
|
||||
if (readSize < fileSize) {
|
||||
readSize = fin.read(bufTrailer, overlapSize, bufTrailer.length - overlapSize);
|
||||
}
|
||||
}
|
||||
|
||||
batchDoc.getBatchMsg().setFileHeader(new String(bufHeader));
|
||||
batchDoc.getBatchMsg().setFileTrailer(new String(bufTrailer));
|
||||
|
||||
} catch (Exception ex) {
|
||||
logger.error( "★★★★★ 파일내용 헤더, 트레일러 DB로그 설정시 오류 발생 !! ★★★★★", ex);
|
||||
} finally {
|
||||
try { if (fin != null) fin.close(); } catch (Exception e) {}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.eactive.eai.adapter.listener;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Adapter 통신 시 예외처리를 위한 Exception
|
||||
* 2. 처리 개요 :
|
||||
* * - Adapter 예외처리
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : TestCall
|
||||
* @since :JDK v1.4.2
|
||||
*/
|
||||
public class AdapterException extends Exception
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Default 생성자 함수
|
||||
* 2. 처리 개요 :
|
||||
* - Default 생성자 함수
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public AdapterException() {
|
||||
super("AdapterException is occured.");
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : Exception 발생 원인을 저장하는 생성자 함수
|
||||
* 2. 처리 개요 :
|
||||
* - Exception 발생 원인을 저장하는 생성자 함수
|
||||
* 3. 주의사항
|
||||
*
|
||||
*@param msg Exception 발생 원인
|
||||
**/
|
||||
public AdapterException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.eactive.eai.adapter.listener;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Adapter start 및 stop 작업을 위한 Interface
|
||||
* 2. 처리 개요 :
|
||||
* - Adapter start
|
||||
* - Adapter stop
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : 관련 기능을 참조
|
||||
* @since :
|
||||
*/
|
||||
public interface AdapterListener
|
||||
{
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보를 저장하는 setter method
|
||||
* 2. 처리 개요 :
|
||||
* - 어댑터 정보를 저장한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param info 어댑터 정보 VO
|
||||
**/
|
||||
public void setAdapterInfo(AdapterVO info);
|
||||
|
||||
/**
|
||||
* 1. 기능 : Adapter start
|
||||
* 2. 처리 개요 :
|
||||
* - 해당 어댑터를 시작한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public void start() throws AdapterException;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Adapter stop
|
||||
* 2. 처리 개요 :
|
||||
* - 해당 어댑터를 중지한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public void stop() throws AdapterException;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.eactive.eai.adapter.listener;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : AdapterListener 인터페어스를 구현한 Base 클래스
|
||||
* 2. 처리 개요 :
|
||||
* - AdapterListener 인터페이스의 구현을 위한 Base 클래스
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : AdapterListener, AdapterManager
|
||||
* @since :JDK v1.4.2
|
||||
*/
|
||||
public class AdapterListenerSupport implements AdapterListener
|
||||
{
|
||||
/**
|
||||
* default logger
|
||||
*/
|
||||
protected Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
/**
|
||||
* 어댑터 정보
|
||||
*/
|
||||
protected AdapterVO info;
|
||||
|
||||
/**
|
||||
* 1. 기능 : 어댑터 정보를 저장하는 setter method
|
||||
* 2. 처리 개요 :
|
||||
* - 어댑터 정보를 저장한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param info 어댑터 정보 VO
|
||||
**/
|
||||
public void setAdapterInfo(AdapterVO info) {
|
||||
this.info = info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : Adapter start
|
||||
* 2. 처리 개요 :
|
||||
* - 해당 어댑터를 시작한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public void start() throws AdapterException {
|
||||
if(logger.isDebugEnabled()){
|
||||
logger.debug("[AdapterListener] It is started. - "+info);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : Adapter stop
|
||||
* 2. 처리 개요 :
|
||||
* - 해당 어댑터를 중지한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public void stop() throws AdapterException {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.eactive.eai.adapter.socket;
|
||||
|
||||
import com.eactive.eai.adapter.WLIDefaultAdapter;
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.service.OutboundControl;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Outbound Socket Adapter를 Access하기 위한 Java Class로 SocketControl에서 사용함.
|
||||
* 2. 처리 개요 :
|
||||
* * - OutboundControl Object를 통해 Outbound Socket을 통해 수동시스템과 Socket인터페이스를 위한
|
||||
* SocketAdapter Class
|
||||
* 3. 주의사항
|
||||
* - Outbound Process에서 Outbound Socket의 Adapter Group Name에 대한 Property를 지정해야한다.
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : 관련 기능을 참조
|
||||
* @since :
|
||||
*/
|
||||
public class SocketAdapter extends WLIDefaultAdapter
|
||||
{
|
||||
public static final String ADAPTER_GORUP_NAME="ADAPTER_GROUP_NAME";
|
||||
|
||||
static SocketAdapter socketAdapter = new SocketAdapter();
|
||||
|
||||
private SocketAdapter() {}
|
||||
|
||||
public static SocketAdapter getInstance()
|
||||
{
|
||||
return socketAdapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : SocketAdapter의 실행 Method
|
||||
* 2. 처리 개요 :
|
||||
* - OutboundControl Object를 생성 후 요청된 메시지를 Assign한 후 CallService를 통해
|
||||
* 해당 Outbound Adapter Group의 Socket Connection을 얻은 후 메시지 송수신에 따른 결과를
|
||||
* 리턴한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param prop WLI OutboundAdapter의 Property정보, SocketAdapter의 경우 ADAPTER_GROUP_NAME
|
||||
* Property Key에 Adapter Group Name을 지정한다.
|
||||
* @param message Outbound process에서 요청하는 메시지 Object로 byte[] 속성의 메시지여야한다.
|
||||
* @return 결과메시지 Object로 SYNC 유형의 경우 byte[] 메시지가 리턴된다.
|
||||
* @exception Exception
|
||||
**/
|
||||
public Object execute(Properties prop, Object message) throws Exception {
|
||||
OutboundControl control = new OutboundControl();
|
||||
String adapterGroupName = prop.getProperty(ADAPTER_GORUP_NAME);
|
||||
control.setAdapterGroupName( adapterGroupName );
|
||||
|
||||
byte[] msg = null;
|
||||
if ( message instanceof byte[]) {
|
||||
msg = (byte[]) message;
|
||||
} else {
|
||||
throw new Exception( CommonLib.getMessage("BECEAIASO003") );
|
||||
}
|
||||
|
||||
return control.callService( adapterGroupName, msg );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.eactive.eai.adapter.socket;
|
||||
|
||||
import com.eactive.eai.adapter.listener.AdapterException;
|
||||
import com.eactive.eai.adapter.listener.AdapterListenerSupport;
|
||||
import com.eactive.eai.adapter.socket.config.*;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Socket Adapter의 기동/중지를 위한 Adapter Listener로 FrameWork에서 SocketAdapter를
|
||||
* 중지/기동하기 위한 Socket Adapter Listener이다.
|
||||
* 2. 처리 개요 :
|
||||
* - SocketAdapterManager Instance를 얻은 후 해당 Adapter에 대한 Stop/Start 기능을 수행한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param
|
||||
* @return
|
||||
* @exception
|
||||
**/
|
||||
public class SocketAdapterListener extends AdapterListenerSupport
|
||||
{
|
||||
|
||||
public void start() throws AdapterException {
|
||||
|
||||
SocketAdapterManager manager = SocketAdapterManager.getInstance();
|
||||
try {
|
||||
manager.start(info); // info : AdapterVO 의 인스탄스
|
||||
} catch(Exception e) {
|
||||
logger.error("[SocketAdapterListener] cannot start : " + e.getMessage(), e);
|
||||
throw new AdapterException("SocketAdapter] start Error. - "+e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() throws AdapterException {
|
||||
|
||||
SocketAdapterManager manager = SocketAdapterManager.getInstance();
|
||||
try {
|
||||
if ( info == null ) throw new Exception(" AdapterVO가 NULL입니다.");
|
||||
manager.stop(info); // info : AdapterVO의 인스탄스
|
||||
} catch(Exception e) {
|
||||
logger.error("[SocketAdapterListener] cannot stop : " + e.getMessage(), e);
|
||||
throw new AdapterException("SocketAdapter] stop Error. - "+e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package com.eactive.eai.adapter.socket.common;
|
||||
|
||||
/**
|
||||
* 1. 기능 : SocketAdapter에서 사용되는 공통기능 제공
|
||||
* 2. 처리 개요 :
|
||||
* -
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param
|
||||
* @return
|
||||
* @exception
|
||||
**/
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.SimpleTimeZone;
|
||||
|
||||
/**
|
||||
* 송수신 메시지 SPEC.
|
||||
* llzz + syncFlag + user data(전문포맷전체를 사용자 DATA로 본다.)
|
||||
* - llzz(2BYTE/4BYTE) UNSIGNED INTEGER로 처리한다. -- ConfigurationContext에 저장
|
||||
* default는 4byte로 한다.
|
||||
* - syncFlag - 'S' - R/R, 'A' - ASYNC, 'K' - ACK ONLY(이 경우, SEVER의 ACK를 받는다.
|
||||
* - llzz+K[ACK|NACK]
|
||||
* - user data,...
|
||||
*
|
||||
*/
|
||||
public class CommonLib {
|
||||
|
||||
public static final char SPACE = ' ';
|
||||
|
||||
public static final char ZERO = '0';
|
||||
|
||||
public static final String EMPTY_STRING = "";
|
||||
|
||||
public static final String EMPTY_STRING_ARRAY[] = new String[0];
|
||||
|
||||
public static final int NEGOTIATING_PROTOCOL = 1;
|
||||
|
||||
public static final int PROCESSING_PROTOCOL = 2;
|
||||
|
||||
public static final byte[] SYNC_PROTOCOL_MESSAGE = "SYNC".getBytes();
|
||||
|
||||
public static final byte[] ASYNC_PROTOCOL_MESSAGE = "ASYN".getBytes();
|
||||
|
||||
public static final byte[] NACK_MESSAGE = "NACK PROTOCOL VIOLATION".getBytes();
|
||||
|
||||
public static final byte[] ACK_MESSAGE = "ACK".getBytes();
|
||||
|
||||
private static final SimpleDateFormat SDF_YYYYMMDDHHMMSSMS_DASH_CEMI_COL = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS" );
|
||||
|
||||
/**
|
||||
* BYTE ARRAY값을 HEXA STRING으로 변환하여 String을 리턴한다.
|
||||
* @param abyte
|
||||
* @return
|
||||
*/
|
||||
public static String byte2Hex(byte[] abyte) {
|
||||
StringBuffer s = new StringBuffer();
|
||||
if (abyte == null)
|
||||
return s.toString();
|
||||
for (int i = 0; i < abyte.length; i++)
|
||||
s.append( Integer.toHexString((abyte[i] & 0xf0) >> 4).toUpperCase() ).append( Integer.toHexString(abyte[i] & 0xf).toUpperCase() );
|
||||
return s.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* HEXA String값을 BYTE ARRAY로 변환한다.
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
public static byte[] hex2Bytes(String s) {
|
||||
byte abyte[] = new byte[s.length() / 2];
|
||||
for (int j = 0; j < abyte.length; j++)
|
||||
abyte[j] = (byte) Integer.parseInt(s.substring(2 * j, 2 * j + 2), 16);
|
||||
return abyte;
|
||||
}
|
||||
|
||||
public static java.lang.String getCurrentDateTime() { // YYYYMMDDHHMMSS
|
||||
return (new SimpleDateFormat("yyyyMMddHHmmss")).format(new java.util.Date());
|
||||
}
|
||||
|
||||
public static String getCurrentTime(long timeLong)
|
||||
{
|
||||
// 1hour(ms) = 60s * 60m * 1000ms
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
|
||||
sdf.setTimeZone(new SimpleTimeZone(9 * 60 * 60 * 1000, "KST"));
|
||||
return sdf.format(new java.util.Date(timeLong));
|
||||
} // end of getCurrentTime()
|
||||
|
||||
public static String getDate(long timeLong)
|
||||
{
|
||||
// 1hour(ms) = 60s * 60m * 1000ms
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
sdf.setTimeZone(new SimpleTimeZone(9 * 60 * 60 * 1000, "KST"));
|
||||
return sdf.format(new java.util.Date(timeLong));
|
||||
} // end of getCurrentTime()
|
||||
|
||||
public static String getTimestamp() {
|
||||
return (SDF_YYYYMMDDHHMMSSMS_DASH_CEMI_COL).format(new java.util.Date());
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 String값을 주어진 길이많큼 Padding/Trim한다.
|
||||
* @param svalue - 입력스트링
|
||||
* @param isRightJustify - true이면 RIGHT JUSTIFY, false이면 LEFT JUSTIFY
|
||||
* @param padding - Padding 문자
|
||||
* @param length - 리턴할 스트링의 바이트수
|
||||
* @return 포맷팅된 String결과
|
||||
*/
|
||||
public static String stringFormat(String svalue, boolean isRightJustify, char padding, int length) {
|
||||
if ( svalue == null ) return svalue;
|
||||
|
||||
StringBuffer mpad = new StringBuffer();
|
||||
StringBuffer fmtStr = new StringBuffer();
|
||||
|
||||
String tvalue = svalue;
|
||||
int pLength = 0;
|
||||
|
||||
pLength = length - svalue.getBytes().length;
|
||||
|
||||
if (pLength == 0)
|
||||
return svalue;
|
||||
else if ( pLength < 0) {
|
||||
byte[] abytes = null;
|
||||
if (isRightJustify) {
|
||||
abytes = (new String( svalue.getBytes(), -(pLength), length)).getBytes();
|
||||
} else {
|
||||
abytes = (new String( svalue.getBytes(), 0, length)).getBytes();
|
||||
}
|
||||
|
||||
if ( abytes.length == length ) {
|
||||
return new String( abytes );
|
||||
} else {
|
||||
tvalue = new String( abytes );
|
||||
pLength = length - tvalue.length();
|
||||
}
|
||||
}
|
||||
|
||||
for(int i =0; i < pLength ; i++) {
|
||||
mpad.append( padding );
|
||||
}
|
||||
|
||||
if ( isRightJustify ) {
|
||||
return fmtStr.append(mpad).append(tvalue).toString();
|
||||
} else {
|
||||
return fmtStr.append(tvalue).append(mpad).toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static java.lang.String getFormatString(long value, int length)
|
||||
{
|
||||
DecimalFormat df = new DecimalFormat("000000000000000000");
|
||||
String fs = df.format( value );
|
||||
return fs.substring(fs.length() - length);
|
||||
}
|
||||
|
||||
public static java.lang.String getFormatString(int value, int length)
|
||||
{
|
||||
DecimalFormat df = new DecimalFormat("000000000000000000");
|
||||
String fs = df.format((long)value);
|
||||
return fs.substring(fs.length() - length);
|
||||
}
|
||||
|
||||
/**
|
||||
* 메시지 비교
|
||||
*/
|
||||
public static boolean compare(byte[] source, byte[] target) {
|
||||
if ( source.length != target.length ) return false;
|
||||
|
||||
for ( int i=0; i < source.length; i++ ) {
|
||||
if ( source[i] != target[i] ) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 송수신전문에 대한 DUMP를 프린트할 수 있는 포맷으로 변환하여 String Array로 리턴한다.
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
public static String[] makeDumpFormat(byte[] bytes) {
|
||||
if (bytes == null || bytes.length == 0)
|
||||
return CommonLib.EMPTY_STRING_ARRAY;
|
||||
|
||||
String[] dumps = new String[bytes.length / 16 + ((bytes.length % 16) == 0 ? 4 : 5)];
|
||||
dumps[0] = "/==========.========================================..==================.";
|
||||
dumps[1] = "| Offset | 0 1 2 3 4 5 6 7 8 9 A B C D E F || U S E R D A T A |";
|
||||
dumps[2] = "|----------+----------------------------------------||------------------|";
|
||||
dumps[dumps.length - 1] = "'=========='========================================''==================/";
|
||||
|
||||
int len = 0;
|
||||
byte PERIOD = 0x2E;
|
||||
char aChar = ' ';
|
||||
boolean isDBCS = false;
|
||||
boolean isHalfDBCS = false;
|
||||
|
||||
for (int i = 3; i < dumps.length - 1; i++) {
|
||||
len = ( ((bytes.length - (i - 2) * 16) >= 0) ? 16 : (bytes.length - (i - 3)*16) );
|
||||
byte[] buf = new byte[len];
|
||||
System.arraycopy( bytes, (i-3)*16, buf, 0, len );
|
||||
StringBuffer strBuf = new StringBuffer();
|
||||
//dumps[i] = EMPTY_STRING;
|
||||
|
||||
strBuf.append("| ").append( stringFormat( new String( Integer.toHexString((i-3)*16) ).toUpperCase(), true, ZERO, 8) ).append(" | ");
|
||||
|
||||
String hexStr = byte2Hex( buf );
|
||||
StringBuffer fmtStr = new StringBuffer();
|
||||
|
||||
int k = hexStr.length()/8 + ((hexStr.length() % 8) == 0 ? 0 : 1);
|
||||
for (int j=0; j < k ; j++) {
|
||||
int l = ((hexStr.length() - (j+1)*8 ) >= 0 ? 8 : (hexStr.length() - j*8 ));
|
||||
fmtStr.append( hexStr.substring(j*8, j*8 + l ) ).append(" ");
|
||||
}
|
||||
|
||||
strBuf.append( stringFormat(fmtStr.toString(), false, SPACE, 39) ).append("|| ");
|
||||
|
||||
k = 0;
|
||||
// 한글 및 특수문자가 깨지게 표시되는 것 을 방지한다.
|
||||
for ( int j=0; j < len; j++) {
|
||||
if ( buf[j] >> 7 == 0 ) {
|
||||
// Single Byte Character
|
||||
if ( isDBCS ) {
|
||||
isDBCS = false;
|
||||
if ( k != 0 && ((k % 2) == 1 )) {
|
||||
buf[j - 1] = PERIOD;
|
||||
}
|
||||
}
|
||||
aChar = (char)buf[j];
|
||||
if ( Character.isWhitespace( aChar ) || Character.isISOControl( aChar ) || buf[j] == 0 ) {
|
||||
buf[j] = PERIOD;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Double Bytes Character.
|
||||
if ( !isDBCS ) isDBCS = true;
|
||||
if ( j == 0 && isHalfDBCS ) {
|
||||
buf[j] = PERIOD;
|
||||
isDBCS = false;
|
||||
continue;
|
||||
}
|
||||
// To check the DBCS pairwise
|
||||
k++;
|
||||
}
|
||||
if ( isDBCS && ((k%2)==1) ) {
|
||||
buf[ len -1 ] = PERIOD;
|
||||
isHalfDBCS = true;
|
||||
} else {
|
||||
isHalfDBCS = false;
|
||||
}
|
||||
|
||||
dumps[i] = strBuf.append( stringFormat(new String(buf), false, SPACE, 16) ).append(" |").toString();
|
||||
}
|
||||
return dumps;
|
||||
}
|
||||
|
||||
public static String getDumpMessage( byte[] message ) {
|
||||
String[] dumpMsg = makeDumpFormat( message );
|
||||
StringBuffer dump = new StringBuffer();
|
||||
dump.append("\n");
|
||||
for(int i=0; i < dumpMsg.length; i++) {
|
||||
dump.append( dumpMsg[i] ).append("\n");
|
||||
}
|
||||
|
||||
return dump.toString();
|
||||
}
|
||||
|
||||
public static String getMessage(String msgCode, String[] params) {
|
||||
return ExceptionUtil.getErrorCode(msgCode, params);
|
||||
}
|
||||
|
||||
public static String getMessage(String msgCode) {
|
||||
return ExceptionUtil.getErrorCode(msgCode);
|
||||
}
|
||||
|
||||
public static String getDebugMessage(String msgCode, String[] params) {
|
||||
return ExceptionUtil.getErrorCode(msgCode, params);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.eactive.eai.adapter.socket.common;
|
||||
|
||||
public class DiagLogger {
|
||||
|
||||
public static final int DEFAULT = 0; // WARNING, ERROR, FATAL인 경우 에러로깅
|
||||
public static final int INFO = 1; // INFO 수준의 LOGGING을 수행한다.
|
||||
public static final int DEBUG = 2; // DEBUG 수준의 송수신전문 및 에러 메인처리내용의 모든수준의 로깅을 수행한다.
|
||||
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Created on 2005. 2. 26.
|
||||
*
|
||||
*/
|
||||
package com.eactive.eai.adapter.socket.common;
|
||||
|
||||
/**
|
||||
* @author janet
|
||||
*
|
||||
*/
|
||||
public class SocketAdapterException extends Exception {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static final int UNEXPECTED_TERMINATION = 1;
|
||||
|
||||
public static final int REMOTE_HOST_DISCONNECTED = 2;
|
||||
|
||||
public static final int INTERNAL_ERROR = 5;
|
||||
|
||||
public static final int CHANNEL_FAILURE = 6;
|
||||
|
||||
public static final int CANCELLED_CONNECTION = 8;
|
||||
|
||||
public static final int CONNECT_FAILED = 10;
|
||||
|
||||
public static final int CONNECTION_CLOSED = 12;
|
||||
|
||||
public static final int AGENT_ERROR = 13;
|
||||
|
||||
public static final int SESSION_STREAM_ERROR = 15;
|
||||
|
||||
int reason;
|
||||
|
||||
Throwable cause;
|
||||
|
||||
/**
|
||||
* Create an exception with the given description and reason.
|
||||
* @param msg
|
||||
* @param reason
|
||||
*/
|
||||
|
||||
public SocketAdapterException(String msg, int reason) {
|
||||
this(msg, reason, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an exception with the given cause and reason.
|
||||
* @param reason
|
||||
* @param cause
|
||||
*/
|
||||
public SocketAdapterException(int reason, Throwable cause) {
|
||||
this(null, reason, cause);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an exception with the given description and cause. The reason given
|
||||
* will be <code>INTERNAL_ERROR</code>.
|
||||
*
|
||||
* @param msg
|
||||
* @param cause
|
||||
*/
|
||||
public SocketAdapterException(String msg, Throwable cause) {
|
||||
this(msg, INTERNAL_ERROR, cause);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param msg
|
||||
*/
|
||||
public SocketAdapterException(String msg) {
|
||||
this(msg, INTERNAL_ERROR, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an exception by providing the cause of the error. This constructor
|
||||
* sets the reason to INTERNAL_ERROR.
|
||||
* @param cause
|
||||
*/
|
||||
public SocketAdapterException(Throwable cause) {
|
||||
this("An unexpected exception was caught: " + cause.getMessage(), cause);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an exception with the given description cause, reason.
|
||||
* @param msg
|
||||
* @param reason
|
||||
* @param cause
|
||||
*/
|
||||
public SocketAdapterException(String msg, int reason, Throwable cause) {
|
||||
super(msg);
|
||||
this.cause = cause;
|
||||
this.reason = reason;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the reason for the exception
|
||||
* @return
|
||||
*/
|
||||
public int getReason() {
|
||||
return reason;
|
||||
}
|
||||
|
||||
/**
|
||||
* If an INTERNAL_ERROR reason is given this method MAY return the cause of
|
||||
* the error.
|
||||
* @return
|
||||
*/
|
||||
public Throwable getCause() {
|
||||
return cause;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.eactive.eai.adapter.socket.common;
|
||||
|
||||
public class StopWatch {
|
||||
private long startTime = -1;
|
||||
private long stopTime = -1;
|
||||
|
||||
public StopWatch() {
|
||||
}
|
||||
|
||||
public void start() {
|
||||
this.startTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
this.stopTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
this.startTime = -1;
|
||||
this.stopTime = -1;
|
||||
}
|
||||
|
||||
public long getTime() {
|
||||
if (stopTime == -1) {
|
||||
return (System.currentTimeMillis() - this.startTime);
|
||||
} else {
|
||||
return (this.stopTime - this.startTime);
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return getTimeString();
|
||||
}
|
||||
|
||||
protected String getTimeString() {
|
||||
int HIM = 60 * 60 * 1000;
|
||||
int MIM = 60 * 1000;
|
||||
int hours;
|
||||
int minutes;
|
||||
int seconds;
|
||||
int milliseconds;
|
||||
long time = getTime();
|
||||
hours = (int) (time / HIM);
|
||||
time = time - (hours * HIM);
|
||||
minutes = (int) (time / MIM);
|
||||
time = time - (minutes * MIM);
|
||||
seconds = (int) (time / 1000);
|
||||
time = time - (seconds * 1000);
|
||||
milliseconds = (int) time;
|
||||
|
||||
return hours + "h:" + minutes + "m:" + seconds + "s:" + milliseconds + "ms";
|
||||
}
|
||||
|
||||
static public void main(String[] strs) {
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
try {
|
||||
Thread.currentThread();
|
||||
Thread.sleep(1500);
|
||||
} catch (InterruptedException ie) {
|
||||
// ignore
|
||||
;
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
package com.eactive.eai.adapter.socket.config;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
|
||||
/**
|
||||
* 1. 기능 : SocketAdapter의 구성정보 및 속성을 나타내는 Object Class
|
||||
* 2. 처리 개요 :
|
||||
* - 구성정보의 DEFAULT값을 갖고 있으며, 각 속성에 대한 getter/setter 기능을 제공한다.
|
||||
* 3. 주의사항
|
||||
* - 해당 Property의 기본속성값을 확인하여, 해당 Property의 속성지정을 생략시 어떤 값을 갖는지
|
||||
* 확인하여야한다.
|
||||
* @param
|
||||
* @return
|
||||
* @exception
|
||||
**/
|
||||
|
||||
public class ConfigurationContext implements Serializable {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
public static final String INBOUND_SOCKET = "INBOUND";
|
||||
public static final String OUTBOUND_SOCKET = "OUTBOUND";
|
||||
public static final String IOBOUND_SOCKET = "IOBOUND";
|
||||
|
||||
public static final String SERVER_SOCKET = "SERVER";
|
||||
public static final String CLIENT_SOCKET = "CLIENT";
|
||||
public static final String ADMIN_SOCKET = "ADMIN";
|
||||
|
||||
public static final String SYNC_MODE = "SYNC";
|
||||
public static final String ASYNC_MODE = "ASYN";
|
||||
|
||||
public static final String TRUE_FLAG = "Y";
|
||||
public static final String FALSE_FLAG = "N";
|
||||
|
||||
/**
|
||||
* Configuration properties
|
||||
*/
|
||||
private String adapterGroupName = ""; // SOCKET ADADAPTER GROUP NAME
|
||||
private String adapterName = ""; // SOCKET ADAPTER 구성 이름
|
||||
|
||||
private String boundUsage = INBOUND_SOCKET; // INBOUND | OUTBOUND
|
||||
private String socketType = SERVER_SOCKET; // SERVER | CLIENT
|
||||
|
||||
private String hostName = "localhost"; // BIND할 서버의 호스트명 또는 IP ADDRESS
|
||||
private int portNumber = 0; // BIND할 서버의 PORT NUMBER
|
||||
|
||||
private String localHostName = ""; // Client Socket Type에 한하여 설정
|
||||
private int localPortNumber = 0; // Client Socket Type으로 원격서버와 연결시 BIND할localPortNumber
|
||||
|
||||
private int connLimitPerIp = 0; // SERVER TYPE SOCKET의 경우 REMOTE의 특정 IP별 CONNECTION 수를 제한시키는 것
|
||||
private int maxConnection = 1; // 원격시스템과 Socket Connection 최대허용 수
|
||||
// Server Socket의 경우 - Server Listening port로 접속허용할 최대 수
|
||||
// Client Socket의 경우 - Remote Host의 지정 포트로 연결할 최대 Connection 수
|
||||
|
||||
private int defaultSession = 2; // Inbound의 Default Session 유지 수
|
||||
private int maxSession = 5; // INBOUND의 경우한하여 의미가 있음.
|
||||
// Socket Adapter의 N개의 Connection에 대해 WLI session을 연결할 최대 수 (실행 Thread Pool의 Session수)
|
||||
|
||||
private int timeout = 0; // SOCKET READ TIMEOUT값 설정
|
||||
// 송수신 메시지의 Socket Read Timeout값을 설정 (단위 : 초) [timeout으로 변경]
|
||||
|
||||
private int sessionTimeout = 10; // 10초의 Session Timeout Time
|
||||
|
||||
private String responseType = SYNC_MODE; // SYNC_MODE, ASYNC_MODE
|
||||
private String socketReuse = TRUE_FLAG; // "Y" - Socket Connection reuse
|
||||
// "N" - try to connect each transaction
|
||||
|
||||
private int llFieldIndex = 0; // LL필드 시작 Index
|
||||
private int llFieldLength = 2; // LL필드길이 2-unsigned short, 4 ~ 8 Numeric Char
|
||||
private String ackProtocol = FALSE_FLAG; // ACK송수신 여부 -- Client Type의 Socket에 적용되며, 서버는 Protocol에 의해 작동판단...
|
||||
|
||||
private String bwkClsCd = ""; // 업무구분코드
|
||||
private boolean responseOnly = false; // 어댑터가 응답전용모드인지 여부
|
||||
private boolean usePollMsg = false; // polling 여부
|
||||
|
||||
private int traceLevel = DiagLogger.DEFAULT; // 추적관리 수준 - 0, 1, 2
|
||||
private String description = ""; // Socket Adapter Configuration에 대한 용도설명
|
||||
//
|
||||
private boolean started = true;
|
||||
|
||||
|
||||
private AdapterVO adapterInfo = null;
|
||||
|
||||
public void setAdapterVO(AdapterVO info) {
|
||||
this.adapterInfo = info;
|
||||
}
|
||||
|
||||
public AdapterVO getAdapterVO() {
|
||||
return this.adapterInfo;
|
||||
}
|
||||
|
||||
|
||||
public ConfigurationContext() {
|
||||
}
|
||||
|
||||
public ConfigurationContext(String adapterGroupName, String adapterName, String boundUsage, String socketType,
|
||||
String hostName, int portNumber ) {
|
||||
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
this.adapterName = adapterName;
|
||||
this.boundUsage = boundUsage;
|
||||
this.socketType = socketType;
|
||||
this.hostName = hostName;
|
||||
this.portNumber = portNumber;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the adapterGroupName.
|
||||
*/
|
||||
public String getAdapterGroupName() {
|
||||
return adapterGroupName;
|
||||
}
|
||||
/**
|
||||
* @param adapterGroupName The adapterGroupName to set.
|
||||
*/
|
||||
public void setAdapterGroupName(String adapterGroupName) {
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
}
|
||||
/**
|
||||
* @return Returns the defaultSession.
|
||||
*/
|
||||
public int getDefaultSession() {
|
||||
return defaultSession;
|
||||
}
|
||||
/**
|
||||
* @param defaultSession The defaultSession to set.
|
||||
*/
|
||||
public void setDefaultSession(
|
||||
int defaultSession) {
|
||||
this.defaultSession = defaultSession;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the socketReuse.
|
||||
*/
|
||||
public String getSocketReuse() {
|
||||
return socketReuse;
|
||||
}
|
||||
/**
|
||||
* @return Returns the connLimitPerIp.
|
||||
*/
|
||||
public int getConnLimitPerIp() {
|
||||
return connLimitPerIp;
|
||||
}
|
||||
/**
|
||||
* @param connLimitPerIp The connLimitPerIp to set.
|
||||
*/
|
||||
public void setConnLimitPerIp(int connLimitPerIp) {
|
||||
this.connLimitPerIp = connLimitPerIp;
|
||||
}
|
||||
/**
|
||||
* @return Returns the adapterName.
|
||||
*/
|
||||
public String getAdapterName() {
|
||||
return adapterName;
|
||||
}
|
||||
/**
|
||||
* @param adapterName The adapterName to set.
|
||||
*/
|
||||
public void setAdapterName(String adapterName) {
|
||||
this.adapterName = adapterName;
|
||||
}
|
||||
/**
|
||||
* @return Returns the bizCode.
|
||||
*/
|
||||
public String getBwkClsCd() {
|
||||
return bwkClsCd;
|
||||
}
|
||||
/**
|
||||
* @param bizCode The bizCode to set.
|
||||
*/
|
||||
public void setBwkClsCd(String bizCode) {
|
||||
this.bwkClsCd = bizCode;
|
||||
}
|
||||
|
||||
public String getAckProtocol() {
|
||||
return ackProtocol;
|
||||
}
|
||||
/**
|
||||
* @param bizCode The bizCode to set.
|
||||
*/
|
||||
public void setAckProtocol(String ackProtocol) {
|
||||
this.ackProtocol = ackProtocol;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the boundUsage.
|
||||
*/
|
||||
public String getBoundUsage() {
|
||||
return boundUsage;
|
||||
}
|
||||
/**
|
||||
* @param boundUsage The boundUsage to set.
|
||||
*/
|
||||
public void setBoundUsage(String boundUsage) {
|
||||
this.boundUsage = boundUsage;
|
||||
}
|
||||
/**
|
||||
* @return Returns the description.
|
||||
*/
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
/**
|
||||
* @param description The description to set.
|
||||
*/
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
/**
|
||||
* @return Returns the hostName.
|
||||
*/
|
||||
public String getHostName() {
|
||||
return hostName;
|
||||
}
|
||||
/**
|
||||
* @param hostName The hostName to set.
|
||||
*/
|
||||
public void setHostName(String hostName) {
|
||||
this.hostName = hostName;
|
||||
}
|
||||
/**
|
||||
* @return Returns the llFieldLength.
|
||||
*/
|
||||
public int getLlFieldIndex() {
|
||||
return llFieldIndex;
|
||||
}
|
||||
/**
|
||||
* @param llFieldLength The llFieldLength to set.
|
||||
*/
|
||||
public void setLlFieldIndex(int llFieldIndex) {
|
||||
this.llFieldIndex = llFieldIndex;
|
||||
}
|
||||
/**
|
||||
* @return Returns the llFieldLength.
|
||||
*/
|
||||
public int getLlFieldLength() {
|
||||
return llFieldLength;
|
||||
}
|
||||
/**
|
||||
* @param llFieldLength The llFieldLength to set.
|
||||
*/
|
||||
public void setLlFieldLength(int llFieldLength) {
|
||||
this.llFieldLength = llFieldLength;
|
||||
}
|
||||
/**
|
||||
* @return Returns the localHostName.
|
||||
*/
|
||||
public String getLocalHostName() {
|
||||
return localHostName;
|
||||
}
|
||||
/**
|
||||
* @param localHostName The localHostName to set.
|
||||
*/
|
||||
public void setLocalHostName(String localHostName) {
|
||||
this.localHostName = localHostName;
|
||||
}
|
||||
/**
|
||||
* @return Returns the localPortNumber.
|
||||
*/
|
||||
public int getLocalPortNumber() {
|
||||
return localPortNumber;
|
||||
}
|
||||
/**
|
||||
* @param localPortNumber The localPortNumber to set.
|
||||
*/
|
||||
public void setLocalPortNumber(int localPortNumber) {
|
||||
this.localPortNumber = localPortNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the maxConnection.
|
||||
*/
|
||||
public int getMaxConnection() {
|
||||
return maxConnection;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param maxConnection The maxConnection to set.
|
||||
*/
|
||||
public void setMaxConnection(
|
||||
int maxConnection) {
|
||||
this.maxConnection = maxConnection;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the maxSession.
|
||||
*/
|
||||
public int getMaxSession() {
|
||||
return maxSession;
|
||||
}
|
||||
/**
|
||||
* @param maxSession The maxSession to set.
|
||||
*/
|
||||
public void setMaxSession(int maxSession) {
|
||||
this.maxSession = maxSession;
|
||||
}
|
||||
/**
|
||||
* @return Returns the portNumber.
|
||||
*/
|
||||
public int getPortNumber() {
|
||||
return portNumber;
|
||||
}
|
||||
/**
|
||||
* @param portNumber The portNumber to set.
|
||||
*/
|
||||
public void setPortNumber(int portNumber) {
|
||||
this.portNumber = portNumber;
|
||||
}
|
||||
/**
|
||||
* @return Returns the readTimeout.
|
||||
*/
|
||||
public int getTimeout() {
|
||||
return timeout;
|
||||
}
|
||||
/**
|
||||
* @param readTimeout The readTimeout to set.
|
||||
*/
|
||||
public void setTimeout(int readTimeout) {
|
||||
this.timeout = readTimeout;
|
||||
}
|
||||
|
||||
public int getSessionTimeout() {
|
||||
return sessionTimeout;
|
||||
}
|
||||
/**
|
||||
* @param readTimeout The readTimeout to set.
|
||||
*/
|
||||
public void setSessionTimeout(int sessionTimeout) {
|
||||
this.sessionTimeout = sessionTimeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the responseType.
|
||||
*/
|
||||
public String getResponseType() {
|
||||
return responseType;
|
||||
}
|
||||
|
||||
public boolean isSyncMode() {
|
||||
return ( this.responseType.equals( SYNC_MODE ) ) ;
|
||||
}
|
||||
|
||||
public boolean isAckProtocol() {
|
||||
return ( this.ackProtocol.equals( TRUE_FLAG ) ) ;
|
||||
}
|
||||
|
||||
public boolean isResponseOnly() {
|
||||
return responseOnly;
|
||||
}
|
||||
|
||||
public void setResponseOnly(boolean responseOnly) {
|
||||
this.responseOnly = responseOnly;
|
||||
}
|
||||
|
||||
public boolean isUsePollMsg() {
|
||||
return usePollMsg;
|
||||
}
|
||||
|
||||
public void setUsePollMsg(boolean usePollMsg) {
|
||||
this.usePollMsg = usePollMsg;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param responseType The responseType to set.
|
||||
*/
|
||||
public void setResponseType(String responseType) {
|
||||
this.responseType = responseType;
|
||||
}
|
||||
/**
|
||||
* @return Returns the socketReuse.
|
||||
*/
|
||||
public boolean isSocketReuse() {
|
||||
return socketReuse.equals( TRUE_FLAG );
|
||||
}
|
||||
/**
|
||||
* @param socketReuse The socketReuse to set.
|
||||
*/
|
||||
public void setSocketReuse(boolean socketReuse) {
|
||||
this.socketReuse = (socketReuse ? TRUE_FLAG : FALSE_FLAG);
|
||||
}
|
||||
|
||||
public void setSocketReuse(String socketReuse) {
|
||||
this.socketReuse = socketReuse;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return Returns the socketType.
|
||||
*/
|
||||
public String getSocketType() {
|
||||
return socketType;
|
||||
}
|
||||
/**
|
||||
* @param socketType The socketType to set.
|
||||
*/
|
||||
public void setSocketType(String socketType) {
|
||||
this.socketType = socketType;
|
||||
}
|
||||
/**
|
||||
* @return Returns the traceLevel.
|
||||
*/
|
||||
public int getTraceLevel() {
|
||||
return traceLevel;
|
||||
}
|
||||
/**
|
||||
* @param traceLevel The traceLevel to set.
|
||||
*/
|
||||
public void setTraceLevel(int traceLevel) {
|
||||
this.traceLevel = traceLevel;
|
||||
}
|
||||
|
||||
public void setStarted(boolean on) {
|
||||
this.started = on;
|
||||
}
|
||||
|
||||
public boolean isStarted() {
|
||||
return this.started;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer strBuff = new StringBuffer();
|
||||
strBuff.append( this.adapterName ).append( " [Adapter의 등록정보입니다. : " );
|
||||
strBuff.append(" adapter.group.name=").append( this.adapterGroupName ).append(",");
|
||||
strBuff.append(" bound.usage=").append( this.boundUsage ).append(",");
|
||||
strBuff.append(" socket.type=").append( this.socketType ).append(",");
|
||||
strBuff.append(" host.name=").append( this.hostName ).append(",");
|
||||
strBuff.append(" port.number=").append( this.portNumber).append(",");
|
||||
strBuff.append(" local.host.name=").append( this.localHostName ).append(",");
|
||||
strBuff.append(" local.port.number=").append( this.localPortNumber ).append(",");
|
||||
if ( this.connLimitPerIp > 0 ) {
|
||||
strBuff.append(" connection.limit.per.ip=").append( this.connLimitPerIp ).append(",");
|
||||
} else {
|
||||
strBuff.append(" connection.limit.per.ip=0(UNLIMITED)" ).append(",");
|
||||
}
|
||||
|
||||
if ( this.maxConnection > 0 ) {
|
||||
strBuff.append(" max.connection=").append( this.maxConnection ).append(",");
|
||||
} else {
|
||||
strBuff.append(" max.connection=0(UNLIMITED)" ).append(",");
|
||||
}
|
||||
|
||||
strBuff.append(" default.session=").append( this.defaultSession ).append(",");
|
||||
strBuff.append(" max.session=").append( this.maxSession ).append(",");
|
||||
strBuff.append(" timeout=").append( this.timeout ).append(",");
|
||||
strBuff.append(" session.timeout=").append( this.sessionTimeout ).append(",");
|
||||
strBuff.append(" response.type=").append( this.responseType ).append(",");
|
||||
strBuff.append(" socket.reuse=").append( this.socketReuse ).append(",");
|
||||
strBuff.append(" ll.field.index=").append( this.llFieldIndex ).append(",");
|
||||
strBuff.append(" ll.field.length=").append( this.llFieldLength ).append(",");
|
||||
strBuff.append(" ack.support=").append( this.ackProtocol ).append(",");
|
||||
strBuff.append(" business.work.class.code=").append( this.bwkClsCd ).append(",");
|
||||
|
||||
if ( this.traceLevel == 2 ) {
|
||||
strBuff.append(" trace.level=").append( this.traceLevel ).append("(DEBUG)").append(",");
|
||||
} else if ( this.traceLevel == 1 ) {
|
||||
strBuff.append(" trace.level=").append( this.traceLevel ).append("(INFO)").append(",");
|
||||
} else {
|
||||
strBuff.append(" trace.level=").append( this.traceLevel ).append("(ERROR)").append(",");
|
||||
}
|
||||
|
||||
strBuff.append(" description=").append(this.description).append("]");
|
||||
|
||||
return strBuff.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.eactive.eai.adapter.socket.config;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Socket Adapter의 구성정보를 지정하기 위한 property의 KEY값을 나타낸다.
|
||||
* 2. 처리 개요 :
|
||||
* -
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param
|
||||
* @return
|
||||
* @exception
|
||||
**/
|
||||
public interface Keys {
|
||||
|
||||
/**
|
||||
* Socket Adapter의 Adapter Group명을 나타낸는 KEY값
|
||||
*/
|
||||
public static final String ADAPTER_GROUP_NAME = "adapter.group.name";
|
||||
|
||||
/**
|
||||
* Socket Adapter가 INBOUND/OUTBOUND/IOBOUND용인지 나타내기위한 KEY값
|
||||
*/
|
||||
public static final String BOUND_USAGE = "bound.usage";
|
||||
|
||||
/**
|
||||
* Socket Adapter의 SOCKET유형이 [SERVER|CLIENT]에 구분을 나타
|
||||
*/
|
||||
public static final String SOCKET_TYPE = "socket.type";
|
||||
public static final String HOST_NAME = "host.name";
|
||||
public static final String PORT_NUMBER = "port.number";
|
||||
public static final String LOCAL_HOST_NAME = "local.host.name";
|
||||
public static final String LOCAL_PORT_NUMBER = "local.port.number";
|
||||
public static final String CONN_LIMIT_PER_IP = "connection.limit.per.ip";
|
||||
public static final String MAX_CONNECTION = "max.connection";
|
||||
public static final String DEFAULT_SESSION = "default.session";
|
||||
public static final String MAX_SESSION = "max.session";
|
||||
public static final String TIMEOUT = "timeout";
|
||||
public static final String SESSION_TIMEOUT = "session.timeout";
|
||||
public static final String RESPONSE_TYPE = "response.type";
|
||||
public static final String SOCKET_REUSE = "socket.reuse";
|
||||
public static final String LL_FIELD_INDEX = "ll.field.index";
|
||||
public static final String LL_FIELD_LENGTH = "ll.field.length";
|
||||
public static final String ACK_PROTOCOL = "ack.support";
|
||||
public static final String WORK_CLASS_CODE = "business.work.class.code";
|
||||
public static final String TRACE_LEVEL = "trace.level";
|
||||
public static final String DESCRIPTION = "description";
|
||||
public static final String RESPONSE_ONLY = "response.olny";
|
||||
public static final String USE_POLLING = "use.polling";
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.eactive.eai.adapter.socket.config;
|
||||
|
||||
import com.eactive.eai.adapter.RequestDispatcher;
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.service.InboundControl;
|
||||
import com.eactive.eai.adapter.socket.service.SocketLogManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class RequestDescriptor {
|
||||
|
||||
private InboundControl control;
|
||||
|
||||
private static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
private static Logger errLogger = SocketLogManager.getInstance().getErrLogger();
|
||||
|
||||
public RequestDescriptor(InboundControl control) {
|
||||
this.control = control;
|
||||
}
|
||||
|
||||
public void request() {
|
||||
|
||||
logger.debug("################ RequestDescriptor.request() 호출됨.");
|
||||
|
||||
long srtTime = 0;
|
||||
srtTime = System.currentTimeMillis();
|
||||
|
||||
//BatchDoc batchMsgDoc = null;
|
||||
|
||||
try {
|
||||
//Properties prop = new Properties();
|
||||
ConfigurationContext ctx = SocketAdapterManager.getInstance().getContext( control.getAdapterName() );
|
||||
|
||||
if ( ctx.getDescription().equals("ECHO SESSION") ) {
|
||||
//수신 메시지와 동일하게 설정
|
||||
control.setResponse( control.getRequest() );
|
||||
|
||||
//SocketAdapter adapter = SocketAdapter.getInstance();
|
||||
//prop.put( SocketAdapter.ADAPTER_GORUP_NAME, "SOCKET_Test_AIX_OUT");
|
||||
//resp = (byte[]) adapter.execute( prop, control.getRequest() );
|
||||
//control.setResponse( resp );
|
||||
|
||||
} else {
|
||||
//================================================================================================
|
||||
//Client Request 메시지 처리 요청
|
||||
RequestDispatcher reqDispacher = RequestDispatcher.getRequestDispatcher( control.getAdapterGroupName() );
|
||||
reqDispacher.handle(control);
|
||||
//batchMsgDoc = reqDispacher.handle(control);
|
||||
|
||||
//control.setResponse( batchMsgDoc.getEAIBatchMessage().getSendTelegram().getBytes() );
|
||||
//control.setBatchMsgDoc(batchMsgDoc);
|
||||
//================================================================================================
|
||||
}
|
||||
|
||||
} catch ( Throwable e ) {
|
||||
control.setLastError( e );
|
||||
String errMsg = CommonLib.getMessage("BECEAIASI001", new String[] { e.getMessage() } );
|
||||
errLogger.error( errMsg, e );
|
||||
errLogger.error( CommonLib.getDumpMessage( control.getRequest() ));
|
||||
|
||||
control.setResponse( errMsg.getBytes() );
|
||||
}
|
||||
|
||||
logger.debug("################ RequestDescriptor.request() 종료. (수행 시간: "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec)");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,131 @@
|
||||
package com.eactive.eai.adapter.socket.outbound;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
import com.eactive.eai.adapter.socket.service.SocketLogManager;
|
||||
import com.eactive.eai.adapter.socket.service.SocketService;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class OutboundSocketClient implements SocketService {
|
||||
|
||||
//파일로거
|
||||
private static Logger logger = SocketLogManager.getInstance().getLogger();
|
||||
|
||||
private boolean active;
|
||||
|
||||
private int currentState;
|
||||
|
||||
private long firstActivity;
|
||||
private long lastActivity;
|
||||
|
||||
private Socket socket;
|
||||
|
||||
private String remoteIPAddress;
|
||||
private String port;
|
||||
|
||||
|
||||
public OutboundSocketClient(Socket socket) {
|
||||
this.active = true;
|
||||
|
||||
this.currentState = CommonLib.PROCESSING_PROTOCOL;
|
||||
|
||||
this.firstActivity = System.currentTimeMillis();
|
||||
this.lastActivity = System.currentTimeMillis();
|
||||
|
||||
this.socket = socket;
|
||||
|
||||
this.remoteIPAddress = socket.getInetAddress().getHostAddress();
|
||||
this.port = socket.getPort() + "";
|
||||
|
||||
}
|
||||
|
||||
public String getPort() {
|
||||
return this.port;
|
||||
}
|
||||
|
||||
public String getRemoteIPAddress() {
|
||||
return this.remoteIPAddress;
|
||||
}
|
||||
|
||||
public ConfigurationContext getContext() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean idle(long timeout) {
|
||||
long idleTime = System.currentTimeMillis() - this.lastActivity;
|
||||
return (idleTime > timeout);
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public synchronized void shutdown() {
|
||||
active = false;
|
||||
|
||||
if (this.socket == null) {
|
||||
logger.info("OutboundSocketClient : socket 이 null 입니다.");
|
||||
return;
|
||||
}
|
||||
if (this.socket.isClosed()) {
|
||||
logger.info("OutboundSocketClient : socket 이 이미 close 되었습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
socket.setSoLinger(true, 100);
|
||||
socket.shutdownInput();
|
||||
socket.shutdownOutput();
|
||||
socket.close();
|
||||
logger.info("OutboundSocketClient : Outbound Socket Closed !!");
|
||||
|
||||
} catch (Exception ex) {
|
||||
logger.error("★★★★★ Outbound Socket Close 시 오류 발생 !! ★★★★★", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public Socket getCurrentSocket() {
|
||||
return this.socket;
|
||||
}
|
||||
|
||||
public boolean connect() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
shutdown();
|
||||
}
|
||||
|
||||
public void setControl(Object control) {
|
||||
}
|
||||
|
||||
public void notifyMessage() {
|
||||
}
|
||||
|
||||
public int getCurrentState() {
|
||||
return this.currentState;
|
||||
}
|
||||
|
||||
public boolean isConnected() throws IOException {
|
||||
return this.socket.isConnected();
|
||||
}
|
||||
|
||||
public void setLastActivity() {
|
||||
lastActivity = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public void checkActivity() {
|
||||
}
|
||||
|
||||
public long getFirstActivity() {
|
||||
return firstActivity;
|
||||
}
|
||||
|
||||
public long getLastActivity() {
|
||||
return lastActivity;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,531 @@
|
||||
//package com.eactive.eai.adapter.socket.service;
|
||||
//
|
||||
//import java.io.IOException;
|
||||
//import java.net.Socket;
|
||||
//import java.nio.ByteBuffer;
|
||||
//import java.nio.channels.ClosedSelectorException;
|
||||
//import java.nio.channels.SelectionKey;
|
||||
//import java.nio.channels.Selector;
|
||||
//import java.nio.channels.SocketChannel;
|
||||
//import java.util.Iterator;
|
||||
//
|
||||
//import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
//import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
//import com.eactive.eai.adapter.socket.common.SocketAdapterException;
|
||||
//import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
//import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//
|
||||
//public class AdminServer extends Thread implements SocketService {
|
||||
//
|
||||
// private ConfigurationContext context;
|
||||
// private SocketChannel socketChannel;
|
||||
// private SocketServer proxy;
|
||||
// private Selector selector;
|
||||
// private SelectionKey key;
|
||||
//
|
||||
// private boolean active;
|
||||
//
|
||||
// // 상태정보
|
||||
// private int sendCount;
|
||||
// private int recvCount;
|
||||
// private long firstActivity;
|
||||
// private long lastActivity;
|
||||
//
|
||||
// // IO BUFFER
|
||||
// private ByteBuffer incomingMessage;
|
||||
// private ByteBuffer outgoingMessage;
|
||||
// private ByteBuffer lenBuffer;
|
||||
//
|
||||
// // Logger
|
||||
// private Logger logger;
|
||||
// private String remoteIPAddress;
|
||||
//
|
||||
// public AdminServer(ConfigurationContext context, SocketChannel socketChannel, SocketServer proxy) {
|
||||
// String name = this.getName();
|
||||
// this.setName( context.getAdapterName() + "-CONNECTION-ADMIN" + name.substring( name.lastIndexOf("-")) );
|
||||
//
|
||||
// this.context = context;
|
||||
// this.socketChannel = socketChannel;
|
||||
// this.proxy = proxy;
|
||||
//
|
||||
// sendCount = 0;
|
||||
// recvCount = 0;
|
||||
// firstActivity = System.currentTimeMillis();
|
||||
// lastActivity = System.currentTimeMillis();
|
||||
//
|
||||
// incomingMessage = null;
|
||||
// outgoingMessage = null;
|
||||
//
|
||||
// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() );
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName());
|
||||
// remoteIPAddress = this.socketChannel.socket().getInetAddress().getHostAddress();
|
||||
// active = true;
|
||||
// }
|
||||
//
|
||||
// private boolean isSyncMode() {
|
||||
// return this.context.isSyncMode();
|
||||
// }
|
||||
//
|
||||
// public String getRemoteIPAddress() {
|
||||
// return this.remoteIPAddress;
|
||||
// }
|
||||
//
|
||||
// private long getTimeout() {
|
||||
// return ( this.context.getTimeout() * 1000L );
|
||||
// }
|
||||
//
|
||||
// private boolean isSocketReuse() {
|
||||
// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG );
|
||||
// }
|
||||
//
|
||||
// private int getTraceLevel() {
|
||||
// return context.getTraceLevel();
|
||||
// }
|
||||
// /**
|
||||
// * @return Returns the context.
|
||||
// */
|
||||
// public ConfigurationContext getContext() {
|
||||
// return context;
|
||||
// }
|
||||
//
|
||||
// public void run() {
|
||||
// SocketAdapterManager.getInstance().addConnection( this );
|
||||
//
|
||||
// String socketInfo = this.getSocketInfo(this.socketChannel);
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIMSA034", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) );
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// openSelector();
|
||||
// } catch(IOException e) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIMSA009", new String[]{context.getAdapterName(), "openSelector", e.getMessage(), "", "" } );
|
||||
// logger.error( errMsg, e );
|
||||
// active = false;
|
||||
// }
|
||||
//
|
||||
// Iterator<SelectionKey> iterator;
|
||||
// long start = System.currentTimeMillis();
|
||||
// while( active ) {
|
||||
// try {
|
||||
// int selected = selector.select( getTimeout() );
|
||||
// if( selected == 0 ) {
|
||||
// long waitTime = System.currentTimeMillis() - start;
|
||||
// if ( lenBuffer.position() > 0 && waitTime >= getTimeout() ) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIMSA024", new String[]{context.getAdapterName(), socketInfo, Long.toString(getTimeout()), "수신", getReadingMessage() });
|
||||
// logger.error( errMsg );
|
||||
// active = false;
|
||||
// }
|
||||
// continue;
|
||||
// }
|
||||
// } catch(IOException e) {
|
||||
// if ( lenBuffer.position() > 0 ) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIMSA009", new String[]{context.getAdapterName(), "select", e.getMessage(), "수신메시지", getReadingMessage() } );
|
||||
// logger.error( errMsg , e);
|
||||
// }
|
||||
// active = false;
|
||||
// } catch(ClosedSelectorException e ) {
|
||||
// continue;
|
||||
// } catch(Exception e) {}
|
||||
//
|
||||
// if ( selector == null || !selector.isOpen() ) continue;
|
||||
//
|
||||
// iterator = selector.selectedKeys().iterator();
|
||||
//
|
||||
// while( iterator.hasNext() ) {
|
||||
// key = (SelectionKey)iterator.next();
|
||||
// iterator.remove();
|
||||
// socketChannel = (SocketChannel)key.channel();
|
||||
// if(key.isReadable()) { // is Readable ? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
|
||||
// try {
|
||||
//
|
||||
// start = System.currentTimeMillis();
|
||||
// if( processReadMessage() ) { // Read Done
|
||||
// byte[] message = incomingMessage.array();
|
||||
//
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIMSA001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage(incomingMessage.array())}));
|
||||
// }
|
||||
//
|
||||
// this.checkActivity();
|
||||
// lastActivity = System.currentTimeMillis();
|
||||
// recvCount++;
|
||||
//
|
||||
// byte[] rtnValue = SocketAdapterManager.getInstance().executeCommand( new String(message) ).getBytes();
|
||||
//
|
||||
// incomingMessage.clear();
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// start = System.currentTimeMillis();
|
||||
//
|
||||
// if ( isSyncMode() ) {
|
||||
// // 동기, SYNC로 간주합니다.
|
||||
// makeFormat( rtnValue );
|
||||
// socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
|
||||
// //selector.wakeup();
|
||||
// } else {
|
||||
// // 비동기, ASYNC로 간주합니다.
|
||||
// socketChannel.register(selector, SelectionKey.OP_READ);
|
||||
// //selector.wakeup();
|
||||
// }
|
||||
// }
|
||||
// } catch(Exception e) {
|
||||
// if ( lenBuffer.position() > 0 ) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIMSA009", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } );
|
||||
// logger.error( errMsg , e);
|
||||
// }
|
||||
// active = false;
|
||||
// } finally {
|
||||
// if(!active) continue;
|
||||
// }
|
||||
// } // end of readable...
|
||||
//
|
||||
// if( key.isWritable() ) { // is Writable ? - - - - - - - - - - - - - - - - - - - //
|
||||
// try {
|
||||
// if( processWriteMessage() ) {
|
||||
//
|
||||
// sendCount++;
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIMSA001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), socketInfo, getWritingMessage()}));
|
||||
// }
|
||||
//
|
||||
// outgoingMessage.clear();
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// socketChannel.register(selector, SelectionKey.OP_READ); // write end. so read only.
|
||||
// }
|
||||
// } catch(IOException e) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIMSA009", new String[]{context.getAdapterName(), "processWriteMessage", e.getMessage(), "송신메시지", getWritingMessage() } );
|
||||
// logger.error( errMsg , e);
|
||||
// active = false;
|
||||
// }
|
||||
// } // end of writables...
|
||||
// } // End of while(iterator.hasNext())
|
||||
//
|
||||
// if ( !isSocketReuse() ) {
|
||||
// active = false;
|
||||
// }
|
||||
//
|
||||
// } // enf of while - active
|
||||
//
|
||||
// try {
|
||||
// closeSelector();
|
||||
// } catch(IOException e) {}
|
||||
//
|
||||
//
|
||||
// SocketAdapterManager.getInstance().removeConnection( this );
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIMSA035", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) );
|
||||
// }
|
||||
//
|
||||
// proxy.quiesceShutdown(this);
|
||||
// interrupt();
|
||||
//
|
||||
// }
|
||||
//
|
||||
// private String getReadingMessage() {
|
||||
// String rMsg = "";
|
||||
// if ( incomingMessage != null && incomingMessage.position() > 0 ) {
|
||||
// byte[] dMsg = new byte[ incomingMessage.position() ];
|
||||
// System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length );
|
||||
// rMsg = CommonLib.getDumpMessage( dMsg );
|
||||
// }
|
||||
// return rMsg;
|
||||
// }
|
||||
//
|
||||
// private String getWritingMessage() {
|
||||
// String rMsg = "";
|
||||
// if ( outgoingMessage != null && outgoingMessage.position() > 0 ) {
|
||||
// byte[] debugMsg = new byte[ outgoingMessage.capacity() - lenBuffer.capacity() ];
|
||||
// System.arraycopy( outgoingMessage.array(), lenBuffer.capacity(), debugMsg, 0, debugMsg.length );
|
||||
// rMsg = CommonLib.getDumpMessage( debugMsg );
|
||||
// }
|
||||
// return rMsg;
|
||||
// }
|
||||
//
|
||||
// private String getSocketInfo(SocketChannel channel) {
|
||||
// StringBuffer connInfo = new StringBuffer();
|
||||
//
|
||||
// connInfo.append("Local Address=");
|
||||
// connInfo.append( channel.socket().getLocalAddress().getHostAddress()).append(":").append(channel.socket().getLocalPort()).append(", ");
|
||||
// connInfo.append("Remote Address=");
|
||||
// connInfo.append( channel.socket().getInetAddress().getHostAddress()).append(":").append(channel.socket().getPort());
|
||||
//
|
||||
// return connInfo.toString();
|
||||
// }
|
||||
//
|
||||
// public boolean idle(long timeout) {
|
||||
// long idleTime = System.currentTimeMillis() - this.lastActivity;
|
||||
// return ( idleTime > timeout );
|
||||
// }
|
||||
//
|
||||
// public boolean isActive() {
|
||||
// return active;
|
||||
// }
|
||||
//
|
||||
// public void shutdown() {
|
||||
// active = false;
|
||||
// try {
|
||||
// closeSelector();
|
||||
// } catch( Exception e ) {}
|
||||
//
|
||||
// interrupt();
|
||||
// }
|
||||
//
|
||||
// public Socket getCurrentSocket() {
|
||||
// return socketChannel.socket();
|
||||
// }
|
||||
//
|
||||
// public boolean connect() {
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// public void disconnect() {
|
||||
// shutdown();
|
||||
// proxy.quiesceShutdown(this);
|
||||
// }
|
||||
//
|
||||
// private void openSelector() throws IOException {
|
||||
//
|
||||
// if ( selector == null || !selector.isOpen() ) {
|
||||
// selector = Selector.open();
|
||||
// }
|
||||
// socketChannel.socket().setTcpNoDelay(true);
|
||||
// socketChannel.configureBlocking(false);
|
||||
// socketChannel.register(selector, SelectionKey.OP_READ);
|
||||
//
|
||||
// }
|
||||
//
|
||||
// private void closeSelector() throws IOException {
|
||||
// if(selector != null) {
|
||||
// selector.wakeup();
|
||||
//
|
||||
// for(Iterator<SelectionKey> iterator = selector.keys().iterator(); iterator.hasNext();) {
|
||||
// try {
|
||||
// key = iterator.next();
|
||||
// iterator.remove();
|
||||
// socketChannel = (SocketChannel)key.channel();
|
||||
// key.cancel();
|
||||
// if(socketChannel != null) {
|
||||
// Socket socket = socketChannel.socket();
|
||||
// if(socket != null) {
|
||||
// socket.setSoLinger(false, 0);
|
||||
// try { socket.close(); } catch(Exception e) {}
|
||||
// }
|
||||
// socketChannel.close();
|
||||
// }
|
||||
// } catch(IOException ioexception) { }
|
||||
// }
|
||||
// selector.close();
|
||||
// }
|
||||
// selector = null;
|
||||
// }
|
||||
//
|
||||
// public void setControl(Object control) {
|
||||
// }
|
||||
//
|
||||
// public void notifyMessage() {
|
||||
// }
|
||||
//
|
||||
//
|
||||
// private boolean processReadMessage() throws Exception {
|
||||
//
|
||||
// int i = 0;
|
||||
// boolean flag = false;
|
||||
//
|
||||
// while ( lenBuffer.position() < lenBuffer.capacity() ) {
|
||||
// i = socketChannel.read( lenBuffer );
|
||||
// if ( i <= 0 ) break;
|
||||
// flag = true;
|
||||
// }
|
||||
//
|
||||
// if(i == -1) {
|
||||
// if ( lenBuffer.position() > 0 ) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIMSA010", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}) );
|
||||
// } else {
|
||||
// String errMsg = CommonLib.getMessage("BICEAIMSA036", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)});
|
||||
// if(logger.isInfoEnabled()){
|
||||
// logger.info( errMsg );
|
||||
// }
|
||||
// throw new SocketAdapterException( errMsg );
|
||||
// }
|
||||
// }
|
||||
// if ( lenBuffer.position() != lenBuffer.capacity() ) return false;
|
||||
//
|
||||
// int length = 0;
|
||||
//
|
||||
// try {
|
||||
// if ( flag ) {
|
||||
// length = checkLengthField( lenBuffer );
|
||||
// incomingMessage = ByteBuffer.allocate( length );
|
||||
// incomingMessage.clear();
|
||||
// }
|
||||
// } catch(Exception le) {
|
||||
// throw le;
|
||||
// }
|
||||
//
|
||||
// i = 0;
|
||||
// while ( incomingMessage.position() < incomingMessage.capacity()) {
|
||||
// i = socketChannel.read(incomingMessage);
|
||||
// if ( i <= 0 ) break;
|
||||
// }
|
||||
//
|
||||
// if(i == -1) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIMSA010", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}) );
|
||||
// } else {
|
||||
// if ( incomingMessage.position() == incomingMessage.capacity() ) {
|
||||
// return true;
|
||||
// } else {
|
||||
// return false;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private boolean processWriteMessage() throws IOException {
|
||||
//
|
||||
// outgoingMessage.flip();
|
||||
//
|
||||
// while ( outgoingMessage.hasRemaining() && active ) {
|
||||
// socketChannel.write(outgoingMessage);
|
||||
// }
|
||||
//
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// // Writing전에 확인...
|
||||
// public boolean isConnected() throws IOException {
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// public int getCurrentState() {
|
||||
// return CommonLib.PROCESSING_PROTOCOL;
|
||||
// }
|
||||
//
|
||||
// private void resetCount() {
|
||||
// this.recvCount = 0;
|
||||
// this.sendCount = 0;
|
||||
// }
|
||||
//
|
||||
// public void checkActivity() {
|
||||
// long currentTime = System.currentTimeMillis();
|
||||
// if ( !CommonLib.getDate( this.lastActivity ).equals( CommonLib.getDate( currentTime )) ) {
|
||||
// this.resetCount();
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private int checkLengthField(ByteBuffer buffer) throws SocketAdapterException {
|
||||
// int length = 0;
|
||||
//
|
||||
// if ( buffer.capacity() == 2 ) {
|
||||
// length = ( buffer.getShort(0) & 0xFFFF );
|
||||
// } else if ( buffer.capacity() == 4 ) {
|
||||
// length = ( buffer.getInt(0) );
|
||||
// if ( length < 0 ) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIMSA027", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.byte2Hex( buffer.array() ) }) );
|
||||
// }
|
||||
// } else {
|
||||
// String lenStr = new String( buffer.array() );
|
||||
// try {
|
||||
// length = Integer.parseInt( lenStr );
|
||||
// } catch ( NumberFormatException e ) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIMSA027", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.byte2Hex( buffer.array() ) }) );
|
||||
// }
|
||||
// }
|
||||
// return length;
|
||||
// }
|
||||
//
|
||||
// private byte[] makeLengthField(int length) {
|
||||
// byte[] lenField = null;
|
||||
//
|
||||
// if ( lenBuffer.capacity() == 2 ) {
|
||||
// ByteBuffer tmpBuffer = ByteBuffer.allocate( lenBuffer.capacity() );
|
||||
// tmpBuffer.clear();
|
||||
// tmpBuffer.putShort( (short) (length & 0xFFFF) );
|
||||
// lenField = tmpBuffer.array();
|
||||
// } else {
|
||||
// String lenStr = CommonLib.getFormatString( length, lenBuffer.capacity() );
|
||||
// lenField = lenStr.getBytes();
|
||||
// }
|
||||
//
|
||||
// return lenField;
|
||||
// }
|
||||
//
|
||||
// private void makeFormat(byte[] data) throws SocketAdapterException {
|
||||
//
|
||||
// int i = data.length + lenBuffer.capacity();
|
||||
//
|
||||
// if(outgoingMessage == null) {
|
||||
// outgoingMessage = ByteBuffer.allocate( data.length + lenBuffer.capacity() );
|
||||
// } else {
|
||||
// if( i != outgoingMessage.capacity() )
|
||||
// outgoingMessage = ByteBuffer.allocate( i );
|
||||
// }
|
||||
//
|
||||
// outgoingMessage.clear();
|
||||
// outgoingMessage.put( makeLengthField( data.length ) );
|
||||
// outgoingMessage.put( data );
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * @return Returns the socketchannel.
|
||||
// */
|
||||
// public SocketChannel getSocketchannel() {
|
||||
// return socketChannel;
|
||||
// }
|
||||
// /**
|
||||
// * @param socketchannel The socketchannel to set.
|
||||
// */
|
||||
// public void setSocketchannel(SocketChannel socketchannel) {
|
||||
// this.socketChannel = socketchannel;
|
||||
// }
|
||||
//
|
||||
// // 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각
|
||||
// public String toString() {
|
||||
// boolean status = true;
|
||||
// StringBuffer strBuff = new StringBuffer();
|
||||
// strBuff.append(context.getAdapterGroupName()).append(",");
|
||||
// strBuff.append(context.getAdapterName()).append(",");
|
||||
// strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(",");
|
||||
// strBuff.append(context.getSocketType()).append(",");
|
||||
// strBuff.append(context.getResponseType()).append(",");
|
||||
// try {
|
||||
// strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(",");
|
||||
// } catch( Exception e ) {
|
||||
// status = false;
|
||||
// strBuff.append("?:?,");
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(",");
|
||||
// } catch( Exception e ) {
|
||||
// status = false;
|
||||
// strBuff.append("?:?,");
|
||||
// }
|
||||
// strBuff.append(this.sendCount).append(",");
|
||||
// strBuff.append(this.recvCount).append(",");
|
||||
// strBuff.append( status ).append(",");
|
||||
// strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(",");
|
||||
// strBuff.append( CommonLib.getCurrentTime( this.lastActivity ));
|
||||
//
|
||||
// return strBuff.toString();
|
||||
// }
|
||||
//
|
||||
// public void setLastActivity() {
|
||||
// }
|
||||
//
|
||||
// public long getFirstActivity() {
|
||||
// return firstActivity;
|
||||
// }
|
||||
//
|
||||
// public long getLastActivity() {
|
||||
// return lastActivity;
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
|
||||
import java.util.Vector;
|
||||
|
||||
|
||||
/**
|
||||
* Adapter Name별관리 대상테이블
|
||||
*/
|
||||
public class AdminTable {
|
||||
|
||||
private String adapterGroupName;
|
||||
private String adapterName;
|
||||
private ConfigurationContext ctx;
|
||||
private Vector<SocketService> connections;
|
||||
private int activeCount;
|
||||
|
||||
public AdminTable(String adapterGroupName, String adapterName, ConfigurationContext context ) {
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
this.adapterName = adapterName;
|
||||
this.ctx = context;
|
||||
this.connections = new Vector<SocketService>();
|
||||
this.activeCount = 0;
|
||||
}
|
||||
|
||||
public String getAdapterGroupName() {
|
||||
return adapterGroupName;
|
||||
}
|
||||
|
||||
public void initialize() {
|
||||
this.connections.clear();
|
||||
this.activeCount = 0;
|
||||
}
|
||||
|
||||
public void setContext( ConfigurationContext context ) {
|
||||
this.ctx = context;
|
||||
}
|
||||
|
||||
public ConfigurationContext getContext() {
|
||||
return ctx;
|
||||
}
|
||||
|
||||
public synchronized Object[] getConnections() {
|
||||
return connections.toArray();
|
||||
}
|
||||
|
||||
public synchronized void checkErrorStatus() {
|
||||
synchronized ( connections ) {
|
||||
updateStatus( SocketAdapterManager.getInstance().checkActiveStatus( adapterGroupName, adapterName ) );
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void checkRecoverStatus() {
|
||||
synchronized ( connections ) {
|
||||
updateStatus( SocketAdapterManager.getInstance().checkActiveStatus( adapterGroupName, adapterName ) );
|
||||
}
|
||||
}
|
||||
|
||||
// Adapter Group Session을 한번에 등록한다.
|
||||
public synchronized void addConnection(SocketService connection) {
|
||||
connections.add( connection );
|
||||
|
||||
}
|
||||
|
||||
public synchronized void removeConnection(Object connection) {
|
||||
synchronized ( connections ) {
|
||||
int size = connections.size();
|
||||
for ( int i=0; i < size; i++ ) {
|
||||
Object x = connections.elementAt( i );
|
||||
if ( x == connection ) {
|
||||
connections.remove( i );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( connections.size() == 0 ) {
|
||||
updateStatus( false );
|
||||
}
|
||||
}
|
||||
|
||||
private void updateStatus( boolean on ) {
|
||||
AdapterVO config = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName);
|
||||
if ( config != null ) {
|
||||
if ( config.isStatus() != on ) {
|
||||
config.setStatus( on );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append("\n ▷ AdminTable [");
|
||||
sb.append("adapterGroupName=" + adapterGroupName + ", ");
|
||||
sb.append("adapterName=" + adapterName + ", ");
|
||||
sb.append("connections=" + connections.size() + ", ");
|
||||
sb.append("activeCount=" + activeCount);
|
||||
sb.append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.TimerTask;
|
||||
|
||||
|
||||
/**
|
||||
* Connection된 모든 Socket에 대한 상태를 관리한다.
|
||||
* 업무별 리스트를 관리
|
||||
*/
|
||||
public class ConnectionManager extends TimerTask {
|
||||
|
||||
private HashMap<String, LinkedList<SocketService>> stateTable;
|
||||
private Logger logger;
|
||||
private long lastActivity;
|
||||
|
||||
public ConnectionManager(HashMap<String, LinkedList<SocketService>> state) {
|
||||
this.stateTable = state;
|
||||
logger = SocketLogManager.getInstance().getLogger();
|
||||
lastActivity = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
// 30분간 미사용 Connection에 대한 강제 CLOSE수행
|
||||
// Inbound의 Server Socket Type에 한하여 정리작업을 수행한다.
|
||||
public void run() {
|
||||
if ( stateTable.size() < 1 ) return;
|
||||
long timeout = SocketAdapterManager.UNUSED_CONNECTION_TIMEOUT;
|
||||
|
||||
if ( !CommonLib.getDate( System.currentTimeMillis() ).equals( CommonLib.getDate( this.lastActivity ) ) ) {
|
||||
this.checkActivity();
|
||||
}
|
||||
|
||||
if ( timeout < 1 ) return;
|
||||
|
||||
Object[] it = stateTable.values().toArray();
|
||||
|
||||
for ( int k=0; k < it.length; k++ ) {
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
LinkedList<SocketService> groupList = (LinkedList<SocketService>) it[k];
|
||||
if ( groupList.size() < 1 ) continue;
|
||||
Object[] x = groupList.toArray();
|
||||
|
||||
SocketService connection = (SocketService) x[0];
|
||||
if ( connection.getContext().getBoundUsage().equals( ConfigurationContext.INBOUND_SOCKET )
|
||||
&& connection.getContext().getSocketType().equals( ConfigurationContext.SERVER_SOCKET ) ) {
|
||||
for ( int i=0; i < x.length; i++ ) {
|
||||
connection = (SocketService) x[i];
|
||||
if ( connection.idle( timeout ) ) {
|
||||
StringBuffer connInfo = new StringBuffer();
|
||||
|
||||
connInfo.append("Local Address=");
|
||||
try {
|
||||
connInfo.append( connection.getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(connection.getCurrentSocket().getLocalPort()).append(", ");
|
||||
} catch( Exception e ) {
|
||||
connInfo.append( "?:?,");
|
||||
}
|
||||
connInfo.append("Remote Address=");
|
||||
try {
|
||||
connInfo.append( connection.getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(connection.getCurrentSocket().getPort());
|
||||
} catch( Exception e ) {
|
||||
connInfo.append( "?:?");
|
||||
}
|
||||
|
||||
if(logger.isInfoEnabled()){
|
||||
logger.info( CommonLib.getMessage("BICEAIMSA027", new String[]{ Long.toString( timeout/1000 ), connInfo.toString() } )) ;
|
||||
}
|
||||
connection.disconnect();
|
||||
if(logger.isInfoEnabled()){
|
||||
logger.info( CommonLib.getMessage("BICEAIMSA028", new String[]{ connInfo.toString() } )) ;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch( Exception e ) {
|
||||
logger.error( CommonLib.getMessage("BECEAIMSA008", new String[]{ e.getMessage() }), e );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void checkActivity() {
|
||||
Object[] it = stateTable.values().toArray();
|
||||
|
||||
for ( int k=0; k < it.length; k++ ) {
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
LinkedList<SocketService> groupList = (LinkedList<SocketService>) it[k];
|
||||
if ( groupList.size() < 1 ) continue;
|
||||
Object[] x = groupList.toArray();
|
||||
|
||||
SocketService connection = null;
|
||||
for ( int i=0; i < x.length; i++ ) {
|
||||
try {
|
||||
connection = (SocketService) x[i];
|
||||
connection.checkActivity();
|
||||
} catch( Exception ie ) {}
|
||||
}
|
||||
} catch( Exception e ) {}
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
sb.append("\n■ ConnectionManager : ");
|
||||
for(Iterator<String> iter = stateTable.keySet().iterator(); iter.hasNext();) {
|
||||
Object key = iter.next();
|
||||
sb.append("\n ▣ " + key + " : ");
|
||||
for(Iterator<SocketService> iter2 = (stateTable.get(key)).iterator(); iter2.hasNext();) {
|
||||
sb.append("\n ● " + iter2.next() + " : ");
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,730 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.BufferOverflowException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
import com.eactive.eai.batch.common.BatchDirUtil;
|
||||
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.flowController.BatchTargetVO;
|
||||
import com.eactive.eai.batch.flowController.FlowControllerManager;
|
||||
import com.eactive.eai.batch.message.EAIBatchMsgManager;
|
||||
import com.eactive.eai.batch.osd.OutsideManager;
|
||||
import com.eactive.eai.batch.osd.OutsideVO;
|
||||
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
|
||||
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
|
||||
import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager;
|
||||
import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO;
|
||||
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.Logger;
|
||||
import com.eactive.eai.inbound.ResponseHandler;
|
||||
|
||||
public class IOboundServer extends Thread implements SocketService {
|
||||
|
||||
private ConfigurationContext context;
|
||||
private SocketChannel socketChannel;
|
||||
private SocketServer proxy;
|
||||
|
||||
private boolean active;
|
||||
|
||||
private long firstActivity;
|
||||
private long lastActivity;
|
||||
|
||||
private int currentState;
|
||||
|
||||
// pending message for checking operation
|
||||
private ByteBuffer pendingMessage;
|
||||
private ByteBuffer incomingMessage;
|
||||
private ByteBuffer pollingMessage;
|
||||
|
||||
// Logger
|
||||
private Logger logger;
|
||||
|
||||
//
|
||||
private String remoteIPAddress;
|
||||
private String remotePort;
|
||||
|
||||
AdapterVO adapter;
|
||||
// String transaction_code;
|
||||
|
||||
private BatchDoc batchMsgDoc;
|
||||
//----------------------------------------------------------------
|
||||
|
||||
|
||||
public IOboundServer(ConfigurationContext context, SocketChannel socketChannel, SocketServer proxy) {
|
||||
String name = this.getName();
|
||||
this.setName( context.getAdapterName() + "-CONNECTION" + name.substring( name.lastIndexOf("-")) );
|
||||
|
||||
this.context = context;
|
||||
this.socketChannel = socketChannel;
|
||||
this.proxy = proxy;
|
||||
|
||||
firstActivity = System.currentTimeMillis();
|
||||
lastActivity = System.currentTimeMillis();
|
||||
|
||||
pendingMessage = ByteBuffer.allocate( 4096 );
|
||||
pendingMessage.clear();
|
||||
|
||||
this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL;
|
||||
|
||||
logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName() );
|
||||
|
||||
active = true;
|
||||
remoteIPAddress = this.socketChannel.socket().getInetAddress().getHostAddress();
|
||||
remotePort = this.socketChannel.socket().getPort() +"";
|
||||
|
||||
|
||||
}
|
||||
|
||||
public long getFirstActivity() {
|
||||
return this.firstActivity;
|
||||
}
|
||||
|
||||
public long getLastActivity() {
|
||||
return this.lastActivity;
|
||||
}
|
||||
|
||||
public String getRemotePort() {
|
||||
return this.remotePort;
|
||||
}
|
||||
|
||||
public String getRemoteIPAddress() {
|
||||
return this.remoteIPAddress;
|
||||
}
|
||||
|
||||
public boolean idle(long timeout) {
|
||||
long idleTime = System.currentTimeMillis() - this.lastActivity;
|
||||
return ( idleTime > timeout );
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public synchronized void shutdown() {
|
||||
active = false;
|
||||
|
||||
notify();
|
||||
|
||||
try {
|
||||
if ( this.socketChannel == null ){
|
||||
logger.info("IOboundServer : socketChannel 이 null 입니다.");
|
||||
return;
|
||||
}
|
||||
Socket socket = this.socketChannel.socket();
|
||||
if (socket == null) {
|
||||
logger.info("IOboundServer : socket 이 null 입니다.");
|
||||
return;
|
||||
}
|
||||
if (socket.isClosed()) {
|
||||
logger.info("IOboundServer : socket 이 이미 close 되었습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
socket.setSoLinger(true, 100);
|
||||
if (socketChannel.isConnectionPending()) {
|
||||
logger.info("IOboundServer : socket channle isConnectionPending OK!!!");
|
||||
socketChannel.finishConnect();
|
||||
}
|
||||
socket.shutdownInput();
|
||||
socket.shutdownOutput();
|
||||
socket.close();
|
||||
socketChannel.close();
|
||||
|
||||
logger.info("IOboundServer : IObound Socket Closed !!");
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error( e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public Socket getCurrentSocket() {
|
||||
return socketChannel.socket();
|
||||
}
|
||||
|
||||
public boolean connect() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
shutdown();
|
||||
proxy.quiesceShutdown(this);
|
||||
interrupt();
|
||||
}
|
||||
|
||||
public void setControl(Object control) {
|
||||
}
|
||||
|
||||
public void notifyMessage() {
|
||||
}
|
||||
|
||||
public int getCurrentState() {
|
||||
return this.currentState;
|
||||
}
|
||||
|
||||
// Writing전에 확인...
|
||||
public boolean isConnected() throws IOException {
|
||||
boolean flag = true;
|
||||
|
||||
if ( socketChannel.isConnected() && socketChannel.socket().isBound() ) {
|
||||
ByteBuffer tmpBuffer = ByteBuffer.allocate( 1 );
|
||||
tmpBuffer.clear();
|
||||
int i = socketChannel.read( tmpBuffer );
|
||||
if ( i > 0 ) {
|
||||
try {
|
||||
pendingMessage.put( tmpBuffer.array() );
|
||||
} catch ( BufferOverflowException e ) {
|
||||
throw new IOException("Socket 어플리케이션 프로토콜에러 발생 : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
if ( i == -1 ) {
|
||||
flag = false;
|
||||
}
|
||||
} else {
|
||||
flag = false;
|
||||
}
|
||||
|
||||
return flag;
|
||||
}
|
||||
|
||||
public void setLastActivity() {
|
||||
lastActivity = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public void checkActivity() {
|
||||
}
|
||||
|
||||
private boolean isAckProtocol() {
|
||||
return this.context.isAckProtocol();
|
||||
}
|
||||
|
||||
private long getTimeout() {
|
||||
return ( this.context.getTimeout() * 1000L );
|
||||
}
|
||||
|
||||
private int getTraceLevel() {
|
||||
return context.getTraceLevel();
|
||||
}
|
||||
|
||||
public ConfigurationContext getContext() {
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
* IOboundServer 는 SocketServer 에서 생성되는 Thread 이다.
|
||||
* 외부에서 연결요청한 사항을 처리하기 위해 사용되며, 실제 배치처리에서는 실질적인 업무 플로우는
|
||||
* JPD에서 처리하므로 여기에서는 소켓자체를 배치용 매니저에 등록해주고, 사용하기 쉽게 해주고,
|
||||
* 모든 context를 JPD 로 넘겨준다.
|
||||
*/
|
||||
public void run() {
|
||||
// try {
|
||||
// Thread.sleep(10000);
|
||||
// } catch( Throwable e ) {}
|
||||
|
||||
SocketAdapterManager.getInstance().addConnection( this );
|
||||
//*** 어댑터에 대해 하나의 대외기관 연결정보(BJ05)만이 매핑되어 있어야 하는 것이 보장되어야 한다.
|
||||
logger.info("[IOboundServer] Group ["+context.getAdapterGroupName()+"] Adapter["+context.getAdapterName()+"]");
|
||||
adapter = AdapterManager.getInstance().getAdapterVO(context.getAdapterGroupName(), context.getAdapterName());
|
||||
|
||||
int readLength = 0;
|
||||
try {
|
||||
readLength = adapter.getContext().getLlFieldIndex() + adapter.getContext().getLlFieldLength();
|
||||
} catch (Exception e) {}
|
||||
if ( readLength < 1 ){
|
||||
readLength = 9;
|
||||
}
|
||||
|
||||
firstActivity = System.currentTimeMillis();
|
||||
lastActivity = firstActivity;
|
||||
|
||||
String socketInfo = "";
|
||||
|
||||
incomingMessage = ByteBuffer.allocate( readLength );
|
||||
|
||||
if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
logger.info( CommonLib.getMessage("BICEAIASI002", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) );
|
||||
}
|
||||
// active 상태에서 LOOP
|
||||
while ( active ) {
|
||||
|
||||
try {
|
||||
// length & message buffer clear
|
||||
if ( incomingMessage != null ) {
|
||||
incomingMessage.clear();
|
||||
|
||||
//logger.debug("incomingMessage-->" + incomingMessage.array().length);
|
||||
//logger.debug("adapter.getContext().getLlFieldIndex()-->" + adapter.getContext().getLlFieldIndex());
|
||||
//logger.debug("adapter.getContext().getLlFieldLength()-->" + adapter.getContext().getLlFieldLength());
|
||||
|
||||
processReadMessage( incomingMessage.array() );// 20250910 npe
|
||||
}
|
||||
if( !active) break;
|
||||
|
||||
lastActivity = System.currentTimeMillis();
|
||||
|
||||
// (DEBUG 레벨일 경우) 메시지수신 로그
|
||||
if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
logger.debug( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage(incomingMessage.array())}));
|
||||
}
|
||||
try {
|
||||
if ( adapter.getContext().getLlFieldLength() > 0 ){
|
||||
int ll_len = adapter.getContext().getLlFieldLength();
|
||||
byte[] ll_fld = new byte[ll_len];
|
||||
System.arraycopy(incomingMessage.array(), adapter.getContext().getLlFieldIndex(), ll_fld, 0, adapter.getContext().getLlFieldLength());
|
||||
if ( Integer.parseInt(new String(ll_fld)) == 0 ) continue;
|
||||
// polling 메세지 처리
|
||||
if ( adapter.getContext().isUsePollMsg() ){
|
||||
|
||||
int msglen = Integer.parseInt(new String(ll_fld));
|
||||
pollingMessage = ByteBuffer.allocate(msglen);
|
||||
try {
|
||||
processReadMessage( pollingMessage.array() );
|
||||
} catch (Exception e) {
|
||||
logger.error( e.getMessage(), e);
|
||||
}
|
||||
//logger.debug("[IOboundServer][run()]polling Msg-->" + new String(pollingMessage.array()));
|
||||
String pollmsg = new String(pollingMessage.array());
|
||||
if ( pollmsg.startsWith("REQPOLL") || pollmsg.startsWith("HDRREQPOLL")){
|
||||
byte[] resPoll = new byte[ll_len+msglen];
|
||||
System.arraycopy(incomingMessage.array(), 0, resPoll, 0, ll_len);
|
||||
System.arraycopy(pollingMessage.array(), 0, resPoll, ll_len, msglen);
|
||||
if ( resPoll[ll_len+2] == 'Q' )
|
||||
resPoll[ll_len+2] = 'S';
|
||||
if ( resPoll[ll_len+5] == 'Q' )
|
||||
resPoll[ll_len+5] = 'S';
|
||||
Socket socket = socketChannel.socket();
|
||||
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
|
||||
dout.write(resPoll, 0, resPoll.length);
|
||||
// logger.debug("[IOboundServer][run()]resPoll Msg-->" + new String(resPoll));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error( e.getMessage(), e);
|
||||
}
|
||||
|
||||
doResposeRecieve();
|
||||
|
||||
// Socket REUSE 모드가 아니라면 Connection Close
|
||||
if ( !isSocketReuse() ) {
|
||||
active = false;
|
||||
closeChannel();
|
||||
}
|
||||
} catch (SocketTimeoutException ex) {
|
||||
checkRequest();
|
||||
long idleTimeOutMin = context.getSessionTimeout();
|
||||
if ((idleTimeOutMin > 0) && this.idle(idleTimeOutMin * 60 * 1000)){
|
||||
logger.debug( "IOBoundServer(" + this.getName() + "), SessionTimeout :" + context.getSessionTimeout()
|
||||
+ ", timeout :" + context.getTimeout());
|
||||
active = false;
|
||||
}
|
||||
continue;
|
||||
} catch( Exception e ) {
|
||||
String msgEOF = ExceptionUtil.getErrorCode("BECEAIFJM010");
|
||||
if ( !e.getMessage().equals(msgEOF)){
|
||||
String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } );
|
||||
if ( errMsg.length() > 0 ) {
|
||||
logger.error( errMsg , e);
|
||||
|
||||
}
|
||||
}
|
||||
active = false;
|
||||
|
||||
continue;
|
||||
}
|
||||
} // end of active
|
||||
|
||||
// LOOP을 빠져나오면 (active가 아닌 경우), Channel 을 Close 한다.
|
||||
try {
|
||||
closeChannel();
|
||||
} catch( Throwable e ) {}
|
||||
|
||||
SocketAdapterManager.getInstance().removeConnection( this );
|
||||
|
||||
logger.info( CommonLib.getMessage("BICEAIASI003", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) );
|
||||
proxy.quiesceShutdown(this);
|
||||
SocketAdapterManager.getInstance().removeConnection( this );
|
||||
|
||||
interrupt();
|
||||
}
|
||||
|
||||
public SocketChannel getSocketchannel() {
|
||||
return socketChannel;
|
||||
}
|
||||
|
||||
public void setSocketchannel(SocketChannel socketchannel) {
|
||||
this.socketChannel = socketchannel;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
boolean status = true;
|
||||
StringBuffer strBuff = new StringBuffer();
|
||||
strBuff.append(context.getAdapterGroupName()).append(",");
|
||||
strBuff.append(context.getAdapterName()).append(",");
|
||||
strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(",");
|
||||
strBuff.append(context.getSocketType()).append(",");
|
||||
strBuff.append(context.getResponseType()).append(",");
|
||||
try {
|
||||
strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(",");
|
||||
} catch( Throwable e ) {
|
||||
status = false;
|
||||
strBuff.append("?:?,");
|
||||
}
|
||||
|
||||
try {
|
||||
strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(",");
|
||||
} catch( Throwable e ) {
|
||||
status = false;
|
||||
strBuff.append("?:?,");
|
||||
}
|
||||
|
||||
strBuff.append( status ).append(",");
|
||||
strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(",");
|
||||
strBuff.append(CommonLib.getCurrentTime( this.lastActivity ));
|
||||
|
||||
return strBuff.toString();
|
||||
}
|
||||
|
||||
private void doResposeRecieve(){
|
||||
|
||||
String strUUID = null;
|
||||
|
||||
//----------------------------------------------------------------
|
||||
//BatchMsgDoc 생성
|
||||
batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(true); //true:초기화함
|
||||
|
||||
//BatchMsgDoc Layer, SubLayer, StartTime 설정
|
||||
EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SOCKET_SERVER, CommonKeys.SUB_LAYER_SOCKET_SERVER);
|
||||
|
||||
try {
|
||||
|
||||
if (adapter.getRqstRspnsDstcd().equalsIgnoreCase("A")) {
|
||||
// 응답수신 셋팅
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_RECEIVE);
|
||||
} else {
|
||||
// 응답송신 셋팅
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_SEND);
|
||||
}
|
||||
logger.info("[IOboundServer] ProcessCode >> " + adapter.getBatchProcessCode());
|
||||
ArrayList<OutsideVO> osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode());
|
||||
int i=0;
|
||||
for (i=0; i<osd_array.size(); i++) {
|
||||
OutsideVO tmpVO = osd_array.get(i);
|
||||
|
||||
if (tmpVO.getOsdCode().equalsIgnoreCase(adapter.getBatchInstitutionCode())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
OutsideVO outside = null;
|
||||
if (i==osd_array.size()) {
|
||||
String errMsg = "[IOboundServer] 대외기관 정보를 구할 수 없습니다. 배치업무코드 [" + adapter.getBatchProcessCode()+"] 대외기관["+adapter.getBatchInstitutionCode()+"]";
|
||||
batchMsgDoc.getBatchMsg().getBody().setErrorCode(99);
|
||||
batchMsgDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
|
||||
throw new Exception(errMsg);
|
||||
} else {
|
||||
logger.info("OUSIDE INFO index [" + i + "]");
|
||||
outside = osd_array.get(i);
|
||||
}
|
||||
|
||||
// BatchMsg 에 기본값 지정..
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessCode(adapter.getBatchProcessCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessName(adapter.getBatchProcessName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(adapter.getBatchInstitutionCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(adapter.getBatchInstitutionName());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setInstituaionType(adapter.getBatchInstitutionType());
|
||||
batchMsgDoc.getBatchMsg().getBody().setPortNo(adapter.getBatchServerPortNo());
|
||||
batchMsgDoc.getBatchMsg().getBody().setTimeoutInterval(Integer.toString(adapter.getBatchInterMsgTimeout()));
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFlowCode(adapter.getBatchRcvFlowRuleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSystemConnCode(adapter.getBatchSystemConnCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleCode(adapter.getBatchRcvFlowRuleCode());
|
||||
RuleInfoVO vo = RuleInfoManager.getInstance().getRuleInfo(adapter.getBatchRcvFlowRuleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleDesc((vo!=null)? vo.getDesc() : "Rule Code not found in the TSEAIBR02");
|
||||
String recvdMsg = new String(incomingMessage.array());
|
||||
if ( adapter.getContext().isUsePollMsg() ){
|
||||
recvdMsg = new String(incomingMessage.array()) + new String(pollingMessage.array());
|
||||
}
|
||||
batchMsgDoc.getBatchMsg().getBody().setRecvedMsg(recvdMsg);
|
||||
|
||||
String strPathName = BatchDirUtil.getResponseRealDir();
|
||||
if ( strPathName.charAt(strPathName.length()-1) != '/' ) {
|
||||
strPathName = strPathName + '/';
|
||||
}
|
||||
BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(outside.getBatchCode(), outside.getOsdCode());
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
sb.append(btVO.getProcessCode());
|
||||
sb.append("/");
|
||||
sb.append(btVO.getOrganCode());
|
||||
strPathName = strPathName + sb.toString();
|
||||
logger.debug("[응답수신] PATH NAME = [" + strPathName + "]");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserID(adapter.getLnkID());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserPassword(adapter.getLnkPwd());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBlockSize(outside.getBlkSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(outside.getSequenceSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPacketSize(outside.getPacketSize()); // 20060411 추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(context.getHostName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPort(context.getPortNumber()+"");
|
||||
//----------------------------------------------------------------
|
||||
logger.info("**** USER ID > [" + batchMsgDoc.getBatchMsg().getHeader().getUserID());
|
||||
logger.info("**** PASS WD > [" + batchMsgDoc.getBatchMsg().getHeader().getUserPassword());
|
||||
logger.info("**** BLOCK > [" + batchMsgDoc.getBatchMsg().getHeader().getBlockSize());
|
||||
logger.info("**** SEQ SIZ > [" + batchMsgDoc.getBatchMsg().getHeader().getSequenceSize());
|
||||
logger.info("**** PACKET > [" + batchMsgDoc.getBatchMsg().getHeader().getPacketSize());
|
||||
|
||||
|
||||
//단계 종료시간 설정
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
|
||||
|
||||
//응답수신에 대한 최초 DB로그. StartLog 호출.
|
||||
LogUtil.setStartLog(batchMsgDoc);
|
||||
|
||||
strUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID();
|
||||
|
||||
// BatchRunningJobManager 에 Running Job 등록
|
||||
logger.info("IOboundServer : BatchRunningJobManager 에 응답송수신 작업 등록......");
|
||||
// 기관별 로그
|
||||
Logger.addInstLog(batchMsgDoc);
|
||||
|
||||
BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, this, batchMsgDoc);
|
||||
logger.info("IOboundServer : FlowController JPD 호출 시작......");
|
||||
ResponseHandler handler = new ResponseHandler();
|
||||
this.batchMsgDoc = handler.execute(this.batchMsgDoc);
|
||||
logger.info("IOboundServer : FlowController JPD 호출 완료 !!");
|
||||
String endComp = this.batchMsgDoc.getBatchMsg().getPhaseinfo().getPhaseType();
|
||||
if ( !"END".equals( endComp ) ) {
|
||||
logger.info( "FlowController JPD 호출결과 정상 종료가 아님 --> 소켓 연결 종료" );
|
||||
socketChannel.close();
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
try {
|
||||
// 파일로그 처리
|
||||
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASI010", new String[] {batchMsgDoc.getBatchMsg().getHeader().getUUID()});
|
||||
logger.error(errMsg, ex); //응답수신 Socket Server 배치메시지 생성 및 정보 설정시 오류가 발생하였습니다. [UUID: {1}]
|
||||
|
||||
// DB로그 처리
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
|
||||
LogUtil.setErrorLog(batchMsgDoc, errMsg);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("[Socket Server] ★★★★★ 응답수신 Socket Server 예외 처리 중 에러 !! ★★★★★", e);
|
||||
}
|
||||
} finally {
|
||||
// BatchRunningJobManager 에서 Running Job 제거
|
||||
logger.info("IOboundServer : BatchRunningJobManager 에서 응답송수신 작업 제거......");
|
||||
BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID);
|
||||
lastActivity = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
||||
private void checkRequest(){
|
||||
|
||||
if ( context.isResponseOnly()) return;
|
||||
|
||||
String processCode = context.getAdapterVO().getBatchProcessCode();
|
||||
String institutionCode = context.getAdapterVO().getBatchInstitutionCode();
|
||||
SchedulerMessageVO info;
|
||||
|
||||
while ( true ){
|
||||
try{
|
||||
info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode );
|
||||
if ( info == null ) {
|
||||
return;
|
||||
}
|
||||
|
||||
info.setSystemConnCode("this");
|
||||
|
||||
//해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동
|
||||
SchedulerMessageManager.getInstance().moveJobQueueToHandle(info);
|
||||
|
||||
//BatchMsgDoc 생성
|
||||
batchMsgDoc = EAIBatchMsgManager.createBatchMsg(true); //true:초기화함
|
||||
|
||||
//BatchMsgDoc Layer, SubLayer, StartTime 설정
|
||||
EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SCHEDULER, CommonKeys.SUB_LAYER_SCHEDULER_PROCESSING);
|
||||
|
||||
//BatchMsgDoc 값 설정
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUUID(info.getUUID());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessCode(info.getProcessCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessName(info.getProcessName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessType(info.getProcessType());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(info.getInstitutionCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFileName(info.getFileName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setInstituaionType(info.getInstitutionType());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserID(adapter.getLnkID());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserPassword(adapter.getLnkPwd());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(context.getHostName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPort(context.getPortNumber()+"");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSystemConnCode(info.getSystemConnCode());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setProtocol("TCP/IP");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRequestResponse(info.getRqstRspnsDstcd());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName());
|
||||
RuleInfoVO vo = RuleInfoManager.getInstance().getRuleInfo(info.getFlowRuleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleDesc((vo != null)? vo.getDesc() : "Rule Code not found in the TSEAIBR02");
|
||||
|
||||
// 레코드 크기 추가 2009.02.03
|
||||
String jobCode = batchMsgDoc.getBatchMsg().getHeader().getJobCode();
|
||||
BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode );
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize());
|
||||
|
||||
// 20120601 추가 -- 시작
|
||||
if ( info.getProcessType().equals(CommonKeys.PROCESS_REQUEST_SEND) ||
|
||||
info.getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND ) ){
|
||||
String hdrInfoName = info.getHdrInfoName();
|
||||
batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName);
|
||||
batchMsgDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName));
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName));
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFileSize(batchMsgDoc.getBatchMsg().getHeader().getRecLen() * batchMsgDoc.getBatchMsg().getHeader().getTotRecCnt());
|
||||
}
|
||||
// 20120601 추가 -- 여기까지
|
||||
|
||||
//재처리 플래그 설정..
|
||||
if (info.getRecvRetryFlag().equals("1")){
|
||||
batchMsgDoc.getBatchMsg().getHeader().setReqSendRetryFlag(true);
|
||||
logger.debug("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: UUID ["+info.getUUID()+"]의 RetryFlag 를 true로 설정합니다." );
|
||||
|
||||
}else {
|
||||
batchMsgDoc.getBatchMsg().getHeader().setReqSendRetryFlag(false);
|
||||
logger.debug("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: UUID ["+info.getUUID()+"]의 RetryFlag 를 false로 설정합니다." );
|
||||
}
|
||||
|
||||
|
||||
batchMsgDoc.getBatchMsg().getBody().setSubUUID(info.getSubUUID());
|
||||
batchMsgDoc.getBatchMsg().getBody().setSubLayerCode(CommonKeys.SUB_LAYER_SCHEDULER_PROCESSING);
|
||||
|
||||
try {
|
||||
LogUtil.updateLogMaster(batchMsgDoc);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
|
||||
logger.info("[IOboundServer] ■ BatchRunningJobManager 등록완료 ");
|
||||
String strUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID();
|
||||
|
||||
// BatchRunningJobManager 에 Running Job 등록
|
||||
logger.info("IOboundServer : BatchRunningJobManager 에 응답송수신 작업 등록......");
|
||||
BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, this, batchMsgDoc);
|
||||
|
||||
try {
|
||||
//===================================================
|
||||
logger.info("IOboundServer : FlowController JPD 호출 시작......");
|
||||
ResponseHandler handler = new ResponseHandler();
|
||||
this.batchMsgDoc = handler.execute(this.batchMsgDoc);
|
||||
logger.info("IOboundServer : FlowController JPD 호출 완료 !!");
|
||||
String endComp = this.batchMsgDoc.getBatchMsg().getPhaseinfo().getPhaseType();
|
||||
if ( !"END".equals( endComp ) ) {
|
||||
logger.info( "FlowController JPD 호출결과 EEND 소켓 연결 종료" );
|
||||
socketChannel.close();
|
||||
}
|
||||
//===================================================
|
||||
|
||||
} finally {
|
||||
// BatchRunningJobManager 에서 Running Job 제거
|
||||
logger.info("IOboundServer : BatchRunningJobManager 에서 응답송수신 작업 제거......");
|
||||
BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID);
|
||||
lastActivity = System.currentTimeMillis();
|
||||
}
|
||||
} catch ( Exception e){
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
public void processReadMessage( byte[] buffer ) throws Exception {
|
||||
if (buffer == null || buffer.length == 0) throw new Exception("");
|
||||
|
||||
int readBytes = 0;
|
||||
boolean isEOF = false;
|
||||
Socket socket = socketChannel.socket();
|
||||
DataInputStream din = new DataInputStream( socket.getInputStream());
|
||||
int len = buffer.length;
|
||||
int timeOut = (int)getTimeout();
|
||||
|
||||
if ( timeOut < 1000 ) {
|
||||
timeOut = 1000;
|
||||
}
|
||||
if ( timeOut > 60000 ) {
|
||||
timeOut = 60000;
|
||||
}
|
||||
|
||||
logger.info( "[IOboundServer][" + context.getAdapterName() + "]데이터 수신 대기 중(타임아웃:" + timeOut + ")");
|
||||
socket.setSoTimeout( timeOut );
|
||||
|
||||
while (readBytes < len) {
|
||||
try {
|
||||
readBytes += din.read(buffer, readBytes, len-readBytes);
|
||||
if (readBytes < 0) {
|
||||
isEOF = true;
|
||||
break;
|
||||
}
|
||||
|
||||
} catch (SocketTimeoutException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) { //throws IOException, NullPointerException, IndexOutOfBoundsException
|
||||
active = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if ( isEOF ) {
|
||||
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJM010");
|
||||
throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다.
|
||||
}
|
||||
|
||||
} // end of readData
|
||||
private boolean isSocketReuse() {
|
||||
return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG );
|
||||
}
|
||||
private synchronized void closeChannel() throws IOException {
|
||||
|
||||
if(socketChannel != null ) {
|
||||
socketChannel.socket().close();
|
||||
socketChannel.close();
|
||||
}
|
||||
socketChannel = null;
|
||||
} //
|
||||
private String getReadingMessage() {
|
||||
String rMsg = "";
|
||||
if ( incomingMessage != null && incomingMessage.position() > 0 ) {
|
||||
byte[] dMsg = new byte[ incomingMessage.position() ];
|
||||
System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length );
|
||||
rMsg = CommonLib.getDumpMessage( dMsg );
|
||||
}
|
||||
return rMsg;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,903 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Properties;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
import com.eactive.eai.batch.common.BatchDirUtil;
|
||||
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.flowController.BatchTargetVO;
|
||||
import com.eactive.eai.batch.flowController.FlowControllerManager;
|
||||
import com.eactive.eai.batch.message.EAIBatchMsgManager;
|
||||
import com.eactive.eai.batch.osd.OutsideManager;
|
||||
import com.eactive.eai.batch.osd.OutsideVO;
|
||||
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
|
||||
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
|
||||
import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager;
|
||||
import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO;
|
||||
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;
|
||||
import com.eactive.eai.inbound.ResponseHandler;
|
||||
|
||||
public class InboundClient extends Thread implements SocketService {
|
||||
|
||||
protected ConfigurationContext context;
|
||||
private boolean active;
|
||||
private SocketChannel channel;
|
||||
|
||||
protected long firstActivity;
|
||||
protected long lastActivity;
|
||||
|
||||
private boolean retryFlag;
|
||||
|
||||
private ByteBuffer incomingMessage;
|
||||
private ByteBuffer pollingMessage;
|
||||
|
||||
private Logger logger;
|
||||
private static Logger errLogger = SocketLogManager.getInstance().getErrLogger();
|
||||
AdapterVO adapter;
|
||||
|
||||
// 응답 송/수신 각 배치작업을 구별하기 위한 ID
|
||||
//----------------------------------------------------------------
|
||||
//배치 응답송수신 전용, 전체 단계 작업에 대한 BatchMsg 객체 (Socket Coneection 내내 동일함)
|
||||
//(전제조건) 1. 배치 전체 단계 전문 Flow 에 대해서 동일한 Socket Connection이 사용되어야 함
|
||||
// 2. 전체 단계 Flow 종료시 해당 Socket Connection 이 종료되고 Inbound Server 가 종료되어야 함
|
||||
private BatchDoc batchMsgDoc;
|
||||
private byte[] MEGA_IN_MSG = { (byte) 0xff, (byte) 0xfb, (byte) 0x00, (byte) 0xff,
|
||||
(byte) 0xfd, (byte) 0x00, (byte) 0xff, (byte) 0xfb,
|
||||
(byte) 0x19, (byte) 0xff, (byte) 0xfd, (byte) 0x19 };
|
||||
private byte[] MEGA_OUT_MSG = { (byte) 0xff, (byte) 0xfd, (byte) 0x19 };
|
||||
private byte[] MEGA_EOR_MSG = { (byte) 0xff, (byte) 0xef };
|
||||
|
||||
private boolean mega_init = false;
|
||||
//----------------------------------------------------------------
|
||||
|
||||
public InboundClient(ConfigurationContext context) {
|
||||
|
||||
String name = this.getName();
|
||||
this.setName( context.getAdapterName() + "-CONNECTION" + name.substring( name.lastIndexOf("-")) );
|
||||
|
||||
this.context = context;
|
||||
active = true;
|
||||
retryFlag = true;
|
||||
|
||||
incomingMessage = null;
|
||||
|
||||
logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName() );
|
||||
|
||||
}
|
||||
|
||||
private int getTraceLevel() {
|
||||
return context.getTraceLevel();
|
||||
}
|
||||
|
||||
private long getTimeout() {
|
||||
return ( this.context.getTimeout() * 1000L );
|
||||
}
|
||||
|
||||
private boolean isSocketReuse() {
|
||||
return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the context.
|
||||
*/
|
||||
public ConfigurationContext getContext() {
|
||||
return context;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
//*** 어댑터에 대해 하나의 대외기관 연결정보(BJ05)만이 매핑되어 있어야 하는 것이 보장되어야 한다.
|
||||
logger.info("[InboundClient] Group ["+context.getAdapterGroupName()+"] Adapter["+context.getAdapterName()+"]");
|
||||
adapter = AdapterManager.getInstance().getAdapterVO(context.getAdapterGroupName(), context.getAdapterName());
|
||||
|
||||
mega_init = false;
|
||||
|
||||
int readLength = 0;
|
||||
try {
|
||||
readLength = adapter.getContext().getLlFieldIndex() + adapter.getContext().getLlFieldLength();
|
||||
} catch (Exception e) {}
|
||||
if ( readLength < 1 ){
|
||||
readLength = 9;
|
||||
}
|
||||
|
||||
firstActivity = System.currentTimeMillis();
|
||||
lastActivity = firstActivity;
|
||||
|
||||
String socketInfo = "";
|
||||
|
||||
|
||||
while ( retryFlag ) {
|
||||
|
||||
active = true;
|
||||
|
||||
// channel 을 열고
|
||||
try {
|
||||
openChannel();
|
||||
socketInfo = this.getSocketInfo( this.getCurrentSocket() );
|
||||
} catch(Exception e) {
|
||||
String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "openChannel", e.getMessage(), "", "" } );
|
||||
logger.error( errMsg, e );
|
||||
|
||||
if ( retryFlag ) {
|
||||
waitRecoverConnection();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
logger.info( CommonLib.getMessage("BICEAIASI002", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) );
|
||||
}
|
||||
|
||||
// active 상태에서 LOOP
|
||||
while ( active ) {
|
||||
try {
|
||||
if ( !mega_init )
|
||||
incomingMessage = ByteBuffer.allocate( readLength );
|
||||
// length & message buffer clear
|
||||
if ( incomingMessage != null ) {
|
||||
incomingMessage.clear();
|
||||
|
||||
processReadMessage( incomingMessage.array() );// 29259819 npe
|
||||
}
|
||||
// 통계데이타 갱신
|
||||
this.checkActivity();
|
||||
lastActivity = System.currentTimeMillis();
|
||||
|
||||
// (DEBUG 레벨일 경우) 메시지수신 로그
|
||||
if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
logger.debug( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage(incomingMessage.array())}));
|
||||
}
|
||||
|
||||
try {
|
||||
//logger.info( "[InboundClient][adapter.getContext().getLlFieldLength()]-->" + adapter.getContext().getLlFieldLength() + ")");
|
||||
if ( adapter.getContext().getLlFieldLength() > 0 && !mega_init ){
|
||||
int ll_len = adapter.getContext().getLlFieldLength();
|
||||
byte[] ll_fld = new byte[ll_len];
|
||||
System.arraycopy(incomingMessage.array(), adapter.getContext().getLlFieldIndex(), ll_fld, 0, adapter.getContext().getLlFieldLength());
|
||||
|
||||
if ( byteCompare( ll_fld, MEGA_EOR_MSG )){
|
||||
continue;
|
||||
}
|
||||
if ( byteCompare( ll_fld, MEGA_IN_MSG )){
|
||||
Socket socket = channel.socket();
|
||||
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
|
||||
dout.write(MEGA_OUT_MSG, 0, MEGA_OUT_MSG.length);
|
||||
mega_init = true;
|
||||
incomingMessage = ByteBuffer.allocate( 2 );
|
||||
continue;
|
||||
}
|
||||
if ( Integer.parseInt(new String(ll_fld)) == 0 ) continue;
|
||||
// polling 메세지 처리
|
||||
//logger.info( "[InboundClient][adapter.getContext().isUsePollMsg()]-->" + adapter.getContext().isUsePollMsg() + ")");
|
||||
if ( adapter.getContext().isUsePollMsg() ){
|
||||
|
||||
int msglen = Integer.parseInt(new String(ll_fld));
|
||||
pollingMessage = ByteBuffer.allocate(msglen);
|
||||
try {
|
||||
processReadMessage( pollingMessage.array() );
|
||||
} catch (Exception e) {
|
||||
logger.error( e.getMessage(), e);
|
||||
}
|
||||
//logger.debug("[IOboundClient][run()]polling Msg-->" + new String(pollingMessage.array()));
|
||||
String pollmsg = new String(pollingMessage.array());
|
||||
if ( pollmsg.startsWith("REQPOLL") || pollmsg.startsWith("HDRREQPOLL")){
|
||||
byte[] resPoll = new byte[ll_len+msglen];
|
||||
System.arraycopy(incomingMessage.array(), 0, resPoll, 0, ll_len);
|
||||
System.arraycopy(pollingMessage.array(), 0, resPoll, ll_len, msglen);
|
||||
if ( resPoll[ll_len+2] == 'Q' )
|
||||
resPoll[ll_len+2] = 'S';
|
||||
if ( resPoll[ll_len+5] == 'Q' )
|
||||
resPoll[ll_len+5] = 'S';
|
||||
|
||||
Socket socket = channel.socket();
|
||||
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
|
||||
dout.write(resPoll, 0, resPoll.length);
|
||||
// logger.debug("[IOboundClient][run()]resPoll Msg-->" + new String(resPoll));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error( e.getMessage(), e);
|
||||
}
|
||||
|
||||
doResposeRecieve();
|
||||
|
||||
// Socket REUSE 모드가 아니라면 Connection Close
|
||||
if ( !isSocketReuse() ) {
|
||||
active = false;
|
||||
closeChannel();
|
||||
}
|
||||
} catch (SocketTimeoutException ex) {
|
||||
checkRequest();
|
||||
if ( adapter.getContext().getLlFieldLength() == 12){
|
||||
try {
|
||||
if ( channel != null ){
|
||||
Socket socket = channel.socket();
|
||||
DataOutputStream dout;
|
||||
dout = new DataOutputStream(socket.getOutputStream());
|
||||
dout.write(MEGA_EOR_MSG, 0, MEGA_EOR_MSG.length);
|
||||
}
|
||||
continue;
|
||||
} catch (IOException e) {
|
||||
waitRecoverConnection();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
long idleTimeOutMin = context.getSessionTimeout();
|
||||
if ((idleTimeOutMin > 0) && this.idle(idleTimeOutMin * 60 * 1000)){
|
||||
logger.debug( "InboundClient(" + this.getName() + "), SessionTimeout :" + context.getSessionTimeout()
|
||||
+ ", timeout :" + context.getTimeout());
|
||||
waitRecoverConnection();
|
||||
}
|
||||
continue;
|
||||
} catch( Exception e ) {
|
||||
String msgEOF = ExceptionUtil.getErrorCode("BECEAIFJM010");
|
||||
if ( !e.getMessage().equals(msgEOF)){
|
||||
String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } );
|
||||
if ( errMsg.length() > 0 ) {
|
||||
logger.error( errMsg , e);
|
||||
|
||||
if ( logger != errLogger ) {
|
||||
errLogger.error( errMsg, e );
|
||||
}
|
||||
}
|
||||
}
|
||||
//active = false;
|
||||
|
||||
waitRecoverConnection();
|
||||
continue;
|
||||
}
|
||||
}// end of active
|
||||
}// end of retry
|
||||
|
||||
// LOOP을 빠져나오면 (active가 아닌 경우), Channel 을 Close 한다.
|
||||
try {
|
||||
closeChannel();
|
||||
} catch( Throwable e ) {}
|
||||
|
||||
SocketAdapterManager.getInstance().removeConnection( this );
|
||||
|
||||
logger.info( CommonLib.getMessage("BICEAIASI003", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) );
|
||||
|
||||
interrupt();
|
||||
|
||||
} // end of startup ...
|
||||
|
||||
private String getReadingMessage() {
|
||||
String rMsg = "";
|
||||
if ( incomingMessage != null && incomingMessage.position() > 0 ) {
|
||||
byte[] dMsg = new byte[ incomingMessage.position() ];
|
||||
System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length );
|
||||
rMsg = CommonLib.getDumpMessage( dMsg );
|
||||
}
|
||||
return rMsg;
|
||||
}
|
||||
|
||||
protected String getSocketInfo(Socket socket) {
|
||||
StringBuffer connInfo = new StringBuffer();
|
||||
|
||||
connInfo.append("Local Address=");
|
||||
connInfo.append( socket.getLocalAddress().getHostAddress()).append(":").append(socket.getLocalPort()).append(", ");
|
||||
connInfo.append("Remote Address=");
|
||||
connInfo.append( socket.getInetAddress().getHostAddress()).append(":").append(socket.getPort());
|
||||
|
||||
return connInfo.toString();
|
||||
}
|
||||
|
||||
public int getCurrentState() {
|
||||
return CommonLib.PROCESSING_PROTOCOL;
|
||||
}
|
||||
|
||||
public boolean isConnected() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void checkActivity() {
|
||||
}
|
||||
|
||||
public boolean idle(long timeout) {
|
||||
long idleTime = System.currentTimeMillis() - this.lastActivity;
|
||||
|
||||
return ( idleTime > timeout );
|
||||
}
|
||||
|
||||
public void setControl(Object control) {
|
||||
}
|
||||
|
||||
public void notifyMessage() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Socket Recovery Manager에 의해 Connection Recovery가 되도록 기다린다.
|
||||
*
|
||||
*/
|
||||
public synchronized void waitRecoverConnection() {
|
||||
mega_init = false;
|
||||
|
||||
try {
|
||||
if ( !retryFlag ) return;
|
||||
|
||||
try { closeChannel(); } catch(Exception ie) {}
|
||||
if ( retryFlag && SocketAdapterManager.getInstance().addError( this ) ) {
|
||||
wait();
|
||||
}
|
||||
} catch ( InterruptedException e ) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Socket Recovery Manager에 의해 recovery되면 Socket Recovery Manager에 의해 통지된다. *
|
||||
*/
|
||||
public synchronized void notifyRecoverConnection() {
|
||||
notify();
|
||||
}
|
||||
public void processReadMessage( byte[] buffer ) throws Exception {
|
||||
processReadMessage( buffer, -1 );
|
||||
}
|
||||
|
||||
public void processReadMessage( byte[] buffer, int rqTime ) throws Exception {
|
||||
if (buffer == null || buffer.length == 0) throw new Exception("");
|
||||
|
||||
int readBytes = 0;
|
||||
boolean isEOF = false;
|
||||
Socket socket = channel.socket();
|
||||
DataInputStream din = new DataInputStream( socket.getInputStream());
|
||||
int len = buffer.length;
|
||||
int timeOut = (int)getTimeout();
|
||||
|
||||
if ( timeOut < 1000 ) {
|
||||
timeOut = 1000;
|
||||
}
|
||||
if ( timeOut > 60000 ) {
|
||||
timeOut = 60000;
|
||||
}
|
||||
if ( rqTime > -1 ){
|
||||
timeOut = rqTime;
|
||||
}
|
||||
|
||||
logger.info( "[InboundClient][" + context.getAdapterName() + "]데이터 수신 대기 중(타임아웃:" + timeOut + ")");
|
||||
socket.setSoTimeout( timeOut );
|
||||
|
||||
while (readBytes < len) {
|
||||
try {
|
||||
readBytes += din.read(buffer, readBytes, len-readBytes);
|
||||
if (readBytes < 0) {
|
||||
isEOF = true;
|
||||
break;
|
||||
}
|
||||
|
||||
} catch (SocketTimeoutException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) { //throws IOException, NullPointerException, IndexOutOfBoundsException
|
||||
logger.error("★★★★★ Socket 에서 데이터 수신 시 오류 발생 !! ★★★★★", ex);
|
||||
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJM011");
|
||||
throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Socket 오류가 발생하여 데이터를 읽어들일 수 없습니다.
|
||||
}
|
||||
}
|
||||
|
||||
if ( isEOF ) {
|
||||
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJM010");
|
||||
throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다.
|
||||
}
|
||||
|
||||
} // end of readData
|
||||
|
||||
public synchronized void shutdown() {
|
||||
|
||||
active = false;
|
||||
retryFlag = false;
|
||||
|
||||
SocketAdapterManager.getInstance().removeError( this );
|
||||
try {
|
||||
notify();
|
||||
} catch( Exception e ) {}
|
||||
|
||||
//to gracefully shutdown the thread
|
||||
try {
|
||||
closeChannel();
|
||||
} catch (Exception e) {}
|
||||
SocketAdapterManager.getInstance().removeError( this );
|
||||
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return retryFlag;
|
||||
}
|
||||
|
||||
public Socket getCurrentSocket() {
|
||||
return channel.socket();
|
||||
}
|
||||
|
||||
public boolean connect() {
|
||||
if ( !retryFlag ) return true;
|
||||
|
||||
try {
|
||||
openChannel();
|
||||
return true;
|
||||
} catch ( Exception e ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
}
|
||||
|
||||
private synchronized void openChannel() throws IOException {
|
||||
|
||||
if ( channel == null || !channel.isOpen() ) {
|
||||
if ( !retryFlag ) return;
|
||||
|
||||
channel = SocketChannel.open();
|
||||
if ( context.getLocalHostName() != null && !context.getLocalHostName().equals("") ) {
|
||||
channel.socket().bind( new InetSocketAddress( InetAddress.getAllByName(context.getLocalHostName())[0], context.getLocalPortNumber() ) );
|
||||
channel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) );
|
||||
} else {
|
||||
channel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) );
|
||||
}
|
||||
|
||||
channel.socket().setTcpNoDelay(true);
|
||||
|
||||
if ( isSocketReuse() ) {
|
||||
channel.socket().setSoLinger(true, 100);
|
||||
}
|
||||
|
||||
// Connection 시 통계자료 RESET
|
||||
this.firstActivity = System.currentTimeMillis();
|
||||
this.lastActivity = this.firstActivity;
|
||||
|
||||
try {
|
||||
Thread.sleep( 300L );
|
||||
} catch( Exception e ) {}
|
||||
|
||||
if ( !this.isConnected() ) {
|
||||
throw new IOException("Closed by Server");
|
||||
}
|
||||
|
||||
if ( retryFlag ) {
|
||||
SocketAdapterManager.getInstance().addConnection( this );
|
||||
} else {
|
||||
closeChannel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getRemoteIPAddress() {
|
||||
return null;
|
||||
}
|
||||
|
||||
private synchronized void closeChannel() throws IOException {
|
||||
if(channel != null ) {
|
||||
channel.socket().close();
|
||||
channel.close();
|
||||
}
|
||||
channel = null;
|
||||
} //
|
||||
|
||||
// 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, SYNC, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각
|
||||
public String toString() {
|
||||
boolean status = true;
|
||||
StringBuffer strBuff = new StringBuffer();
|
||||
strBuff.append(context.getAdapterGroupName()).append(",");
|
||||
strBuff.append(context.getAdapterName()).append(",");
|
||||
strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(",");
|
||||
strBuff.append(context.getSocketType()).append(",");
|
||||
strBuff.append(context.getResponseType()).append(",");
|
||||
|
||||
try {
|
||||
strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(",");
|
||||
} catch( Throwable e ) {
|
||||
status = false;
|
||||
strBuff.append("?:?,");
|
||||
}
|
||||
|
||||
try {
|
||||
strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(",");
|
||||
} catch( Throwable e ) {
|
||||
status = false;
|
||||
strBuff.append("?:?,");
|
||||
}
|
||||
|
||||
strBuff.append( status ).append(",");
|
||||
strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(",");
|
||||
strBuff.append(CommonLib.getCurrentTime( this.lastActivity ));
|
||||
|
||||
return strBuff.toString();
|
||||
}
|
||||
|
||||
public void setLastActivity() {
|
||||
}
|
||||
|
||||
public long getFirstActivity() {
|
||||
return firstActivity;
|
||||
}
|
||||
|
||||
public long getLastActivity() {
|
||||
return lastActivity;
|
||||
}
|
||||
|
||||
private void doResposeRecieve(){
|
||||
PropManager manager = PropManager.getInstance();
|
||||
Properties prop = manager.getProperties( adapter.getPropGroupName() );
|
||||
String rcvFlowRuleCode = prop.getProperty("reponse.rule.code");
|
||||
String strUUID = null;
|
||||
|
||||
//----------------------------------------------------------------
|
||||
//BatchMsgDoc 생성
|
||||
batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(true); //true:초기화함
|
||||
|
||||
//BatchMsgDoc Layer, SubLayer, StartTime 설정
|
||||
EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SOCKET_SERVER, CommonKeys.SUB_LAYER_SOCKET_SERVER);
|
||||
|
||||
try {
|
||||
if (adapter.getRqstRspnsDstcd().equalsIgnoreCase("A")) {
|
||||
// 응답수신 셋팅
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_RECEIVE);
|
||||
} else {
|
||||
// 응답송신 셋팅
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_SEND);
|
||||
}
|
||||
logger.info("[InboundClient] ProcessCode >> " + adapter.getBatchProcessCode());
|
||||
ArrayList<OutsideVO> osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode());
|
||||
int i=0;
|
||||
for (i=0; i<osd_array.size(); i++) {
|
||||
OutsideVO tmpVO = osd_array.get(i);
|
||||
if (tmpVO.getOsdCode().equalsIgnoreCase(adapter.getBatchInstitutionCode())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
OutsideVO outside = null;
|
||||
if (i==osd_array.size()) {
|
||||
String errMsg = "[InboundClient] 대외기관 정보를 구할 수 없습니다. 배치업무코드 [" + adapter.getBatchProcessCode()+"] 대외기관["+adapter.getBatchInstitutionCode()+"]";
|
||||
batchMsgDoc.getBatchMsg().getBody().setErrorCode(99);
|
||||
batchMsgDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
|
||||
throw new Exception(errMsg);
|
||||
} else {
|
||||
logger.info("OUSIDE INFO index [" + i + "]");
|
||||
outside = (OutsideVO) osd_array.get(i);
|
||||
}
|
||||
|
||||
// BatchMsg 에 기본값 지정..
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessCode(adapter.getBatchProcessCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessName(adapter.getBatchProcessName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(adapter.getBatchInstitutionCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(adapter.getBatchInstitutionName());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setInstituaionType(adapter.getBatchInstitutionType());
|
||||
batchMsgDoc.getBatchMsg().getBody().setPortNo(adapter.getBatchServerPortNo());
|
||||
batchMsgDoc.getBatchMsg().getBody().setTimeoutInterval(Integer.toString(adapter.getBatchInterMsgTimeout()));
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFlowCode(rcvFlowRuleCode);
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSystemConnCode(adapter.getBatchSystemConnCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleCode(rcvFlowRuleCode);
|
||||
RuleInfoVO vo = RuleInfoManager.getInstance().getRuleInfo(rcvFlowRuleCode);
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleDesc((vo!=null)? vo.getDesc() : "Rule Code not found in the TSEAIBR02");
|
||||
String recvdMsg = new String(incomingMessage.array());
|
||||
if ( adapter.getContext().isUsePollMsg() ){
|
||||
recvdMsg = new String(incomingMessage.array()) + new String(pollingMessage.array());
|
||||
}
|
||||
batchMsgDoc.getBatchMsg().getBody().setRecvedMsg(recvdMsg);
|
||||
|
||||
|
||||
// // 응답송신기능의 추가를 위해 일부 기능 수정 함.
|
||||
// if (adapter.getRqstRspnsDstcd().equalsIgnoreCase("C") ) {
|
||||
// // 응답송신 이면
|
||||
// String strPathName = BatchDirUtil.getResSendRealDir();
|
||||
// if ( strPathName.charAt(strPathName.length()-1) != '/' ) {
|
||||
// strPathName = strPathName + '/';
|
||||
// }
|
||||
// BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(outside.getBatchCode(), outside.getOsdCode());
|
||||
// StringBuffer sb = new StringBuffer();
|
||||
//
|
||||
// sb.append(btVO.getProcessCode());
|
||||
// sb.append("/");
|
||||
// sb.append(btVO.getOrganCode());
|
||||
// strPathName = strPathName + sb.toString();
|
||||
// logger.debug("[응답송신] PATH NAME = [" + strPathName + "]");
|
||||
//
|
||||
// File ff = new File(strPathName);
|
||||
// if (!ff.exists()) {
|
||||
// logger.warn("응답송신용 디렉토리 [" + strPathName + "] 이 없습니다.");
|
||||
// throw new Exception(ExceptionUtil.getErrorCode("BWCEAIASI003"));
|
||||
// }
|
||||
// File[] fileList = ff.listFiles();
|
||||
// String strFileName = "";
|
||||
// long lnFileSize = -1;
|
||||
// if (fileList.length> 0) {
|
||||
// for (int i1=0; i1<fileList.length; i1++) {
|
||||
// if ( fileList[i1].isFile()) {
|
||||
// strFileName = fileList[i1].getName();
|
||||
// lnFileSize = fileList[i1].length();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFlowCode(outside.getSendRuleCode());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRuleCode(outside.getSendRuleCode());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRuleDesc(RuleInfoManager.getInstance().getRuleInfo(outside.getSendRuleCode()).getDesc());
|
||||
//
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFileName(strFileName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(strFileName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFileSize(lnFileSize);
|
||||
// }
|
||||
// else {
|
||||
// //응답 수신 디렉토리 설정
|
||||
// String strPathName = BatchDirUtil.getResponseRealDir();
|
||||
// if ( strPathName.charAt(strPathName.length()-1) != '/' ) {
|
||||
// strPathName = strPathName + '/';
|
||||
// }
|
||||
// BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(outside.getBatchCode(), outside.getOsdCode());
|
||||
// StringBuffer sb = new StringBuffer();
|
||||
//
|
||||
// sb.append(btVO.getProcessName()).append("_").append(btVO.getProcessCode());
|
||||
// sb.append("/");
|
||||
// sb.append(btVO.getOrganName()).append("_").append(btVO.getOrganCode());
|
||||
// strPathName = strPathName + sb.toString();
|
||||
// logger.debug("[응답수신] PATH NAME = [" + strPathName + "]");
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// // <<< 응답수신 디렉토리 설정
|
||||
// }
|
||||
|
||||
//응답 수신 디렉토리 설정
|
||||
String strPathName = BatchDirUtil.getResponseRealDir();
|
||||
if ( strPathName.charAt(strPathName.length()-1) != '/' ) {
|
||||
strPathName = strPathName + '/';
|
||||
}
|
||||
BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(outside.getBatchCode(), outside.getOsdCode());
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
sb.append(btVO.getProcessCode());
|
||||
sb.append("/");
|
||||
sb.append(btVO.getOrganCode());
|
||||
strPathName = strPathName + sb.toString();
|
||||
logger.debug("[응답수신] PATH NAME = [" + strPathName + "]");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// <<< 응답수신 디렉토리 설정
|
||||
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setProtocol("TCP/IP");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserID(adapter.getLnkID());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserPassword(adapter.getLnkPwd());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBlockSize(outside.getBlkSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(outside.getSequenceSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPacketSize(outside.getPacketSize()); // 20060411 추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(context.getHostName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPort(context.getPortNumber()+"");
|
||||
//----------------------------------------------------------------
|
||||
logger.info("**** USER ID > [" + batchMsgDoc.getBatchMsg().getHeader().getUserID());
|
||||
logger.info("**** PASS WD > [" + batchMsgDoc.getBatchMsg().getHeader().getUserPassword());
|
||||
logger.info("**** BLOCK > [" + batchMsgDoc.getBatchMsg().getHeader().getBlockSize());
|
||||
logger.info("**** SEQ SIZ > [" + batchMsgDoc.getBatchMsg().getHeader().getSequenceSize());
|
||||
logger.info("**** PACKET > [" + batchMsgDoc.getBatchMsg().getHeader().getPacketSize());
|
||||
|
||||
//단계 종료시간 설정
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
|
||||
|
||||
// 기관별 로그
|
||||
Logger.addInstLog(batchMsgDoc);
|
||||
|
||||
//응답수신에 대한 최초 DB로그. StartLog 호출.
|
||||
LogUtil.setStartLog(batchMsgDoc);
|
||||
|
||||
strUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID();
|
||||
|
||||
// BatchRunningJobManager 에 Running Job 등록
|
||||
logger.info("InboundClient : BatchRunningJobManager 에 응답송수신 작업 등록......");
|
||||
|
||||
BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, this, batchMsgDoc);
|
||||
logger.info("InboundClient : FlowController JPD 호출 시작......");
|
||||
ResponseHandler handler = new ResponseHandler();
|
||||
this.batchMsgDoc = handler.execute(this.batchMsgDoc);
|
||||
logger.info("InboundClient : FlowController JPD 호출 완료 !!");
|
||||
String endComp = this.batchMsgDoc.getBatchMsg().getPhaseinfo().getPhaseType();
|
||||
if ( !"END".equals( endComp ) ) {
|
||||
logger.info( "FlowController JPD 호출결과 정상 종료가 아님 --> 소켓 연결 종료" );
|
||||
waitRecoverConnection();
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
try {
|
||||
// 파일로그 처리
|
||||
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASI010", new String[] {batchMsgDoc.getBatchMsg().getHeader().getUUID()});
|
||||
logger.error(errMsg, ex); //응답수신 Socket Server 배치메시지 생성 및 정보 설정시 오류가 발생하였습니다. [UUID: {1}]
|
||||
|
||||
// DB로그 처리
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
|
||||
LogUtil.setErrorLog(batchMsgDoc, errMsg);
|
||||
waitRecoverConnection();
|
||||
} catch (Exception e) {
|
||||
logger.error("[Socket Server] ★★★★★ 응답수신 Socket Server 예외 처리 중 에러 !! ★★★★★", e);
|
||||
}
|
||||
} finally {
|
||||
// BatchRunningJobManager 에서 Running Job 제거
|
||||
logger.info("InboundClient : BatchRunningJobManager 에서 응답송수신 작업 제거......");
|
||||
BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID);
|
||||
lastActivity = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
||||
private void checkRequest(){
|
||||
|
||||
if ( context.isResponseOnly()) return;
|
||||
|
||||
String processCode = context.getAdapterVO().getBatchProcessCode();
|
||||
String institutionCode = context.getAdapterVO().getBatchInstitutionCode();
|
||||
SchedulerMessageVO info;
|
||||
|
||||
while ( true ){
|
||||
try{
|
||||
info = SchedulerMessageManager.getInstance().getExecutableJobFromQueue(processCode, institutionCode );
|
||||
if ( info == null ) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info("[InboundClient] ProcessCode >> " + adapter.getBatchProcessCode());
|
||||
ArrayList<OutsideVO> osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode());
|
||||
int i=0;
|
||||
for (i=0; i<osd_array.size(); i++) {
|
||||
OutsideVO tmpVO = osd_array.get(i);
|
||||
if (tmpVO.getOsdCode().equalsIgnoreCase(adapter.getBatchInstitutionCode())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
OutsideVO outside = null;
|
||||
if (i==osd_array.size()) {
|
||||
String errMsg = "[InboundClient] 대외기관 정보를 구할 수 없습니다. 배치업무코드 [" + adapter.getBatchProcessCode()+"] 대외기관["+adapter.getBatchInstitutionCode()+"]";
|
||||
batchMsgDoc.getBatchMsg().getBody().setErrorCode(99);
|
||||
batchMsgDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
|
||||
throw new Exception(errMsg);
|
||||
} else {
|
||||
logger.info("OUSIDE INFO index [" + i + "]");
|
||||
outside = (OutsideVO) osd_array.get(i);
|
||||
}
|
||||
|
||||
//해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동
|
||||
SchedulerMessageManager.getInstance().moveJobQueueToHandle(info);
|
||||
|
||||
//BatchMsgDoc 생성
|
||||
batchMsgDoc = EAIBatchMsgManager.createBatchMsg(true); //true:초기화함
|
||||
|
||||
//BatchMsgDoc Layer, SubLayer, StartTime 설정
|
||||
EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SCHEDULER, CommonKeys.SUB_LAYER_SCHEDULER_PROCESSING);
|
||||
|
||||
//BatchMsgDoc 값 설정
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUUID(info.getUUID());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessCode(info.getProcessCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessName(info.getProcessName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessType(info.getProcessType());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(info.getInstitutionCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFileName(info.getFileName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(info.getInstitutionName());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setInstituaionType(info.getInstitutionType());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBlockSize(outside.getBlkSize());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(outside.getSequenceSize());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPacketSize(outside.getPacketSize());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserID(adapter.getLnkID());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserPassword(adapter.getLnkPwd());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(context.getHostName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPort(context.getPortNumber()+"");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSystemConnCode(info.getSystemConnCode());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setProtocol("TCP/IP");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRequestResponse(info.getRqstRspnsDstcd());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(info.getHdrInfoName());
|
||||
RuleInfoVO vo = RuleInfoManager.getInstance().getRuleInfo(info.getFlowRuleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleDesc((vo != null)? vo.getDesc() : "Rule Code not found in the TSEAIBR02");
|
||||
|
||||
// 레코드 크기 추가 2009.02.03
|
||||
String jobCode = batchMsgDoc.getBatchMsg().getHeader().getJobCode();
|
||||
BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode );
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize());
|
||||
|
||||
// 20120601 추가 -- 시작
|
||||
if ( info.getProcessType().equals(CommonKeys.PROCESS_REQUEST_SEND) ||
|
||||
info.getProcessType().equals(CommonKeys.PROCESS_RESPONSE_SEND ) ){
|
||||
String hdrInfoName = info.getHdrInfoName();
|
||||
batchMsgDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName);
|
||||
batchMsgDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName));
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName));
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFileSize(batchMsgDoc.getBatchMsg().getHeader().getRecLen() * batchMsgDoc.getBatchMsg().getHeader().getTotRecCnt());
|
||||
}
|
||||
// 20120601 추가 -- 여기까지
|
||||
|
||||
//재처리 플래그 설정..
|
||||
if (info.getRecvRetryFlag().equals("1")){
|
||||
batchMsgDoc.getBatchMsg().getHeader().setReqSendRetryFlag(true);
|
||||
logger.debug("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: UUID ["+info.getUUID()+"]의 RetryFlag 를 true로 설정합니다." );
|
||||
|
||||
}else {
|
||||
batchMsgDoc.getBatchMsg().getHeader().setReqSendRetryFlag(false);
|
||||
logger.debug("[스케쥴 핸들러] ■ 요구송수신 JPD 호출: UUID ["+info.getUUID()+"]의 RetryFlag 를 false로 설정합니다." );
|
||||
}
|
||||
|
||||
batchMsgDoc.getBatchMsg().getBody().setSubUUID(info.getSubUUID());
|
||||
batchMsgDoc.getBatchMsg().getBody().setSubLayerCode(CommonKeys.SUB_LAYER_SCHEDULER_PROCESSING);
|
||||
|
||||
try {
|
||||
LogUtil.updateLogMaster(batchMsgDoc);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
|
||||
logger.info("[InboundClient] ■ BatchRunningJobManager 등록완료 ");
|
||||
String strUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID();
|
||||
|
||||
// BatchRunningJobManager 에 Running Job 등록
|
||||
logger.info("InboundClient : BatchRunningJobManager 에 응답송수신 작업 등록......");
|
||||
BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, this, batchMsgDoc);
|
||||
|
||||
try {
|
||||
// TimeoutException 기관로거 설정
|
||||
Logger.addInstLog(batchMsgDoc);
|
||||
//===================================================
|
||||
logger.info("InboundClient : FlowController JPD 호출 시작......");
|
||||
ByteBuffer tmpBuf = null;
|
||||
try {
|
||||
tmpBuf = ByteBuffer.allocate(4096);
|
||||
processReadMessage( tmpBuf.array(), 500);
|
||||
} catch (Exception e) {
|
||||
if(tmpBuf != null)
|
||||
logger.warn( e.getMessage()+ new String(tmpBuf.array()), e );
|
||||
else // 20250910 npe
|
||||
logger.warn( e.getMessage(), e );
|
||||
}
|
||||
ResponseHandler handler = new ResponseHandler();
|
||||
this.batchMsgDoc = handler.execute(this.batchMsgDoc);
|
||||
logger.info("InboundClient : FlowController JPD 호출 완료 !!");
|
||||
String endComp = this.batchMsgDoc.getBatchMsg().getPhaseinfo().getPhaseType();
|
||||
|
||||
if ( !"END".equals( endComp) ) {
|
||||
logger.info( "FlowController JPD 호출결과 EEND 소켓 연결 종료" );
|
||||
waitRecoverConnection();
|
||||
}
|
||||
//===================================================
|
||||
|
||||
} finally {
|
||||
// BatchRunningJobManager 에서 Running Job 제거
|
||||
logger.info("InboundClient : BatchRunningJobManager 에서 요구답송수신 작업 제거......");
|
||||
BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID);
|
||||
lastActivity = System.currentTimeMillis();
|
||||
}
|
||||
} catch ( Exception e){
|
||||
logger.error(e.getMessage(), e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean byteCompare( byte[] arr1, byte[]arr2){
|
||||
for ( int inx = 0; inx < Math.min(arr1.length,arr2.length); inx++)
|
||||
if ( arr1[inx] != arr2[inx])
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
import com.eactive.eai.batch.doc.BatchDoc;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class InboundControl implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
private String adapterGroupName;
|
||||
private String adapterName;
|
||||
private boolean ready;
|
||||
private String responseType;
|
||||
private long timeout;
|
||||
private Throwable lastError;
|
||||
private BatchDoc batchMsgDoc;
|
||||
|
||||
public InboundControl(String adapterGroupName, String adapterName) {
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
this.adapterName = adapterName;
|
||||
this.lastError = null;
|
||||
this.ready = false;
|
||||
}
|
||||
|
||||
public InboundControl(String adapterGroupName, String adapterName, long timeout) {
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
this.adapterName = adapterName;
|
||||
this.lastError = null;
|
||||
this.ready = false;
|
||||
this.timeout = timeout;
|
||||
}
|
||||
|
||||
public BatchDoc getBatchMsgDoc() {
|
||||
return batchMsgDoc;
|
||||
}
|
||||
public void setBatchMsgDoc(BatchDoc batchMsgDoc) {
|
||||
this.batchMsgDoc = batchMsgDoc;
|
||||
}
|
||||
public void initBatchMsgDocStage() {
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setSubLayerCode("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseType("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setSndMsgCode("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setRcvMsgCode("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseStartTime("");
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime("");
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the code.
|
||||
*/
|
||||
public String getAdapterGroupName() {
|
||||
return adapterGroupName;
|
||||
}
|
||||
/**
|
||||
* @param code The code to set.
|
||||
*/
|
||||
public void setAdapterGroupName(String code) {
|
||||
this.adapterGroupName = code;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the responseType.
|
||||
*/
|
||||
public String getResponseType() {
|
||||
return responseType;
|
||||
}
|
||||
/**
|
||||
* @param responseType The responseType to set.
|
||||
*/
|
||||
public void setResponseType(String responseType) {
|
||||
this.responseType = responseType;
|
||||
}
|
||||
|
||||
public boolean isSyncMode() {
|
||||
return this.responseType.equals( ConfigurationContext.SYNC_MODE );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the adapterName.
|
||||
*/
|
||||
public String getAdapterName() {
|
||||
return adapterName;
|
||||
}
|
||||
/**
|
||||
* @param adapterName The adapterName to set.
|
||||
*/
|
||||
public void setAdapterName(String adapterName) {
|
||||
this.adapterName = adapterName;
|
||||
}
|
||||
/**
|
||||
* @return Returns the request.
|
||||
*/
|
||||
public byte[] getRequest() {
|
||||
return new byte[2];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param request The request to set.
|
||||
*/
|
||||
public void setRequest(byte[] request) throws Exception {
|
||||
|
||||
}
|
||||
/**
|
||||
* @return Returns the response.
|
||||
*/
|
||||
public byte[] getResponse() {
|
||||
return new byte[2];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param response The response to set.
|
||||
*/
|
||||
public void setResponse(byte[] response) {
|
||||
|
||||
}
|
||||
|
||||
public byte[] request() throws Exception {
|
||||
logger.debug("[ELINK]################ InboundControl.request() 호출됨.");
|
||||
long srtTime = 0;
|
||||
srtTime = System.currentTimeMillis();
|
||||
|
||||
// Session pool에서 사용할 session을 얻어온다.
|
||||
// SessionManager는 SocketAdapterManager 에서 생성하여 사용함.
|
||||
SessionManager mgr = SessionManager.getInstance();
|
||||
SessionService service = null;
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
long waitTime = 0;
|
||||
|
||||
while ( true ) {
|
||||
service = mgr.getSession( this.adapterGroupName );
|
||||
if ( service != null ) break;
|
||||
|
||||
waitTime = System.currentTimeMillis() - start;
|
||||
if ( waitTime >= timeout )
|
||||
break;
|
||||
try {
|
||||
Thread.sleep( 20L );
|
||||
} catch( InterruptedException e ) {}
|
||||
}
|
||||
|
||||
if ( service == null )
|
||||
throw new Exception( CommonLib.getMessage("BECEAIASI004", new String[]{ adapterGroupName } ));
|
||||
|
||||
|
||||
service.setControl( this );
|
||||
service.notifyMessage(); //wait 중인 SessionService 객체에 request 처리 호출
|
||||
|
||||
//Request 처리가 완료 될 때까지 대기...처리가 완료되면 SessionServer에서 이 클래의 wakeup() 메소드 호출함.
|
||||
waitReply();
|
||||
|
||||
if ( isSyncMode() && this.getResponse() == null || this.getResponse().equals("")) {
|
||||
throw new Exception( CommonLib.getMessage("BECEAIASI010") );
|
||||
}
|
||||
|
||||
logger.debug("[ELINK]################ InboundControl.request() 종료. (수행 시간: "+ ((System.currentTimeMillis() - srtTime)/1000.0) +" Sec)");
|
||||
|
||||
return this.getResponse();
|
||||
}
|
||||
|
||||
protected synchronized void waitReply() {
|
||||
try {
|
||||
while ( !ready ) {
|
||||
this.wait();
|
||||
}
|
||||
} catch ( InterruptedException ie ) {}
|
||||
}
|
||||
|
||||
public synchronized void wakeup() {
|
||||
this.ready = true;
|
||||
try {
|
||||
this.notify();
|
||||
} catch( Throwable e ) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the lastError.
|
||||
*/
|
||||
public Throwable getLastError() {
|
||||
return lastError;
|
||||
}
|
||||
/**
|
||||
* @param lastError The lastError to set.
|
||||
*/
|
||||
public void setLastError(Throwable lastError) {
|
||||
this.lastError = lastError;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.nio.BufferOverflowException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.SelectionKey;
|
||||
import java.nio.channels.Selector;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
import com.eactive.eai.batch.common.BatchDirUtil;
|
||||
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.doc.BatchDoc;
|
||||
import com.eactive.eai.batch.flowController.BatchTargetVO;
|
||||
import com.eactive.eai.batch.flowController.FlowControllerManager;
|
||||
import com.eactive.eai.batch.message.EAIBatchMsgManager;
|
||||
import com.eactive.eai.batch.osd.OutsideManager;
|
||||
import com.eactive.eai.batch.osd.OutsideVO;
|
||||
import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager;
|
||||
import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO;
|
||||
import com.eactive.eai.batch.running.BatchRunningJobManager;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.inbound.ResponseHandler;
|
||||
|
||||
public class InboundServer extends Thread implements SocketService {
|
||||
|
||||
private ConfigurationContext context;
|
||||
private SocketChannel socketChannel;
|
||||
private SocketServer proxy;
|
||||
private Selector selector;
|
||||
private boolean active;
|
||||
|
||||
// 상태정보
|
||||
private int sendCount;
|
||||
private int recvCount;
|
||||
private long firstActivity;
|
||||
private long lastActivity;
|
||||
|
||||
private int currentState;
|
||||
|
||||
// pending message for checking operation
|
||||
private ByteBuffer pendingMessage;
|
||||
// Logger
|
||||
private Logger logger;
|
||||
|
||||
private String remoteIPAddress;
|
||||
private String remotePort;
|
||||
|
||||
//----------------------------------------------------------------
|
||||
//배치 응답송수신 전용, 전체 단계 작업에 대한 BatchMsg 객체 (Socket Coneection 내내 동일함)
|
||||
//(전제조건) 1. 배치 전체 단계 전문 Flow 에 대해서 동일한 Socket Connection이 사용되어야 함
|
||||
// 2. 전체 단계 Flow 종료시 해당 Socket Connection 이 종료되고 Inbound Server 가 종료되어야 함
|
||||
private BatchDoc batchMsgDoc;
|
||||
//----------------------------------------------------------------
|
||||
|
||||
|
||||
public InboundServer(ConfigurationContext context, SocketChannel socketChannel, SocketServer proxy) {
|
||||
String name = this.getName();
|
||||
this.setName( context.getAdapterName() + "-CONNECTION" + name.substring( name.lastIndexOf("-")) );
|
||||
|
||||
this.context = context;
|
||||
this.socketChannel = socketChannel;
|
||||
this.proxy = proxy;
|
||||
|
||||
sendCount = 0;
|
||||
recvCount = 0;
|
||||
firstActivity = System.currentTimeMillis();
|
||||
lastActivity = System.currentTimeMillis();
|
||||
|
||||
pendingMessage = ByteBuffer.allocate( 4096 );
|
||||
pendingMessage.clear();
|
||||
|
||||
this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL;
|
||||
|
||||
logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName() );
|
||||
|
||||
active = true;
|
||||
remoteIPAddress = this.socketChannel.socket().getInetAddress().getHostAddress();
|
||||
remotePort = this.socketChannel.socket().getPort() +"";
|
||||
|
||||
//----------------------------------------------------------------
|
||||
//BatchMsgDoc 생성
|
||||
batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(true); //true:초기화함
|
||||
|
||||
//BatchMsgDoc Layer, SubLayer, StartTime 설정
|
||||
EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SOCKET_SERVER, CommonKeys.SUB_LAYER_SOCKET_SERVER);
|
||||
|
||||
try {
|
||||
|
||||
//*** 어댑터에 대해 하나의 대외기관 연결정보(BJ05)만이 매핑되어 있어야 하는 것이 보장되어야 한다.
|
||||
logger.info("[InboundServer] Group ["+context.getAdapterGroupName()+"] Adapter["+context.getAdapterName()+"]");
|
||||
AdapterVO adapter = AdapterManager.getInstance().getAdapterVO(context.getAdapterGroupName(), context.getAdapterName());
|
||||
if (adapter.getRqstRspnsDstcd().equalsIgnoreCase("A")) {
|
||||
// 응답수신 셋팅
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_RECEIVE);
|
||||
} else {
|
||||
// 응답송신 셋팅
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_RESPONSE_SEND);
|
||||
}
|
||||
logger.info("[InboundServer] ProcessCode >> " + adapter.getBatchProcessCode());
|
||||
ArrayList<OutsideVO> osd_array = OutsideManager.getInstance().getOutsideInfo(adapter.getBatchProcessCode());
|
||||
int i=0;
|
||||
for (i=0; i<osd_array.size(); i++) {
|
||||
OutsideVO tmpVO = osd_array.get(i);
|
||||
/*
|
||||
logger.info("OSD CODE > [" + tmpVO.getOsdCode() + "]");
|
||||
logger.info("BLK SIZE > [" + tmpVO.getBlkSize() + "]");
|
||||
logger.info("SEQ SIZE > [" + tmpVO.getSequenceSize() + "]");
|
||||
*/
|
||||
if (tmpVO.getOsdCode().equalsIgnoreCase(adapter.getBatchInstitutionCode())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
OutsideVO outside = null;
|
||||
if (i==osd_array.size()) {
|
||||
String errMsg = "[InboundServer] 대외기관 정보를 구할 수 없습니다. 배치업무코드 [" + adapter.getBatchProcessCode()+"] 대외기관["+adapter.getBatchInstitutionCode()+"]";
|
||||
batchMsgDoc.getBatchMsg().getBody().setErrorCode(99);
|
||||
batchMsgDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
|
||||
throw new Exception(errMsg);
|
||||
} else {
|
||||
logger.info("OUSIDE INFO index [" + i + "]");
|
||||
outside = (OutsideVO) osd_array.get(i);
|
||||
}
|
||||
|
||||
// BatchMsg 에 기본값 지정..
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessCode(adapter.getBatchProcessCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setProcessName(adapter.getBatchProcessName());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(adapter.getBatchInstitutionCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(adapter.getBatchInstitutionName());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setInstituaionType(adapter.getBatchInstitutionType());
|
||||
batchMsgDoc.getBatchMsg().getBody().setPortNo(adapter.getBatchServerPortNo());
|
||||
batchMsgDoc.getBatchMsg().getBody().setTimeoutInterval(Integer.toString(adapter.getBatchInterMsgTimeout()));
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFlowCode(adapter.getBatchRcvFlowRuleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSystemConnCode(adapter.getBatchSystemConnCode());
|
||||
// 새로 추가되는 것들
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleCode(adapter.getBatchRcvFlowRuleCode());
|
||||
RuleInfoVO vo = RuleInfoManager.getInstance().getRuleInfo(adapter.getBatchRcvFlowRuleCode());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRuleDesc((vo!=null)? vo.getDesc() : "Rule Code not found in the TSEAIBR02");
|
||||
|
||||
// // 응답송신기능의 추가를 위해 일부 기능 수정 함.
|
||||
// if (adapter.getRqstRspnsDstcd().equalsIgnoreCase("C") ) {
|
||||
// // 응답송신 이면
|
||||
// String strPathName = BatchDirUtil.getResSendRealDir();
|
||||
// if ( strPathName.charAt(strPathName.length()-1) != '/' ) {
|
||||
// strPathName = strPathName + '/';
|
||||
// }
|
||||
// BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(outside.getBatchCode(), outside.getOsdCode());
|
||||
// StringBuffer sb = new StringBuffer();
|
||||
//
|
||||
// sb.append(btVO.getProcessCode());
|
||||
// sb.append("/");
|
||||
// sb.append(btVO.getOrganCode());
|
||||
// strPathName = strPathName + sb.toString();
|
||||
// logger.debug("[응답송신] PATH NAME = [" + strPathName + "]");
|
||||
//
|
||||
// File ff = new File(strPathName);
|
||||
// if (!ff.exists()) {
|
||||
// logger.warn("응답송신용 디렉토리 [" + strPathName + "] 이 없습니다.");
|
||||
// throw new Exception(ExceptionUtil.getErrorCode("BWCEAIASI003"));
|
||||
// }
|
||||
// File[] fileList = ff.listFiles();
|
||||
// String strFileName = "";
|
||||
// long lnFileSize = -1;
|
||||
// if (fileList.length> 0) {
|
||||
// for (int i1=0; i1<fileList.length; i1++) {
|
||||
// if ( fileList[i1].isFile()) {
|
||||
// strFileName = fileList[i1].getName();
|
||||
// lnFileSize = fileList[i1].length();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFlowCode(outside.getSendRuleCode());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRuleCode(outside.getSendRuleCode());
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRuleDesc(RuleInfoManager.getInstance().getRuleInfo(outside.getSendRuleCode()).getDesc());
|
||||
//
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFileName(strFileName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setRenamedFileName(strFileName);
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFileSize(lnFileSize);
|
||||
// }
|
||||
// else {
|
||||
// //응답 수신 디렉토리 설정
|
||||
// String strPathName = BatchDirUtil.getResponseRealDir();
|
||||
// if ( strPathName.charAt(strPathName.length()-1) != '/' ) {
|
||||
// strPathName = strPathName + '/';
|
||||
// }
|
||||
// BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(outside.getBatchCode(), outside.getOsdCode());
|
||||
// StringBuffer sb = new StringBuffer();
|
||||
//
|
||||
// sb.append(btVO.getProcessCode());
|
||||
// sb.append("/");
|
||||
// sb.append(btVO.getOrganCode());
|
||||
// strPathName = strPathName + sb.toString();
|
||||
// logger.debug("[응답수신] PATH NAME = [" + strPathName + "]");
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// // <<< 응답수신 디렉토리 설정
|
||||
// }
|
||||
|
||||
//응답 수신 디렉토리 설정
|
||||
String strPathName = BatchDirUtil.getResponseRealDir();
|
||||
if ( strPathName.charAt(strPathName.length()-1) != '/' ) {
|
||||
strPathName = strPathName + '/';
|
||||
}
|
||||
BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(outside.getBatchCode(), outside.getOsdCode());
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
sb.append(btVO.getProcessCode());
|
||||
sb.append("/");
|
||||
sb.append(btVO.getOrganCode());
|
||||
strPathName = strPathName + sb.toString();
|
||||
logger.debug("[응답수신] PATH NAME = [" + strPathName + "]");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setFilePath(strPathName);
|
||||
// <<< 응답수신 디렉토리 설정
|
||||
|
||||
|
||||
// batchMsgDoc.getBatchMsg().getHeader().setProtocol("TCP/IP");
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserID(adapter.getLnkID());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setUserPassword(adapter.getLnkPwd());
|
||||
batchMsgDoc.getBatchMsg().getHeader().setBlockSize(outside.getBlkSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setSequenceSize(outside.getSequenceSize()); //TSEAIBJ06에 필드추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPacketSize(outside.getPacketSize()); // 20060411 추가
|
||||
batchMsgDoc.getBatchMsg().getHeader().setRemoteIP(remoteIPAddress);
|
||||
batchMsgDoc.getBatchMsg().getHeader().setPort(remotePort);
|
||||
//----------------------------------------------------------------
|
||||
logger.info("**** USER ID > [" + batchMsgDoc.getBatchMsg().getHeader().getUserID());
|
||||
logger.info("**** PASS WD > [" + batchMsgDoc.getBatchMsg().getHeader().getUserPassword());
|
||||
logger.info("**** BLOCK > [" + batchMsgDoc.getBatchMsg().getHeader().getBlockSize());
|
||||
logger.info("**** SEQ SIZ > [" + batchMsgDoc.getBatchMsg().getHeader().getSequenceSize());
|
||||
logger.info("**** PACKET > [" + batchMsgDoc.getBatchMsg().getHeader().getPacketSize());
|
||||
|
||||
|
||||
//단계 종료시간 설정
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
|
||||
|
||||
//응답수신에 대한 최초 DB로그. StartLog 호출.
|
||||
LogUtil.setStartLog(batchMsgDoc);
|
||||
|
||||
|
||||
} catch (Exception ex) {
|
||||
try {
|
||||
// 파일로그 처리
|
||||
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASI010", new String[] {batchMsgDoc.getBatchMsg().getHeader().getUUID()});
|
||||
logger.error(errMsg, ex); //응답수신 Socket Server 배치메시지 생성 및 정보 설정시 오류가 발생하였습니다. [UUID: {1}]
|
||||
|
||||
// DB로그 처리
|
||||
batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
|
||||
LogUtil.setErrorLog(batchMsgDoc, errMsg);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("[Socket Server] ★★★★★ 응답수신 Socket Server 예외 처리 중 에러 !! ★★★★★", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public long getFirstActivity() {
|
||||
return this.firstActivity;
|
||||
}
|
||||
|
||||
public long getLastActivity() {
|
||||
return this.lastActivity;
|
||||
}
|
||||
|
||||
public String getRemotePort() {
|
||||
return this.remotePort;
|
||||
}
|
||||
|
||||
public String getRemoteIPAddress() {
|
||||
return this.remoteIPAddress;
|
||||
}
|
||||
|
||||
public boolean idle(long timeout) {
|
||||
long idleTime = System.currentTimeMillis() - this.lastActivity;
|
||||
return ( idleTime > timeout );
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public synchronized void shutdown() {
|
||||
active = false;
|
||||
|
||||
notify();
|
||||
|
||||
try {
|
||||
Socket socket = this.socketChannel.socket();
|
||||
if (socket == null) {
|
||||
logger.info("InboundServer : socket 이 null 입니다.");
|
||||
return;
|
||||
}
|
||||
if (socket.isClosed()) {
|
||||
logger.info("InboundServer : socket 이 이미 close 되었습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
socket.setSoLinger(true, 100);
|
||||
if (socketChannel.isConnectionPending()) {
|
||||
logger.info("InboundServer : socket channle isConnectionPending OK!!!");
|
||||
socketChannel.finishConnect();
|
||||
}
|
||||
socket.shutdownInput();
|
||||
socket.shutdownOutput();
|
||||
socket.close();
|
||||
socketChannel.close();
|
||||
|
||||
logger.info("InboundServer : Inbound Socket Closed !!");
|
||||
logger.info("inbound socket : "+ socket );
|
||||
logger.info("inbound socket.isBound() : "+ socket.isBound() );
|
||||
logger.info("inbound socket.isClosed() : "+ socket.isClosed() );
|
||||
logger.info("inbound socket.isConnected() : "+ socket.isConnected() );
|
||||
logger.info("inbound socket.isInputShutdown() : "+ socket.isInputShutdown() );
|
||||
logger.info("inbound socket.isOutputShutdown() : "+ socket.isOutputShutdown());
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error( e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public Socket getCurrentSocket() {
|
||||
return socketChannel.socket();
|
||||
}
|
||||
|
||||
public boolean connect() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
shutdown();
|
||||
proxy.quiesceShutdown(this);
|
||||
interrupt();
|
||||
}
|
||||
|
||||
public void setControl(Object control) {
|
||||
}
|
||||
|
||||
public void notifyMessage() {
|
||||
}
|
||||
|
||||
public int getCurrentState() {
|
||||
return this.currentState;
|
||||
}
|
||||
|
||||
// Writing전에 확인...
|
||||
public boolean isConnected() throws IOException {
|
||||
boolean flag = true;
|
||||
|
||||
if ( socketChannel.isConnected() && socketChannel.socket().isBound() ) {
|
||||
ByteBuffer tmpBuffer = ByteBuffer.allocate( 1 );
|
||||
tmpBuffer.clear();
|
||||
int i = socketChannel.read( tmpBuffer );
|
||||
if ( i > 0 ) {
|
||||
try {
|
||||
pendingMessage.put( tmpBuffer.array() );
|
||||
} catch ( BufferOverflowException e ) {
|
||||
throw new IOException("Socket 어플리케이션 프로토콜에러 발생 : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
if ( i == -1 ) {
|
||||
flag = false;
|
||||
}
|
||||
} else {
|
||||
flag = false;
|
||||
}
|
||||
|
||||
return flag;
|
||||
}
|
||||
|
||||
public void setLastActivity() {
|
||||
lastActivity = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public void checkActivity() {
|
||||
long currentTime = System.currentTimeMillis();
|
||||
if ( !CommonLib.getDate( this.lastActivity ).equals( CommonLib.getDate( currentTime )) ) { //날자비교
|
||||
this.resetCount();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void resetCount() {
|
||||
this.recvCount = 0;
|
||||
this.sendCount = 0;
|
||||
}
|
||||
|
||||
private boolean isAckProtocol() {
|
||||
return this.context.isAckProtocol();
|
||||
}
|
||||
|
||||
private long getTimeout() {
|
||||
return ( this.context.getTimeout() * 1000L );
|
||||
}
|
||||
|
||||
private int getTraceLevel() {
|
||||
return context.getTraceLevel();
|
||||
}
|
||||
|
||||
public ConfigurationContext getContext() {
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
* InboundServer 는 SocketServer 에서 생성되는 Thread 이다.
|
||||
* 외부에서 연결요청한 사항을 처리하기 위해 사용되며, 실제 배치처리에서는 실질적인 업무 플로우는
|
||||
* JPD에서 처리하므로 여기에서는 소켓자체를 배치용 매니저에 등록해주고, 사용하기 쉽게 해주고,
|
||||
* 모든 context를 JPD 로 넘겨준다.
|
||||
*/
|
||||
public void run() {
|
||||
SocketAdapterManager.getInstance().addConnection( this );
|
||||
String socketInfo = this.getSocketInfo(this.socketChannel);
|
||||
|
||||
if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
logger.info( CommonLib.getMessage("BICEAIASI002", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) );
|
||||
}
|
||||
|
||||
String strUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID();
|
||||
|
||||
// BatchRunningJobManager 에 Running Job 등록
|
||||
logger.info("InboundServer : BatchRunningJobManager 에 응답송수신 작업 등록......");
|
||||
BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, this, batchMsgDoc);
|
||||
|
||||
|
||||
try {
|
||||
// 기관별 로그
|
||||
Logger.addInstLog(batchMsgDoc);
|
||||
|
||||
//===================================================
|
||||
logger.info("InboundServer : FlowController JPD 호출 시작......");
|
||||
ResponseHandler handler = new ResponseHandler();
|
||||
this.batchMsgDoc = handler.execute(this.batchMsgDoc);
|
||||
logger.info("InboundServer : FlowController JPD 호출 완료 !!");
|
||||
//===================================================
|
||||
|
||||
} finally {
|
||||
// BatchRunningJobManager 에서 Running Job 제거
|
||||
logger.info("InboundServer : BatchRunningJobManager 에서 응답송수신 작업 제거......");
|
||||
BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID);
|
||||
|
||||
shutdown();
|
||||
proxy.quiesceShutdown(this);
|
||||
|
||||
// 인바운드 소켓연결이 없어질 때, 처리
|
||||
SocketAdapterManager.getInstance().removeConnection( this );
|
||||
if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
logger.info( CommonLib.getMessage("BICEAIASI003", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String getSocketInfo(SocketChannel channel) {
|
||||
StringBuffer connInfo = new StringBuffer();
|
||||
|
||||
connInfo.append("Local Address=");
|
||||
connInfo.append( channel.socket().getLocalAddress().getHostAddress()).append(":").append(channel.socket().getLocalPort()).append(", ");
|
||||
connInfo.append("Remote Address=");
|
||||
connInfo.append( channel.socket().getInetAddress().getHostAddress()).append(":").append(channel.socket().getPort());
|
||||
|
||||
return connInfo.toString();
|
||||
}
|
||||
|
||||
|
||||
public int write(ByteBuffer src) throws IOException {
|
||||
|
||||
if (this.selector == null) {// 20250910 uwf
|
||||
this.selector = Selector.open();
|
||||
}
|
||||
|
||||
this.socketChannel.register( this.selector, SelectionKey.OP_WRITE );
|
||||
|
||||
try {
|
||||
selector.select( getTimeout() );
|
||||
} catch(Exception e) {
|
||||
throw new IOException("Write Select Error");
|
||||
}
|
||||
|
||||
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
|
||||
int writtenBytes = 0;
|
||||
SelectionKey key = null;
|
||||
|
||||
while ( it.hasNext() ) {
|
||||
key = it.next();
|
||||
it.remove();
|
||||
if ( key.isWritable() ) {
|
||||
writtenBytes = this.socketChannel.write( src );
|
||||
}
|
||||
}
|
||||
return writtenBytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the socketchannel.
|
||||
*/
|
||||
public SocketChannel getSocketchannel() {
|
||||
return socketChannel;
|
||||
}
|
||||
/**
|
||||
* @param socketchannel The socketchannel to set.
|
||||
*/
|
||||
public void setSocketchannel(SocketChannel socketchannel) {
|
||||
this.socketChannel = socketchannel;
|
||||
}
|
||||
|
||||
// 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각
|
||||
public String toString() {
|
||||
boolean status = true;
|
||||
StringBuffer strBuff = new StringBuffer();
|
||||
strBuff.append(context.getAdapterGroupName()).append(",");
|
||||
strBuff.append(context.getAdapterName()).append(",");
|
||||
strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(",");
|
||||
strBuff.append(context.getSocketType()).append(",");
|
||||
strBuff.append(context.getResponseType()).append(",");
|
||||
try {
|
||||
strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(",");
|
||||
} catch( Throwable e ) {
|
||||
status = false;
|
||||
strBuff.append("?:?,");
|
||||
}
|
||||
|
||||
try {
|
||||
strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(",");
|
||||
} catch( Throwable e ) {
|
||||
status = false;
|
||||
strBuff.append("?:?,");
|
||||
}
|
||||
strBuff.append(this.sendCount).append(",");
|
||||
strBuff.append(this.recvCount).append(",");
|
||||
strBuff.append( status ).append(",");
|
||||
strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(",");
|
||||
strBuff.append(CommonLib.getCurrentTime( this.lastActivity ));
|
||||
|
||||
return strBuff.toString();
|
||||
}
|
||||
|
||||
|
||||
// static Object arrayGrow(Object a) {
|
||||
// Class cl = a.getClass();
|
||||
// if ( !cl.isArray() ) return null;
|
||||
//
|
||||
// Class compType = a.getClass().getComponentType();
|
||||
// int length = Array.getLength(a);
|
||||
// int newLength = length * 11 / 10 + 10;
|
||||
// Object newArray = Array.newInstance(compType, newLength);
|
||||
// System.arraycopy(a, 0, newArray, 0, length);
|
||||
// return newArray;
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.BufferOverflowException;
|
||||
|
||||
import java.nio.channels.ByteChannel;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.nio.channels.Selector;
|
||||
import java.nio.channels.SelectionKey;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
public class NBChannel implements ByteChannel {
|
||||
|
||||
SocketChannel channel;
|
||||
Selector selector;
|
||||
Selector writeSelector;
|
||||
ByteBuffer pendingMessage;
|
||||
Logger logger ;
|
||||
long timeout;
|
||||
|
||||
public NBChannel(SocketChannel channel, long timeout) throws IOException {
|
||||
|
||||
this.channel = channel;
|
||||
this.selector = Selector.open();
|
||||
this.writeSelector = Selector.open();
|
||||
this.channel.register( this.selector, SelectionKey.OP_READ );
|
||||
this.channel.register( this.writeSelector, SelectionKey.OP_WRITE );
|
||||
this.timeout = timeout;
|
||||
|
||||
pendingMessage = ByteBuffer.allocate( 4096 );
|
||||
pendingMessage.clear();
|
||||
logger = SocketLogManager.getInstance().getLogger();
|
||||
}
|
||||
|
||||
public int read(ByteBuffer dst) throws IOException {
|
||||
if ( dst.capacity() == 0 || !dst.hasRemaining() ) return 0;
|
||||
int y = 0;
|
||||
boolean isDone = false;
|
||||
|
||||
if ( pendingMessage.position() > 0 ) {
|
||||
if ( pendingMessage.position() <= dst.remaining() ) {
|
||||
y += pendingMessage.position();
|
||||
byte[] data = new byte[ pendingMessage.position() ];
|
||||
pendingMessage.flip();
|
||||
pendingMessage.get( data );
|
||||
dst.put( data, 0, data.length );
|
||||
pendingMessage.clear();
|
||||
} else {
|
||||
int shiftCount = dst.remaining();
|
||||
y += shiftCount;
|
||||
byte[] data = new byte[ shiftCount ];
|
||||
pendingMessage.flip();
|
||||
pendingMessage.get( data );
|
||||
pendingMessage.position( pendingMessage.limit() );
|
||||
|
||||
dst.put( data, 0, data.length );
|
||||
shiftBuffer( pendingMessage, shiftCount );
|
||||
isDone = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ( isDone ) return y;
|
||||
selector.select( timeout );
|
||||
y += this.channel.read( dst );
|
||||
return y;
|
||||
}
|
||||
|
||||
private void shiftBuffer(ByteBuffer buffer, int shiftBytes) {
|
||||
int pos = buffer.position();
|
||||
if ( pos <= shiftBytes ) {
|
||||
buffer.clear();
|
||||
return;
|
||||
}
|
||||
byte[] tmpBuff = new byte[ pos ];
|
||||
buffer.flip();
|
||||
buffer.get( tmpBuff );
|
||||
|
||||
buffer.clear();
|
||||
buffer.put( tmpBuff, shiftBytes, tmpBuff.length - shiftBytes );
|
||||
}
|
||||
|
||||
public int write(ByteBuffer src) throws IOException {
|
||||
|
||||
try {
|
||||
writeSelector.select( timeout );
|
||||
} catch(Exception e) {
|
||||
throw new IOException("Write Select Error");
|
||||
}
|
||||
|
||||
Iterator<SelectionKey> it = writeSelector.selectedKeys().iterator();
|
||||
int writtenBytes = 0;
|
||||
SelectionKey key = null;
|
||||
|
||||
while ( it.hasNext() ) {
|
||||
key = (SelectionKey)it.next();
|
||||
it.remove();
|
||||
if ( key.isWritable() ) {
|
||||
writtenBytes = this.channel.write( src );
|
||||
}
|
||||
}
|
||||
|
||||
return writtenBytes;
|
||||
}
|
||||
|
||||
public boolean isConnected() throws IOException {
|
||||
|
||||
if ( !isOpen() ) {
|
||||
logger.info( CommonLib.getMessage("BICEAIASO003", new String[]{"", getSocketInfo()} ));
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean flag = false;
|
||||
|
||||
if ( this.channel.isConnected() && this.channel.socket().isBound() ) {
|
||||
ByteBuffer tmpBuffer = ByteBuffer.allocate( 1 );
|
||||
tmpBuffer.clear();
|
||||
int i = channel.read( tmpBuffer );
|
||||
if ( i > 0 ) {
|
||||
try {
|
||||
pendingMessage.put( tmpBuffer.array() );
|
||||
} catch ( BufferOverflowException e ) {
|
||||
throw new IOException("Socket 어플리케이션 프로토콜 에러 발생 : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
flag = true;
|
||||
if ( i == -1 ) {
|
||||
flag = false;
|
||||
}
|
||||
} else {
|
||||
flag = false;
|
||||
}
|
||||
|
||||
return flag;
|
||||
}
|
||||
|
||||
public void wakeup() {
|
||||
try {
|
||||
if ( selector != null && selector.isOpen() ) {
|
||||
selector.wakeup();
|
||||
writeSelector.wakeup();
|
||||
}
|
||||
} catch (Throwable e) {}
|
||||
}
|
||||
|
||||
public void close() {
|
||||
if ( this.channel == null || !this.channel.isOpen() ) return;
|
||||
|
||||
// try {
|
||||
// if ( selector != null && selector.isOpen() ) {
|
||||
// selector.wakeup();
|
||||
// writeSelector.close();
|
||||
// }
|
||||
// this.channel.socket().close();
|
||||
// this.channel.close();
|
||||
// this.selector.close();
|
||||
// this.writeSelector.close();
|
||||
// } catch (Throwable e) {}
|
||||
|
||||
try {// 20250910 npe
|
||||
if (selector != null) {
|
||||
if (selector.isOpen()) {
|
||||
selector.wakeup();
|
||||
}
|
||||
this.selector.close();
|
||||
}
|
||||
|
||||
if (writeSelector != null) {
|
||||
writeSelector.close();
|
||||
}
|
||||
|
||||
if (this.channel != null) {
|
||||
if (this.channel.socket() != null) {
|
||||
this.channel.socket().close();
|
||||
}
|
||||
this.channel.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace(); // 최소한 로그는 남기는 것이 좋음
|
||||
}
|
||||
}
|
||||
|
||||
public Socket getSocket() {
|
||||
return this.channel.socket();
|
||||
}
|
||||
|
||||
public boolean isOpen() {
|
||||
if ( this.channel == null || !this.channel.isOpen() ) return false;
|
||||
|
||||
return this.channel.socket().isConnected();
|
||||
}
|
||||
|
||||
private String getSocketInfo() {
|
||||
StringBuffer connInfo = new StringBuffer();
|
||||
|
||||
connInfo.append("Local Address=");
|
||||
connInfo.append( getSocket().getLocalAddress().getHostAddress()).append(":").append(getSocket().getLocalPort()).append(", ");
|
||||
connInfo.append("Remote Address=");
|
||||
connInfo.append( getSocket().getInetAddress().getHostAddress()).append(":").append(getSocket().getPort());
|
||||
|
||||
return connInfo.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Vector;
|
||||
|
||||
import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
|
||||
public class OutboundChannel
|
||||
{
|
||||
private Vector<SocketService> connectionList;
|
||||
|
||||
public OutboundChannel(long sessionTimeout) {
|
||||
connectionList = new Vector<SocketService>();
|
||||
}
|
||||
|
||||
public void addConnection( SocketService connection ) throws Exception {
|
||||
synchronized ( this.connectionList ) {
|
||||
SocketService svc = connection;
|
||||
if ( svc.getContext().isStarted() && svc.isActive() ) {
|
||||
if ( connectionList.size() == 0 ) {
|
||||
SocketAdapterManager.getInstance().changeAdapterStatus( connection, true );
|
||||
}
|
||||
this.connectionList.add( connection );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int getPoolSize() {
|
||||
return connectionList.size();
|
||||
}
|
||||
|
||||
public Object getConnection() throws Exception {
|
||||
synchronized ( this.connectionList ) {
|
||||
if ( this.connectionList.size() > 0 ) {
|
||||
try {
|
||||
SocketService svc = (SocketService) connectionList.remove( 0 );
|
||||
if ( svc.getContext().isStarted() && svc.isActive() ) {
|
||||
return svc;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void removeConnection( Object connection ) throws Exception {
|
||||
synchronized ( this.connectionList ) {
|
||||
int size = this.connectionList.size();
|
||||
for( int i=0; i < size; i++ ) {
|
||||
Object x = this.connectionList.elementAt( i );
|
||||
if ( x == connection ) {
|
||||
this.connectionList.remove( i );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void removeAllConnection() throws Exception {
|
||||
this.connectionList.clear();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
for(Iterator<SocketService> iter = connectionList.iterator(); iter.hasNext();) {
|
||||
Object key = iter.next();
|
||||
sb.append("\n ▣ " + key);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
|
||||
public class OutboundChannelManager {
|
||||
|
||||
private static OutboundChannelManager instance = new OutboundChannelManager();
|
||||
private HashMap<String,OutboundChannel> pool = new HashMap<String,OutboundChannel>() ;
|
||||
|
||||
public OutboundChannelManager() {
|
||||
}
|
||||
|
||||
public static OutboundChannelManager getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
this.removeAll();
|
||||
}
|
||||
|
||||
public void removeAll() {
|
||||
pool.clear();
|
||||
}
|
||||
|
||||
public void start(String adapterGroupName, OutboundChannel channel) {
|
||||
this.addConnectionGroup(adapterGroupName, channel);
|
||||
}
|
||||
|
||||
// Adapter Group Connection 을 한번에 등록한다.
|
||||
public synchronized void addConnectionGroup(String adapterGroupName, OutboundChannel channel) {
|
||||
OutboundChannel oc = pool.get( adapterGroupName );
|
||||
if ( oc == null ) {
|
||||
synchronized ( pool ) {
|
||||
oc = pool.get( adapterGroupName );
|
||||
if ( oc == null ) {
|
||||
pool.put( adapterGroupName, channel );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addConnection( String adapterGroupName, SocketService connection ) {
|
||||
OutboundChannel channel = this.getChannel( adapterGroupName );
|
||||
if ( channel == null ) return;
|
||||
try {
|
||||
channel.addConnection( connection );
|
||||
} catch( Exception e ) {}
|
||||
}
|
||||
|
||||
public void stop(String adapterGroupName) {
|
||||
// adapterGroupName의 Connection stop & clear
|
||||
OutboundChannel channel = this.getChannel( adapterGroupName );
|
||||
if ( channel == null ) return;
|
||||
try {
|
||||
channel.removeAllConnection();
|
||||
} catch ( Exception e ) {}
|
||||
|
||||
pool.remove( adapterGroupName );
|
||||
}
|
||||
|
||||
public OutboundChannel getChannel( String adapterGroupName ) {
|
||||
return (OutboundChannel) pool.get( adapterGroupName );
|
||||
}
|
||||
|
||||
public boolean hasChannel( String adapterGroupName ) {
|
||||
return pool.containsKey( adapterGroupName );
|
||||
}
|
||||
|
||||
public SocketService getConnection( String adapterGroupName ) {
|
||||
OutboundChannel channel = this.getChannel( adapterGroupName );
|
||||
if ( channel == null ) return null;
|
||||
|
||||
SocketService connection = null;
|
||||
try {
|
||||
connection = (SocketService) channel.getConnection();
|
||||
} catch ( Exception e ) { }
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
public void removeConnection ( String adapterGroupName, Object connection ) {
|
||||
OutboundChannel channel = this.getChannel( adapterGroupName );
|
||||
if ( channel == null ) return;
|
||||
try {
|
||||
channel.removeConnection( connection );
|
||||
} catch (Exception e) {}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
sb.append("\n■ OutboundChannelManager : ");
|
||||
try {
|
||||
for(Iterator<String> iter = pool.keySet().iterator(); iter.hasNext();) {
|
||||
String key = iter.next();
|
||||
sb.append("\n ▣ " + key + " : " + pool.get(key).getPoolSize());
|
||||
}
|
||||
} catch(Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,798 @@
|
||||
//package com.eactive.eai.adapter.socket.service;
|
||||
//
|
||||
//import java.io.IOException;
|
||||
//import java.net.InetAddress;
|
||||
//import java.net.Socket;
|
||||
//import java.nio.ByteBuffer;
|
||||
//
|
||||
////import com.eactive.eai.adapter.socket.common.BoundedLinkedQueue;
|
||||
//import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
//import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
//import com.eactive.eai.adapter.socket.common.SocketAdapterException;
|
||||
//import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
//import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
////import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
//import java.net.InetSocketAddress;
|
||||
//import java.nio.channels.SocketChannel;
|
||||
//
|
||||
//public class OutboundClient extends Thread implements SocketService {
|
||||
//
|
||||
// protected ConfigurationContext context;
|
||||
// protected boolean active;
|
||||
// protected NBChannel channel;
|
||||
// protected Exception lastError;
|
||||
// protected boolean retryFlag;
|
||||
// protected int sendCount;
|
||||
// protected int recvCount;
|
||||
// protected long firstActivity;
|
||||
// protected long lastActivity;
|
||||
// protected ByteBuffer incomingMessage;
|
||||
// protected ByteBuffer outgoingMessage;
|
||||
// protected ByteBuffer lenBuffer;
|
||||
// protected int currentState;
|
||||
// protected Logger logger;
|
||||
// protected static Logger errLogger = SocketLogManager.getInstance().getErrLogger();
|
||||
// protected OutboundControl control;
|
||||
//
|
||||
// public OutboundClient(ConfigurationContext context) {
|
||||
// String name = this.getName();
|
||||
// this.setName( context.getAdapterName() + "-CONNECTION" + name.substring( name.lastIndexOf("-")) );
|
||||
//
|
||||
// this.context = context;
|
||||
// active = true;
|
||||
// retryFlag = true;
|
||||
//
|
||||
// sendCount = 0;
|
||||
// recvCount = 0;
|
||||
// firstActivity = System.currentTimeMillis();
|
||||
// lastActivity = System.currentTimeMillis();
|
||||
//
|
||||
// incomingMessage = null;
|
||||
// outgoingMessage = null;
|
||||
// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() );
|
||||
// lenBuffer.clear();
|
||||
// this.control = null;
|
||||
// this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL;
|
||||
// logger = SocketLogManager.getInstance().getLogger( this.context.getAdapterGroupName());
|
||||
// }
|
||||
//
|
||||
// protected int getTraceLevel() {
|
||||
// return context.getTraceLevel();
|
||||
// }
|
||||
// /**
|
||||
// * @return Returns the context.
|
||||
// */
|
||||
// public ConfigurationContext getContext() {
|
||||
// return context;
|
||||
// }
|
||||
//
|
||||
// protected boolean isSyncMode() {
|
||||
// return context.isSyncMode();
|
||||
// }
|
||||
//
|
||||
// protected boolean isAckProtocol() {
|
||||
// return context.isAckProtocol();
|
||||
// }
|
||||
//
|
||||
// protected long getTimeout() {
|
||||
// return ( this.context.getTimeout() * 1000L );
|
||||
// }
|
||||
//
|
||||
// protected boolean isSocketReuse() {
|
||||
// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG );
|
||||
// }
|
||||
//
|
||||
// public void run() {
|
||||
//
|
||||
// String socketInfo = "";
|
||||
//
|
||||
// while ( active && retryFlag ) {
|
||||
// try {
|
||||
// openChannel();
|
||||
// if ( !socketInfo.equals( getSocketInfo(this.getCurrentSocket()) ) ) {
|
||||
// socketInfo = getSocketInfo( this.getCurrentSocket() );
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIASO001", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) );
|
||||
// }
|
||||
// }
|
||||
// if ( currentState == CommonLib.NEGOTIATING_PROTOCOL ) {
|
||||
// if ( !negotiateProtocol() ) {
|
||||
// if ( active ) {
|
||||
// waitRecoverConnection();
|
||||
// }
|
||||
// continue;
|
||||
// } else {
|
||||
// currentState = CommonLib.PROCESSING_PROTOCOL;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// onMessage();
|
||||
//
|
||||
// if ( control == null ) {
|
||||
// continue;
|
||||
// }
|
||||
//
|
||||
// doRequest();
|
||||
//
|
||||
// if ( !isSocketReuse() ) {
|
||||
// closeChannel();
|
||||
// }
|
||||
//
|
||||
// } catch (Exception e) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "openChannel", e.getMessage(), "", "" } );
|
||||
// logger.error( errMsg, e );
|
||||
//
|
||||
// if ( this.control != null ) {
|
||||
// lastError = new SocketAdapterException( errMsg );
|
||||
// wakeup();
|
||||
// }
|
||||
// if ( active && retryFlag ) {
|
||||
// waitRecoverConnection();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// closeChannel();
|
||||
// } catch( Throwable e ) {}
|
||||
//
|
||||
// SocketAdapterManager.getInstance().removeConnection( this );
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIASO002", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) );
|
||||
// }
|
||||
//
|
||||
// interrupt();
|
||||
// }
|
||||
//
|
||||
// protected String getReadingMessage() {
|
||||
// String rMsg = "";
|
||||
// if ( incomingMessage != null && incomingMessage.position() > 0 ) {
|
||||
// byte[] dMsg = new byte[ incomingMessage.position() ];
|
||||
// System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length );
|
||||
// rMsg = CommonLib.getDumpMessage( dMsg );
|
||||
// }
|
||||
// return rMsg;
|
||||
// }
|
||||
//
|
||||
// protected String getWritingMessage() {
|
||||
// String rMsg = "";
|
||||
// if ( outgoingMessage != null ) {
|
||||
// byte[] debugMsg = new byte[ outgoingMessage.capacity() - lenBuffer.capacity() ];
|
||||
// System.arraycopy( outgoingMessage.array(), lenBuffer.capacity(), debugMsg, 0, debugMsg.length );
|
||||
// rMsg = CommonLib.getDumpMessage( debugMsg );
|
||||
// }
|
||||
// return rMsg;
|
||||
// }
|
||||
//
|
||||
// protected String getSocketInfo(Socket socket) {
|
||||
// StringBuffer connInfo = new StringBuffer();
|
||||
//
|
||||
// connInfo.append("Local Address=");
|
||||
// connInfo.append( socket.getLocalAddress().getHostAddress()).append(":").append(socket.getLocalPort()).append(", ");
|
||||
// connInfo.append("Remote Address=");
|
||||
// connInfo.append( socket.getInetAddress().getHostAddress()).append(":").append(socket.getPort());
|
||||
//
|
||||
// return connInfo.toString();
|
||||
// }
|
||||
//
|
||||
// protected synchronized void onMessage() {
|
||||
// try {
|
||||
// if ( this.control == null ) {
|
||||
// this.wait( 1000L );
|
||||
// }
|
||||
// if ( retryFlag && this.control == null ) {
|
||||
// checkConnection();
|
||||
// }
|
||||
// this.lastError = null;
|
||||
// } catch ( InterruptedException ie ) {}
|
||||
// }
|
||||
//
|
||||
// public void wakeup() {
|
||||
// this.control.setLastError( this.lastError );
|
||||
// this.control.wakeup();
|
||||
// this.control = null;
|
||||
// if ( retryFlag ) {
|
||||
// OutboundChannelManager.getInstance().addConnection(context.getAdapterGroupName(), this );
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public synchronized void notifyMessage() {
|
||||
// this.notify();
|
||||
// }
|
||||
//
|
||||
// public synchronized void setControl(Object control) {
|
||||
// this.control = (OutboundControl) control;
|
||||
// this.control.setRespTimeout( getTimeout() );
|
||||
// }
|
||||
//
|
||||
//
|
||||
// public int getCurrentState() {
|
||||
// return this.currentState;
|
||||
// }
|
||||
//
|
||||
// protected void resetCount() {
|
||||
// this.recvCount = 0;
|
||||
// this.sendCount = 0;
|
||||
// }
|
||||
//
|
||||
// public boolean isConnected() {
|
||||
// boolean flag = false;
|
||||
// try {
|
||||
// flag = this.channel.isConnected();
|
||||
// } catch( Exception e ) {}
|
||||
// return flag;
|
||||
// }
|
||||
//
|
||||
// public void checkActivity() {
|
||||
// long currentTime = System.currentTimeMillis();
|
||||
// if ( !CommonLib.getDate( this.lastActivity ).equals( CommonLib.getDate( currentTime )) ) {
|
||||
// this.resetCount();
|
||||
// }
|
||||
// }
|
||||
// /**
|
||||
// * NEGOTIATING PROTOCOL WITH REMOTE SERVER, WITH ACK-PROTOCOL
|
||||
// * 1. SEND '<SYNC>|<ASYN>'
|
||||
// * 2. RECV 'ACK|NACK ...'
|
||||
// * 3. RETURN TRUE/FALSE
|
||||
// */
|
||||
//
|
||||
// protected boolean negotiateProtocol() {
|
||||
//
|
||||
// boolean success = false;
|
||||
// this.checkActivity();
|
||||
// lastActivity = System.currentTimeMillis();
|
||||
// try {
|
||||
// if ( isSyncMode() ) {
|
||||
// processWriteMessage( CommonLib.SYNC_PROTOCOL_MESSAGE );
|
||||
// } else {
|
||||
// processWriteMessage( CommonLib.ASYNC_PROTOCOL_MESSAGE );
|
||||
// }
|
||||
// sendCount++;
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), this.getSocketInfo( getCurrentSocket() ), getWritingMessage()}));
|
||||
// }
|
||||
//
|
||||
// lenBuffer.clear();
|
||||
// incomingMessage = ByteBuffer.allocate( readLength( lenBuffer ) );
|
||||
// processReadMessage( incomingMessage );
|
||||
// recvCount++;
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), this.getSocketInfo( getCurrentSocket() ), getReadingMessage()}));
|
||||
// }
|
||||
//
|
||||
// if ( CommonLib.compare( incomingMessage.array(), CommonLib.ACK_MESSAGE ) ) {
|
||||
// success = true;
|
||||
// } else {
|
||||
// // 메시지수신
|
||||
// logger.error( CommonLib.getMessage("BECEAIASO005", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}) );
|
||||
// logger.error( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), this.getSocketInfo(getCurrentSocket()), getReadingMessage()}));
|
||||
// }
|
||||
//
|
||||
// } catch ( Exception e ) {
|
||||
// String errMsg = "";
|
||||
// if ( lenBuffer.position() > 0 ) {
|
||||
// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "negotiateProtocol", e.getMessage(), "수신메시지", getReadingMessage() } );
|
||||
// } else {
|
||||
// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "negotiateProtocol", e.getMessage(), "송신메시지", getWritingMessage() } );
|
||||
// }
|
||||
// logger.error( errMsg , e);
|
||||
// }
|
||||
// lenBuffer.clear();
|
||||
// return success;
|
||||
// }
|
||||
//
|
||||
// protected void processWriteAckMessage() throws Exception {
|
||||
// try {
|
||||
// processWriteMessage( CommonLib.ACK_MESSAGE );
|
||||
// } catch( Exception e ) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processWriteAckMessage", e.getMessage(), "수신메시지", getReadingMessage() } );
|
||||
// logger.error( errMsg , e);
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg, e );
|
||||
// }
|
||||
// throw new Exception("ACK메시지 송신에러 : " + e.getMessage() );
|
||||
// }
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), this.getSocketInfo(getCurrentSocket()), CommonLib.getDumpMessage(CommonLib.ACK_MESSAGE) }));
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// protected void processReadAckMessage() throws Exception {
|
||||
//
|
||||
// try {
|
||||
// lenBuffer.clear();
|
||||
// incomingMessage = ByteBuffer.allocate( readLength( lenBuffer ) );
|
||||
// processReadMessage( incomingMessage );
|
||||
// } catch (Exception e) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processReadAckMessage", e.getMessage(), "송신메시지", getWritingMessage() } );
|
||||
// logger.error( errMsg , e);
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg, e );
|
||||
// }
|
||||
// lenBuffer.clear();
|
||||
// throw new Exception("ACK메시지 수신에러 : " + e.getMessage() );
|
||||
// }
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), getSocketInfo(getCurrentSocket()), CommonLib.getDumpMessage(incomingMessage.array())}));
|
||||
// }
|
||||
//
|
||||
// if ( CommonLib.compare( incomingMessage.array(), CommonLib.ACK_MESSAGE ) ) {
|
||||
// lenBuffer.clear();
|
||||
// return;
|
||||
// } else {
|
||||
// // 메시지수신
|
||||
// logger.error( CommonLib.getMessage("BECEAIASO006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.getDumpMessage(incomingMessage.array())}));
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( CommonLib.getMessage("BECEAIASO006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.getDumpMessage(incomingMessage.array())}));
|
||||
// }
|
||||
// lenBuffer.clear();
|
||||
// throw new IOException("송신에 대한 ACK 메시지 수신에러");
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// protected void checkConnection() {
|
||||
// try {
|
||||
// boolean flag = false;
|
||||
// if ( this.control != null ) return;
|
||||
//
|
||||
// synchronized ( this ) {
|
||||
// if ( channel == null ) return;
|
||||
// flag = channel.isConnected();
|
||||
// }
|
||||
//
|
||||
// if ( active && this.control == null && !flag ) {
|
||||
// waitRecoverConnection();
|
||||
// }
|
||||
// } catch( Exception e ) {
|
||||
// if ( active ) {
|
||||
// waitRecoverConnection();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//
|
||||
// // RESPONSE MODE의 경우
|
||||
// protected void doRequest() throws Exception {
|
||||
//
|
||||
// try {
|
||||
// openChannel();
|
||||
// } catch(IOException e) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "doRequest의 openChannel", e.getMessage(), "", "" } );
|
||||
// logger.error( errMsg, e );
|
||||
// lastError = new SocketAdapterException( errMsg );
|
||||
// wakeup();
|
||||
// if ( active ) {
|
||||
// waitRecoverConnection();
|
||||
// }
|
||||
// return;
|
||||
// }
|
||||
//
|
||||
// this.checkActivity();
|
||||
// lastActivity = System.currentTimeMillis();
|
||||
//
|
||||
// try {
|
||||
//
|
||||
// processWriteMessage( this.control.getRequest() );
|
||||
//
|
||||
// sendCount++;
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), getSocketInfo(getCurrentSocket()), getWritingMessage()}));
|
||||
// }
|
||||
//
|
||||
// if ( isAckProtocol() ) {
|
||||
// processReadAckMessage();
|
||||
// }
|
||||
//
|
||||
// if ( !isSyncMode() ) {
|
||||
// wakeup();
|
||||
// return;
|
||||
// }
|
||||
//
|
||||
// outgoingMessage.clear();
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// // 동기인 경우, SYNC
|
||||
// incomingMessage = ByteBuffer.allocate( readLength( lenBuffer ) );
|
||||
// processReadMessage( incomingMessage );
|
||||
//
|
||||
// recvCount++;
|
||||
//
|
||||
// this.control.setResponse( incomingMessage.array() );
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), getSocketInfo(getCurrentSocket()), CommonLib.getDumpMessage(incomingMessage.array())}));
|
||||
// }
|
||||
//
|
||||
// if ( isAckProtocol() ) {
|
||||
// processWriteAckMessage();
|
||||
// }
|
||||
//
|
||||
// incomingMessage.clear();
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// wakeup();
|
||||
//
|
||||
// } catch( Exception e) {
|
||||
// String errMsg = "";
|
||||
// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "송신메시지", CommonLib.getDumpMessage( this.control.getRequest() ) } );
|
||||
// logger.error( errMsg , e);
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg, e );
|
||||
// }
|
||||
//
|
||||
// if ( lenBuffer.position() > 0 ) {
|
||||
// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } );
|
||||
// logger.error( errMsg , e);
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg, e );
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// lastError = new SocketAdapterException( errMsg );
|
||||
//
|
||||
// wakeup();
|
||||
//
|
||||
// if ( active ) {
|
||||
// waitRecoverConnection();
|
||||
// }
|
||||
// }
|
||||
// } // end of doRequest()
|
||||
//
|
||||
// /**
|
||||
// * Socket Recovery Manager에 의해 Connection Recovery가 되도록 기다린다.
|
||||
// *
|
||||
// */
|
||||
// public synchronized void waitRecoverConnection() {
|
||||
// try {
|
||||
// if ( !retryFlag ) return;
|
||||
// this.currentState = CommonLib.NEGOTIATING_PROTOCOL;
|
||||
// try { closeChannel(); } catch(Exception ie) {}
|
||||
// if ( retryFlag && SocketAdapterManager.getInstance().addError( this ) ) {
|
||||
// this.wait();
|
||||
// this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL;
|
||||
// }
|
||||
// } catch ( InterruptedException e ) {}
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Socket Recovery Manager에 의해 recovery되면 Socket Recovery Manager에 의해 통지된다.
|
||||
// *
|
||||
// */
|
||||
// public synchronized void notifyRecoverConnection() {
|
||||
//
|
||||
// if ( !this.retryFlag ) return;
|
||||
//
|
||||
// this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL;
|
||||
//
|
||||
// this.notify();
|
||||
// }
|
||||
//
|
||||
// public boolean idle(long timeout) {
|
||||
// long idleTime = System.currentTimeMillis() - this.lastActivity;
|
||||
//
|
||||
// return ( idleTime > timeout );
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * @param buffer
|
||||
// * @return
|
||||
// * @throws Exception
|
||||
// */
|
||||
// protected int readLength( ByteBuffer buffer ) throws Exception {
|
||||
// int length = 0;
|
||||
//
|
||||
// long waitTime = ( getTimeout() <= 0 ) ? System.currentTimeMillis() : getTimeout();
|
||||
// long start = System.currentTimeMillis();
|
||||
// long msecs = waitTime;
|
||||
//
|
||||
// while ( buffer.position() < buffer.capacity() ) {
|
||||
// while ( buffer.position() < buffer.capacity() ) {
|
||||
// length = channel.read( buffer );
|
||||
//
|
||||
// waitTime = msecs - (System.currentTimeMillis() - start);
|
||||
//
|
||||
// if ( waitTime <= 0 ) {
|
||||
// byte[] lmsg = new byte[ buffer.position() ];
|
||||
// System.arraycopy( buffer.array(), 0, lmsg, 0, lmsg.length );
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASO004", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "수신", "X'" + CommonLib.byte2Hex( lmsg )+ "'" });
|
||||
// logger.error( errMsg );
|
||||
//
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg );
|
||||
// }
|
||||
// throw new Exception( errMsg );
|
||||
// }
|
||||
//
|
||||
// if ( length < 1 ) break;
|
||||
// }
|
||||
// if(length == -1) {
|
||||
// if ( buffer.position() > 0 ) {
|
||||
// throw new Exception( CommonLib.getMessage("BECEAIASO002", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}) );
|
||||
// } else {
|
||||
// String errMsg = CommonLib.getMessage("BICEAIASO003", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())});
|
||||
// if(logger.isInfoEnabled()){
|
||||
// logger.info( errMsg );
|
||||
// }
|
||||
// throw new Exception( errMsg );
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if ( buffer.position() == buffer.capacity() ) {
|
||||
// length = checkLengthField( buffer );
|
||||
// }
|
||||
// }
|
||||
// return length;
|
||||
// }
|
||||
//
|
||||
//
|
||||
// protected void processReadMessage( ByteBuffer buffer ) throws Exception {
|
||||
// int i = 0;
|
||||
// boolean isDone = false;
|
||||
// buffer.clear();
|
||||
//
|
||||
// long waitTime = ( getTimeout() <= 0 ) ? System.currentTimeMillis() : getTimeout();
|
||||
// long start = System.currentTimeMillis();
|
||||
// long msecs = waitTime;
|
||||
//
|
||||
// while ( !isDone ) {
|
||||
//
|
||||
// while ( buffer.position() < buffer.capacity() ) {
|
||||
// i = channel.read( buffer );
|
||||
//
|
||||
// waitTime = msecs - (System.currentTimeMillis() - start);
|
||||
//
|
||||
// if ( waitTime <= 0 ) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "수신", getReadingMessage() });
|
||||
// logger.error( errMsg );
|
||||
//
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg );
|
||||
// }
|
||||
// throw new Exception( CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "", "" }) );
|
||||
// }
|
||||
//
|
||||
// if ( i < 1 ) break;
|
||||
// }
|
||||
//
|
||||
// if(i == -1) {
|
||||
// throw new Exception( CommonLib.getMessage("BECEAIASO002", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}) );
|
||||
// } else if ( buffer.position() == buffer.capacity() ) {
|
||||
// isDone = true;
|
||||
// }
|
||||
// } // end of while
|
||||
// } // end of readData
|
||||
//
|
||||
// protected void processWriteMessage( byte[] data ) throws IOException {
|
||||
//
|
||||
// outgoingMessage = ByteBuffer.allocate( data.length + lenBuffer.capacity() );
|
||||
// outgoingMessage.clear();
|
||||
// outgoingMessage.put( makeLengthField( data.length ) );
|
||||
// outgoingMessage.put( data );
|
||||
// outgoingMessage.flip();
|
||||
//
|
||||
// long writeStart = System.currentTimeMillis();
|
||||
//
|
||||
// int expectedWrite = outgoingMessage.capacity();
|
||||
// int writtenByte = channel.write( outgoingMessage );
|
||||
//
|
||||
// if ( expectedWrite != writtenByte ) {
|
||||
// ByteBuffer buf = null;
|
||||
// while ( writtenByte < expectedWrite ) {
|
||||
// buf = ByteBuffer.allocate( expectedWrite - writtenByte );
|
||||
// buf.clear();
|
||||
// buf.put( outgoingMessage.array(), writtenByte, buf.capacity() );
|
||||
// writtenByte += channel.write( buf );
|
||||
// if ( expectedWrite == writtenByte ) return;
|
||||
// long waitTime = System.currentTimeMillis() - writeStart;
|
||||
// if ( waitTime >= getTimeout() ) {
|
||||
// throw new IOException("메시지 송신 타임아웃");
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// protected byte[] makeLengthField(int length) {
|
||||
// byte[] lenField = new byte[ lenBuffer.capacity() ];
|
||||
//
|
||||
// if ( lenField.length == 2 ) {
|
||||
// lenBuffer.clear();
|
||||
// lenBuffer.putShort( (short) (length & 0xFFFF) );
|
||||
// lenField = lenBuffer.array();
|
||||
// } else if ( lenField.length == 4 ) {
|
||||
// lenBuffer.clear();
|
||||
// lenBuffer.putInt( length );
|
||||
// lenField = lenBuffer.array();
|
||||
// } else {
|
||||
// String lenStr = CommonLib.getFormatString( length, lenField.length );
|
||||
// lenField = lenStr.getBytes();
|
||||
// }
|
||||
//
|
||||
// return lenField;
|
||||
// }
|
||||
//
|
||||
// protected int checkLengthField(ByteBuffer buffer) throws SocketAdapterException {
|
||||
// int length = 0;
|
||||
//
|
||||
// if ( buffer.capacity() == 2 ) {
|
||||
// length = ( buffer.getShort(0) & 0xFFFF );
|
||||
// } else if ( buffer.capacity() == 4 ) {
|
||||
// length = ( buffer.getInt(0) );
|
||||
// if ( length < 0 ) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASO007", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.byte2Hex( buffer.array() ) }) );
|
||||
// }
|
||||
// } else {
|
||||
// String lenStr = new String( buffer.array() );
|
||||
// try {
|
||||
// length = Integer.parseInt( lenStr );
|
||||
// } catch ( NumberFormatException e ) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASO007", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.byte2Hex( buffer.array() ) }) );
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return length;
|
||||
// }
|
||||
//
|
||||
// public boolean isActive() {
|
||||
// return retryFlag;
|
||||
// }
|
||||
//
|
||||
// public synchronized void shutdown() {
|
||||
//
|
||||
// active = false;
|
||||
// retryFlag = false;
|
||||
// SocketAdapterManager.getInstance().removeError( this );
|
||||
// try {
|
||||
// this.notify();
|
||||
// } catch( Exception e ) {}
|
||||
//
|
||||
// try {
|
||||
// if ( this.channel != null ) {
|
||||
// this.channel.wakeup();
|
||||
// }
|
||||
// } catch ( Throwable e ) {}
|
||||
//
|
||||
// try {
|
||||
// closeChannel();
|
||||
// } catch (Exception e) {}
|
||||
//
|
||||
// SocketAdapterManager.getInstance().removeError( this );
|
||||
// }
|
||||
//
|
||||
// public Socket getCurrentSocket() {
|
||||
// return channel.getSocket();
|
||||
// }
|
||||
//
|
||||
// public boolean connect() {
|
||||
//
|
||||
// try {
|
||||
// openChannel();
|
||||
// return true;
|
||||
// } catch ( Exception e ) {
|
||||
// return false;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public void disconnect() {
|
||||
// shutdown();
|
||||
// }
|
||||
//
|
||||
// protected synchronized void openChannel() throws IOException {
|
||||
//
|
||||
// if ( channel != null ) {
|
||||
// try {
|
||||
// if ( !channel.isConnected() ) {
|
||||
// SocketAdapterManager.getInstance().removeState( this );
|
||||
// closeChannel();
|
||||
// }
|
||||
// } catch(Exception e) {
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if ( channel == null || !channel.isOpen() ) {
|
||||
// if (!retryFlag) return;
|
||||
//
|
||||
// SocketChannel socketChannel = SocketChannel.open();
|
||||
// if ( context.getLocalHostName() != null && !context.getLocalHostName().equals("") ) {
|
||||
// socketChannel.socket().bind( new InetSocketAddress( InetAddress.getAllByName(context.getLocalHostName())[0], context.getLocalPortNumber() ) );
|
||||
// socketChannel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) );
|
||||
// } else {
|
||||
// socketChannel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) );
|
||||
// }
|
||||
//
|
||||
// socketChannel.socket().setTcpNoDelay(true);
|
||||
// socketChannel.configureBlocking(false);
|
||||
//
|
||||
// if ( isSocketReuse() ) {
|
||||
// socketChannel.socket().setSoLinger(true, 0);
|
||||
// }
|
||||
//
|
||||
// channel = new NBChannel( socketChannel, getTimeout() );
|
||||
//
|
||||
// // Connection 시 통계자료 RESET
|
||||
// this.firstActivity = System.currentTimeMillis();
|
||||
// this.lastActivity = this.firstActivity;
|
||||
// this.sendCount = 0;
|
||||
// this.recvCount = 0;
|
||||
//
|
||||
// this.currentState = isAckProtocol() ? CommonLib.NEGOTIATING_PROTOCOL : CommonLib.PROCESSING_PROTOCOL;
|
||||
//
|
||||
// try {
|
||||
// Thread.sleep( 300L );
|
||||
// } catch(Exception e ) {}
|
||||
//
|
||||
// if ( !this.isConnected() ) {
|
||||
// throw new IOException("Closed by Server");
|
||||
// }
|
||||
//
|
||||
// if ( retryFlag ) {
|
||||
// //
|
||||
// SocketAdapterManager.getInstance().addConnection( this );
|
||||
// } else {
|
||||
// closeChannel();
|
||||
// }
|
||||
//
|
||||
// } // Open Selector....
|
||||
// }
|
||||
//
|
||||
// public String getRemoteIPAddress() {
|
||||
// return null;
|
||||
// }
|
||||
// protected synchronized void closeChannel() throws IOException {
|
||||
//
|
||||
// if(channel != null ) {
|
||||
// channel.close();
|
||||
// }
|
||||
// this.currentState = CommonLib.NEGOTIATING_PROTOCOL;
|
||||
//
|
||||
// channel = null;
|
||||
// }
|
||||
//
|
||||
// // 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각
|
||||
// public String toString() {
|
||||
// boolean status = true;
|
||||
// StringBuffer strBuff = new StringBuffer();
|
||||
// strBuff.append(context.getAdapterGroupName()).append(",");
|
||||
// strBuff.append(context.getAdapterName()).append(",");
|
||||
// strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(",");
|
||||
// strBuff.append(context.getSocketType()).append(",");
|
||||
// strBuff.append(context.getResponseType()).append(",");
|
||||
// try {
|
||||
// strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(",");
|
||||
// } catch( Throwable e ) {
|
||||
// status = false;
|
||||
// strBuff.append("?:?,");
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(",");
|
||||
// } catch( Throwable e ) {
|
||||
// status = false;
|
||||
// strBuff.append("?:?,");
|
||||
// }
|
||||
// strBuff.append(this.sendCount).append(",");
|
||||
// strBuff.append(this.recvCount).append(",");
|
||||
// strBuff.append( status ).append(",");
|
||||
// strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(",");
|
||||
// strBuff.append(CommonLib.getCurrentTime( this.lastActivity ));
|
||||
//
|
||||
// return strBuff.toString();
|
||||
// }
|
||||
//
|
||||
// public void setLastActivity() {
|
||||
// }
|
||||
//
|
||||
// public long getFirstActivity() {
|
||||
// return firstActivity;
|
||||
// }
|
||||
//
|
||||
// public long getLastActivity() {
|
||||
// return lastActivity;
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,194 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class OutboundControl implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private String adapterGroupName;
|
||||
private byte[] response;
|
||||
private byte[] request;
|
||||
private Throwable lastError;
|
||||
private Logger logger;
|
||||
private static Logger errLogger = SocketLogManager.getInstance().getErrLogger();
|
||||
private boolean ready;
|
||||
private long respTimeout;
|
||||
/**
|
||||
* @return Returns the code.
|
||||
*/
|
||||
public String getAdapterGroupName() {
|
||||
return adapterGroupName;
|
||||
}
|
||||
/**
|
||||
* @param code The code to set.
|
||||
*/
|
||||
public void setAdapterGroupName(String code) {
|
||||
this.adapterGroupName = code;
|
||||
}
|
||||
/**
|
||||
* @return Returns the request.
|
||||
*/
|
||||
public byte[] getRequest() {
|
||||
return request;
|
||||
}
|
||||
/**
|
||||
* @param request The request to set.
|
||||
*/
|
||||
public void setRequest(byte[] request) {
|
||||
this.request = request;
|
||||
}
|
||||
/**
|
||||
* @return Returns the resposne.
|
||||
*/
|
||||
public byte[] getResponse() {
|
||||
return response;
|
||||
}
|
||||
/**
|
||||
* @param resposne The resposne to set.
|
||||
*/
|
||||
public synchronized void setResponse(byte[] response) {
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
public OutboundControl() {
|
||||
logger = SocketLogManager.getInstance().getLogger();
|
||||
ready = false;
|
||||
respTimeout = 0;
|
||||
}
|
||||
|
||||
public OutboundControl(String adapterGroupName) {
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
logger = SocketLogManager.getInstance().getLogger( adapterGroupName );
|
||||
}
|
||||
|
||||
public byte[] callService(String adapterGroupName, byte[] message) throws Exception {
|
||||
|
||||
// Connection을 얻어온다...
|
||||
OutboundChannelManager mgr = OutboundChannelManager.getInstance();
|
||||
|
||||
SocketService service = null;
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
long waitTime = 0;
|
||||
long timeout = SocketAdapterManager.getInstance().getTimeout( adapterGroupName );
|
||||
|
||||
while ( true ) {
|
||||
service = mgr.getConnection(adapterGroupName);
|
||||
if ( service != null ) {
|
||||
//break;
|
||||
try {
|
||||
//if ( service.getCurrentState() == CommonLib.PROCESSING_PROTOCOL && service.isConnected() ) {
|
||||
if ( service.isActive() && service.getCurrentState() == CommonLib.PROCESSING_PROTOCOL ) {
|
||||
break;
|
||||
} else if ( service.isActive() ) {
|
||||
mgr.addConnection( adapterGroupName, service);
|
||||
}
|
||||
} catch( Throwable e ) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
waitTime = System.currentTimeMillis() - start;
|
||||
if ( waitTime >= timeout ) break;
|
||||
try {
|
||||
Thread.sleep( 20L );
|
||||
} catch( Exception e ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ( service == null ) {
|
||||
String errMsg = CommonLib.getMessage("BECEAIASO008", new String[]{ this.adapterGroupName } );
|
||||
|
||||
logger.error( errMsg );
|
||||
logger.error( CommonLib.getDumpMessage( message ) );
|
||||
|
||||
if ( logger != errLogger ) {
|
||||
errLogger.error( errMsg );
|
||||
errLogger.error( CommonLib.getDumpMessage( message ) );
|
||||
}
|
||||
throw new Exception( errMsg );
|
||||
}
|
||||
|
||||
this.setRequest( message );
|
||||
|
||||
//bmchae - 이거 버그있음 - lock에 걸림
|
||||
//System.out.println("//bmchae - 이거 버그있음 - lock에 걸림");
|
||||
//Thread.dumpStack();
|
||||
|
||||
try {
|
||||
service.setControl(this);
|
||||
service.notifyMessage();
|
||||
// 응답전문을 기다림...
|
||||
waitReply();
|
||||
} catch( Throwable e ) {
|
||||
//bmchae
|
||||
//e.printStackTrace();
|
||||
String errMsg = CommonLib.getMessage("BECEAIASO008", new String[]{ this.adapterGroupName } );
|
||||
lastError = new Exception( errMsg );
|
||||
}
|
||||
|
||||
if ( lastError != null ) {
|
||||
String errMsg = CommonLib.getMessage("BECEAIASO009", new String[]{ lastError.getMessage() });
|
||||
|
||||
logger.error( errMsg, lastError );
|
||||
|
||||
if ( logger != errLogger ) {
|
||||
errLogger.error( errMsg );
|
||||
errLogger.error( CommonLib.getDumpMessage( message ) );
|
||||
}
|
||||
throw new Exception( errMsg );
|
||||
}
|
||||
|
||||
return this.response;
|
||||
}
|
||||
|
||||
protected synchronized void waitReply() {
|
||||
//synchronized(request) {
|
||||
long start = System.currentTimeMillis();
|
||||
if ( respTimeout == 0 )
|
||||
respTimeout = 60000L;
|
||||
try {
|
||||
while ( !ready ) {
|
||||
this.wait( respTimeout );
|
||||
break;
|
||||
}
|
||||
} catch ( InterruptedException ie ) {}
|
||||
|
||||
if ( respTimeout > 0 && ( System.currentTimeMillis() - start ) >= respTimeout ) {
|
||||
String errMsg = CommonLib.getMessage("BECEAIASO008", new String[]{ this.adapterGroupName } );
|
||||
lastError = new Exception( errMsg );
|
||||
}
|
||||
//}
|
||||
}
|
||||
|
||||
public void setRespTimeout(long timeout) {
|
||||
this.respTimeout = timeout;
|
||||
}
|
||||
|
||||
public synchronized void wakeup() {
|
||||
//synchronized(request) {
|
||||
this.ready = true;
|
||||
try {
|
||||
this.notify();
|
||||
} catch( Throwable e ) {}
|
||||
//}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the lastError.
|
||||
*/
|
||||
public Throwable getLastError() {
|
||||
return lastError;
|
||||
}
|
||||
/**
|
||||
* @param lastError The lastError to set.
|
||||
*/
|
||||
public synchronized void setLastError(Throwable lastError) {
|
||||
this.lastError = lastError;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,577 @@
|
||||
//package com.eactive.eai.adapter.socket.service;
|
||||
//
|
||||
//import java.io.IOException;
|
||||
//import java.net.InetAddress;
|
||||
//import java.net.Socket;
|
||||
//import java.nio.ByteBuffer;
|
||||
//
|
||||
//import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
//import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
//import com.eactive.eai.adapter.socket.common.SocketAdapterException;
|
||||
//import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
//import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//
|
||||
//import java.net.InetSocketAddress;
|
||||
//import java.nio.channels.SocketChannel;
|
||||
//
|
||||
//public class ReaderClient extends Thread implements SocketService {
|
||||
//
|
||||
// private ConfigurationContext context;
|
||||
// private boolean active;
|
||||
// private NBChannel channel;
|
||||
//
|
||||
// private int sendCount;
|
||||
// private int recvCount;
|
||||
// private long firstActivity;
|
||||
// private long lastActivity;
|
||||
//
|
||||
// private boolean retryFlag;
|
||||
//
|
||||
// private ByteBuffer incomingMessage;
|
||||
//
|
||||
// private ByteBuffer lenBuffer;
|
||||
// private Logger logger;
|
||||
// private static Logger errLogger = SocketLogManager.getInstance().getErrLogger();
|
||||
//
|
||||
// private WriterClient writer;
|
||||
//
|
||||
// public ReaderClient(ConfigurationContext context) {
|
||||
//
|
||||
// String name = this.getName();
|
||||
// this.setName( context.getAdapterName() + "-CONNECTION-READER" + name.substring( name.lastIndexOf("-")) );
|
||||
//
|
||||
// this.context = context;
|
||||
// active = true;
|
||||
// retryFlag = true;
|
||||
//
|
||||
// incomingMessage = null;
|
||||
//
|
||||
// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() );
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// sendCount = 0;
|
||||
// recvCount = 0;
|
||||
// firstActivity = System.currentTimeMillis();
|
||||
// lastActivity = firstActivity;
|
||||
//
|
||||
// logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName() );
|
||||
//
|
||||
// }
|
||||
//
|
||||
// public void addSendCount() {
|
||||
// this.sendCount++;
|
||||
// }
|
||||
//
|
||||
// public void setLastActivity(long lastAccess) {
|
||||
// this.lastActivity = lastAccess;
|
||||
// }
|
||||
//
|
||||
// public void shutdownWriter() {
|
||||
// // 2005.10.17 --
|
||||
// shutdown();
|
||||
// writer = null;
|
||||
// }
|
||||
//
|
||||
// private int getTraceLevel() {
|
||||
// return context.getTraceLevel();
|
||||
// }
|
||||
//
|
||||
// private long getTimeout() {
|
||||
// return ( this.context.getTimeout() * 1000L );
|
||||
// }
|
||||
//
|
||||
// private boolean isSocketReuse() {
|
||||
// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG );
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * @return Returns the context.
|
||||
// */
|
||||
// public ConfigurationContext getContext() {
|
||||
// return context;
|
||||
// }
|
||||
//
|
||||
//// private boolean isSyncMode() {
|
||||
//// return context.isSyncMode();
|
||||
//// }
|
||||
//
|
||||
// public void run() {
|
||||
//
|
||||
// String socketInfo = "";
|
||||
//
|
||||
// while ( retryFlag ) {
|
||||
//
|
||||
// active = true;
|
||||
//
|
||||
// try {
|
||||
// openChannel();
|
||||
// socketInfo = this.getSocketInfo( this.getCurrentSocket() );
|
||||
// } catch(Exception e) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "openChannel", e.getMessage(), "", "" } );
|
||||
// logger.error( errMsg, e );
|
||||
//
|
||||
// waitRecoverConnection();
|
||||
// continue;
|
||||
// }
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIASI002", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) );
|
||||
// }
|
||||
//
|
||||
//// int msgLen = 0;
|
||||
//
|
||||
// writer = new WriterClient( this.context, this.channel, this );
|
||||
// writer.start();
|
||||
//
|
||||
// while ( active ) {
|
||||
// try {
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// incomingMessage = ByteBuffer.allocate( readLength( lenBuffer ) );
|
||||
// processReadMessage( incomingMessage );
|
||||
//
|
||||
// this.checkActivity();
|
||||
//
|
||||
// lastActivity = System.currentTimeMillis();
|
||||
// recvCount++;
|
||||
//
|
||||
// // 메시지수신
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage(incomingMessage.array())}));
|
||||
// }
|
||||
//
|
||||
// incomingMessage.clear();
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// InboundControl control = new InboundControl( context.getAdapterGroupName(), context.getAdapterName(), getTimeout() );
|
||||
// control.setRequest( incomingMessage.array() );
|
||||
// control.setResponseType( context.getResponseType() );
|
||||
//
|
||||
//// byte[] rtnValue = null;
|
||||
//
|
||||
// try {
|
||||
//// rtnValue =
|
||||
// control.request();
|
||||
// } catch( Exception e ) {
|
||||
//// rtnValue =
|
||||
//// e.getMessage().getBytes();
|
||||
//
|
||||
// logger.error( e.getMessage(), e );
|
||||
// logger.error( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage( control.getRequest() )}));
|
||||
//
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( e.getMessage(), e );
|
||||
// errLogger.error( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage( control.getRequest() )}));
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if ( !isSocketReuse() ) {
|
||||
// active = false;
|
||||
// closeChannel();
|
||||
// }
|
||||
// } catch( Exception e ) {
|
||||
// String errMsg = "";
|
||||
// if ( lenBuffer.position() > 0 ) {
|
||||
// errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } );
|
||||
// }
|
||||
//
|
||||
// if ( errMsg.length() > 0 ) {
|
||||
// logger.error( errMsg , e);
|
||||
//
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg, e );
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// active = false;
|
||||
// writer.shutdown();
|
||||
//
|
||||
// waitRecoverConnection();
|
||||
// lenBuffer.clear();
|
||||
// continue;
|
||||
// }
|
||||
// } // end of active
|
||||
// } // end of retry
|
||||
//
|
||||
// try {
|
||||
// if ( writer != null ) {
|
||||
// writer.shutdown();
|
||||
// }
|
||||
// } catch( Throwable e ) {}
|
||||
//
|
||||
// try {
|
||||
// closeChannel();
|
||||
// } catch( Throwable e ) {}
|
||||
//
|
||||
// SocketAdapterManager.getInstance().removeConnection( this );
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIASI003", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) );
|
||||
// }
|
||||
//
|
||||
// interrupt();
|
||||
//
|
||||
// } // end of startup ...
|
||||
//
|
||||
// private String getReadingMessage() {
|
||||
// String rMsg = "";
|
||||
// if ( incomingMessage != null && incomingMessage.position() > 0 ) {
|
||||
// byte[] dMsg = new byte[ incomingMessage.position() ];
|
||||
// System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length );
|
||||
// rMsg = CommonLib.getDumpMessage( dMsg );
|
||||
// }
|
||||
// return rMsg;
|
||||
// }
|
||||
//
|
||||
// private String getSocketInfo(Socket socket) {
|
||||
// StringBuffer connInfo = new StringBuffer();
|
||||
//
|
||||
// connInfo.append("Local Address=");
|
||||
// connInfo.append( socket.getLocalAddress().getHostAddress()).append(":").append(socket.getLocalPort()).append(", ");
|
||||
// connInfo.append("Remote Address=");
|
||||
// connInfo.append( socket.getInetAddress().getHostAddress()).append(":").append(socket.getPort());
|
||||
//
|
||||
// return connInfo.toString();
|
||||
// }
|
||||
//
|
||||
// public boolean idle(long timeout) {
|
||||
// long idleTime = System.currentTimeMillis() - this.lastActivity;
|
||||
//
|
||||
// return ( idleTime > timeout );
|
||||
// }
|
||||
//
|
||||
// public void setControl(Object control) {
|
||||
// }
|
||||
//
|
||||
// public void notifyMessage() {
|
||||
// }
|
||||
//
|
||||
// public int getCurrentState() {
|
||||
// return CommonLib.PROCESSING_PROTOCOL;
|
||||
// }
|
||||
//
|
||||
// private void resetCount() {
|
||||
// this.recvCount = 0;
|
||||
// this.sendCount = 0;
|
||||
// }
|
||||
//
|
||||
// public boolean isConnected() {
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// public String getRemoteIPAddress() {
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// public void checkActivity() {
|
||||
// long currentTime = System.currentTimeMillis();
|
||||
// if ( !CommonLib.getDate( this.lastActivity ).equals( CommonLib.getDate( currentTime )) ) {
|
||||
// this.resetCount();
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Socket Recovery Manager에 의해 Connection Recovery가 되도록 기다린다.
|
||||
// *
|
||||
// */
|
||||
// public synchronized void waitRecoverConnection() {
|
||||
// try {
|
||||
// if ( !retryFlag ) return;
|
||||
//
|
||||
// try { closeChannel(); } catch(Exception ie) {}
|
||||
// if ( retryFlag && SocketAdapterManager.getInstance().addError( this ) ) {
|
||||
// wait();
|
||||
// }
|
||||
// } catch ( InterruptedException e ) {}
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Socket Recovery Manager에 의해 recovery되면 Socket Recovery Manager에 의해 통지된다. *
|
||||
// */
|
||||
//
|
||||
// public synchronized void notifyRecoverConnection() {
|
||||
// notify();
|
||||
// }
|
||||
//
|
||||
// private int readLength( ByteBuffer buffer ) throws Exception {
|
||||
// int length = 0;
|
||||
//
|
||||
// long waitTime = ( getTimeout() <= 0 ) ? System.currentTimeMillis() : getTimeout();
|
||||
// long start = 0;
|
||||
// long msecs = waitTime;
|
||||
//
|
||||
// while ( buffer.position() < buffer.capacity() ) {
|
||||
// while ( buffer.position() < buffer.capacity() ) {
|
||||
// length = channel.read( buffer );
|
||||
//
|
||||
// if ( start == 0L && buffer.position() > 0 ) {
|
||||
// start = System.currentTimeMillis();
|
||||
// } else if ( start > 0 ) {
|
||||
// waitTime = msecs - (System.currentTimeMillis() - start);
|
||||
// }
|
||||
//
|
||||
// if ( waitTime <= 0 ) {
|
||||
// byte[] lmsg = new byte[ buffer.position() ];
|
||||
// System.arraycopy( buffer.array(), 0, lmsg, 0, lmsg.length );
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "수신", "X'" + CommonLib.byte2Hex( lmsg )+ "'" });
|
||||
//
|
||||
// logger.error( errMsg );
|
||||
//
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg );
|
||||
// }
|
||||
// throw new Exception( errMsg );
|
||||
// }
|
||||
// if ( length < 1 ) break;
|
||||
// }
|
||||
// //* 2005.10.17
|
||||
// //if ( !active ) throw new Exception("어뎁터중지명령에 의해 CLOSED되었습니다.");
|
||||
// // *정상적인 Normal Shutdown을 위한 확인...
|
||||
//
|
||||
// if ( length == 0 && buffer.position() == 0 && !retryFlag ) {
|
||||
// String errMsg = CommonLib.getMessage("BICEAIASI004", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())});
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( errMsg );
|
||||
// }
|
||||
// throw new Exception( errMsg );
|
||||
// }
|
||||
//
|
||||
// if(length == -1) {
|
||||
// if ( buffer.position() > 0 ) {
|
||||
// throw new Exception( CommonLib.getMessage("BECEAIASI003", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}) );
|
||||
// } else {
|
||||
// String errMsg = CommonLib.getMessage("BICEAIASI004", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())});
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( errMsg );
|
||||
// }
|
||||
// throw new Exception( errMsg );
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if ( buffer.position() == buffer.capacity() ) {
|
||||
// length = checkLengthField( buffer );
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// return length;
|
||||
// }
|
||||
//
|
||||
//
|
||||
// private void processReadMessage( ByteBuffer buffer ) throws Exception {
|
||||
// int i = 0;
|
||||
// boolean isDone = false;
|
||||
// buffer.clear();
|
||||
//
|
||||
// long waitTime = ( getTimeout() <= 0 ) ? System.currentTimeMillis() : getTimeout();
|
||||
// long start = System.currentTimeMillis();
|
||||
// long msecs = waitTime;
|
||||
//
|
||||
// while ( !isDone ) {
|
||||
//
|
||||
// while ( buffer.position() < buffer.capacity() ) {
|
||||
// i = channel.read( buffer );
|
||||
//
|
||||
// waitTime = msecs - (System.currentTimeMillis() - start);
|
||||
//
|
||||
// if ( waitTime <= 0 ) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "수신", getReadingMessage() });
|
||||
//
|
||||
// logger.error( errMsg );
|
||||
//
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg );
|
||||
// }
|
||||
// throw new Exception( CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), Long.toString(getTimeout()), "", "" }) );
|
||||
// }
|
||||
//
|
||||
// if ( i < 1 ) break;
|
||||
// }
|
||||
//
|
||||
// if(i == -1) {
|
||||
// throw new Exception( CommonLib.getMessage("BECEAIASI003", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket())}) );
|
||||
// } else if ( buffer.position() == buffer.capacity() ) {
|
||||
// isDone = true;
|
||||
// }
|
||||
// } // end of while
|
||||
// } // end of readData
|
||||
//
|
||||
// private int checkLengthField(ByteBuffer buffer) throws SocketAdapterException {
|
||||
// int length = 0;
|
||||
//
|
||||
// if ( buffer.capacity() == 2 ) {
|
||||
// length = ( buffer.getShort(0) & 0xFFFF );
|
||||
// } else if ( buffer.capacity() == 4 ) {
|
||||
// length = ( buffer.getInt(0) );
|
||||
// if ( length < 0 ) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI009", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.byte2Hex( buffer.array() ) }) );
|
||||
// }
|
||||
// } else {
|
||||
// String lenStr = new String( buffer.array() );
|
||||
// try {
|
||||
// length = Integer.parseInt( lenStr );
|
||||
// } catch ( NumberFormatException e ) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI009", new String[]{context.getAdapterName(), getSocketInfo(getCurrentSocket()), CommonLib.byte2Hex( buffer.array() ) }) );
|
||||
// }
|
||||
// }
|
||||
// return length;
|
||||
//
|
||||
// }
|
||||
//
|
||||
// public boolean isActive() {
|
||||
// return retryFlag;
|
||||
// }
|
||||
//
|
||||
// public synchronized void shutdown() {
|
||||
//
|
||||
// active = false;
|
||||
// retryFlag = false;
|
||||
//
|
||||
// try {
|
||||
// notify();
|
||||
// } catch( Exception e ) {}
|
||||
//
|
||||
// //* 2005.10.17
|
||||
// try {
|
||||
// this.channel.wakeup();
|
||||
// } catch( Throwable e ) {}
|
||||
//
|
||||
// /*
|
||||
// try {
|
||||
// writer.shutdown();
|
||||
// } catch( Exception e ) {}
|
||||
// */
|
||||
//
|
||||
// // to gracefully shutdown the thread
|
||||
// try {
|
||||
// closeChannel();
|
||||
// } catch (Exception e) {}
|
||||
// //interrupt();
|
||||
// }
|
||||
//
|
||||
// public Socket getCurrentSocket() {
|
||||
// return channel.getSocket();
|
||||
// }
|
||||
//
|
||||
// public boolean connect() {
|
||||
// if ( !retryFlag ) return true;
|
||||
//
|
||||
// try {
|
||||
// openChannel();
|
||||
// return true;
|
||||
// } catch ( Exception e ) {
|
||||
// return false;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public void disconnect() {
|
||||
// shutdown();
|
||||
// }
|
||||
//
|
||||
// private synchronized void openChannel() throws IOException {
|
||||
//
|
||||
// if ( channel == null || !channel.isOpen() ) {
|
||||
// // Sleep Time조정.... HotDeploy시 Multi Connection 현상방지...
|
||||
// //try {
|
||||
// // Thread.sleep( 1000L );
|
||||
// //} catch( InterruptedException e ) {
|
||||
// // if ( !retryFlag ) return;
|
||||
// //}
|
||||
// if ( !retryFlag ) return;
|
||||
//
|
||||
// SocketChannel socketChannel = SocketChannel.open();
|
||||
// //if ( context.getLocalHostName() != null && !context.getLocalHostName().equals("") && context.getLocalPortNumber() > 1024 ) {
|
||||
// if ( context.getLocalHostName() != null && !context.getLocalHostName().equals("") ) {
|
||||
// socketChannel.socket().bind( new InetSocketAddress( InetAddress.getAllByName(context.getLocalHostName())[0], context.getLocalPortNumber() ) );
|
||||
// socketChannel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) );
|
||||
// //socket = new Socket(context.getHostName(), context.getPortNumber(), InetAddress.getAllByName(context.getLocalHostName())[0], context.getLocalPortNumber() );
|
||||
// } else {
|
||||
// socketChannel.connect( new InetSocketAddress( context.getHostName(), context.getPortNumber() ) );
|
||||
// //socket = new Socket(context.getHostName(), context.getPortNumber());
|
||||
// }
|
||||
//
|
||||
// socketChannel.socket().setTcpNoDelay(true);
|
||||
// socketChannel.configureBlocking(false);
|
||||
//
|
||||
// if ( isSocketReuse() ) {
|
||||
// socketChannel.socket().setSoLinger(true, 0);
|
||||
// }
|
||||
//
|
||||
// channel = new NBChannel( socketChannel, getTimeout() );
|
||||
//
|
||||
// // Connection 시 통계자료 RESET
|
||||
// this.firstActivity = System.currentTimeMillis();
|
||||
// this.lastActivity = this.firstActivity;
|
||||
// this.sendCount = 0;
|
||||
// this.recvCount = 0;
|
||||
//
|
||||
// try {
|
||||
// Thread.sleep( 300L );
|
||||
// } catch( Exception e ) {}
|
||||
//
|
||||
// if ( !this.isConnected() ) {
|
||||
// throw new IOException("Closed by Server");
|
||||
// }
|
||||
//
|
||||
// if ( retryFlag ) {
|
||||
// //
|
||||
// SocketAdapterManager.getInstance().addConnection( this );
|
||||
// } else {
|
||||
// closeChannel();
|
||||
// }
|
||||
//
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private synchronized void closeChannel() throws IOException {
|
||||
//
|
||||
// if(channel != null ) {
|
||||
// channel.close();
|
||||
// }
|
||||
// channel = null;
|
||||
// } //
|
||||
//
|
||||
// // 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, SYNC, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각
|
||||
// public String toString() {
|
||||
// boolean status = true;
|
||||
// StringBuffer strBuff = new StringBuffer();
|
||||
// strBuff.append(context.getAdapterGroupName()).append(",");
|
||||
// strBuff.append(context.getAdapterName()).append(",");
|
||||
// strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(",");
|
||||
// strBuff.append(context.getSocketType()).append(",");
|
||||
// strBuff.append(context.getResponseType()).append(",");
|
||||
// try {
|
||||
// strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(",");
|
||||
// } catch( Throwable e ) {
|
||||
// status = false;
|
||||
// strBuff.append("?:?,");
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(",");
|
||||
// } catch( Throwable e ) {
|
||||
// status = false;
|
||||
// strBuff.append("?:?,");
|
||||
// }
|
||||
// strBuff.append(this.sendCount).append(",");
|
||||
// strBuff.append(this.recvCount).append(",");
|
||||
// strBuff.append( status ).append(",");
|
||||
// strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(",");
|
||||
// strBuff.append(CommonLib.getCurrentTime( this.lastActivity ));
|
||||
//
|
||||
// return strBuff.toString();
|
||||
// }
|
||||
//
|
||||
// public void setLastActivity() {
|
||||
// }
|
||||
//
|
||||
// public long getFirstActivity() {
|
||||
// return firstActivity;
|
||||
// }
|
||||
//
|
||||
// public long getLastActivity() {
|
||||
// return lastActivity;
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,613 @@
|
||||
//package com.eactive.eai.adapter.socket.service;
|
||||
//
|
||||
//import java.io.IOException;
|
||||
//import java.net.Socket;
|
||||
//import java.nio.BufferOverflowException;
|
||||
//import java.nio.ByteBuffer;
|
||||
//import java.nio.channels.ClosedSelectorException;
|
||||
//import java.nio.channels.SelectionKey;
|
||||
//import java.nio.channels.Selector;
|
||||
//import java.nio.channels.SocketChannel;
|
||||
//import java.util.Iterator;
|
||||
//
|
||||
//import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
//import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
//import com.eactive.eai.adapter.socket.common.SocketAdapterException;
|
||||
//import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
//import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//
|
||||
//public class ReaderServer extends Thread implements SocketService {
|
||||
//
|
||||
// private ConfigurationContext context;
|
||||
// private SocketChannel socketChannel;
|
||||
// private SocketServer proxy;
|
||||
// private Selector selector;
|
||||
// private SelectionKey key;
|
||||
//
|
||||
// private boolean active;
|
||||
//
|
||||
// // 상태정보
|
||||
// private int sendCount;
|
||||
// private int recvCount;
|
||||
// private long firstActivity;
|
||||
// private long lastActivity;
|
||||
//
|
||||
// // IO BUFFER
|
||||
// private ByteBuffer incomingMessage;
|
||||
// private ByteBuffer lenBuffer;
|
||||
//
|
||||
// // pending message for checking operation
|
||||
// private ByteBuffer pendingMessage;
|
||||
// // Logger
|
||||
// private Logger logger;
|
||||
// private static Logger errLogger = SocketLogManager.getInstance().getErrLogger();
|
||||
// private WriterServer writer;
|
||||
// private boolean shutdownFlag;
|
||||
// private String remoteIPAddress;
|
||||
//
|
||||
// public ReaderServer(ConfigurationContext context, SocketChannel socketChannel, SocketServer proxy) {
|
||||
// String name = this.getName();
|
||||
// this.setName( context.getAdapterName() + "-CONNECTION-READER" + name.substring( name.lastIndexOf("-")) );
|
||||
//
|
||||
// this.context = context;
|
||||
// this.socketChannel = socketChannel;
|
||||
// this.proxy = proxy;
|
||||
// this.writer = null;
|
||||
//
|
||||
// sendCount = 0;
|
||||
// recvCount = 0;
|
||||
// firstActivity = System.currentTimeMillis();
|
||||
// lastActivity = System.currentTimeMillis();
|
||||
//
|
||||
// incomingMessage = null;
|
||||
//
|
||||
// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() );
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// pendingMessage = ByteBuffer.allocate( 4096 );
|
||||
// pendingMessage.clear();
|
||||
//
|
||||
// logger = SocketLogManager.getInstance().getLogger( context.getAdapterGroupName());
|
||||
//
|
||||
// remoteIPAddress = this.socketChannel.socket().getInetAddress().getHostAddress();
|
||||
// active = true;
|
||||
// shutdownFlag = false;
|
||||
// }
|
||||
//
|
||||
//// private boolean isSyncMode() {
|
||||
//// return this.context.isSyncMode();
|
||||
//// }
|
||||
////
|
||||
//// private boolean isAckProtocol() {
|
||||
//// return this.context.isAckProtocol();
|
||||
//// }
|
||||
//
|
||||
// private long getTimeout() {
|
||||
// return ( this.context.getTimeout() * 1000L );
|
||||
// }
|
||||
//
|
||||
//// private boolean isSocketReuse() {
|
||||
//// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG );
|
||||
//// }
|
||||
//
|
||||
// private int getTraceLevel() {
|
||||
// return context.getTraceLevel();
|
||||
// }
|
||||
// /**
|
||||
// * @return Returns the context.
|
||||
// */
|
||||
// public ConfigurationContext getContext() {
|
||||
// return context;
|
||||
// }
|
||||
//
|
||||
// public String getRemoteIPAddress() {
|
||||
// return this.remoteIPAddress;
|
||||
// }
|
||||
//
|
||||
// public void run() {
|
||||
// SocketAdapterManager.getInstance().addConnection( this );
|
||||
// String socketInfo = this.getSocketInfo(this.socketChannel);
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIASI002", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) );
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// openSelector();
|
||||
// } catch(IOException e) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "openSelector", e.getMessage(), "", "" } );
|
||||
// logger.error( errMsg, e );
|
||||
// active = false;
|
||||
// }
|
||||
//
|
||||
//
|
||||
//// Iterator iterator;
|
||||
// if ( active ) {
|
||||
// try {
|
||||
// writer = new WriterServer( this.context, this.socketChannel, this, this.selector );
|
||||
// writer.start();
|
||||
// } catch( Exception e ) { }
|
||||
// }
|
||||
//
|
||||
// long start = System.currentTimeMillis();
|
||||
//
|
||||
// while( active ) {
|
||||
// try {
|
||||
// int selected = selector.select( 1000L );
|
||||
// if( selected == 0 ) {
|
||||
// long waitTime = System.currentTimeMillis() - start;
|
||||
// if ( lenBuffer.position() > 0 && waitTime >= getTimeout() ) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASI006", new String[]{context.getAdapterName(), socketInfo, Long.toString(getTimeout()), "수신", getReadingMessage() });
|
||||
// logger.error( errMsg );
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg );
|
||||
// }
|
||||
// active = false;
|
||||
// } else if ( lenBuffer.position() > 0 ){
|
||||
// active = isConnected();
|
||||
// } else if ( shutdownFlag && lenBuffer.position() == 0 ) {
|
||||
// active = false;
|
||||
// }
|
||||
// continue;
|
||||
// }
|
||||
// //* 2005.10.17
|
||||
// if ( shutdownFlag && lenBuffer.position() == 0 ) {
|
||||
// active = false;
|
||||
// continue;
|
||||
// }
|
||||
// } catch(IOException e) {
|
||||
// if ( lenBuffer.position() > 0 ) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "select", e.getMessage(), "수신메시지", getReadingMessage() } );
|
||||
// logger.error( errMsg , e);
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg, e );
|
||||
// }
|
||||
// }
|
||||
// active = false;
|
||||
// } catch(ClosedSelectorException e ) {
|
||||
// continue;
|
||||
// } catch(Exception e) {}
|
||||
//
|
||||
// if ( selector == null || !selector.isOpen() ) continue;
|
||||
//
|
||||
// Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
|
||||
//
|
||||
// while( iterator.hasNext() ) {
|
||||
// key = iterator.next();
|
||||
// iterator.remove();
|
||||
// socketChannel = (SocketChannel)key.channel();
|
||||
// if(key.isReadable()) { // is Readable ? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
|
||||
// try {
|
||||
// start = System.currentTimeMillis();
|
||||
// if( processReadMessage() ) { // Read Done
|
||||
// byte[] message = incomingMessage.array();
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG ) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage(incomingMessage.array())}));
|
||||
// }
|
||||
// this.checkActivity();
|
||||
// lastActivity = System.currentTimeMillis();
|
||||
// recvCount++;
|
||||
//
|
||||
// incomingMessage.clear();
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// InboundControl control = new InboundControl( context.getAdapterGroupName(), context.getAdapterName(), getTimeout() );
|
||||
// control.setRequest( message );
|
||||
// control.setResponseType( context.getResponseType() );
|
||||
//
|
||||
//// byte[] rtnValue = null;
|
||||
//
|
||||
// try {
|
||||
// control.request();
|
||||
// } catch( Exception e ) {
|
||||
//// rtnValue = e.getMessage().getBytes();
|
||||
// logger.error( e.getMessage(), e );
|
||||
// logger.error( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo,CommonLib.getDumpMessage( control.getRequest() )}));
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( e.getMessage(), e );
|
||||
// errLogger.error( CommonLib.getMessage("BDCEAIASI001", new String[]{context.getAdapterName(), "RECV", CommonLib.getTimestamp(), socketInfo, CommonLib.getDumpMessage( control.getRequest() )}));
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// start = System.currentTimeMillis();
|
||||
//
|
||||
// socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
|
||||
//
|
||||
// if ( shutdownFlag ) active = false;
|
||||
// }
|
||||
// } catch(Exception e) {
|
||||
// if ( lenBuffer.position() > 0 ) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASI002", new String[]{context.getAdapterName(), "processReadMessage", e.getMessage(), "수신메시지", getReadingMessage() } );
|
||||
// logger.error( errMsg , e);
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg, e );
|
||||
// }
|
||||
// }
|
||||
// active = false;
|
||||
//
|
||||
// } finally {
|
||||
// if(!active) continue;
|
||||
// }
|
||||
// } // end of readable...
|
||||
// } // End of while(iterator.hasNext())
|
||||
// } // enf of while - active
|
||||
//
|
||||
// try {
|
||||
// try {
|
||||
// if ( writer != null ) {
|
||||
// writer.shutdown();
|
||||
// }
|
||||
// } catch( Throwable e ) {}
|
||||
// closeSelector();
|
||||
// } catch(Throwable e) {}
|
||||
//
|
||||
// SocketAdapterManager.getInstance().removeConnection( this );
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIASI003", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) );
|
||||
// }
|
||||
//
|
||||
// proxy.quiesceShutdown(this);
|
||||
//
|
||||
// interrupt();
|
||||
//
|
||||
// }
|
||||
//
|
||||
// private String getReadingMessage() {
|
||||
// String rMsg = "";
|
||||
// if ( incomingMessage != null && incomingMessage.position() > 0 ) {
|
||||
// byte[] dMsg = new byte[ incomingMessage.position() ];
|
||||
// System.arraycopy( incomingMessage.array(), 0, dMsg, 0, dMsg.length );
|
||||
// rMsg = CommonLib.getDumpMessage( dMsg );
|
||||
// }
|
||||
// return rMsg;
|
||||
// }
|
||||
//
|
||||
// private String getSocketInfo(SocketChannel channel) {
|
||||
// StringBuffer connInfo = new StringBuffer();
|
||||
//
|
||||
// connInfo.append("Local Address=");
|
||||
// connInfo.append( channel.socket().getLocalAddress().getHostAddress()).append(":").append(channel.socket().getLocalPort()).append(", ");
|
||||
// connInfo.append("Remote Address=");
|
||||
// connInfo.append( channel.socket().getInetAddress().getHostAddress()).append(":").append(channel.socket().getPort());
|
||||
//
|
||||
// return connInfo.toString();
|
||||
// }
|
||||
//
|
||||
// public boolean idle(long timeout) {
|
||||
// long idleTime = System.currentTimeMillis() - this.lastActivity;
|
||||
// return ( idleTime > timeout );
|
||||
// }
|
||||
//
|
||||
// public void addSendCount() {
|
||||
// this.sendCount++;
|
||||
// }
|
||||
//
|
||||
// public void setLastActivity(long lastAccess) {
|
||||
// this.lastActivity = lastAccess;
|
||||
// }
|
||||
//
|
||||
// public void shutdownWriter() {
|
||||
// shutdown();
|
||||
// writer = null;
|
||||
// }
|
||||
//
|
||||
// public boolean isActive() {
|
||||
// return shutdownFlag;
|
||||
// }
|
||||
//
|
||||
// public synchronized void shutdown() {
|
||||
// //* 2005.10.17
|
||||
// active = false;
|
||||
// shutdownFlag = true;
|
||||
//
|
||||
// try {
|
||||
// notify();
|
||||
// } catch( Exception e ) {}
|
||||
//
|
||||
// try {
|
||||
// if ( selector != null && selector.isOpen() ) {
|
||||
// selector.wakeup();
|
||||
// }
|
||||
// } catch (Throwable e) {}
|
||||
//
|
||||
// //* to gracefully shutdown the thread
|
||||
// //* 2005.10.17
|
||||
// //try {
|
||||
// // writer.shutdown();
|
||||
// //} catch( Exception e ) {}
|
||||
//
|
||||
// try {
|
||||
// closeSelector();
|
||||
// } catch( Exception e ) {}
|
||||
// //*/
|
||||
// //interrupt();
|
||||
// }
|
||||
//
|
||||
// public Socket getCurrentSocket() {
|
||||
// return socketChannel.socket();
|
||||
// }
|
||||
//
|
||||
// public boolean connect() {
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// public void disconnect() {
|
||||
// shutdown();
|
||||
// proxy.quiesceShutdown(this);
|
||||
// }
|
||||
//
|
||||
// private void openSelector() throws IOException {
|
||||
//
|
||||
// if ( selector == null || !selector.isOpen() ) {
|
||||
// selector = Selector.open();
|
||||
// // Connection 시 통계자료 RESET
|
||||
// this.firstActivity = System.currentTimeMillis();
|
||||
// this.lastActivity = this.firstActivity;
|
||||
// this.sendCount = 0;
|
||||
// this.recvCount = 0;
|
||||
//
|
||||
// socketChannel.socket().setTcpNoDelay(true);
|
||||
// socketChannel.configureBlocking(false);
|
||||
// socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE );
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// private void closeSelector() throws IOException {
|
||||
// if(selector != null) {
|
||||
// selector.wakeup();
|
||||
//
|
||||
// for(Iterator<SelectionKey> iterator = selector.keys().iterator(); iterator.hasNext();) {
|
||||
// try {
|
||||
// key = iterator.next();
|
||||
// iterator.remove();
|
||||
// socketChannel = (SocketChannel)key.channel();
|
||||
// key.cancel();
|
||||
// if(socketChannel != null) {
|
||||
// Socket socket = socketChannel.socket();
|
||||
// if(socket != null) {
|
||||
// socket.setSoLinger(false, 0);
|
||||
// try { socket.close(); } catch(Exception e) {}
|
||||
// }
|
||||
// socketChannel.close();
|
||||
// }
|
||||
// } catch(IOException ioexception) { }
|
||||
// }
|
||||
// selector.close();
|
||||
// }
|
||||
// selector = null;
|
||||
// }
|
||||
//
|
||||
// public void setControl(Object control) {
|
||||
// }
|
||||
//
|
||||
// public void notifyMessage() {
|
||||
// }
|
||||
//
|
||||
//
|
||||
// private boolean processReadMessage() throws Exception {
|
||||
//
|
||||
// int i = 0;
|
||||
// boolean flag = false;
|
||||
//
|
||||
// if ( pendingMessage.position() > 0 && lenBuffer.hasRemaining() ) {
|
||||
// if ( pendingMessage.position() <= lenBuffer.remaining() ) {
|
||||
// byte[] data = new byte[ pendingMessage.position() ];
|
||||
// pendingMessage.flip();
|
||||
// pendingMessage.get( data );
|
||||
// lenBuffer.put( data );
|
||||
// pendingMessage.clear();
|
||||
// } else {
|
||||
// byte[] data = new byte[ lenBuffer.remaining() ];
|
||||
// pendingMessage.flip();
|
||||
// pendingMessage.get( data );
|
||||
// lenBuffer.put( data );
|
||||
// pendingMessage.position( pendingMessage.limit() );
|
||||
// shiftBuffer( pendingMessage, data.length );
|
||||
// }
|
||||
// if ( lenBuffer.position() == lenBuffer.capacity() ) flag = true;
|
||||
// }
|
||||
//
|
||||
// while ( lenBuffer.position() < lenBuffer.capacity() ) {
|
||||
// i = socketChannel.read( lenBuffer );
|
||||
// if ( i <= 0 ) break;
|
||||
// if ( lenBuffer.position() == lenBuffer.capacity() ) flag = true;
|
||||
// }
|
||||
//
|
||||
// if(i == -1) {
|
||||
// if ( lenBuffer.position() > 0 ) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI003", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}) );
|
||||
// } else {
|
||||
// String errMsg = CommonLib.getMessage("BICEAIASI004", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)});
|
||||
// if(logger.isInfoEnabled()){
|
||||
// logger.info( errMsg );
|
||||
// }
|
||||
// throw new SocketAdapterException( errMsg );
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if ( lenBuffer.position() != lenBuffer.capacity() ) return false;
|
||||
//
|
||||
// int length = 0;
|
||||
//
|
||||
// try {
|
||||
// if ( flag ) {
|
||||
// length = checkLengthField( lenBuffer );
|
||||
// incomingMessage = ByteBuffer.allocate( length );
|
||||
// incomingMessage.clear();
|
||||
// }
|
||||
// } catch(Exception le) {
|
||||
// throw le;
|
||||
// }
|
||||
//
|
||||
// i = 0;
|
||||
//
|
||||
// if ( pendingMessage.position() > 0 && incomingMessage.hasRemaining()) {
|
||||
// if ( pendingMessage.position() <= incomingMessage.remaining() ) {
|
||||
// byte[] data = new byte[ pendingMessage.position() ];
|
||||
// pendingMessage.flip();
|
||||
// pendingMessage.get( data );
|
||||
// incomingMessage.put( data );
|
||||
// pendingMessage.clear();
|
||||
// } else {
|
||||
// byte[] data = new byte[ incomingMessage.remaining() ];
|
||||
// pendingMessage.flip();
|
||||
// pendingMessage.get( data );
|
||||
// lenBuffer.put( data );
|
||||
// pendingMessage.position( pendingMessage.limit() );
|
||||
// shiftBuffer( pendingMessage, data.length );
|
||||
// }
|
||||
// if ( incomingMessage.position() == incomingMessage.capacity() ) return true;
|
||||
// }
|
||||
//
|
||||
// while ( incomingMessage.position() < incomingMessage.capacity()) {
|
||||
// i = socketChannel.read(incomingMessage);
|
||||
// if ( i <= 0 ) break;
|
||||
// }
|
||||
//
|
||||
// if(i == -1) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI003", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel)}) );
|
||||
// } else {
|
||||
// if ( incomingMessage.position() == incomingMessage.capacity() ) {
|
||||
// return true;
|
||||
// } else {
|
||||
// return false;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private void shiftBuffer(ByteBuffer buffer, int shiftBytes) {
|
||||
// int pos = buffer.position();
|
||||
// if ( pos <= shiftBytes ) {
|
||||
// buffer.clear();
|
||||
// return;
|
||||
// }
|
||||
// byte[] tmpBuff = new byte[ pos ];
|
||||
// buffer.flip();
|
||||
// buffer.get( tmpBuff );
|
||||
//
|
||||
// buffer.clear();
|
||||
// buffer.put( tmpBuff, shiftBytes, tmpBuff.length - shiftBytes );
|
||||
// }
|
||||
//
|
||||
// // Writing전에 확인...
|
||||
// public boolean isConnected() throws IOException {
|
||||
// boolean flag = true;
|
||||
//
|
||||
// if ( socketChannel.isConnected() && socketChannel.socket().isBound() ) {
|
||||
// ByteBuffer tmpBuffer = ByteBuffer.allocate( 1 );
|
||||
// tmpBuffer.clear();
|
||||
// int i = socketChannel.read( tmpBuffer );
|
||||
// if ( i > 0 ) {
|
||||
// try {
|
||||
// pendingMessage.put( tmpBuffer );
|
||||
// } catch ( BufferOverflowException e ) {
|
||||
// throw new IOException("Socket 어플리케이션 프로토콜에러 발생 : " + e.getMessage());
|
||||
// }
|
||||
// }
|
||||
// if ( i == -1 ) {
|
||||
// flag = false;
|
||||
// }
|
||||
// } else {
|
||||
// flag = false;
|
||||
// }
|
||||
//
|
||||
// return flag;
|
||||
// }
|
||||
//
|
||||
// public int getCurrentState() {
|
||||
// return CommonLib.PROCESSING_PROTOCOL;
|
||||
// }
|
||||
//
|
||||
// private void resetCount() {
|
||||
// this.recvCount = 0;
|
||||
// this.sendCount = 0;
|
||||
// }
|
||||
//
|
||||
// public void checkActivity() {
|
||||
// long currentTime = System.currentTimeMillis();
|
||||
// if ( !CommonLib.getDate( this.lastActivity ).equals( CommonLib.getDate( currentTime )) ) {
|
||||
// this.resetCount();
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private int checkLengthField(ByteBuffer buffer) throws SocketAdapterException {
|
||||
// int length = 0;
|
||||
//
|
||||
// if ( buffer.capacity() == 2 ) {
|
||||
// length = ( buffer.getShort(0) & 0xFFFF );
|
||||
// } else if ( buffer.capacity() == 4 ) {
|
||||
// length = ( buffer.getInt(0) );
|
||||
// if ( length < 0 ) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI009", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.byte2Hex( buffer.array() ) }) );
|
||||
// }
|
||||
// } else {
|
||||
// String lenStr = new String( buffer.array() );
|
||||
// try {
|
||||
// length = Integer.parseInt( lenStr );
|
||||
// } catch ( NumberFormatException e ) {
|
||||
// throw new SocketAdapterException( CommonLib.getMessage("BECEAIASI009", new String[]{context.getAdapterName(), getSocketInfo(this.socketChannel), CommonLib.byte2Hex( buffer.array() ) }) );
|
||||
// }
|
||||
// }
|
||||
// return length;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * @return Returns the socketchannel.
|
||||
// */
|
||||
// public SocketChannel getSocketchannel() {
|
||||
// return socketChannel;
|
||||
// }
|
||||
// /**
|
||||
// * @param socketchannel The socketchannel to set.
|
||||
// */
|
||||
// public void setSocketchannel(SocketChannel socketchannel) {
|
||||
// this.socketChannel = socketchannel;
|
||||
// }
|
||||
//
|
||||
// // 1. Connection 리스트정보 - AdapterGroupName,AdapterName,업무코드,INBOUND, CLIENT, LocalIP:Port, RemoteIP:Port, 송신건수, 수신건수, 상태, 최초연결시각, 최종사용시각
|
||||
// public String toString() {
|
||||
// boolean status = true;
|
||||
// StringBuffer strBuff = new StringBuffer();
|
||||
// strBuff.append(context.getAdapterGroupName()).append(",");
|
||||
// strBuff.append(context.getAdapterName()).append(",");
|
||||
// strBuff.append(context.getBwkClsCd()).append(",").append(context.getBoundUsage()).append(",");
|
||||
// strBuff.append(context.getSocketType()).append(",");
|
||||
// strBuff.append(context.getResponseType()).append(",");
|
||||
// try {
|
||||
// strBuff.append( getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(getCurrentSocket().getLocalPort()).append(",");
|
||||
// } catch( Throwable e ) {
|
||||
// status = false;
|
||||
// strBuff.append("?:?,");
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// strBuff.append( getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(getCurrentSocket().getPort()).append(",");
|
||||
// } catch( Throwable e ) {
|
||||
// status = false;
|
||||
// strBuff.append("?:?,");
|
||||
// }
|
||||
// strBuff.append(this.sendCount).append(",");
|
||||
// strBuff.append(this.recvCount).append(",");
|
||||
// strBuff.append( status ).append(",");
|
||||
// strBuff.append( CommonLib.getCurrentTime( this.firstActivity )).append(",");
|
||||
// strBuff.append(CommonLib.getCurrentTime( this.lastActivity ));
|
||||
//
|
||||
// return strBuff.toString();
|
||||
// }
|
||||
//
|
||||
// public void setLastActivity() {
|
||||
// }
|
||||
//
|
||||
// public long getFirstActivity() {
|
||||
// return firstActivity;
|
||||
// }
|
||||
//
|
||||
// public long getLastActivity() {
|
||||
// return lastActivity;
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
import java.util.TimerTask;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
|
||||
|
||||
/**
|
||||
* Client Socket mode로 사용되는 connection 장애 시 일정간격으로 Recovery를 시도한다.
|
||||
* Only 1 thread가 처리한다.
|
||||
*/
|
||||
public class RecoveryManager extends TimerTask {
|
||||
|
||||
private LinkedList<SocketService> errorTable;
|
||||
private Logger logger = SocketLogManager.getInstance().getLogger();
|
||||
|
||||
public RecoveryManager(LinkedList<SocketService> errorTable) {
|
||||
this.errorTable = errorTable;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
|
||||
if ( errorTable.size() > 0 ) {
|
||||
if(logger.isInfoEnabled()){
|
||||
logger.info( CommonLib.getMessage("BICEAIMSA029", new String[]{ Integer.toString( errorTable.size() )} ) );
|
||||
}
|
||||
retryTheConnect();
|
||||
}
|
||||
}
|
||||
|
||||
public void retryTheConnect() {
|
||||
|
||||
int count = errorTable.size();
|
||||
|
||||
SocketService aService = null;
|
||||
for ( int i=0; i < count; i++) {
|
||||
try {
|
||||
aService = ( SocketService ) errorTable.removeFirst();
|
||||
if ( !aService.isActive() ) continue;
|
||||
if ( aService.connect() ) {
|
||||
InboundClient client = ( InboundClient )aService;
|
||||
client.notifyRecoverConnection();
|
||||
|
||||
try {
|
||||
StringBuffer connInfo = new StringBuffer();
|
||||
connInfo.append("Local Address=");
|
||||
connInfo.append( aService.getCurrentSocket().getLocalAddress().getHostAddress()).append(":").append(aService.getCurrentSocket().getLocalPort()).append(", ");
|
||||
connInfo.append("Remote Address=");
|
||||
connInfo.append( aService.getCurrentSocket().getInetAddress().getHostAddress()).append(":").append(aService.getCurrentSocket().getPort());
|
||||
|
||||
if(logger.isInfoEnabled())
|
||||
logger.info( CommonLib.getMessage("BICEAIMSA030", new String[]{ aService.getContext().getAdapterName(), connInfo.toString() }) );
|
||||
} catch (Throwable t) {
|
||||
logger.error(t.getMessage(),t);
|
||||
}
|
||||
} else {
|
||||
// 에러 복구에 실패하면 로깅하도록 변경. 2009.01.09 정동한
|
||||
logger.warn("[RecoveryManager:retryTheConnect]에러 복구 실패[" + aService.getContext().getAdapterName() + "]");
|
||||
errorTable.add( aService );
|
||||
}
|
||||
} catch ( Throwable t ) {
|
||||
//if ( aService != null && aService instanceof SocketService ){
|
||||
if ( aService != null){// 20250910 npe
|
||||
errorTable.add( aService );
|
||||
}
|
||||
continue;
|
||||
}
|
||||
} // trying to reconnect in errorTable...
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
sb.append("\n■ RecoveryManager : ");
|
||||
for(Iterator<SocketService> iter = errorTable.iterator(); iter.hasNext();) {
|
||||
sb.append("\n ▣ " + iter.next() + " : ");
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import java.util.Vector;
|
||||
|
||||
/**
|
||||
* AdapterGroupName별 SessionChannel를 갖는다.
|
||||
*/
|
||||
public class SessionChannel
|
||||
{
|
||||
private int defaultNumOfSessions;
|
||||
private int maxNumOfSessions;
|
||||
private Vector<SessionService> activeSessions;
|
||||
private long sessionTimeout;
|
||||
|
||||
public SessionChannel(int defaultNumOfSessions, int maxNumOfSessions) {
|
||||
this( defaultNumOfSessions, maxNumOfSessions, 0L );
|
||||
}
|
||||
|
||||
public SessionChannel(int defaultNumOfSessions, int maxNumOfSessions, long sessionTimeout) {
|
||||
this.defaultNumOfSessions = defaultNumOfSessions;
|
||||
this.maxNumOfSessions = maxNumOfSessions;
|
||||
this.sessionTimeout = sessionTimeout * 1000;
|
||||
this.activeSessions = new Vector<SessionService>();
|
||||
}
|
||||
|
||||
public int getDefaultNumOfSessions() {
|
||||
return this.defaultNumOfSessions;
|
||||
}
|
||||
|
||||
public int getMaxNumOfSessions() {
|
||||
return this.maxNumOfSessions;
|
||||
}
|
||||
|
||||
public void setMaxNumOfSessions( int newNumOfSessions ) {
|
||||
if ( newNumOfSessions < this.maxNumOfSessions ) return;
|
||||
this.maxNumOfSessions = newNumOfSessions;
|
||||
}
|
||||
|
||||
public long getSessionTimeout() {
|
||||
return this.sessionTimeout;
|
||||
}
|
||||
|
||||
public void setSessionTimeout(long timeout) {
|
||||
this.sessionTimeout = timeout * 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* SessionService를 parameter로 갖는다.
|
||||
*/
|
||||
public void addSession( SessionService session ) throws Exception {
|
||||
this.addSession( session, true );
|
||||
}
|
||||
|
||||
public void addSession( SessionService session, boolean isPermanent ) throws Exception {
|
||||
synchronized ( this.activeSessions ) {
|
||||
this.activeSessions.add( session );
|
||||
}
|
||||
}
|
||||
|
||||
public Object getSession() throws Exception {
|
||||
synchronized ( this.activeSessions ) {
|
||||
if ( this.activeSessions.size() > 0 ) {
|
||||
//Object x = this.activeSessions.get( 0 );
|
||||
return this.activeSessions.remove( 0 );
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void removeSession( Object session ) throws Exception {
|
||||
synchronized ( this.activeSessions ) {
|
||||
this.activeSessions.remove( session );
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
int active = 0, idle = 0;
|
||||
active = (this.maxNumOfSessions - this.activeSessions.size());
|
||||
//idle = this.activeSessions.size();
|
||||
idle = this.maxNumOfSessions - active;
|
||||
sb.append("SessionChannel [DefaultSessions=").append( this.defaultNumOfSessions ).append(",");
|
||||
sb.append("MaxSessions=").append( this.maxNumOfSessions ).append(",");
|
||||
sb.append("ActiveSessions=").append( active ).append(",");
|
||||
sb.append("IdleSessions=").append( idle ).append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
|
||||
public class SessionManager {
|
||||
|
||||
private static SessionManager instance = new SessionManager();
|
||||
private HashMap<String, SessionChannel> pool = new HashMap<String, SessionChannel>();
|
||||
// private Logger logger;
|
||||
|
||||
public SessionManager() {
|
||||
// logger = SocketLogManager.getInstance().getLogger();
|
||||
}
|
||||
|
||||
public static SessionManager getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
this.removeAll();
|
||||
}
|
||||
|
||||
public void removeAll() {
|
||||
pool.clear();
|
||||
}
|
||||
|
||||
public void start(String adapterGroupName, SessionChannel channel) {
|
||||
this.addSessionGroup(adapterGroupName, channel);
|
||||
}
|
||||
|
||||
// Adapter Group Session을 한번에 등록한다.
|
||||
public synchronized void addSessionGroup(String adapterGroupName, SessionChannel channel) {
|
||||
Object o = pool.get( adapterGroupName );
|
||||
if ( o == null ) {
|
||||
synchronized ( pool ) {
|
||||
o = pool.get( adapterGroupName );
|
||||
if ( o == null ) {
|
||||
pool.put( adapterGroupName, channel );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addSession(String adapterGroupName, SessionService session) {
|
||||
SessionChannel channel = this.getChannel( adapterGroupName );
|
||||
if ( channel == null ) return;
|
||||
try {
|
||||
channel.addSession( session );
|
||||
} catch( Exception e ) {}
|
||||
}
|
||||
|
||||
public void removeSession(String adapterGroupName, Object session) {
|
||||
SessionChannel channel = this.getChannel( adapterGroupName );
|
||||
if ( channel == null ) return;
|
||||
try {
|
||||
channel.removeSession( session );
|
||||
} catch( Exception e ) {}
|
||||
}
|
||||
|
||||
public void stop(String adapterGroupName) {
|
||||
// adapterGroupName의 session stop & clear
|
||||
pool.remove( adapterGroupName );
|
||||
}
|
||||
|
||||
public SessionChannel getChannel( String adapterGroupName ) {
|
||||
return (SessionChannel) pool.get( adapterGroupName );
|
||||
}
|
||||
|
||||
public boolean hasChannel( String adapterGroupName ) {
|
||||
return pool.containsKey( adapterGroupName );
|
||||
}
|
||||
|
||||
public SessionService getSession( String adapterGroupName ) {
|
||||
SessionChannel channel = this.getChannel( adapterGroupName );
|
||||
if ( channel == null ) return null;
|
||||
|
||||
SessionService service = null;
|
||||
try {
|
||||
service = (SessionService) channel.getSession();
|
||||
} catch ( Exception e ) { }
|
||||
|
||||
return service;
|
||||
}
|
||||
|
||||
public String getSessionInfo() {
|
||||
StringBuffer strBuff = new StringBuffer();
|
||||
Object[] adapterGroupList = pool.keySet().toArray();
|
||||
if ( adapterGroupList == null || adapterGroupList.length < 1 ) {
|
||||
//strBuff.append("This server don't have any session infomrations");
|
||||
strBuff.append( CommonLib.getMessage("BWCEAIMSA006") );
|
||||
return strBuff.toString();
|
||||
}
|
||||
Arrays.sort( adapterGroupList );
|
||||
for( int i=0; i < adapterGroupList.length; i++ ) {
|
||||
strBuff.append( this.getSessionInfo( (String)adapterGroupList[i] )).append("\n");
|
||||
}
|
||||
|
||||
return strBuff.toString();
|
||||
}
|
||||
|
||||
public String getSessionInfo( String adapterGroupName ) {
|
||||
StringBuffer strBuff = new StringBuffer();
|
||||
SessionChannel channel = this.getChannel( adapterGroupName );
|
||||
if ( channel == null ) {
|
||||
//strBuff.append("Session not found for ").append(adapterGroupName).append(" Adapter Group ");
|
||||
strBuff.append( CommonLib.getMessage("BWCEAIMSA007", new String[]{ adapterGroupName }) );
|
||||
return strBuff.toString();
|
||||
}
|
||||
|
||||
return strBuff.append(adapterGroupName).append("-").append( channel.toString() ).toString();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
sb.append("\n■ SessionManager : ");
|
||||
for(Iterator<String> iter = pool.keySet().iterator(); iter.hasNext();) {
|
||||
Object key = iter.next();
|
||||
sb.append("\n ▣ " + key + " : " + pool.get(key));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.config.RequestDescriptor;
|
||||
import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class SessionService extends Thread {
|
||||
|
||||
private String adapterGroupName;
|
||||
private boolean active;
|
||||
private boolean permanent;
|
||||
private Logger logger;
|
||||
private static Logger errLogger = SocketLogManager.getInstance().getErrLogger();
|
||||
private InboundControl control;
|
||||
|
||||
private int sendCount;
|
||||
private int recvCount;
|
||||
|
||||
public SessionService(String adapterGroupName, boolean permanent, int seq) {
|
||||
this.setName( adapterGroupName + "-SESSION-" + Integer.toString( seq ) );
|
||||
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
this.active = true;
|
||||
this.permanent = permanent;
|
||||
this.logger = SocketLogManager.getInstance().getLogger( adapterGroupName );
|
||||
this.sendCount = 0;
|
||||
this.recvCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the adapterGroupName.
|
||||
*/
|
||||
public String getAdapterGroupName() {
|
||||
return adapterGroupName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param adapterGroupName The adapterGroupName to set.
|
||||
*/
|
||||
public void setAdapterGroupName(String adapterGroupName) {
|
||||
this.adapterGroupName = adapterGroupName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the permanent.
|
||||
*/
|
||||
public boolean isPermanent() {
|
||||
return permanent;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param permanent The permanent to set.
|
||||
*/
|
||||
public void setPermanent(boolean permanent) {
|
||||
this.permanent = permanent;
|
||||
}
|
||||
|
||||
// private int getTraceLevel() {
|
||||
// return this.traceLevel;
|
||||
// }
|
||||
|
||||
// private boolean isSyncMode() {
|
||||
// return control.isSyncMode();
|
||||
// }
|
||||
|
||||
public void run() {
|
||||
SocketAdapterManager.getInstance().addSession( this );
|
||||
if(logger.isDebugEnabled())
|
||||
logger.debug( CommonLib.getMessage("BICEAIASI001", new String[]{ adapterGroupName, Thread.currentThread().getName() }));
|
||||
|
||||
while ( active ) {
|
||||
try {
|
||||
|
||||
onMessage();
|
||||
if ( control == null ) {
|
||||
continue;
|
||||
}
|
||||
doRequest();
|
||||
|
||||
} catch (Exception e) {
|
||||
if ( control != null ) {
|
||||
logger.error( CommonLib.getMessage("BECEAIASI005",
|
||||
new String[]{ e.getMessage(),CommonLib.getDumpMessage(control.getRequest()) } ), e );
|
||||
|
||||
if ( logger != errLogger ) {
|
||||
errLogger.error( CommonLib.getMessage("BECEAIASI005",
|
||||
new String[]{ e.getMessage(),CommonLib.getDumpMessage(control.getRequest()) } ), e );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SocketAdapterManager.getInstance().removeSession( this );
|
||||
|
||||
if(logger.isInfoEnabled())
|
||||
logger.info( CommonLib.getMessage("BICEAIASI005", new String[]{ adapterGroupName, Thread.currentThread().getName() }));
|
||||
interrupt();
|
||||
}
|
||||
|
||||
private synchronized void onMessage() {
|
||||
try {
|
||||
if ( this.control == null ) {
|
||||
this.wait( 1000 );
|
||||
}
|
||||
} catch ( InterruptedException ie ) {}
|
||||
}
|
||||
|
||||
public void wakeup() {
|
||||
try {
|
||||
this.control.wakeup();
|
||||
} catch( Throwable e ) {}
|
||||
|
||||
this.control = null;
|
||||
SessionManager.getInstance().addSession( this.adapterGroupName, this );
|
||||
}
|
||||
|
||||
public synchronized void notifyMessage() {
|
||||
//recvCount++;
|
||||
this.notify();
|
||||
}
|
||||
|
||||
private void doRequest() {
|
||||
this.recvCount++;
|
||||
logger.debug("[ELINK]################ <"+ Thread.currentThread().getName() +"> InboundControl 데이터: 길어서 print skip..."); //"+ new String(control.getRequest()));
|
||||
RequestDescriptor descriptor = new RequestDescriptor( control );
|
||||
//RequestDescriptorTest descriptor = new RequestDescriptorTest( control );
|
||||
descriptor.request();
|
||||
|
||||
wakeup();
|
||||
|
||||
this.sendCount++;
|
||||
|
||||
} // end of doRequest()
|
||||
|
||||
|
||||
public synchronized void shutdown() {
|
||||
active = false;
|
||||
|
||||
notifyAll();
|
||||
|
||||
interrupt();
|
||||
|
||||
}
|
||||
|
||||
public void setControl(InboundControl control) {
|
||||
this.control = control;
|
||||
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer strBuff = new StringBuffer();
|
||||
|
||||
strBuff.append( this.getName() ).append("[ RecvCount = ").append( recvCount )
|
||||
.append(" SendCount = ").append( sendCount ).append(" ]");
|
||||
|
||||
return strBuff.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class SocketLogManager {
|
||||
|
||||
private static SocketLogManager instance = new SocketLogManager();
|
||||
|
||||
//Singleton
|
||||
private SocketLogManager() {}
|
||||
public static SocketLogManager getInstance() { return instance; }
|
||||
|
||||
|
||||
public Logger getLogger( String adapterGroupName ) {
|
||||
Logger logger = (Logger) Logger.getLogger("FileLogger{"+ adapterGroupName + "}");
|
||||
|
||||
return logger;
|
||||
}
|
||||
|
||||
public Logger getErrLogger() {
|
||||
return (Logger) Logger.getLogger(Logger.LOGGER_ADAPTER_ERR);
|
||||
}
|
||||
|
||||
public Logger getLogger() {
|
||||
return (Logger) Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
import com.eactive.eai.adapter.socket.common.SocketAdapterException;
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.channels.SelectionKey;
|
||||
import java.nio.channels.Selector;
|
||||
import java.nio.channels.ServerSocketChannel;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.util.Iterator;
|
||||
import java.util.Vector;
|
||||
|
||||
import java.nio.channels.ClosedSelectorException;
|
||||
import java.util.HashMap;
|
||||
|
||||
|
||||
public class SocketServer extends Thread implements SocketService {
|
||||
|
||||
private ConfigurationContext context;
|
||||
private Vector<SocketService> threadPool;
|
||||
private boolean active;
|
||||
private Selector selector;
|
||||
private ServerSocketChannel serverSocketChannel;
|
||||
private ServerSocket serverSocket;
|
||||
private Logger logger;
|
||||
private HashMap<String, Integer> ipTable; // IP별 Connection 수 제한이 있는 경우 , KEY-RemoteIP, VALUE-Integer
|
||||
|
||||
//소켓 관련 프라퍼티 정보
|
||||
public static final String PROP_GROUP_SOCKET = "socket";
|
||||
public static final String PROP_BLOCK_IP_LIST = "block.ip.list"; //연결 거부 IP 리스트
|
||||
public static final String PROP_BLOCK_SLEEP = "sleep.time"; //close 하기 전에 대기 시간
|
||||
|
||||
public SocketServer(ConfigurationContext context) {
|
||||
String name = this.getName();
|
||||
this.setName( context.getAdapterName() + "-LISTENER" + name.substring( name.lastIndexOf("-")) );
|
||||
|
||||
this.context = context;
|
||||
active = true;
|
||||
threadPool = new Vector<SocketService>();
|
||||
logger = (Logger) SocketLogManager.getInstance().getLogger( this.context.getAdapterGroupName() );
|
||||
ipTable = new HashMap<String, Integer>();
|
||||
}
|
||||
|
||||
private int getTraceLevel() {
|
||||
return context.getTraceLevel();
|
||||
}
|
||||
|
||||
public void run() {
|
||||
// Server Socket을 기동하는 순간 Connection없음을 나타내도록 Adapter Status를 false로 변경한다.
|
||||
SocketAdapterManager.getInstance().changeAdapterStatus( this, false);
|
||||
try {
|
||||
openSelector();
|
||||
} catch(IOException e) {
|
||||
logger.error(CommonLib.getMessage("BECEAIMSA029", new String[] { context.getAdapterName(), context.getHostName() + ":" + context.getPortNumber(), e.getMessage() } ), e);
|
||||
active = false;
|
||||
SocketAdapterManager.getInstance().stop( context.getAdapterGroupName(), context.getAdapterName() );
|
||||
}
|
||||
|
||||
Iterator<SelectionKey> it;
|
||||
SocketChannel channel;
|
||||
SelectionKey key;
|
||||
while ( active ) {
|
||||
try {
|
||||
// select(miliseconds) : 대기시간
|
||||
int i = selector.select(2000L);
|
||||
if(i == 0) {
|
||||
if ( threadPool == null || threadPool.size() == 0 ) {
|
||||
SocketAdapterManager.getInstance().changeAdapterStatus( this, false );
|
||||
}
|
||||
continue;
|
||||
}
|
||||
} catch(IOException e) {
|
||||
active = false;
|
||||
shutdown();
|
||||
break;
|
||||
} catch( ClosedSelectorException e ) {
|
||||
} catch( Exception e ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( selector == null || !selector.isOpen() ) break;
|
||||
|
||||
it = selector.selectedKeys().iterator();
|
||||
|
||||
while( it.hasNext() ) {
|
||||
// 소켓 서버로 연결 요청이 있는 경우.
|
||||
try {
|
||||
key = it.next();
|
||||
it.remove();
|
||||
if ( !key.isValid() ) continue;
|
||||
ServerSocketChannel server = (ServerSocketChannel)key.channel();
|
||||
if ( !server.isOpen() ){
|
||||
continue;
|
||||
}
|
||||
|
||||
channel = server.accept();
|
||||
|
||||
if(channel == null) continue;
|
||||
|
||||
// L4에서 보내온 세션인 경우
|
||||
String remoteIp = channel.socket().getRemoteSocketAddress().toString().substring(1,channel.socket().getRemoteSocketAddress().toString().indexOf(":") );
|
||||
String blockIpList = PropManager.getInstance().getProperty(PROP_GROUP_SOCKET, PROP_BLOCK_IP_LIST);
|
||||
|
||||
if (( blockIpList != null) && ( blockIpList.indexOf(remoteIp) > -1 ) ) {
|
||||
|
||||
try {
|
||||
long delayTime = 1000;
|
||||
try {
|
||||
delayTime = Long.parseLong(PropManager.getInstance().getProperty(PROP_GROUP_SOCKET, PROP_BLOCK_SLEEP));
|
||||
} catch (Exception e) {}
|
||||
if ( delayTime > 0 )
|
||||
Thread.sleep(delayTime);
|
||||
channel.socket().close();
|
||||
channel.close();
|
||||
} catch(IOException ie) {}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( context.getMaxConnection() > 0 && context.getMaxConnection() <= threadPool.size() ) {
|
||||
try {
|
||||
for ( int inx = 0; inx < threadPool.size(); inx++){
|
||||
SocketService oldService = threadPool.get(inx);
|
||||
if ( oldService.isActive()){
|
||||
logger.warn( CommonLib.getMessage("BECEAIMSA022", new String[]{ context.getAdapterName(), Integer.toString( context.getMaxConnection() ),this.getSocketInfo( oldService.getCurrentSocket() ) } ) );
|
||||
oldService.shutdown();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error( e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
// Client Socket별 (REMOTE IP) Connection 수 제한 있는 경우
|
||||
if ( context.getConnLimitPerIp() > 0 ) {
|
||||
String ip = channel.socket().getInetAddress().getHostAddress();
|
||||
Integer connCount = ipTable.get( ip );
|
||||
if ( connCount == null ) {
|
||||
ipTable.put( ip, new Integer( 1 ) );
|
||||
} else if ( connCount.intValue() < context.getConnLimitPerIp() ) {
|
||||
int newCount = connCount.intValue() + 1;
|
||||
ipTable.put( ip, new Integer( newCount ));
|
||||
} else {
|
||||
logger.error( CommonLib.getMessage("BECEAIMSA023", new String[]{ context.getAdapterName(), Integer.toString( context.getConnLimitPerIp() ),this.getSocketInfo( channel ) } ) );
|
||||
try {
|
||||
channel.socket().close();
|
||||
channel.close();
|
||||
} catch(IOException ie) {}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
logger.info( CommonLib.getMessage("BICEAIMSA033", new String[]{ context.getAdapterName(), this.getSocketInfo( channel ) } ) );
|
||||
}
|
||||
|
||||
if ( this.context.isSocketReuse() ) {
|
||||
channel.socket().setSoLinger(true, 100);
|
||||
}
|
||||
|
||||
// 신규 Connection Process 쓰레드를 생성 후 수행시킨다...
|
||||
if ( isForInbound() && context.getSocketType().equals( ConfigurationContext.SERVER_SOCKET ) ) {
|
||||
InboundServer aProcess = new InboundServer(context, channel, this);
|
||||
logger.debug("# INBOUND SOCKETSERVER CREATED.[" + this.getName() + "]");
|
||||
//
|
||||
threadPool.addElement( aProcess );
|
||||
aProcess.start();
|
||||
logger.debug("# INBOUND SOCKETSERVER STARTED.[" + this.getName() + "]");
|
||||
synchronized ( threadPool ) {
|
||||
if ( threadPool.size() == 1 ) {
|
||||
SocketAdapterManager.getInstance().changeAdapterStatus( this, true );
|
||||
}
|
||||
}
|
||||
} else if ( isForOutbound() ) {
|
||||
// OutboundServer aProcess = new OutboundServer(context, channel, this);
|
||||
// logger.debug("# OUTBOUND SOCKETSERVER CREATED.[" + this.getName() + "]");
|
||||
// if ( !OutboundChannelManager.getInstance().hasChannel( context.getAdapterGroupName() )) {
|
||||
// OutboundChannel connection = new OutboundChannel(context.getSessionTimeout()*1000);
|
||||
// OutboundChannelManager.getInstance().addConnectionGroup( context.getAdapterGroupName(), connection );
|
||||
// }
|
||||
// threadPool.addElement( aProcess );
|
||||
// aProcess.start();
|
||||
// logger.debug("# OUTBOUND SOCKETSERVER STARTED.[" + this.getName() + "]");
|
||||
// synchronized ( threadPool ) {
|
||||
// if ( threadPool.size() == 1 ) {
|
||||
// SocketAdapterManager.getInstance().changeAdapterStatus( this, true );
|
||||
// }
|
||||
// }
|
||||
} else if ( isForIobound() ) {
|
||||
IOboundServer aProcess = new IOboundServer(context, channel, this);
|
||||
logger.debug("# IOBOUND SOCKETSERVER CREATED.[" + this.getName() + "]");
|
||||
if ( !OutboundChannelManager.getInstance().hasChannel( context.getAdapterGroupName() )) {
|
||||
OutboundChannel connection = new OutboundChannel(context.getSessionTimeout()*1000);
|
||||
OutboundChannelManager.getInstance().addConnectionGroup( context.getAdapterGroupName(), connection );
|
||||
}
|
||||
threadPool.addElement( aProcess );
|
||||
aProcess.start();
|
||||
logger.debug("# IOBOUND SOCKETSERVER STARTED.[" + this.getName() + "]");
|
||||
synchronized ( threadPool ) {
|
||||
if ( threadPool.size() == 1 ) {
|
||||
SocketAdapterManager.getInstance().changeAdapterStatus( this, true );
|
||||
}
|
||||
}
|
||||
// } else {
|
||||
// AdminServer aProcess = new AdminServer(context, channel, this);
|
||||
// logger.debug("# ADMIN SOCKETSERVER CREATED.[" + this.getName() + "]");
|
||||
// threadPool.addElement( aProcess );
|
||||
// aProcess.start();
|
||||
// logger.debug("# ADMIN SOCKETSERVER STARTED.[" + this.getName() + "]");
|
||||
// synchronized ( threadPool ) {
|
||||
// if ( threadPool.size() == 1 ) {
|
||||
// SocketAdapterManager.getInstance().changeAdapterStatus( this, true );
|
||||
// }
|
||||
// }
|
||||
}
|
||||
// Process 쓰레드 Started
|
||||
} catch(Exception e) {
|
||||
logger.error(CommonLib.getMessage("BECEAIMSA030", new String[] { context.getAdapterName(), e.getMessage() } ), e);
|
||||
logger.error( e.getMessage(), e);
|
||||
}
|
||||
} // End of While - it.hasNext
|
||||
} // End of While - active
|
||||
|
||||
try {
|
||||
closeSelector();
|
||||
} catch( Throwable e ) {}
|
||||
|
||||
interrupt();
|
||||
} // end of startup ...
|
||||
|
||||
public String getRemoteIPAddress() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Socket getCurrentSocket() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean idle(long timeout) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean connect() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
}
|
||||
|
||||
|
||||
public int getCurrentState() {
|
||||
return CommonLib.PROCESSING_PROTOCOL;
|
||||
}
|
||||
|
||||
public boolean isConnected() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void checkActivity() {
|
||||
}
|
||||
|
||||
public synchronized void shutdown() {
|
||||
|
||||
active = false;
|
||||
if ( threadPool != null ) {
|
||||
for ( int i=0; i < threadPool.size(); i++ ) {
|
||||
try {
|
||||
SocketService service = (SocketService)threadPool.get(i);
|
||||
|
||||
if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
try {
|
||||
logger.info( CommonLib.getMessage("BICEAIMSA031", new String[]{ context.getAdapterName(), this.getSocketInfo( service.getCurrentSocket() )} ) );
|
||||
} catch( Exception e ) {}
|
||||
}
|
||||
service.shutdown();
|
||||
} catch( Throwable e ) {logger.error( e.getMessage(), e);}
|
||||
}
|
||||
}
|
||||
|
||||
threadPool = null;
|
||||
try {
|
||||
closeSelector();
|
||||
} catch (Throwable t) {logger.error( t.getMessage(), t);}
|
||||
|
||||
try {
|
||||
serverSocket.close();
|
||||
} catch (Throwable t) {logger.error( t.getMessage(), t);}
|
||||
|
||||
SocketAdapterManager.getInstance().changeAdapterStatus( this, false );
|
||||
//*interrupt();
|
||||
}
|
||||
/**
|
||||
* @return Returns the context.
|
||||
*/
|
||||
public ConfigurationContext getContext() {
|
||||
return context;
|
||||
}
|
||||
/**
|
||||
* @return Returns the active.
|
||||
*/
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public void notifyMessage() {
|
||||
}
|
||||
|
||||
public void setControl(Object control) {
|
||||
}
|
||||
|
||||
public void setLastActivity() {
|
||||
}
|
||||
|
||||
private String getSocketInfo(SocketChannel channel) {
|
||||
StringBuffer connInfo = new StringBuffer();
|
||||
|
||||
connInfo.append("Local Address=");
|
||||
connInfo.append( channel.socket().getLocalAddress().getHostAddress()).append(":").append(channel.socket().getLocalPort()).append(", ");
|
||||
connInfo.append("Remote Address=");
|
||||
connInfo.append( channel.socket().getInetAddress().getHostAddress()).append(":").append(channel.socket().getPort());
|
||||
|
||||
return connInfo.toString();
|
||||
}
|
||||
|
||||
private String getSocketInfo(Socket socket) {
|
||||
StringBuffer connInfo = new StringBuffer();
|
||||
|
||||
if ( socket != null ) {
|
||||
connInfo.append("Local Address=");
|
||||
connInfo.append( socket.getLocalAddress().getHostAddress()).append(":").append(socket.getLocalPort()).append(", ");
|
||||
connInfo.append("Remote Address=");
|
||||
connInfo.append( socket.getInetAddress().getHostAddress()).append(":").append(socket.getPort());
|
||||
}else {
|
||||
connInfo.append("SOCKET IS NULL");
|
||||
}
|
||||
|
||||
return connInfo.toString();
|
||||
}
|
||||
|
||||
private boolean isForInbound() {
|
||||
return ( this.context.getBoundUsage().equals( ConfigurationContext.INBOUND_SOCKET ));
|
||||
}
|
||||
|
||||
private boolean isForIobound() {
|
||||
return ( this.context.getBoundUsage().equals( ConfigurationContext.IOBOUND_SOCKET ));
|
||||
}
|
||||
|
||||
private boolean isForOutbound() {
|
||||
return ( this.context.getBoundUsage().equals( ConfigurationContext.OUTBOUND_SOCKET ));
|
||||
}
|
||||
|
||||
public synchronized void quiesceShutdown(SocketService service) {
|
||||
if ( threadPool == null ) return;
|
||||
|
||||
for ( int i=0; i < threadPool.size(); i++) {
|
||||
SocketService aService = (SocketService) threadPool.elementAt( i );
|
||||
if ( service != aService ) continue;
|
||||
//service.shutdown();
|
||||
if ( context.getConnLimitPerIp() > 0 ) {
|
||||
String ip = service.getRemoteIPAddress();
|
||||
if ( ip != null ) {
|
||||
Integer connCount = (Integer)ipTable.get( ip );
|
||||
if ( connCount != null ) {
|
||||
int newCount = connCount.intValue() - 1;
|
||||
if ( newCount < 0 ) newCount = 0;
|
||||
|
||||
ipTable.put( ip, new Integer( newCount ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
threadPool.remove(i);
|
||||
break;
|
||||
}
|
||||
// Adapter status 변경
|
||||
if ( threadPool == null || threadPool.size() == 0 ) {
|
||||
SocketAdapterManager.getInstance().changeAdapterStatus( this, false );
|
||||
}
|
||||
}
|
||||
|
||||
private void openSelector() throws IOException {
|
||||
|
||||
serverSocketChannel = ServerSocketChannel.open();
|
||||
serverSocket = serverSocketChannel.socket();
|
||||
selector = Selector.open();
|
||||
|
||||
if( context.getHostName() == null || context.getHostName().equals("*") || context.getHostName().equals("") || context.getHostName().equals("localhost")
|
||||
|| context.getHostName().equals("0.0.0.0") || context.getHostName().equals("127.0.0.1") ) {
|
||||
serverSocket.bind(new InetSocketAddress(context.getPortNumber()), 1024);
|
||||
if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
logger.info( CommonLib.getMessage("BICEAIMSA032", new String[]{ context.getAdapterName(), context.getHostName(), Integer.toString(context.getPortNumber()) }) );
|
||||
}
|
||||
} else {
|
||||
serverSocket.bind(new InetSocketAddress(context.getHostName(), context.getPortNumber()), 1024);
|
||||
if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
logger.info( CommonLib.getMessage("BICEAIMSA032", new String[]{ context.getAdapterName(), context.getHostName(), Integer.toString(context.getPortNumber()) }) );
|
||||
}
|
||||
}
|
||||
|
||||
serverSocketChannel.configureBlocking(false);
|
||||
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
|
||||
|
||||
synchronized ( threadPool ) {
|
||||
if ( threadPool.size() == 0 ) {
|
||||
SocketAdapterManager.getInstance().changeAdapterStatus( this, false );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void closeSelector() throws IOException {
|
||||
|
||||
if(selector != null) {
|
||||
for(Iterator<SelectionKey> iterator = selector.keys().iterator(); iterator.hasNext();)
|
||||
try {
|
||||
SelectionKey selectionkey = iterator.next();
|
||||
ServerSocketChannel serversocketchannel = (ServerSocketChannel)selectionkey.channel();
|
||||
selectionkey.cancel();
|
||||
serversocketchannel.socket().close();
|
||||
serversocketchannel.close();
|
||||
iterator.remove();
|
||||
}catch(UnsupportedOperationException e) {
|
||||
// Do nothing!!!
|
||||
}catch(IOException e) {
|
||||
logger.error( e.getMessage(), e);
|
||||
}catch(Exception e) {
|
||||
logger.error( e.getMessage(), e);
|
||||
}
|
||||
selector.close();
|
||||
}
|
||||
} // end of closeSelector...
|
||||
|
||||
public void disconnect(String localHostname, int localPortNumber)
|
||||
throws SocketAdapterException {
|
||||
}
|
||||
|
||||
public void setContext(ConfigurationContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public long getFirstActivity() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public long getLastActivity() {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.eactive.eai.adapter.socket.service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
|
||||
import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
|
||||
public interface SocketService {
|
||||
|
||||
/**
|
||||
* Stop the service
|
||||
*/
|
||||
public void shutdown();
|
||||
|
||||
public Socket getCurrentSocket();
|
||||
|
||||
public boolean connect();
|
||||
|
||||
public void disconnect();
|
||||
|
||||
public ConfigurationContext getContext();
|
||||
|
||||
public void setControl(Object control);
|
||||
|
||||
public void notifyMessage();
|
||||
|
||||
public boolean idle(long timeout);
|
||||
|
||||
public int getCurrentState();
|
||||
|
||||
public boolean isConnected() throws IOException;
|
||||
|
||||
public boolean isActive();
|
||||
|
||||
public void checkActivity();
|
||||
|
||||
public String getRemoteIPAddress();
|
||||
|
||||
public void setLastActivity();
|
||||
|
||||
public long getFirstActivity();
|
||||
|
||||
public long getLastActivity();
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
//package com.eactive.eai.adapter.socket.service;
|
||||
//
|
||||
//import java.io.IOException;
|
||||
//import java.net.Socket;
|
||||
//import java.nio.ByteBuffer;
|
||||
//
|
||||
//import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
//import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
//import com.eactive.eai.adapter.socket.common.SocketAdapterException;
|
||||
//import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//
|
||||
//public class WriterClient extends Thread implements SocketService {
|
||||
//
|
||||
// private ConfigurationContext context;
|
||||
// private boolean active;
|
||||
// private NBChannel channel;
|
||||
//
|
||||
// private Exception lastError;
|
||||
//
|
||||
// private ByteBuffer outgoingMessage;
|
||||
// private ByteBuffer lenBuffer;
|
||||
//
|
||||
// private Logger logger;
|
||||
// private static Logger errLogger = SocketLogManager.getInstance().getErrLogger();
|
||||
//
|
||||
// private OutboundControl control;
|
||||
// private ReaderClient proxy;
|
||||
// private boolean shutdownFlag;
|
||||
//
|
||||
// public WriterClient(ConfigurationContext context, NBChannel channel, ReaderClient proxy ) {
|
||||
// String name = this.getName();
|
||||
// this.setName( context.getAdapterName() + "-CONNECTION-WRITER" + name.substring( name.lastIndexOf("-")) );
|
||||
//
|
||||
// this.context = context;
|
||||
// active = true;
|
||||
//
|
||||
// outgoingMessage = null;
|
||||
// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() );
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// this.control = null;
|
||||
// this.proxy = proxy;
|
||||
// this.channel = channel;
|
||||
// this.shutdownFlag = false;
|
||||
//
|
||||
// logger = SocketLogManager.getInstance().getLogger( this.context.getAdapterGroupName());
|
||||
// }
|
||||
//
|
||||
// public boolean isActive() {
|
||||
// return active;
|
||||
// }
|
||||
//
|
||||
// private int getTraceLevel() {
|
||||
// return context.getTraceLevel();
|
||||
// }
|
||||
// /**
|
||||
// * @return Returns the context.
|
||||
// */
|
||||
// public ConfigurationContext getContext() {
|
||||
// return context;
|
||||
// }
|
||||
//
|
||||
//// private boolean isSyncMode() {
|
||||
//// return context.isSyncMode();
|
||||
//// }
|
||||
//
|
||||
// private long getTimeout() {
|
||||
// return ( this.context.getTimeout() * 1000L );
|
||||
// }
|
||||
//
|
||||
// private boolean isSocketReuse() {
|
||||
// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG );
|
||||
// }
|
||||
//
|
||||
// public void run() {
|
||||
//
|
||||
// OutboundChannelManager.getInstance().addConnection(context.getAdapterGroupName(), this);
|
||||
// String socketInfo = "";
|
||||
//
|
||||
// while ( active ) {
|
||||
// try {
|
||||
// openChannel();
|
||||
// if ( !socketInfo.equals( getSocketInfo(this.getCurrentSocket()) ) ) {
|
||||
// socketInfo = getSocketInfo( this.getCurrentSocket() );
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIASO001", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) );
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// onMessage();
|
||||
//
|
||||
// if ( control == null ) continue;
|
||||
//
|
||||
// doRequest();
|
||||
// if ( !isSocketReuse() ) {
|
||||
// active = false;
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "openChannel", e.getMessage(), "", "" } );
|
||||
// logger.error( errMsg, e );
|
||||
// active = false;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// OutboundChannelManager.getInstance().removeConnection(context.getAdapterGroupName(), this);
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIASO002", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) );
|
||||
// }
|
||||
//
|
||||
// if ( !shutdownFlag ) {
|
||||
// proxy.shutdownWriter();
|
||||
// }
|
||||
//
|
||||
// interrupt();
|
||||
// }
|
||||
//
|
||||
//// private String getWritingMessage() {
|
||||
//// String rMsg = "";
|
||||
//// if ( outgoingMessage != null ) {
|
||||
//// byte[] debugMsg = new byte[ outgoingMessage.capacity() - lenBuffer.capacity() ];
|
||||
//// System.arraycopy( outgoingMessage.array(), lenBuffer.capacity(), debugMsg, 0, debugMsg.length );
|
||||
//// rMsg = CommonLib.getDumpMessage( debugMsg );
|
||||
//// }
|
||||
//// return rMsg;
|
||||
//// }
|
||||
//
|
||||
// private String getSocketInfo(Socket socket) {
|
||||
// StringBuffer connInfo = new StringBuffer();
|
||||
//
|
||||
// connInfo.append("Local Address=");
|
||||
// connInfo.append( socket.getLocalAddress().getHostAddress()).append(":").append(socket.getLocalPort()).append(", ");
|
||||
// connInfo.append("Remote Address=");
|
||||
// connInfo.append( socket.getInetAddress().getHostAddress()).append(":").append(socket.getPort());
|
||||
//
|
||||
// return connInfo.toString();
|
||||
// }
|
||||
//
|
||||
// private synchronized void onMessage() {
|
||||
// try {
|
||||
// this.wait( );
|
||||
// this.lastError = null;
|
||||
// } catch ( InterruptedException ie ) {}
|
||||
// }
|
||||
//
|
||||
// public void wakeup() {
|
||||
// this.control.setLastError( this.lastError );
|
||||
// this.control.wakeup();
|
||||
// this.control = null;
|
||||
// // 사용한 Connection 반납한다.
|
||||
// if ( active ) {
|
||||
// OutboundChannelManager.getInstance().addConnection(context.getAdapterGroupName(), this );
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public synchronized void notifyMessage() {
|
||||
// this.notify();
|
||||
// }
|
||||
//
|
||||
// public synchronized void setControl(Object control) {
|
||||
// this.control = (OutboundControl) control;
|
||||
// }
|
||||
//
|
||||
// // RESPONSE MODE의 경우
|
||||
// private void doRequest() {
|
||||
//
|
||||
// this.checkActivity();
|
||||
// proxy.setLastActivity( System.currentTimeMillis() );
|
||||
//
|
||||
// try {
|
||||
//
|
||||
// processWriteMessage( this.control.getRequest() );
|
||||
//
|
||||
// proxy.addSendCount();
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), this.getSocketInfo( getCurrentSocket() ), CommonLib.getDumpMessage(this.control.getRequest())}));
|
||||
// }
|
||||
//
|
||||
// wakeup();
|
||||
//
|
||||
// } catch( Exception e) {
|
||||
// String errMsg = "";
|
||||
// errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processWriteMessage", e.getMessage(), "송신메시지", CommonLib.getDumpMessage( this.control.getRequest() ) } );
|
||||
// logger.error( errMsg , e);
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg, e );
|
||||
// }
|
||||
//
|
||||
// lastError = new SocketAdapterException( errMsg );
|
||||
// active = false;
|
||||
// wakeup();
|
||||
// }
|
||||
// } // end of doRequest()
|
||||
//
|
||||
// /**
|
||||
// * Socket Recovery Manager에 의해 Connection Recovery가 되도록 기다린다.
|
||||
// */
|
||||
// public boolean idle(long timeout) {
|
||||
// return false;
|
||||
// }
|
||||
//
|
||||
// public int getCurrentState() {
|
||||
// return proxy.getCurrentState();
|
||||
// }
|
||||
//
|
||||
//// private void resetCount() {
|
||||
//// }
|
||||
//
|
||||
// public boolean isConnected() {
|
||||
// return proxy.isConnected();
|
||||
// }
|
||||
//
|
||||
// public void checkActivity() {
|
||||
// proxy.checkActivity();
|
||||
// }
|
||||
//
|
||||
// private void processWriteMessage( byte[] data ) throws IOException {
|
||||
//
|
||||
// outgoingMessage = ByteBuffer.allocate( data.length + lenBuffer.capacity() );
|
||||
// outgoingMessage.clear();
|
||||
// outgoingMessage.put( makeLengthField( data.length ) );
|
||||
// outgoingMessage.put( data );
|
||||
// outgoingMessage.flip();
|
||||
//
|
||||
// long writeStart = System.currentTimeMillis();
|
||||
//
|
||||
// int expectedWrite = outgoingMessage.capacity();
|
||||
// int writtenByte = channel.write( outgoingMessage );
|
||||
//
|
||||
// if ( expectedWrite != writtenByte ) {
|
||||
// ByteBuffer buf = null;
|
||||
// while ( writtenByte < expectedWrite ) {
|
||||
// buf = ByteBuffer.allocate( expectedWrite - writtenByte );
|
||||
// buf.clear();
|
||||
// buf.put( outgoingMessage.array(), writtenByte, buf.capacity() );
|
||||
// writtenByte += channel.write( buf );
|
||||
// if ( expectedWrite == writtenByte ) return;
|
||||
// long waitTime = System.currentTimeMillis() - writeStart;
|
||||
// if ( waitTime >= getTimeout() ) {
|
||||
// throw new IOException("메시지 송신 타임아웃");
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// private byte[] makeLengthField(int length) {
|
||||
// byte[] lenField = new byte[ lenBuffer.capacity() ];
|
||||
//
|
||||
// if ( lenField.length == 2 ) {
|
||||
// lenBuffer.clear();
|
||||
// lenBuffer.putShort( (short) (length & 0xFFFF) );
|
||||
// lenField = lenBuffer.array();
|
||||
// } else if ( lenField.length == 4 ) {
|
||||
// lenBuffer.clear();
|
||||
// lenBuffer.putInt( length );
|
||||
// lenField = lenBuffer.array();
|
||||
// } else {
|
||||
// String lenStr = CommonLib.getFormatString( length, lenField.length );
|
||||
// lenField = lenStr.getBytes();
|
||||
// }
|
||||
//
|
||||
// return lenField;
|
||||
// }
|
||||
//
|
||||
// public synchronized void shutdown() {
|
||||
//
|
||||
// active = false;
|
||||
// // 2005.10.17
|
||||
// shutdownFlag = true;
|
||||
//
|
||||
// try {
|
||||
// notify();
|
||||
// } catch( Exception e ) {}
|
||||
//
|
||||
// //* 2005.10.17
|
||||
// try {
|
||||
// this.channel.wakeup();
|
||||
// } catch( Throwable e ) {}
|
||||
// // interrupt();
|
||||
// }
|
||||
//
|
||||
// public Socket getCurrentSocket() {
|
||||
// return channel.getSocket();
|
||||
// }
|
||||
//
|
||||
// public boolean connect() {
|
||||
// return false;
|
||||
// }
|
||||
//
|
||||
// public void disconnect() {
|
||||
// }
|
||||
//
|
||||
// private synchronized void openChannel() throws IOException {
|
||||
//
|
||||
// try {
|
||||
// if ( channel !=null && !channel.isConnected() ) {
|
||||
// throw new Exception("");
|
||||
// }
|
||||
// } catch(Exception e) {
|
||||
// throw new IOException("Connection Closed in openChannel");
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public String getRemoteIPAddress() {
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
//// private synchronized void closeChannel() throws IOException {
|
||||
//// } // end of closeChannel...
|
||||
//
|
||||
// public void setLastActivity() {
|
||||
// }
|
||||
//
|
||||
// public long getFirstActivity() {
|
||||
// return 0;
|
||||
// }
|
||||
//
|
||||
// public long getLastActivity() {
|
||||
// return 0;
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,403 @@
|
||||
//package com.eactive.eai.adapter.socket.service;
|
||||
//
|
||||
//import java.io.IOException;
|
||||
//import java.net.Socket;
|
||||
//import java.nio.ByteBuffer;
|
||||
//import java.nio.channels.SelectionKey;
|
||||
//import java.nio.channels.Selector;
|
||||
//import java.nio.channels.SocketChannel;
|
||||
//import java.util.Iterator;
|
||||
//
|
||||
//import com.eactive.eai.adapter.socket.common.CommonLib;
|
||||
//import com.eactive.eai.adapter.socket.common.DiagLogger;
|
||||
//import com.eactive.eai.adapter.socket.common.SocketAdapterException;
|
||||
//import com.eactive.eai.adapter.socket.config.ConfigurationContext;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//
|
||||
//public class WriterServer extends Thread implements SocketService {
|
||||
//
|
||||
// private ConfigurationContext context;
|
||||
// private SocketChannel socketChannel;
|
||||
// private ReaderServer proxy;
|
||||
//
|
||||
// private boolean active;
|
||||
//
|
||||
// private ByteBuffer outgoingMessage;
|
||||
//
|
||||
// private ByteBuffer lenBuffer;
|
||||
//
|
||||
// private Exception lastError;
|
||||
// private Logger logger;
|
||||
// private Selector selector;
|
||||
// private static Logger errLogger = SocketLogManager.getInstance().getErrLogger();
|
||||
//
|
||||
// private OutboundControl control;
|
||||
// private boolean shutdownFlag;
|
||||
//
|
||||
// public WriterServer(ConfigurationContext context, SocketChannel socketChannel, ReaderServer proxy, Selector selector ) throws IOException {
|
||||
// String name = this.getName();
|
||||
// this.setName( context.getAdapterName() + "-CONNECTION-WRITER" + name.substring( name.lastIndexOf("-")) );
|
||||
//
|
||||
// this.context = context;
|
||||
// this.socketChannel = socketChannel;
|
||||
// this.proxy = proxy;
|
||||
//
|
||||
// this.selector = selector;
|
||||
// socketChannel.register( this.selector, SelectionKey.OP_WRITE | SelectionKey.OP_WRITE );
|
||||
//
|
||||
// outgoingMessage = null;
|
||||
// lenBuffer = ByteBuffer.allocate( this.context.getLlFieldLength() );
|
||||
// lenBuffer.clear();
|
||||
//
|
||||
// this.control = null;
|
||||
//
|
||||
// active = true;
|
||||
// shutdownFlag = false;
|
||||
// logger = SocketLogManager.getInstance().getLogger( this.context.getAdapterGroupName());
|
||||
// }
|
||||
//
|
||||
//// private boolean isSyncMode() {
|
||||
//// return this.context.isSyncMode();
|
||||
//// }
|
||||
//
|
||||
// private int getTraceLevel() {
|
||||
// return context.getTraceLevel();
|
||||
// }
|
||||
//
|
||||
// private long getTimeout() {
|
||||
// return ( this.context.getTimeout() * 1000L );
|
||||
// }
|
||||
//
|
||||
// private boolean isSocketReuse() {
|
||||
// return this.context.getSocketReuse().equals( ConfigurationContext.TRUE_FLAG );
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * @return Returns the context.
|
||||
// */
|
||||
// public ConfigurationContext getContext() {
|
||||
// return context;
|
||||
// }
|
||||
//
|
||||
// public void run() {
|
||||
//
|
||||
// OutboundChannelManager.getInstance().addConnection(context.getAdapterGroupName(), this);
|
||||
// String socketInfo = this.getSocketInfo(this.socketChannel);
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIASO001", new String[]{ context.getAdapterName(), socketInfo , Thread.currentThread().getName() }) );
|
||||
// }
|
||||
//
|
||||
// while ( active ) {
|
||||
// try {
|
||||
//
|
||||
// openSelector();
|
||||
//
|
||||
// onMessage();
|
||||
//
|
||||
// if ( control == null ) continue;
|
||||
//
|
||||
// doRequest();
|
||||
//
|
||||
// if ( shutdownFlag ) active = false;
|
||||
//
|
||||
// if ( !isSocketReuse() ) {
|
||||
// active = false;
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "openSelector", e.getMessage(), "", "" } );
|
||||
// logger.error( errMsg, e );
|
||||
// active = false;
|
||||
// continue;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// closeSelector();
|
||||
// } catch(IOException e) { }
|
||||
//
|
||||
// OutboundChannelManager.getInstance().removeConnection( context.getAdapterGroupName(), this);
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.INFO ) {
|
||||
// logger.info( CommonLib.getMessage("BICEAIASO002", new String[]{ context.getAdapterName(), socketInfo, Thread.currentThread().getName() }) );
|
||||
// }
|
||||
//
|
||||
// if ( !shutdownFlag ) {
|
||||
// proxy.shutdownWriter();
|
||||
// }
|
||||
// interrupt();
|
||||
// }
|
||||
//
|
||||
// private String getWritingMessage() {
|
||||
// String rMsg = "";
|
||||
// if ( outgoingMessage != null ) {
|
||||
// byte[] debugMsg = new byte[ outgoingMessage.capacity() - lenBuffer.capacity() ];
|
||||
// System.arraycopy( outgoingMessage.array(), lenBuffer.capacity(), debugMsg, 0, debugMsg.length );
|
||||
// rMsg = CommonLib.getDumpMessage( debugMsg );
|
||||
// }
|
||||
// return rMsg;
|
||||
// }
|
||||
//
|
||||
// private String getSocketInfo(SocketChannel channel) {
|
||||
// StringBuffer connInfo = new StringBuffer();
|
||||
//
|
||||
// connInfo.append("Local Address=");
|
||||
// connInfo.append( channel.socket().getLocalAddress().getHostAddress()).append(":").append(channel.socket().getLocalPort()).append(", ");
|
||||
// connInfo.append("Remote Address=");
|
||||
// connInfo.append( channel.socket().getInetAddress().getHostAddress()).append(":").append(channel.socket().getPort());
|
||||
//
|
||||
// return connInfo.toString();
|
||||
// }
|
||||
//
|
||||
//
|
||||
// private synchronized void onMessage() {
|
||||
// try {
|
||||
// this.wait( );
|
||||
// this.lastError = null;
|
||||
// } catch ( InterruptedException ie ) {
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public void wakeup() {
|
||||
// this.control.setLastError( this.lastError );
|
||||
// this.control.wakeup();
|
||||
// this.control = null;
|
||||
// if ( active ) {
|
||||
// OutboundChannelManager.getInstance().addConnection(context.getAdapterGroupName(), this );
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public synchronized void notifyMessage() {
|
||||
// this.notify();
|
||||
// }
|
||||
//
|
||||
// public synchronized void setControl(Object control) {
|
||||
// this.control = (OutboundControl) control;
|
||||
// }
|
||||
//
|
||||
// public void doRequest() {
|
||||
//
|
||||
//// Iterator iterator;
|
||||
//
|
||||
// makeFormat( this.control.getRequest() );
|
||||
//
|
||||
// boolean isDone = false;
|
||||
//
|
||||
// this.checkActivity();
|
||||
// proxy.setLastActivity( System.currentTimeMillis() );
|
||||
//// long start = System.currentTimeMillis();
|
||||
//
|
||||
// while( !isDone ) {
|
||||
// /**
|
||||
// * Write the message to the target
|
||||
// */
|
||||
// try {
|
||||
// if( processWriteMessage() ) {
|
||||
//
|
||||
// proxy.addSendCount();
|
||||
//
|
||||
// if ( getTraceLevel() >= DiagLogger.DEBUG) {
|
||||
// logger.debug( CommonLib.getMessage("BDCEAIASO001", new String[]{context.getAdapterName(), "SEND", CommonLib.getTimestamp(), getSocketInfo(this.socketChannel), getWritingMessage()}));
|
||||
// }
|
||||
// wakeup();
|
||||
// return;
|
||||
// }
|
||||
// } catch(Exception e) {
|
||||
// String errMsg = CommonLib.getMessage("BECEAIASO001", new String[]{context.getAdapterName(), "processWriteMessage", e.getMessage(), "송신메시지", getWritingMessage() } );
|
||||
// logger.error( errMsg , e);
|
||||
// if ( logger != errLogger ) {
|
||||
// errLogger.error( errMsg, e );
|
||||
// }
|
||||
// lastError = new SocketAdapterException( errMsg );
|
||||
//
|
||||
// active = false;
|
||||
// wakeup();
|
||||
// return;
|
||||
// }
|
||||
// } // enf of while - isDone
|
||||
// }
|
||||
//
|
||||
// public int getCurrentState() {
|
||||
// return proxy.getCurrentState();
|
||||
// }
|
||||
//
|
||||
//// private void resetCount() {
|
||||
//// }
|
||||
//
|
||||
// public boolean isConnected() throws IOException {
|
||||
// return proxy.isConnected();
|
||||
// }
|
||||
//
|
||||
// public void checkActivity() {
|
||||
// proxy.checkActivity();
|
||||
// }
|
||||
//
|
||||
// public boolean isActive() {
|
||||
// return active;
|
||||
// }
|
||||
//
|
||||
// public String getRemoteIPAddress() {
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// public synchronized void shutdown() {
|
||||
// // 2005.10.17
|
||||
// active = false;
|
||||
// shutdownFlag = true;
|
||||
//
|
||||
// try {
|
||||
// notify();
|
||||
// } catch( Exception e ) {}
|
||||
//
|
||||
// try {
|
||||
// if ( selector != null && selector.isOpen() ) {
|
||||
// selector.wakeup();
|
||||
// }
|
||||
// } catch( Throwable e ) {}
|
||||
//
|
||||
// }
|
||||
//
|
||||
// public Socket getCurrentSocket() {
|
||||
// return socketChannel.socket();
|
||||
// }
|
||||
//
|
||||
// public boolean connect() {
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// public void disconnect() {
|
||||
// shutdown();
|
||||
// }
|
||||
//
|
||||
// public boolean idle(long timeout) {
|
||||
// return false;
|
||||
// }
|
||||
//
|
||||
// private void openSelector() throws IOException {
|
||||
// if ( socketChannel.socket().isConnected() && socketChannel.socket().isBound() ) {
|
||||
// return;
|
||||
// } else {
|
||||
// throw new IOException("Connection Closed in openSelector");
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private void closeSelector() throws IOException {
|
||||
// // nothing...
|
||||
// }
|
||||
//
|
||||
//
|
||||
// private boolean processWriteMessage() throws IOException {
|
||||
//
|
||||
// outgoingMessage.flip();
|
||||
// long writeStart = System.currentTimeMillis();
|
||||
// int expectedWrite = outgoingMessage.capacity();
|
||||
// int writtenByte = socketChannel.write( outgoingMessage );
|
||||
//
|
||||
// if ( expectedWrite != writtenByte ) {
|
||||
// ByteBuffer buf = null;
|
||||
// while ( writtenByte < expectedWrite ) {
|
||||
//
|
||||
// buf = ByteBuffer.allocate( expectedWrite - writtenByte );
|
||||
// buf.clear();
|
||||
// buf.put( outgoingMessage.array(), writtenByte, buf.capacity() );
|
||||
// writtenByte += write( buf );
|
||||
//
|
||||
// if ( expectedWrite == writtenByte ) return true;
|
||||
// long waitTime = System.currentTimeMillis() - writeStart;
|
||||
//
|
||||
// if ( waitTime >= getTimeout() ) {
|
||||
// throw new IOException("메시지 송신 타임아웃");
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// this.socketChannel.register( this.selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ );
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// public int write(ByteBuffer src) throws IOException {
|
||||
//
|
||||
// this.socketChannel.register( this.selector, SelectionKey.OP_WRITE );
|
||||
//// int selected = 0;
|
||||
//
|
||||
// try {
|
||||
// //selected =
|
||||
// selector.select( getTimeout() );
|
||||
// } catch(Exception e) {
|
||||
// throw new IOException("Write Select Error");
|
||||
// }
|
||||
//
|
||||
// Iterator<SelectionKey> it = selector.selectedKeys().iterator();
|
||||
// int writtenBytes = 0;
|
||||
// SelectionKey key = null;
|
||||
//
|
||||
// while ( it.hasNext() ) {
|
||||
// key = (SelectionKey)it.next();
|
||||
// it.remove();
|
||||
// if ( key.isWritable() ) {
|
||||
// writtenBytes = this.socketChannel.write( src );
|
||||
// }
|
||||
// }
|
||||
// return writtenBytes;
|
||||
// }
|
||||
//
|
||||
// private byte[] makeLengthField(int length) {
|
||||
// byte[] lenField = new byte[ lenBuffer.capacity() ];
|
||||
//
|
||||
// if ( lenBuffer.capacity() == 2 ) {
|
||||
// ByteBuffer tmpBuffer = ByteBuffer.allocate( lenBuffer.capacity() );
|
||||
// tmpBuffer.clear();
|
||||
// tmpBuffer.putShort( (short) (length & 0xFFFF) );
|
||||
// lenField = tmpBuffer.array();
|
||||
// } else if ( lenBuffer.capacity() == 4 ) {
|
||||
// ByteBuffer tmpBuffer = ByteBuffer.allocate( lenBuffer.capacity() );
|
||||
// tmpBuffer.clear();
|
||||
// tmpBuffer.putInt( length );
|
||||
// lenField = tmpBuffer.array();
|
||||
// } else {
|
||||
// String lenStr = CommonLib.getFormatString( length, lenBuffer.capacity() );
|
||||
// lenField = lenStr.getBytes();
|
||||
// }
|
||||
//
|
||||
// return lenField;
|
||||
// }
|
||||
//
|
||||
// private void makeFormat( byte[] data ) {
|
||||
//
|
||||
// int i = data.length + lenBuffer.capacity();
|
||||
//
|
||||
// if(outgoingMessage == null) {
|
||||
// outgoingMessage = ByteBuffer.allocate( data.length + lenBuffer.capacity() );
|
||||
// } else {
|
||||
// if( i != outgoingMessage.capacity() )
|
||||
// outgoingMessage = ByteBuffer.allocate( i );
|
||||
// }
|
||||
// outgoingMessage.clear();
|
||||
// outgoingMessage.put( makeLengthField( data.length ) );
|
||||
// outgoingMessage.put( data );
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * @return Returns the socketchannel.
|
||||
// */
|
||||
// public SocketChannel getSocketchannel() {
|
||||
// return socketChannel;
|
||||
// }
|
||||
// /**
|
||||
// * @param socketchannel The socketchannel to set.
|
||||
// */
|
||||
// public void setSocketchannel(SocketChannel socketchannel) {
|
||||
// this.socketChannel = socketchannel;
|
||||
// }
|
||||
//
|
||||
// public void setLastActivity() {
|
||||
// }
|
||||
//
|
||||
// public long getFirstActivity() {
|
||||
// return 0;
|
||||
// }
|
||||
//
|
||||
// public long getLastActivity() {
|
||||
// return 0;
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,216 @@
|
||||
package com.eactive.eai.agent;
|
||||
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.common.dao.DAOFactory;
|
||||
import com.eactive.eai.common.server.EAIServerDAO;
|
||||
import com.eactive.eai.common.server.EAIServerVO;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* 1. 기능 : 등록된 EAI Server 에 Command를 broadcast
|
||||
* 2. 처리 개요 : 등록된 EAI Server 에 Command를 broadcast
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*/
|
||||
public class AgentUtil
|
||||
{
|
||||
private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
private static final String WEB_AGENT_SERVLET_URL = "/BAPAppWeb/WebAgent";
|
||||
|
||||
|
||||
//생성자 (private : 객체 생성 불가)
|
||||
private AgentUtil() {}
|
||||
|
||||
|
||||
private static HashMap<String, String> getAllSvrUrl() throws Exception {
|
||||
|
||||
EAIServerDAO dao = (EAIServerDAO) DAOFactory.newInstance().create(EAIServerDAO.class);
|
||||
ArrayList<EAIServerVO> serverList = dao.getAllServerList();
|
||||
if (serverList == null || serverList.size() == 0) return null;
|
||||
|
||||
HashMap<String, String> urlLists = new HashMap<String, String>();
|
||||
|
||||
for (int i = 0; i<serverList.size(); i++) {
|
||||
EAIServerVO vo = (EAIServerVO) serverList.get(i);
|
||||
if (vo.getName().equalsIgnoreCase("ALL")) continue; //서버명이 'ALL' 인 경우는 무시
|
||||
urlLists.put(vo.getName(), vo.toURL(EAIServerVO.HTTP_PROTOCOL) + WEB_AGENT_SERVLET_URL);
|
||||
logger.debug("[ AgentUtil ] getAllSvrUrl - URL : " + urlLists.get(vo.getName()));
|
||||
}
|
||||
return urlLists;
|
||||
}
|
||||
|
||||
private static HashMap<String, String> getSvrUrl(EAIServerVO vo) throws Exception {
|
||||
|
||||
if (vo == null) return null;
|
||||
|
||||
HashMap<String, String> urlLists = new HashMap<String, String>();
|
||||
urlLists.put(vo.getName(), vo.toURL(EAIServerVO.HTTP_PROTOCOL) + WEB_AGENT_SERVLET_URL);
|
||||
logger.debug("[ AgentUtil ] getAllSvrUrl - URL : " + urlLists.get(vo.getName()));
|
||||
return urlLists;
|
||||
}
|
||||
|
||||
public static HashMap<String, Object> broadcast(EAIServerVO serverVO, Command command) throws Exception {
|
||||
return broadcast(getSvrUrl(serverVO), command);
|
||||
}
|
||||
|
||||
public static HashMap<String, Object> broadcast(Command command) throws Exception {
|
||||
return broadcast(getAllSvrUrl(), command);
|
||||
}
|
||||
|
||||
public static HashMap<String, Object> callMainServer(Command command) throws Exception {
|
||||
return broadcast(getSvrUrl(getMainServerVO()), command);
|
||||
}
|
||||
|
||||
public static EAIServerVO getServerVO(String serverName) throws Exception {
|
||||
if (serverName == null || serverName.equals("")) throw new Exception("서버명 파라미터가 null 또는 공백입니다.");
|
||||
|
||||
EAIServerDAO dao = (EAIServerDAO) DAOFactory.newInstance().create(EAIServerDAO.class);
|
||||
ArrayList<EAIServerVO> serverList = dao.getAllServerList();
|
||||
if (serverList == null || serverList.size() == 0) return null;
|
||||
|
||||
for (int i = 0; i < serverList.size(); i++) {
|
||||
EAIServerVO vo = (EAIServerVO) serverList.get(i);
|
||||
if (vo.getName().equals(serverName)) return vo;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static EAIServerVO getMainServerVO() throws Exception {
|
||||
|
||||
EAIServerDAO dao = (EAIServerDAO) DAOFactory.newInstance().create(EAIServerDAO.class);
|
||||
ArrayList<EAIServerVO> serverList = dao.getAllServerList();
|
||||
|
||||
if ( serverList.size() > 0 )
|
||||
return serverList.get(0);
|
||||
// //서버명 중에 xxxxxi11 로 끝나는 서버를 메인서버로 본다.
|
||||
// for (int i = 0; serverList != null && i < serverList.size(); i++) {
|
||||
// EAIServerVO vo = serverList.get(i);
|
||||
//// if (vo.getName().endsWith("i11")) return vo;
|
||||
// return vo;
|
||||
// }
|
||||
throw new Exception("서버정보 테이블(TSEAIBP03) 에 메인서버를 설정하세요.");
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 등록된 EAI Server에 Command를 broadcast
|
||||
* 2. 처리 개요 : 등록된 EAI Server의 URLConnection을 생성하여 Command broadcast하고
|
||||
* 전송된 결과값의 HashMap을 생성하여 반환
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param command broadcast할 Command
|
||||
* @return HashMap broadcast후 전송된 결과값.
|
||||
* 전송된 데이터가 sucess가 아니면 Exception이 전송된 것임.
|
||||
* @exception Exception
|
||||
**/
|
||||
public static HashMap<String, Object> broadcast(HashMap<String, String> servers, Command command) throws Exception {
|
||||
|
||||
HashMap<String, Object> returnValue = new HashMap<String, Object>();
|
||||
|
||||
logger.debug("[ AgentUtil ] broadcast 시작...");
|
||||
if (servers != null) {
|
||||
|
||||
logger.debug("[ AgentUtil ] 대상 서버수 =" + servers.size());
|
||||
Iterator<String> it = servers.keySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
String svrName = (String) it.next();
|
||||
String url = (String) servers.get(svrName);
|
||||
URLConnection urlCon = getURLConnection(url);
|
||||
try {
|
||||
logger.debug("[ AgentUtil ] COMMAND = " + command);
|
||||
Object response = sendCommand(urlCon, command);
|
||||
returnValue.put(svrName, response);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("[ AgentUtil ] ★★★★★ broadcast 예외 발생 !! ★★★★★", e);
|
||||
returnValue.put(svrName, e.getMessage());
|
||||
}
|
||||
logger.debug("[ AgentUtil ] 대상 서버 ["+svrName+"] 결과 = ["+ returnValue.get(svrName) +"]");
|
||||
}
|
||||
|
||||
} else {
|
||||
logger.error("[ AgentUtil ] 대상 서버 없음.");
|
||||
}
|
||||
logger.debug("[ AgentUtil ] broadcast 완료.");
|
||||
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 해당 URLConnection으로 command 전송 처리 결과를 반환
|
||||
* 2. 처리 개요 : 해당 URLConnection으로 command 전송하고 처리 결과를 반환
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param urlCon 연결할 URLConnection
|
||||
* @param command 전송할 Command
|
||||
* @return String 처리된 결과
|
||||
* @exception Exception
|
||||
**/
|
||||
private static Object sendCommand(URLConnection urlCon, Command command) throws Exception {
|
||||
|
||||
ObjectOutputStream oos = null;
|
||||
ObjectInputStream ois = null;
|
||||
Object response = "";
|
||||
|
||||
try {
|
||||
HashMap<String, Command> hm = new HashMap<String, Command>();
|
||||
hm.put("command", command);
|
||||
|
||||
oos = new ObjectOutputStream(urlCon.getOutputStream());
|
||||
oos.writeObject((Serializable) hm);
|
||||
oos.flush();
|
||||
logger.debug("[ AgentUtil ] SendCommand - " + urlCon.getURL().toString() +" ["+ command.getClass().getName() + "]");
|
||||
|
||||
ois = new ObjectInputStream(urlCon.getInputStream());
|
||||
response = ois.readObject();
|
||||
|
||||
} finally {
|
||||
try { if (oos != null) oos.close(); } catch (Exception ex) {}
|
||||
try { if (ois != null) ois.close(); } catch (Exception ex) {}
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 지정된 url의 URLConnection 생성
|
||||
* 2. 처리 개요 : 지정된 url의 URLConnection 생성
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param url URLConnection을 생성을 위한 url
|
||||
* @return URLConnection 생성된 URLConnection
|
||||
* @exception
|
||||
**/
|
||||
private static URLConnection getURLConnection(String url) throws Exception {
|
||||
|
||||
URL u = new URL(url);
|
||||
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
|
||||
|
||||
if (conn == null) throw new Exception("HttpURLConnection 을 생성할 수 없습니다. (URL : "+ url +")");
|
||||
|
||||
conn.setDoInput(true);
|
||||
conn.setDoOutput(true);
|
||||
conn.setUseCaches(false);
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setRequestProperty("Content-type", "application/octet-stream");
|
||||
|
||||
return conn;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.eactive.eai.agent.adapter;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 AdapterManager의 정보 변경
|
||||
* 2. 처리 개요 : AdapterGroupVO를 manager에서 remove
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*/
|
||||
public class RemoveAdapterGroupCommand extends Command
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 1. 기능 : RemoveAdapterGroupCommand 생성자
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public RemoveAdapterGroupCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : AdapterManager에 AdapterGroupVO를 제거
|
||||
* 2. 처리 개요 : AdapterGroupVO의 EAISvrInstNm이 DEFAULT_SERVER(ALL) 이거나 LocalServer인 경우
|
||||
* AdapterManager에 등록된 해당 AdapterGroupVO를 제거
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
String adapterGroupName = (String)args;
|
||||
logger.debug("adapterGroupName : "+adapterGroupName );
|
||||
AdapterGroupVO gvo = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
|
||||
if (gvo != null) {
|
||||
gvo.stop();
|
||||
AdapterManager.getInstance().removeAdapterGroupVO(adapterGroupName);
|
||||
}
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "sucess";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.eactive.eai.agent.adapter;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 AdapterManager의 정보 변경
|
||||
* 2. 처리 개요 : AdapterGroupVO의 member variable 값 변경
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see
|
||||
* @since
|
||||
*/
|
||||
public class UpdateAdapterGroupCommand extends Command
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 1. 기능 : UpdateAdapterGroupCommand 생성자
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
**/
|
||||
public UpdateAdapterGroupCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : AdapterManager의 AdapterGroupVO를 수정
|
||||
* 2. 처리 개요 : AdapterGroupVO의 EAISvrInstNm이 DEFAULT_SERVER(ALL) 이거나 LocalServer인 경우
|
||||
* AdapterManager에 등록된 해당 AdapterGroupVO의 데이터 수정
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
|
||||
String adapterGroupName = (String)args;
|
||||
AdapterGroupVO current = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
|
||||
if (current != null) {
|
||||
current.stop();
|
||||
AdapterManager.getInstance().removeAdapterGroupVO(adapterGroupName);
|
||||
// } else {
|
||||
// logger.info("Manager's AdapterGroupVO is null. -- "+vo.getName());
|
||||
}
|
||||
AdapterGroupVO vo = AdapterManager.getInstance().getAdapterGroupInDB(adapterGroupName);
|
||||
|
||||
if (vo.isUsedFlag()) {
|
||||
vo.start();
|
||||
AdapterManager.getInstance().addAdapterGroupVO(vo);
|
||||
}
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "sucess";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.eactive.eai.agent.adapter.socket;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.osd.OutsideManager;
|
||||
import com.eactive.eai.batch.osd.OutsideVO;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 CodeMessageManager의 정보 변경
|
||||
* 2. 처리 개요 : CodeMessageManager에 CodeMessageVO추가
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*/
|
||||
public class SocketServerCommand extends Command
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
/**
|
||||
* 1. 기능 : SelectSocketServerCommand 생성자
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public SocketServerCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : ServerSocket 정보를 가지고옮
|
||||
* 2. 처리 개요 : ServerSocket 정보를 가지고옮
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
try {
|
||||
|
||||
List<Map<String,Serializable>> ls = getSocketServerAdapterInfo();
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return ls;
|
||||
|
||||
} catch (Exception ex) {
|
||||
String msg = makeException("BECEAICAG002", ex);
|
||||
logger.error(msg, ex);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private List<Map<String,Serializable>> getSocketServerAdapterInfo() throws Exception {
|
||||
|
||||
try {
|
||||
//리턴 ArrayList 생성
|
||||
List<Map<String,Serializable>> retList = new ArrayList<Map<String,Serializable>>();
|
||||
|
||||
//메모리의 전체 AdapterGroup 객체 조회
|
||||
HashMap<String, AdapterGroupVO> allAdapterGroupMap = AdapterManager.getInstance().getAllAdapterGroupVO();
|
||||
|
||||
//AdapterGroup 이 없으면
|
||||
if (allAdapterGroupMap == null || allAdapterGroupMap.size() == 0) {
|
||||
return retList;
|
||||
}
|
||||
|
||||
//AdapterGroup 명으로 정렬
|
||||
Object[] adapterGroupNames = allAdapterGroupMap.keySet().toArray();
|
||||
Arrays.sort(adapterGroupNames);
|
||||
|
||||
//===================================================================================
|
||||
//AdapterGroup 별 LOOP
|
||||
for (int i=0; i<adapterGroupNames.length; i++) {
|
||||
AdapterGroupVO gvo = allAdapterGroupMap.get(adapterGroupNames[i]);
|
||||
String adapterGroupName = gvo.getName();
|
||||
String processCode = gvo.getBatchProcessCode();
|
||||
String organCode = gvo.getBatchInstitutionCode();
|
||||
OutsideVO ovo = OutsideManager.getInstance().getOutsideInfo(processCode, organCode);
|
||||
String processName = ovo.getBatchName();
|
||||
String organName = ovo.getOsdName();
|
||||
|
||||
//해당 AdapterGroup의 전체 Adapter 객체 조회
|
||||
HashMap<String,AdapterVO> allAdapterMap = gvo.getAllAdapters();
|
||||
|
||||
//Adapter 가 없으면 디폴트 값 설정
|
||||
if (allAdapterMap == null || allAdapterMap.size() == 0) {
|
||||
Map<String, Serializable> map = new HashMap<String, Serializable>();
|
||||
map.put("adptrBzwkGroupName", adapterGroupName);
|
||||
map.put("bjobBzwkDstcd" , processCode );
|
||||
map.put("processName" , processName );
|
||||
map.put("organName" , organName );
|
||||
map.put("osidInstiDstCd" , organCode );
|
||||
map.put("adptrBzwkName" , "No Adapters" );
|
||||
map.put("ip" , "" );
|
||||
map.put("port" , "" );
|
||||
map.put("maxConnectioncount", 0 );
|
||||
map.put("curConnectioncount", 0 );
|
||||
map.put("status" , "N/A" );
|
||||
retList.add(map);
|
||||
continue;
|
||||
}
|
||||
|
||||
//Adapter 명으로 정렬
|
||||
Object[] adapterNames = allAdapterMap.keySet().toArray();
|
||||
Arrays.sort(adapterNames);
|
||||
|
||||
//-------------------------------------------------------------------
|
||||
//Adapter 별 LOOP
|
||||
for (int k=0; k<adapterNames.length; k++) {
|
||||
AdapterVO avo = (AdapterVO) allAdapterMap.get(adapterNames[k]);
|
||||
String adapterName = avo.getName();
|
||||
int maxConnCnt = avo.getContext().getMaxConnection();
|
||||
int curConnCnt = SocketAdapterManager.getInstance().getSocketServiceCount(adapterGroupName, adapterName);
|
||||
boolean isActive = avo.isStarted();
|
||||
|
||||
Map<String, Serializable> map = new HashMap<String, Serializable>();
|
||||
map.put("adptrBzwkGroupName", adapterGroupName );
|
||||
map.put("bjobBzwkDstcd" , processCode );
|
||||
map.put("processName" , processName );
|
||||
map.put("organName" , organName );
|
||||
map.put("osidInstiDstCd" , organCode );
|
||||
map.put("adptrBzwkName" , adapterName );
|
||||
map.put("ip" , avo.getBatchServerIP() );
|
||||
map.put("port" , avo.getBatchServerPortNo());
|
||||
map.put("maxConnectioncount", maxConnCnt );
|
||||
map.put("curConnectioncount", curConnCnt );
|
||||
map.put("status" , isActive? "기동중" : "중지" );
|
||||
retList.add(map);
|
||||
}
|
||||
}
|
||||
return retList;
|
||||
|
||||
}catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.eactive.eai.agent.adapter.socket;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class SocketServerVO implements Serializable {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String serverName; //서버명
|
||||
private String bjobBzwkDstcd; //작업업무구분코드
|
||||
private String osidInstiDstCd; //대외기관구분코드
|
||||
private String osidInstiName; //대외기관명
|
||||
private String adptrBzwkGroupName; //어댑터업무그룹명
|
||||
private String adptrBzwkName; //어댑터업무명
|
||||
private String ip; //아이피
|
||||
private String port; //포트
|
||||
private String status; //상태
|
||||
private int maxConnectionCount;
|
||||
private int curConnectionCount;
|
||||
public String getServerName() {
|
||||
return serverName;
|
||||
}
|
||||
public void setServerName(String serverName) {
|
||||
this.serverName = serverName;
|
||||
}
|
||||
public String getBjobBzwkDstcd() {
|
||||
return bjobBzwkDstcd;
|
||||
}
|
||||
public void setBjobBzwkDstcd(String bjobBzwkDstcd) {
|
||||
this.bjobBzwkDstcd = bjobBzwkDstcd;
|
||||
}
|
||||
public String getOsidInstiDstCd() {
|
||||
return osidInstiDstCd;
|
||||
}
|
||||
public void setOsidInstiDstCd(String osidInstiDstCd) {
|
||||
this.osidInstiDstCd = osidInstiDstCd;
|
||||
}
|
||||
public String getOsidInstiName() {
|
||||
return osidInstiName;
|
||||
}
|
||||
public void setOsidInstiName(String osidInstiName) {
|
||||
this.osidInstiName = osidInstiName;
|
||||
}
|
||||
public String getAdptrBzwkGroupName() {
|
||||
return adptrBzwkGroupName;
|
||||
}
|
||||
public void setAdptrBzwkGroupName(String adptrBzwkGroupName) {
|
||||
this.adptrBzwkGroupName = adptrBzwkGroupName;
|
||||
}
|
||||
public String getAdptrBzwkName() {
|
||||
return adptrBzwkName;
|
||||
}
|
||||
public void setAdptrBzwkName(String adptrBzwkName) {
|
||||
this.adptrBzwkName = adptrBzwkName;
|
||||
}
|
||||
public String getIp() {
|
||||
return ip;
|
||||
}
|
||||
public void setIp(String ip) {
|
||||
this.ip = ip;
|
||||
}
|
||||
public String getPort() {
|
||||
return port;
|
||||
}
|
||||
public void setPort(String port) {
|
||||
this.port = port;
|
||||
}
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
public int getMaxConnectionCount() {
|
||||
return maxConnectionCount;
|
||||
}
|
||||
public void setMaxConnectionCount(int maxConnectionCount) {
|
||||
this.maxConnectionCount = maxConnectionCount;
|
||||
}
|
||||
public int getCurConnectionCount() {
|
||||
return curConnectionCount;
|
||||
}
|
||||
public void setCurConnectionCount(int curConnectionCount) {
|
||||
this.curConnectionCount = curConnectionCount;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SocketServerVO [serverName=" + serverName + ", bjobBzwkDstcd="
|
||||
+ bjobBzwkDstcd + ", osidInstiDstCd=" + osidInstiDstCd
|
||||
+ ", osidInstiName=" + osidInstiName + ", adptrBzwkGroupName="
|
||||
+ adptrBzwkGroupName + ", adptrBzwkName=" + adptrBzwkName
|
||||
+ ", ip=" + ip + ", port=" + port + ", status=" + status
|
||||
+ ", maxConnectionCount=" + maxConnectionCount
|
||||
+ ", curConnectionCount=" + curConnectionCount + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.eactive.eai.agent.adapter.socket;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.eactive.eai.adapter.socket.service.SocketService;
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.doc.BatchDoc;
|
||||
import com.eactive.eai.batch.running.BatchRunningJobManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class SocketSessionCommand extends Command
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
public SocketSessionCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
try {
|
||||
List<Map<String, String>> alist = getAllRunningSessionVO();
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return alist;
|
||||
|
||||
} catch (Exception ex) {
|
||||
String msg = makeException("BECEAICAG002", ex);
|
||||
logger.error(msg, ex);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private List<Map<String, String>> getAllRunningSessionVO() throws Exception {
|
||||
List<Map<String, String>> retList = new ArrayList<Map<String, String>>();
|
||||
|
||||
HashMap<String, BatchDoc> allDocs = BatchRunningJobManager.getInstance().getAllRunningDocuments();
|
||||
Object[] uuids = allDocs.keySet().toArray();
|
||||
|
||||
for (int i=0; i<allDocs.size(); i++) {
|
||||
BatchDoc batchDoc = (BatchDoc) BatchRunningJobManager.getInstance().getRunningDocument((String)uuids[i]);
|
||||
SocketService service = (SocketService) BatchRunningJobManager.getInstance().getRunningSocketService((String)uuids[i]);
|
||||
|
||||
//socket 이 null 이거나 remote address 가 null 이어서 remote에 연결되지 않은 소켓은 목록에 추가 안함
|
||||
if (service == null ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Date date = new Date(service.getFirstActivity());
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
|
||||
String timestamp = sdf.format(date);
|
||||
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
map.put( "serverName" , batchDoc.getBatchMsg().getBody().getWLIServerName());
|
||||
map.put( "processName" , batchDoc.getBatchMsg().getHeader().getProcessName());
|
||||
map.put( "organName" , batchDoc.getBatchMsg().getHeader().getInstitutionName());
|
||||
map.put( "processType" , batchDoc.getBatchMsg().getHeader().getProcessType());
|
||||
map.put( "uuid" , batchDoc.getBatchMsg().getHeader().getUUID());
|
||||
map.put( "adapterGroupName", service.getContext()==null? "" : service.getContext().getAdapterGroupName());
|
||||
map.put( "adapterName" , service.getContext()==null? "" : service.getContext().getAdapterName());
|
||||
map.put( "localIpPort" , service.getCurrentSocket() == null || service.getCurrentSocket().getLocalAddress() == null?
|
||||
"" :
|
||||
service.getCurrentSocket().getLocalAddress().getHostAddress() + ":" + service.getCurrentSocket().getLocalPort());
|
||||
map.put( "remoteIpPort" , service.getCurrentSocket() == null || service.getCurrentSocket().getInetAddress() == null ?
|
||||
"" :
|
||||
service.getCurrentSocket().getInetAddress().getHostAddress() + ":" + service.getCurrentSocket().getPort());
|
||||
map.put( "startTimeStamp" , timestamp);
|
||||
map.put( "status" , "연결됨");
|
||||
retList.add(map);
|
||||
}
|
||||
return retList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.eactive.eai.agent.adapter.socket;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class SocketSessionVO implements Serializable//, Comparable
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
private String serverName = ""; //서버인스턴스명
|
||||
private String uuid = ""; //UUID
|
||||
private String processType = ""; //업무유형
|
||||
private String processCode = ""; //업무코드
|
||||
private String processName = ""; //업무명
|
||||
private String organCode = ""; //대외기관코드
|
||||
private String organName = ""; //대외기관명
|
||||
private String adapterGroupName = ""; //어댑터그룹명
|
||||
private String adapterName = ""; //어댑터명
|
||||
private String localIp = ""; //로컬IP
|
||||
private String localPort = ""; //로컬Port
|
||||
private String remoteIp = ""; //리모트IP
|
||||
private String remotePort = ""; //리모트Port
|
||||
private long startTimeStamp = 0; //연결시작시간
|
||||
private long endTimeStamp = 0; //연결종료시간 (배치에서는 무의미함)
|
||||
private String status = ""; //Session Service 상태
|
||||
|
||||
public void setServerName (String arg) { this.serverName = arg; }
|
||||
public void setUuid (String arg) { this.uuid = arg; }
|
||||
public void setProcessType (String arg) { this.processType = arg; }
|
||||
public void setProcessCode (String arg) { this.processCode = arg; }
|
||||
public void setProcessName (String arg) { this.processName = arg; }
|
||||
public void setOrganCode (String arg) { this.organCode = arg; }
|
||||
public void setOrganName (String arg) { this.organName = arg; }
|
||||
public void setAdapterGroupName(String arg) { this.adapterGroupName = arg; }
|
||||
public void setAdapterName (String arg) { this.adapterName = arg; }
|
||||
public void setLocalIp (String arg) { this.localIp = arg; }
|
||||
public void setLocalPort (String arg) { this.localPort = arg; }
|
||||
public void setRemoteIp (String arg) { this.remoteIp = arg; }
|
||||
public void setRemotePort (String arg) { this.remotePort = arg; }
|
||||
public void setStartTimeStamp (long arg) { this.startTimeStamp = arg; }
|
||||
public void setEndTimeStamp (long arg) { this.endTimeStamp = arg; }
|
||||
public void setStatus (String arg) { this.status = arg; }
|
||||
|
||||
public String getServerName () { return this.serverName ; }
|
||||
public String getUuid () { return this.uuid ; }
|
||||
public String getProcessType () { return this.processType ; }
|
||||
public String getProcessCode () { return this.processCode ; }
|
||||
public String getProcessName () { return this.processName ; }
|
||||
public String getOrganCode () { return this.organCode ; }
|
||||
public String getOrganName () { return this.organName ; }
|
||||
public String getAdapterGroupName() { return this.adapterGroupName; }
|
||||
public String getAdapterName () { return this.adapterName ; }
|
||||
public String getLocalIp () { return this.localIp ; }
|
||||
public String getLocalPort () { return this.localPort ; }
|
||||
public String getRemoteIp () { return this.remoteIp ; }
|
||||
public String getRemotePort () { return this.remotePort ; }
|
||||
public long getStartTimeStamp () { return this.startTimeStamp ; }
|
||||
public long getEndTimeStamp () { return this.endTimeStamp ; }
|
||||
public String getStatus () { return this.status ; }
|
||||
|
||||
// public int compareTo(Object arg0) {
|
||||
// SocketSessionVO info = (SocketSessionVO) arg0;
|
||||
// int compare = 0;
|
||||
// if ((compare = this.getServerName ().compareTo(info.getServerName ())) != 0) return compare;
|
||||
// if ((compare = this.getAdapterGroupName().compareTo(info.getAdapterGroupName())) != 0) return compare;
|
||||
// if ((compare = this.getAdapterName ().compareTo(info.getAdapterName ())) != 0) return compare;
|
||||
// return (int) (this.getStartTimeStamp() - info.getStartTimeStamp());
|
||||
// }
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append("\nSocketSessionVO [ ");
|
||||
sb.append("serverName=" ).append(serverName );
|
||||
sb.append(", uuid=" ).append(uuid );
|
||||
sb.append(", processType=" ).append(processType );
|
||||
sb.append(", processCode=" ).append(processCode );
|
||||
sb.append(", processName=" ).append(processName );
|
||||
sb.append(", organCode=" ).append(organCode );
|
||||
sb.append(", organName=" ).append(organName );
|
||||
sb.append(", adapterGroupName=").append(adapterGroupName);
|
||||
sb.append(", adapterName=" ).append(adapterName );
|
||||
sb.append(", localIp=" ).append(localIp );
|
||||
sb.append(", localPort=" ).append(localPort );
|
||||
sb.append(", remoteIp=" ).append(remoteIp );
|
||||
sb.append(", remotePort=" ).append(remotePort );
|
||||
sb.append(", startTimeStamp=" ).append(startTimeStamp );
|
||||
sb.append(", endTimeStamp=" ).append(endTimeStamp );
|
||||
sb.append(", status=" ).append(status );
|
||||
sb.append(" ]");
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.eactive.eai.agent.adapter.socket;
|
||||
|
||||
import com.eactive.eai.adapter.socket.config.SocketAdapterManager;
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.running.BatchRunningJobManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class SocketStartStopCommand extends Command
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
public static final String START_SOCKET_SERVER = "START_SOCKET_SERVER";
|
||||
public static final String STOP_SOCKET_SERVER = "STOP_SOCKET_SERVER";
|
||||
public static final String START_SOCKET_SESSION = "START_SOCKET_SESSION";
|
||||
public static final String STOP_SOCKET_SESSION = "STOP_SOCKET_SESSION";
|
||||
|
||||
|
||||
public SocketStartStopCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String[] argArray = (String[]) args;
|
||||
String startStopType = argArray[0]; //기동중지 구분
|
||||
String adapterGroupName = argArray[1]; //어댑터그룹명
|
||||
String adapterName = argArray[2]; //어댑터명
|
||||
String uuid = argArray.length<4? "":argArray[3]; //UUID (세션종료시만 사용)
|
||||
logger.info("※ 기동/종료구분 : "+ startStopType);
|
||||
logger.info("※ 어댑터그룹 : "+ adapterGroupName);
|
||||
logger.info("※ 어댑터 : "+ adapterName);
|
||||
logger.info("※ UUID : "+ uuid);
|
||||
|
||||
String retValue = "";
|
||||
if (startStopType.equals(START_SOCKET_SERVER)) {
|
||||
retValue = SocketAdapterManager.getInstance().start(adapterGroupName, adapterName);
|
||||
|
||||
} else if (startStopType.equals(STOP_SOCKET_SERVER)) {
|
||||
retValue = SocketAdapterManager.getInstance().stop(adapterGroupName, adapterName);
|
||||
|
||||
} else if (startStopType.equals(STOP_SOCKET_SESSION)) {
|
||||
logger.debug("★★★★★★★★★★★★★★★★ SocketStartStopCommand : 사용자에 의한 Socket Session 강제 종료가 요청되었습니다. ★★★★★★★★★★★★★★★★");
|
||||
BatchRunningJobManager.getInstance().closeRunningSocket(uuid);
|
||||
retValue = "Socket Session 강제 종료가 완료 되었습니다.";
|
||||
|
||||
} else {
|
||||
throw new Exception("Start/Stop 구분 파라미터 오류");
|
||||
}
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return retValue;
|
||||
|
||||
} catch (Exception ex) {
|
||||
String msg = makeException("BECEAICAG002", ex);
|
||||
logger.error(msg, ex);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// private void stopSession(String adapterGroupName, String adapterName, String remoteIpPort) throws Exception {
|
||||
//
|
||||
// String[] TempIpPort = remoteIpPort.split(":");
|
||||
// String remoteIp = TempIpPort[0];
|
||||
// String remotePort = TempIpPort[1];
|
||||
//
|
||||
// //소켓서버에 연결된 전체 Session 정보를 메모리에서 조회
|
||||
// //(연결된 Session 이 없어도 각 AdapterGroup 별 LinkedList 정보가 존재함)
|
||||
// HashMap allSessions = SocketAdapterManager.getInstance().getAllSessions();
|
||||
// if (allSessions == null || allSessions.size() == 0) throw new Exception("모든 어댑터그룹의 세션 정보가 비어있습니다.");
|
||||
//
|
||||
// //AdapterGroup 명 조회
|
||||
// Object[] adapterGroupNames = allSessions.keySet().toArray();
|
||||
// //Arrays.sort(adapterGroupNames);
|
||||
//
|
||||
// //===================================================================================
|
||||
// //AdapterGroup 별 LOOP
|
||||
// for (int i=0; i<allSessions.size(); i++) {
|
||||
//
|
||||
// logger.debug("> "+ adapterGroupNames[i]);
|
||||
// if (!adapterGroupName.equals(adapterGroupNames[i])) continue;
|
||||
//
|
||||
// //해당 AdapterGroup의 현재 연결된 Session 정보 조회
|
||||
// //(Adapter 별로 분리하지 않고 연결 순서대로 들어가있다)
|
||||
// LinkedList serviceList = (LinkedList) allSessions.get(adapterGroupNames[i]);
|
||||
// if (serviceList == null || serviceList.size() == 0) break;
|
||||
//
|
||||
// //-------------------------------------------------------------------
|
||||
// //Adapter 별 LOOP
|
||||
// for (int k=0; k<serviceList.size(); k++) {
|
||||
// InboundServer session = (InboundServer) serviceList.get(k);
|
||||
// AdapterVO avo = session.getContext().getAdapterVO();
|
||||
// logger.debug(" > "+ avo.getName() +" / "+ session.getRemoteIPAddress() +" / "+ session.getRemotePort());
|
||||
//
|
||||
// if (adapterName.equals(avo.getName()) &&
|
||||
// remoteIp.equals(session.getRemoteIPAddress()) &&
|
||||
// remotePort.equals(session.getRemotePort()) ) {
|
||||
//
|
||||
// session.disconnect();
|
||||
// SocketAdapterManager.getInstance().removeConnection(session);
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
// //-------------------------------------------------------------------
|
||||
// }
|
||||
// //===================================================================================
|
||||
//
|
||||
// throw new Exception("해당 세션이 이미 종료 되었습니다.");
|
||||
// }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.eactive.eai.agent.code;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.code.CodeMessageManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 CodeMessageManager의 정보 변경
|
||||
* 2. 처리 개요 : CodeMessageManager에 CodeMessageVO제거
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*/
|
||||
public class RemoveCodeMessageCommand extends Command
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public RemoveCodeMessageCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : CodeMessageManager에 CodeMessageVO제거
|
||||
* 2. 처리 개요 : CodeMessageManager에 CodeMessageVO제거
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String msgKey = (String) args;
|
||||
CodeMessageManager.getInstance().removeMessage(msgKey);
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "success";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.eactive.eai.agent.code;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.code.CodeMessageManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 CodeMessageManager의 정보 변경
|
||||
* 2. 처리 개요 : CodeMessageManager에 CodeMessageVO 데이터 변경
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*/
|
||||
public class UpdateCodeMessageCommand extends Command
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public UpdateCodeMessageCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : CodeMessageManager에 CodeMessageVO 데이터 변경
|
||||
* 2. 처리 개요 : CodeMessageManager에 CodeMessageVO 데이터 변경
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if( !(args instanceof java.lang.String) ) {
|
||||
String rspErrorCode = "RECEAIMCM001";
|
||||
String msg = makeException(rspErrorCode, null);
|
||||
if (logger.isError()) logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
String key = (String) args;
|
||||
|
||||
try{
|
||||
CodeMessageManager manager = CodeMessageManager.getInstance();
|
||||
manager.reload(key);
|
||||
}catch (Exception e){
|
||||
String rspErrorCode = "RECEAIMCM002";
|
||||
String msg = makeException(rspErrorCode, e);
|
||||
if (logger.isError()) logger.error(msg,e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "success";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.eactive.eai.agent.command;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Agent에 의해 실행될 Command 를 정의하기 위한 base class
|
||||
* 2. 처리 개요 : Agent에 의해 실행될 Command 를 정의하기 위한 base class
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*
|
||||
*/
|
||||
public abstract class Command implements Serializable {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
/** Command object name */
|
||||
protected String name;
|
||||
/** Command Arguments */
|
||||
protected Object args;
|
||||
|
||||
private HashMap<String,String> errorCode ;
|
||||
|
||||
static {
|
||||
HashMap<String,String> errorCode = new HashMap<String,String>();
|
||||
errorCode.put("RECEAIMCM001", "Command 이름[{1}] 유효하지 않은 파라메터 타입 - {2}");
|
||||
errorCode.put("RECEAIMCM002", "Command 이름[{1}] execute 메소드 실행중 에러가 발생 - {2}");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 1. 기능 : Default Constructor
|
||||
* 2. 처리 개요 : name을 Class name으로 setting한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public Command() {
|
||||
this.name = this.getClass().getName();
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : 파리미터의 name을 setting하는 Constructor
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param name Command object name
|
||||
**/
|
||||
public Command(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : command의 arguments를 setting하는 setter method
|
||||
* 2. 처리 개요 : command의 arguments를 setting하는 setter method
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param args command arguments
|
||||
**/
|
||||
public void setArgs(Object args) {
|
||||
this.args = args;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 1. 기능 : command의 business logic method<br>
|
||||
* 2. 처리 개요 : command의 business logic method<br>
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception CommandException
|
||||
**/
|
||||
public abstract Object execute() throws CommandException;
|
||||
|
||||
/**
|
||||
* 1. 기능 : 에러 Message 생성
|
||||
* 2. 처리 개요 : 에러코드와 Exception cause로 에러 메시지 생성
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param rspErrorcode EAI 에러코드
|
||||
* @param cause Exception cause
|
||||
* @return String 에러 메시지
|
||||
* @exception CommandException
|
||||
**/
|
||||
protected String makeException(String rspErrorCode, Throwable cause) throws CommandException{
|
||||
String[] msgArgs = new String[2];
|
||||
msgArgs[0] = name;
|
||||
if(cause == null){
|
||||
msgArgs[1] = args.toString();
|
||||
}
|
||||
else{
|
||||
msgArgs[1] = cause.getMessage();
|
||||
}
|
||||
String msg = makeMessage((String)errorCode.get(rspErrorCode),msgArgs) ;
|
||||
|
||||
return msg;
|
||||
}
|
||||
|
||||
protected static String makeMessage(String msg, String[] args) {
|
||||
String keyword = null, head = null, tail = null;
|
||||
int idx = -1;
|
||||
for(int i=0;i<args.length;i++) {
|
||||
keyword = "{"+(i+1)+"}";
|
||||
idx = msg.indexOf(keyword);
|
||||
if(idx == -1) {
|
||||
continue;
|
||||
}
|
||||
head = msg.substring(0,idx);
|
||||
tail = msg.substring(idx+keyword.length());
|
||||
msg = head+args[i]+tail;
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.eactive.eai.agent.command;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Command Logic을 실행하다 발생될 User Define 오류를 처리하기 위한 Exception class<br>
|
||||
* 2. 처리 개요 : Command Logic을 실행하다 발생될 User Define 오류를 처리하기 위한 Exception class<br>
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*
|
||||
*/
|
||||
public class CommandException extends Exception {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Default Constructor
|
||||
* 2. 처리 개요 : Default Constructor
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public CommandException() {
|
||||
super("CommandException is occured.");
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : Exception message를 초기화하는 Constructor
|
||||
* 2. 처리 개요 : Exception message를 초기화하는 Constructor
|
||||
* -
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param msg Exception message
|
||||
**/
|
||||
public CommandException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.eactive.eai.agent.command;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
|
||||
/**
|
||||
* 1. 기능 : 공통 command
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*
|
||||
*/
|
||||
public class CommonCommand extends Command {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
|
||||
public CommonCommand(String name,Object args) {
|
||||
this.name = name;
|
||||
this.args = args;
|
||||
}
|
||||
|
||||
public CommonCommand(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
if (name.indexOf(".") >=0 ){
|
||||
try {
|
||||
@SuppressWarnings("rawtypes")
|
||||
Class cl = Class.forName(this.name);
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
Constructor constructor = cl.getConstructor(String.class);
|
||||
Object obj = constructor.newInstance(this.name);
|
||||
Command c = (Command)obj;
|
||||
c.setArgs(args);
|
||||
return c.execute();
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
String rspErrorCode = "RECEAIMCM002";
|
||||
String msg = makeException(rspErrorCode, null);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}else{
|
||||
String rspErrorCode = "RECEAIMCM001";
|
||||
String msg = makeException(rspErrorCode, null);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.eactive.eai.agent.flowController;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.flowController.BatchTargetVO;
|
||||
import com.eactive.eai.batch.flowController.FlowControllerDAO;
|
||||
import com.eactive.eai.batch.flowController.FlowControllerManager;
|
||||
import com.eactive.eai.common.dao.DAOFactory;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class AddBatchTargetCommand extends Command
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 1. 기능 : AddBatchTargetCommand 생성자
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param
|
||||
* @return
|
||||
* @exception
|
||||
**/
|
||||
public AddBatchTargetCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : FlowControllerManager BatchTargetVO 추가
|
||||
* 2. 처리 개요 : FlowControllerManager BatchTargetVO 추가
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param
|
||||
* @return
|
||||
* @exception CommandException
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String[] argArray = (String[]) args;
|
||||
String processCode = argArray[0];
|
||||
String organCode = argArray[1];
|
||||
// add by kscheon
|
||||
// String adapterGroupName = argArray[2];
|
||||
|
||||
FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class);
|
||||
BatchTargetVO vo = dao.getBatchTargetVO(processCode, organCode);
|
||||
|
||||
FlowControllerManager.getInstance().getTargets().put(processCode + organCode, vo);
|
||||
|
||||
// //20080429 Adapter에 대외기관 코드 추가 - by kscheon - start
|
||||
// AdapterGroupVO current = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
// if (current == null){
|
||||
// logger.info(this.name +" Manager's AdapterGroupVO is null. -- "+adapterGroupName);
|
||||
//
|
||||
// }else {
|
||||
// current.setBatchProcessCode(processCode);
|
||||
// current.setBatchInstitutionCode(organCode);
|
||||
// }
|
||||
// //20080429 Adapter에 대외기관 코드 추가 - by kscheon - end
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "success";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.eactive.eai.agent.flowController;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.flowController.FlowControllerManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class RemoveBatchTargetCommand extends Command
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 1. 기능 : RemoveBatchTargetCommand 생성자
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @paramw
|
||||
* @return
|
||||
* @exception
|
||||
**/
|
||||
public RemoveBatchTargetCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : RemoveBatchTargetCommand BatchTargetVO 제거
|
||||
* 2. 처리 개요 : RemoveBatchTargetCommand BatchTargetVO 제거
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param
|
||||
* @return
|
||||
* @exception CommandException
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String[] argArray = (String[]) args;
|
||||
String processCode = argArray[0];
|
||||
String organCode = argArray[1];
|
||||
|
||||
FlowControllerManager.getInstance().getTargets().remove(processCode + organCode);
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "success";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.eactive.eai.agent.flowController;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.flowController.BatchTargetVO;
|
||||
import com.eactive.eai.batch.flowController.DemandTargetVO;
|
||||
import com.eactive.eai.batch.flowController.FlowControllerDAO;
|
||||
import com.eactive.eai.batch.flowController.FlowControllerManager;
|
||||
import com.eactive.eai.common.dao.DAOFactory;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class UpdateBatchTargetCommand extends Command
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 1. 기능 : UpdateBatchTargetCommand 생성자
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param
|
||||
* @return
|
||||
* @exception
|
||||
**/
|
||||
public UpdateBatchTargetCommand() {
|
||||
super("UpdateBatchTargetCommand");
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : UpdateBatchTargetCommand BatchTargetVO 변경
|
||||
* 2. 처리 개요 : UpdateBatchTargetCommand BatchTargetVO 변경
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param
|
||||
* @return
|
||||
* @exception CommandException
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String[] argArray = (String[]) args;
|
||||
String processCode = argArray[0];
|
||||
String organCode = argArray[1];
|
||||
String organStatus = (argArray.length > 2)? argArray[2] : "";
|
||||
|
||||
//Framework 에서 장애(회복)통보 전문 수신시 대외기관 상태를 변경하는 경우
|
||||
//테이블 update 가 commit이 안된 상태이므로 메모리의 정보를 직접 변경해야 한다.
|
||||
if (!organStatus.equals("")) {
|
||||
logger.debug(" - 대외기관 요구송수신 연결 정보 Memory update ("+ processCode +", "+ organCode +", "+ (organStatus.equals(DemandTargetVO.ORGAN_SOCKET_STATUS_ERROR)? "장애" : "정상") +")");
|
||||
DemandTargetVO[] demandTargetList = FlowControllerManager.getInstance().getRemoteHostInfo(processCode, organCode);
|
||||
for (int i=0; i<demandTargetList.length; i++) {
|
||||
demandTargetList[i].setOrganSocketStatus(organStatus);
|
||||
logger.debug(" > 대외기관 요구송수신 연결 정보 ☞ (IP: "+ demandTargetList[i].getIpAddress() +", Port: "+ demandTargetList[i].getPortNumber() +", ID: "+ demandTargetList[i].getSocketID() +", PW: "+ demandTargetList[i].getSocketPwd() +", Timeout: "+ demandTargetList[i].getTimeoutInterval() +", OrganStatus: "+ demandTargetList[i].getOrganSocketStatus() +")");
|
||||
}
|
||||
|
||||
//관리 UI에서 대외기관 정보를 수정한 경우
|
||||
} else {
|
||||
FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class);
|
||||
BatchTargetVO vo = dao.getBatchTargetVO(processCode, organCode);
|
||||
|
||||
FlowControllerManager.getInstance().getTargets().put(processCode + organCode, vo);
|
||||
}
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
|
||||
return "success";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.eactive.eai.agent.flowController;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.flowController.BatchTargetVO;
|
||||
import com.eactive.eai.batch.flowController.FlowControllerDAO;
|
||||
import com.eactive.eai.batch.flowController.FlowControllerManager;
|
||||
import com.eactive.eai.common.dao.DAOFactory;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class UpdateBatchTargetForRTSCommand extends Command
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 1. 기능 : UpdateBatchTargetForRTSCommand 생성자
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param
|
||||
* @return
|
||||
* @exception
|
||||
**/
|
||||
public UpdateBatchTargetForRTSCommand() {
|
||||
super("UpdateBatchTargetForRTSCommand");
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : UpdateBatchTargetForRTSCommand BatchTargetVO 변경
|
||||
* 2. 처리 개요 : UpdateBatchTargetForRTSCommand BatchTargetVO 변경
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param
|
||||
* @return
|
||||
* @exception CommandException
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String[] argArray = (String[]) args;
|
||||
String processCode = argArray[0];
|
||||
String organCode = argArray[1];
|
||||
// add by kscheon
|
||||
String adapterGroupName = argArray[2];
|
||||
|
||||
FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class);
|
||||
BatchTargetVO vo = dao.getBatchTargetVO(processCode, organCode);
|
||||
|
||||
FlowControllerManager.getInstance().getTargets().put(processCode + organCode, vo);
|
||||
|
||||
// 20080429 Adapter에 대외기관 코드 추가 - by kscheon - start
|
||||
AdapterGroupVO current = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
|
||||
if (current == null){
|
||||
logger.info(this.name +" Manager's AdapterGroupVO is null. -- "+adapterGroupName);
|
||||
|
||||
} else {
|
||||
current.setBatchProcessCode(processCode);
|
||||
current.setBatchInstitutionCode(organCode);
|
||||
}
|
||||
//20080429 Adapter에 대외기관 코드 추가 - by kscheon - end
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
|
||||
return "success";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.eactive.eai.agent.ftp;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.inbound.remote.RemoteTransfer;
|
||||
import com.eactive.eai.inbound.remote.RemoteTransferLogKeys;
|
||||
import com.eactive.eai.inbound.remote.RemoteTransferLogManager;
|
||||
import com.eactive.eai.inbound.remote.RemoteTransferLogVO;
|
||||
|
||||
public class RemoteTransferCommand extends Command
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public RemoteTransferCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
String[] param = (String[])args;
|
||||
String logID = param[0];
|
||||
String userId = param[1];
|
||||
|
||||
try {
|
||||
logger.debug("[RemoteTransferCommand]logID-->[" + logID + "]");
|
||||
RemoteTransferLogVO log = RemoteTransferLogManager.getInstance().getRemoteTransferLog(logID);
|
||||
RemoteTransfer transfer = new RemoteTransfer();
|
||||
if (log.getSendRecvYn().equals(RemoteTransferLogKeys.SEND)){
|
||||
transfer.sendFile(log.getBjobBzwkDstcd(), log.getOsidInstiDstcd(), log.getTrsmtFileName(), RemoteTransferLogKeys.START_BY_UI, userId, false);
|
||||
return transfer.sendFile(log.getBjobBzwkDstcd(), log.getOsidInstiDstcd(), log.getTrsmtFileName(), RemoteTransferLogKeys.START_BY_UI, userId, true);
|
||||
}else{
|
||||
return transfer.recvFile( log.getRmtFileTrsmtPathName() + "/" + log.getTrsmtFileName(), RemoteTransferLogKeys.START_BY_UI, userId);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.eactive.eai.agent.holiday;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.eventscheduler.holiday.HolidayManager;
|
||||
import com.eactive.eai.batch.eventscheduler.holiday.HolidayVO;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 HolidayManager의 정보 변경
|
||||
* 2. 처리 개요 : HolidayManager에 HolidayVO제거
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*/
|
||||
public class RemoveHolidayCommand extends Command
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public RemoveHolidayCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : HolidayManager에 HolidayVO제거
|
||||
* 2. 처리 개요 : HolidayManager에 HolidayVO제거
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String[] argArray = (String[]) args;
|
||||
String holidayType = argArray[0];
|
||||
String holiday = argArray[1];
|
||||
String description = argArray[2];
|
||||
|
||||
HolidayVO vo = new HolidayVO(holidayType, holiday, description);
|
||||
HolidayManager manager = HolidayManager.getInstance();
|
||||
|
||||
manager.removeHoliday(vo);
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "success";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.eactive.eai.agent.holiday;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.eventscheduler.holiday.HolidayManager;
|
||||
import com.eactive.eai.batch.eventscheduler.holiday.HolidayVO;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 HolidayManager의 정보 변경
|
||||
* 2. 처리 개요 : HolidayManager에 HolidayVO추가
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*/
|
||||
public class UpdateHolidayCommand extends Command
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public UpdateHolidayCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : HolidayManager에 HolidayVO추가
|
||||
* 2. 처리 개요 : HolidayManager에 HolidayVO추가
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String[] argArray = (String[]) args;
|
||||
String holidayType = argArray[0];
|
||||
String holiday = argArray[1];
|
||||
String description = argArray[2];
|
||||
|
||||
|
||||
HolidayVO vo = new HolidayVO(holidayType, holiday, description);
|
||||
|
||||
HolidayManager manager = HolidayManager.getInstance();
|
||||
manager.setHoliday(vo);
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "success";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.eactive.eai.agent.kikwaninfo;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.rule.kikwanInfo.KikwanInfoManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 HolidayManager의 정보 변경
|
||||
* 2. 처리 개요 : HolidayManager에 HolidayVO제거
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*/
|
||||
public class RemoveKikwaninfoCommand extends Command
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public RemoveKikwaninfoCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : HolidayManager에 HolidayVO제거
|
||||
* 2. 처리 개요 : HolidayManager에 HolidayVO제거
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
if ( args == null || !(args instanceof String) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String kikwanCd = (String) args;
|
||||
KikwanInfoManager manager = KikwanInfoManager.getInstance();
|
||||
|
||||
manager.removeKikwanInfo(kikwanCd);
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "success";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.eactive.eai.agent.kikwaninfo;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.rule.kikwanInfo.KikwanInfoManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 HolidayManager의 정보 변경
|
||||
* 2. 처리 개요 : HolidayManager에 HolidayVO추가
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*/
|
||||
public class UpdateKikwaninfoCommand extends Command
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public UpdateKikwaninfoCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : HolidayManager에 HolidayVO추가
|
||||
* 2. 처리 개요 : HolidayManager에 HolidayVO추가
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String kikwanCd = (String) args;
|
||||
|
||||
KikwanInfoManager manager = KikwanInfoManager.getInstance();
|
||||
manager.setKikwanInfo(kikwanCd);
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "success";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//package com.eactive.eai.agent.makeDir;
|
||||
//
|
||||
//import java.io.File;
|
||||
//import java.util.ArrayList;
|
||||
//import java.util.Collections;
|
||||
//
|
||||
//import com.eactive.eai.agent.command.Command;
|
||||
//import com.eactive.eai.agent.command.CommandException;
|
||||
//import com.eactive.eai.common.property.PropManager;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//import com.eactive.eai.inbound.remote.NDMTransferByScript;
|
||||
//
|
||||
//
|
||||
//public class GetScriptListCommand extends Command
|
||||
//{
|
||||
//
|
||||
// /**
|
||||
// *
|
||||
// */
|
||||
// private static final long serialVersionUID = 1L;
|
||||
//
|
||||
// public GetScriptListCommand() {
|
||||
// super("GetScriptListCommand");
|
||||
// }
|
||||
//
|
||||
// public Object execute() throws CommandException
|
||||
// {
|
||||
// Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_DEFAULT);
|
||||
// logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
//
|
||||
// ArrayList<String> returnList = new ArrayList<String>();
|
||||
// String sendShell = PropManager.getInstance().getProperty(NDMTransferByScript.PROP_GROUP_REMOTE_TRANSFER_NDM, NDMTransferByScript.PROP_NDM_SEND_SCRIPT_PATH);
|
||||
// if ( sendShell == null ){
|
||||
// logger.error(this.name + "PROPERTY가 등록되어 있지 않습니다.[" + NDMTransferByScript.PROP_GROUP_REMOTE_TRANSFER_NDM + "],[" + NDMTransferByScript.PROP_NDM_SEND_SCRIPT_PATH + "]");
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// File file = new File(sendShell);
|
||||
// String path = file.getParent();
|
||||
//
|
||||
// file = new File(path);
|
||||
//
|
||||
// if ( file.exists() ) {
|
||||
// File[] tmplist = file.listFiles();
|
||||
// ArrayList<File> al = new ArrayList<File>();
|
||||
// for ( int inx = 0; inx < tmplist.length; inx++){
|
||||
// al.add(tmplist[inx]);
|
||||
// }
|
||||
//
|
||||
// Collections.sort( al );
|
||||
//
|
||||
// int len = al.size();
|
||||
// File[] list = new File[len];
|
||||
// for ( int inx = 0; inx < len; inx++ ){
|
||||
// list[inx]=al.get(inx);
|
||||
// }
|
||||
// for ( int inx = 0; inx < list.length; inx++){
|
||||
// file = list[inx];
|
||||
// if ( file.isFile()){
|
||||
// String fileName = file.getPath();
|
||||
// if ( fileName.endsWith( ".sh" ) )
|
||||
// {
|
||||
// returnList.add( fileName );
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return returnList;
|
||||
//
|
||||
// }
|
||||
//
|
||||
//}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.eactive.eai.agent.makeDir;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.common.BatchDirUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class MakeDirOrganCommand extends Command
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public MakeDirOrganCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String[] argArray = (String[]) args;
|
||||
|
||||
String processCode = argArray[0];
|
||||
String organCode = argArray[1];
|
||||
|
||||
BatchDirUtil.makeDirOrgan(processCode, organCode);
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "sucess";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.eactive.eai.agent.makeDir;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.common.BatchDirUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class MakeDirProcessCommand extends Command
|
||||
{
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public MakeDirProcessCommand() {
|
||||
super("MakeDirProcessCommand");
|
||||
}
|
||||
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String[] argArray = (String[]) args;
|
||||
|
||||
String processCode = argArray[0];
|
||||
|
||||
BatchDirUtil.makeDirProcess(processCode);
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "sucess";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.eactive.eai.agent.makeDir;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.common.BatchDirUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class RemoveDirOrganCommand extends Command
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public RemoveDirOrganCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String[] argArray = (String[]) args;
|
||||
|
||||
String processCode = argArray[0];
|
||||
String organCode = argArray[1];
|
||||
|
||||
BatchDirUtil.removeDirOrgan(processCode, organCode);
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "sucess";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.eactive.eai.agent.makeDir;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.common.BatchDirUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
public class RemoveDirProcessCommand extends Command
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public RemoveDirProcessCommand() {
|
||||
super("RemoveDirProcessCommand");
|
||||
}
|
||||
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
try {
|
||||
String[] argArray = (String[]) args;
|
||||
|
||||
String processCode = argArray[0];
|
||||
|
||||
BatchDirUtil.removeDirProcess(processCode);
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "sucess";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.eactive.eai.agent.osd;
|
||||
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.batch.osd.OutsideManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 OutsideManager의 정보 변경
|
||||
* 2. 처리 개요 : OutsideManager에 OutsideVO추가
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*/
|
||||
public class RemoveOutsideCommand extends Command
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public RemoveOutsideCommand(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : OutsideManager에 OutsideVO추가
|
||||
* 2. 처리 개요 : OutsideManager에 OutsideVO추가
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException
|
||||
{
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
logger.info(this.name + " Agent 가 호출되었습니다.");
|
||||
|
||||
if ( args == null || !(args instanceof String[]) ) {
|
||||
String msg = makeException("BECEAICAG001", null);
|
||||
logger.error(msg);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
String[] argArray = (String[]) args;
|
||||
String batchCode = argArray[0];
|
||||
String outCode = argArray[1];
|
||||
|
||||
try {
|
||||
|
||||
OutsideManager manager = OutsideManager.getInstance();
|
||||
|
||||
manager.removeOutsideInfo(batchCode, outCode);
|
||||
manager.removeOutsideLinkInfo(batchCode, outCode);
|
||||
|
||||
logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
|
||||
return "success";
|
||||
|
||||
} catch (Exception e) {
|
||||
String msg = makeException("BECEAICAG002", e);
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user