This commit is contained in:
Rinjae
2025-10-23 13:21:43 +09:00
commit d6bf8e1943
1004 changed files with 192647 additions and 0 deletions
@@ -0,0 +1,284 @@
package com.eactive.eai.batch.bokex;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import com.eactive.eai.batch.flowController.DemandTargetVO;
import com.eactive.eai.batch.flowController.FlowControllerManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageDAO;
import com.eactive.eai.common.dao.DAOFactory;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;
public class BOKEXAddTelegramManager {
private static BOKEXAddTelegramManager instance = new BOKEXAddTelegramManager();
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
public static BOKEXAddTelegramManager getInstance() {
return instance;
}
private Socket socket = null;
private DataInputStream din = null;
private DataOutputStream dout = null;
private String userId;
private String password;
private BOKEXAddTelegramManager(){
}
public String doTelegram( String reqData ){
String resData = "";
if ( socket != null){
return "";
}
try {
if ( !connect()) {
return "";
}
din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
// "FOREXFTP2FXB110406000010 N000200902261755301104FTP00000000000011104FTP@ 0030B0N";
byte[] loginData = "FOREXFTP2FXB113706000010 N000 0030B0N".getBytes();
//
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String curDate = formatter.format(Calendar.getInstance().getTime());
System.arraycopy( curDate.getBytes() , 0, loginData, 30, 14);
System.arraycopy( userId.getBytes() , 0, loginData, 44, userId.getBytes().length);
System.arraycopy( password.getBytes() , 0, loginData, 64, password.getBytes().length);
String loginResult = getRecvData( new String(loginData) );
if ( !loginResult.substring(27,30).equals("000") ){
return loginResult;
}
resData = getRecvData(reqData);
// "FOREXFTP2FXB110406000040 N00020090226175530";
byte[] looutData = "FOREXFTP2FXB113706000040 N000 ".getBytes();
System.arraycopy( curDate.getBytes() , 0, looutData, 30, 14);
getRecvData(new String (looutData));
} catch (Exception e) {
logger.error( e.getMessage(), e);
} finally {
if ( socket != null ){
try {
socket.close();
} catch (Exception e) {}
}
socket = null;
}
return resData;
}
private String getRecvData( String sendData ){
String recvData = null;
try {
int sendLen = sendData.getBytes().length;
byte[] sendBuf = new byte[sendLen + 4];
System.arraycopy( ( ""+(sendLen + 10000)).getBytes(), 1, sendBuf, 0, 4 );
System.arraycopy( sendData.getBytes(), 0, sendBuf, 4, sendLen);
dout.write(sendBuf);
byte[] recvBuf = new byte[4096];
ByteArrayOutputStream boutll = new ByteArrayOutputStream();
ArrayList<String> al = new ArrayList<String>();
boolean contFlag = false;
do {
// LL 필드 수신
int nRemainBytes = 4;
while (nRemainBytes > 0) {
int nReadBytes = recvData(din, 60, recvBuf, nRemainBytes); //한번에 필드 길이만큼 읽지 않을수도 있음
boutll.write(recvBuf, 0, nReadBytes);
nRemainBytes -= nReadBytes;
}
String strll = new String(boutll.toByteArray());
nRemainBytes = Integer.parseInt(strll);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
while (nRemainBytes > 0) {
int nReadBytes = recvData(din, 60, recvBuf, nRemainBytes); //한번에 필드 길이만큼 읽지 않을수도 있음
bout.write(recvBuf, 0, nReadBytes);
nRemainBytes -= nReadBytes;
}
String resTelegram = new String(bout.toByteArray());
al.add(resTelegram);
String resTelegramType = getTelegramType(resTelegram);
if ( resTelegramType.equals("02100010")){
if (resTelegram.substring(50,51).equals("Y") ){
contFlag = true;
}else{
contFlag = false;
}
if ( recvData != null ){
recvData = recvData + resTelegram.substring(51);
}else{
recvData = resTelegram;
}
}else if ( resTelegramType.equals("02100020")){
if (resTelegram.substring(42,43).equals("Y") ){
contFlag = true;
}else{
contFlag = false;
}
if ( recvData != null ){
recvData = recvData + resTelegram.substring(43);
}else{
recvData = resTelegram;
}
}else if ( resTelegramType.equals("02100030")){
if (resTelegram.substring(50,51).equals("Y") ){
contFlag = true;
}else{
contFlag = false;
}
if ( recvData != null ){
recvData = recvData + resTelegram.substring(51);
}else{
recvData = resTelegram;
}
} else {
recvData = resTelegram;
}
} while (contFlag);
} catch (Exception e) {
logger.error( e.getMessage(), e);
return "";
}
return recvData;
}
private boolean connect() throws Exception{
DemandTargetVO vo = getSysConnList();
if ( vo == null ){
return false;
}
userId = vo.getSocketID();
password = vo.getSocketPwd();
int nPortNum = -1;
try {
nPortNum = Integer.parseInt(vo.getPortNumber());
} catch (Exception ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJC002", new String[] {vo.getPortNumber()});
throw new Exception(errMsg);
}
socket = socketInit(vo.getIpAddress(), nPortNum);
if (socket == null) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJC003");
throw new Exception(errMsg);
}
return true;
}
private String getTelegramType(String str){
byte[] telegramType = new byte[8];
System.arraycopy( str.getBytes(), 16, telegramType, 0, 8);
return new String(telegramType);
}
private Socket socketInit(String remoteIP, int remotePort) throws Exception
{
try {
return new Socket(remoteIP, remotePort);
} catch (UnknownHostException ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC001", new String[] {remoteIP, Integer.toString(remotePort)});
throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), 서버를 찾을 수 없습니다.
} catch (Exception ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC002", new String[] {remoteIP, Integer.toString(remotePort)});
throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), I/O Exception이 발생했습니다.
}
}
private DemandTargetVO getSysConnList() {
DemandTargetVO dtVO = null;
try {
//1. 해당 작업의 대외기관 연결정보 조회
DemandTargetVO[] sysConnList = FlowControllerManager.getInstance().getRemoteHostInfo(BOKEXKeys.PROC_CODE, BOKEXKeys.INSTI_CODE);
if (sysConnList == null || sysConnList.length == 0) {
logger.info("[BOKEXAddTelegramManager:checkSysConnList]["+ BOKEXKeys.PROC_CODE +" | "+ BOKEXKeys.INSTI_CODE +"] ==> 해당 작업의 요구송수신 연결정보가 존재하지 않음 !! ★★ 연결정보 체크 필요 ★★");
return null;
}
//1. Job_Processing 테이블에서 모든 연결정보ID 조회
SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class);
HashSet<String> runsysConnList = dao.getExecutingSysConnList();
for (int inx=0; inx < sysConnList.length; inx++) {
//대외기관 연결상태가 장애이면 다음 연결정보 조회
if (sysConnList[inx].getOrganSocketStatus().equals(DemandTargetVO.ORGAN_SOCKET_STATUS_ERROR)) {
continue;
}
//해당 연결정보가 사용중이지 않으면 해당 연결정보 할당
if (!runsysConnList.contains(sysConnList[inx].getSystemConnCode())) {
dtVO = sysConnList[inx];
break;
}
}
if ( dtVO == null ) {
logger.info("[BOKEXAddTelegramManager:checkSysConnList]["+ BOKEXKeys.PROC_CODE +" | "+ BOKEXKeys.INSTI_CODE +"]★★★ ==> 해당 작업의 연결정보가 모두 사용중 임 !! -> 다음 Timer Event 시 연결정보 Release 된 경우 수행됨.");
return null;
}
} catch (Exception e) {
logger.warn( "진행작업 조회 중 오류 발생");
return null;
}
return dtVO;
}
private int recvData(DataInputStream din, int timeoutMilisec, byte[] buffer, int len) throws Exception
{
if (buffer == null || buffer.length == 0) throw new Exception("");
int readBytes = 0;
int timoutCount = 0;
while (true) {
try {
readBytes = din.read(buffer, 0, len);
if (readBytes < 0) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJM010");
throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다.
}
return readBytes; //socket 에서 읽어들인 byte 수 리턴 (1 이상)
} catch (SocketTimeoutException ex) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJM008", new String[] { timoutCount+"", (timeoutMilisec/1000)+"" });
throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Timeout 이 발생하였습니다 (읽어들인 데이터 없음). 해당 대외기관에 연락바랍니다. [Timeout회수:{1}, soTimeout:{2}초]
} catch (Exception ex) { //throws IOException, NullPointerException, IndexOutOfBoundsException
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJM011");
throw new Exception(errMsg); //대외기관으로부터 전문 수신 시 Socket 오류가 발생하여 데이터를 읽어들일 수 없습니다.
}
}
}
}
@@ -0,0 +1,14 @@
package com.eactive.eai.batch.bokex;
/**
* 1. 기능 : 한국은행 외환망 부가전문 용 패키지에서 사용하는 상수를 정의한 Interface
* 2. 처리 개요 :
* - 한국은행 외환망 부가전문 용 패키지에서 사용하는 상수를 정의한 Interface
* 3. 주의사항
*
*/
public class BOKEXKeys
{
public static final String PROC_CODE = "FNF00";
public static final String INSTI_CODE = "BOK1";
}
@@ -0,0 +1,85 @@
package com.eactive.eai.batch.code;
import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import java.sql.ResultSet;
import java.util.HashMap;
/**
* 1. 기능 : 각종 메시지를 코드로 관리하기 위한 Rule 정보 테이블에 대한 Data Access Object 클래스
* 2. 처리 개요 : 각종 메시지를 코드로 관리하기 위한 Rulw 정보에 대한 DB 로직을 처리한다.
* * -
* 3. 주의사항
*
* @author :
* @version : v 1.0.0
* @see : 관련 기능을 참조
* @since :
*/
public class CodeMessageDAO extends BaseDAO implements CodeMessageQuery
{
/**
* 1. 기능 : 메시지/코드 Rule 정보 전체를 SELECT하는 메서드
* 2. 처리 개요 : 메시지/코드 Rule 정보 전체를 SELECT 한다.
* -
* 3. 주의사항
*
* @return 코드, 메시지를 저장하고 있는 Properties 객체
* @exception DAOException JDBC 관련 오류(SQLException)
**/
public HashMap<String, CodeMessageVO> getAllMessages() throws DAOException {
HashMap<String, CodeMessageVO> allMsg = new HashMap<String, CodeMessageVO>();
ResultSet rs = null;
CodeMessageVO cmv = null;
try {
this.connect(GET_ALL_MESSAGES);
rs = executeQuery();
while(rs.next()) {
cmv = new CodeMessageVO();
cmv.setMsgKey (rs.getString("Msg" ));
cmv.setMsgTxt (rs.getString("MsgCtnt" ));
cmv.setMsgEtc (rs.getString("TreatMatrCtnt" ));
cmv.setSmsSendType (rs.getString("SMSSendYn" ));
cmv.setItsmObstclGrdDstcd(rs.getString("ITSMObstclGrdDstcd" ));
allMsg.put(cmv.getMsgKey(), cmv);
}
return allMsg;
} catch(Exception e) {
throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMCD101"));
} finally {
disconnect();
}
}
/**
* 지정된 메시지코드를 가지는 코드메시지 레코드를 읽어서 리턴한다.
*/
public CodeMessageVO getOneCodeMessage(String msg) throws DAOException {
ResultSet rs = null;
try {
this.connect(GET_ONE_MESSAGE);
this.preparedStatement.setString(1, msg);
rs = this.executeQuery();
CodeMessageVO cmv = null;
while(rs.next()) {
cmv = new CodeMessageVO();
cmv.setMsgKey (rs.getString("Msg" ));
cmv.setMsgTxt (rs.getString("MsgCtnt" ));
cmv.setMsgEtc (rs.getString("TreatMatrCtnt" ));
cmv.setSmsSendType (rs.getString("SMSSendYn" ));
cmv.setItsmObstclGrdDstcd(rs.getString("ITSMObstclGrdDstcd" ));
}
return (cmv);
} catch(Exception e) {
//ExceptionUtil.getErrorCode() 사용 불가 (무한 LOOP 발생)
throw new DAOException( "코드 [" + msg + "] 의 레코드를 TSEAIBP05 테이블 에서 찾을 수 없습니다." );
} finally {
this.disconnect();
}
}
}
@@ -0,0 +1,81 @@
package com.eactive.eai.batch.code;
/**
* 1. 기능 : 메시지 코드 Rule 정보에 대한 Utility 기능을 제공하는 클래스
* 2. 처리 개요 : 코드에 대한 메시지를 얻거나 생성한다.
* * -
* 3. 주의사항
*
* @author :
* @version : v 1.0.0
* @see : 관련 기능을 참조
* @since :
*/
public class CodeMessageHandler
{
/**
* 1. 기능 : Default Constructor
* 2. 처리 개요 : Default Constructor
* -
* 3. 주의사항
*
**/
private CodeMessageHandler() {
}
/**
* 1. 기능 : 코드에 대한 메시지 텍스트를 찾아 반환하는 메서드
* 2. 처리 개요 : 코드에 대한 메시지 텍스트를 찾아 반환한다.
* -
* 3. 주의사항
*
* @param code 메시지 코드
* @return 메시지 텍스트
**/
public static String getMessage(String code) {
return CodeMessageManager.getInstance().getMessage(code);
}
/**
* 1. 기능 : 코드에 대한 메시지 텍스트를 찾아 반환하는 메서드
* 2. 처리 개요 : 코드에 대한 메시지 텍스트를 찾아 반환한다.
* -
* 3. 주의사항
*
* @param code 메시지 코드
* @param args 메시지 텍스트를 만들기 위한 인수 리스트
* @return 메시지 텍스트
**/
public static String getMessage(String code, String[] args) {
String msg = CodeMessageManager.getInstance().getMessage(code);
return makeMessage(msg,args);
}
/**
* 1. 기능 :
* 2. 처리 개요 :
* -
* 3. 주의사항
*
* @param
* @return
* @exception
**/
private 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,293 @@
package com.eactive.eai.batch.code;
import java.util.HashMap;
import java.util.Iterator;
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;
/**
* 1. 기능 : 코드, 텍스트 Rule 정보를 DB로 부터 로딩해 메모리에 관리하는 Manager 클래스
* 2. 처리 개요 : DB Rule 정보에 저장된코드, 텍스트 Rule 정보를 메모리에 로딩 관리한다.
* * -
* 3. 주의사항
*/
public class CodeMessageManager implements Lifecycle
{
/**
* CodeMessageManager Singleton Instance
*/
private static CodeMessageManager instance = new CodeMessageManager();
/**
* CodeMessage Rule 정보를 저장하기 위한 HashMap
*/
private HashMap<String, CodeMessageVO> messages;
/**
* LifeccyleSupport object
*/
private LifecycleSupport lifecycle = new LifecycleSupport(this);
/**
* 기동 여부
*/
private boolean started;
/**
* 1. 기능 : Default Constructor
* 2. 처리 개요 : messages를 저장하기 위한 HashMap을 초기화한다.
* -
* 3. 주의사항
*
**/
private CodeMessageManager() {
messages = new HashMap<String, CodeMessageVO>();
}
/**
* 1. 기능 : CodeMessageManager Singleton Object를 반환하는 getter method
* 2. 처리 개요 : CodeMessageManager Singleton Object를 반환한다.
* -
* 3. 주의사항
*
* @return CodeMessageManager
**/
public static CodeMessageManager getInstance() {
return instance;
}
/**
* 1. 기능 : Lifecycle의 start 메서드로 CodeMessageManager를 초기화하는 메서드
* 2. 처리 개요 : CodeMessageDAO를 이용해 추출 Rule 정보 모두를 가져와 초기화한다.
* -
* 3. 주의사항
*
* @exception LifecycleException
**/
public void start() throws LifecycleException {
if (started)
throw new LifecycleException("BECEAIMCD201");
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
messages = null;
CodeMessageDAO dao = null;
try {
dao = (CodeMessageDAO)DAOFactory.newInstance().create(CodeMessageDAO.class);
messages = dao.getAllMessages();
} catch(DAOException e) {
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "BECEAIMCD202"));
}
started = true;
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
}
/**
* 1. 기능 : Lifecycle의 stop 메서드로 CodeMessageManager를 종료하는 메서드
* 2. 처리 개요 : 멤버에 캐싱항 코드, 텍스트 Rule 정보를 clear한다.
* -
* 3. 주의사항
*
* @exception LifecycleException
**/
public void stop() throws LifecycleException {
// Validate and update our current component state
if (!started)
throw new LifecycleException("BECEAIMCD203");
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
messages.clear();
started = 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);
}
/**
* 1. 기능 : BizKeyManager의 초기화 여부를 반환하는 getter 메서드
* 2. 처리 개요 : BizKeyManager의 초기화 여부를 반환한다.
* 3. 주의사항
*
* @return 초기화 여부
**/
public boolean isStarted() {
return this.started;
}
/**
* 1. 기능 : 코드에 대한 메시지 텍스트를 반환하는 메서드
* 2. 처리 개요 : 파라미터 코드에 대한 메시지 텍스트를 찾아 반환한다.
* -
* 3. 주의사항
*
* @param code 메시지 코드
* @return 메시지 텍스트
**/
public String getMessage(String code) {
if(code==null) return null;
//String msg = (String)messages.get(code);
if (messages == null || messages.size() == 0) {
CodeMessageDAO dao = null;
try {
dao = (CodeMessageDAO)DAOFactory.newInstance().create(CodeMessageDAO.class);
CodeMessageVO codeInfo = dao.getOneCodeMessage(code);
if (codeInfo==null) return "UNDEFINE";
String msg = codeInfo.getMsgTxt();
return (msg==null) ? "UNDEFINE" : msg;
} catch(DAOException e) {
return "The CodeMessage["+code+"] is not defiend.";
}
} else {
CodeMessageVO vo = (CodeMessageVO)messages.get(code);
if(vo==null) return "The CodeMessage["+code+"] is not defiend.";
String msg = vo.getMsgTxt();
return (msg==null) ? "UNDEFINE" : msg;
}
}
/**
* 1. 기능 : 코드에 대한 메시지 내용과 조치사항내용을 반환하는 메서드
* 2. 처리 개요 : 파라미터 코드에 대한 메시지 내용과 조치사항내용을 찾아 반환한다.
* -
* 3. 주의사항
*
* @param code 메시지 코드
* @return 메시지 Value Object
**/
public CodeMessageVO getMessageVO(String code) {
if(code==null) return null;
CodeMessageVO cmv = null;
if (messages == null || messages.size() == 0) {
CodeMessageDAO dao = null;
try {
dao = (CodeMessageDAO)DAOFactory.newInstance().create(CodeMessageDAO.class);
cmv = dao.getOneCodeMessage(code);
} catch(DAOException e) {
cmv = null;
}
} else {
cmv = (CodeMessageVO)messages.get( code );
}
return cmv;
}
/**
* 1. 기능 : 메시지, 메시지 내용, 조치사항내용을 저장/변경하는 메서드
* 2. 처리 개요 : 메시지에 대한 텍스트를 변경하거나 저장한다.
* -
* 3. 주의사항
*
* @param code 메시지 코드
* @param msg 메시지 텍스트
**/
public void setMessage(CodeMessageVO cmm) {
messages.put(cmm.getMsgKey(), cmm);
}
/**
* 1. 기능 : 코드 메시지 Rule 정보를 삭제하는 메서드.
* 2. 처리 개요 : 파라미터의 메시지 코드에 대한 Rule 정보를 삭제한다.
* -
* 3. 주의사항
*
* @param code 메시지 코드
**/
public void removeMessage(String code) {
messages.remove(code);
}
/**
* 1. 기능 : 코드 리스트를 반환하는 메서드
* 2. 처리 개요 : 코드 리스트를 반환한다.
* -
* 3. 주의사항
*
* @return 코드 리스트
**/
public String[] getAllCodes() {
String[] codes = new String[messages.size()];
Iterator<String> it = messages.keySet().iterator();
for(int i=0;it.hasNext();i++) {
codes[i] = it.next();
}
return codes;
}
/**
* 1. 기능 : 전체 코드메시지 리스트를 Properties 로 반환하는 메서드
* 2. 처리 개요 : 전체 코드메시지 리스틀 Properties로 반환한다.
* -
* 3. 주의사항
*
* @return 전체 코드 메시지 리스트를 저장하고 있는 Properties
**/
public HashMap<String, CodeMessageVO> getAllCodeMessages() {
return this.messages;
}
public synchronized void reload(String key) throws Exception {
CodeMessageDAO dao = (CodeMessageDAO)DAOFactory.newInstance().create(CodeMessageDAO.class);
CodeMessageVO vo = dao.getOneCodeMessage(key);
if(vo != null) {
this.messages.put(key, vo);
}
else {
throw new Exception("CodeMessageManager not found in Database : key["+key+"]");
}
}
}
@@ -0,0 +1,39 @@
package com.eactive.eai.batch.code;
import com.eactive.eai.common.dao.Keys;
/**
* 1. 기능 : CodeMessageDAO에서 사용하는 SQL Query를 정의한 상수 인터페이스
* 2. 처리 개요 : CodeMessageDAO에서 사용하는 SQL Query를 정의한다.
* * -
* 3. 주의사항
*
* @author :
* @version : v 1.0.0
* @see : 관련 기능을 참조
* @since :
*/
public interface CodeMessageQuery
{
/**
* 코드, 텍스트 Rule 정보 전체를 SELECT하는 SQL Query
*/
public static final String GET_ALL_MESSAGES = "SELECT Msg ,\n" +
" MsgCtnt ,\n" +
" TreatMatrCtnt ,\n" +
" SMSSendYn ,\n" +
" ITSMObstclGrdDstcd\n" +
"FROM " + Keys.TABLE_OWNER + "TSEAIBP05";
/**
* 특정 코드메시지 레코드를 읽어낸다.
*/
public static final String GET_ONE_MESSAGE = "SELECT Msg ,\n" +
" MsgCtnt ,\n" +
" TreatMatrCtnt ,\n" +
" SMSSendYn ,\n" +
" ITSMObstclGrdDstcd\n" +
"FROM " + Keys.TABLE_OWNER + "TSEAIBP05\n" +
"WHERE Msg = ?";
}
@@ -0,0 +1,78 @@
package com.eactive.eai.batch.code;
import com.eactive.eai.common.util.NullControl;
import java.io.Serializable;
public class CodeMessageVO implements Serializable
{
@Override
public String toString() {
return "CodeMessageVO [msgKey=" + msgKey + ", msgTxt=" + msgTxt
+ ", msgEtc=" + msgEtc + ", smsSendType=" + smsSendType
+ ", itsmObstclGrdDstcd=" + itsmObstclGrdDstcd + "]";
}
/**
*
*/
private static final long serialVersionUID = 1L;
private String msgKey; // 메시지ID
private String msgTxt; // 메시지내용
private String msgEtc; // 조치사항내용 --> SMS발송 시 사용 문구
private String smsSendType = "";// SMS발송 여부
private String itsmObstclGrdDstcd = "";// ITSM장애등급구분코드
public CodeMessageVO() {
this("");
}
public CodeMessageVO(String msgKey) {
this(msgKey, "");
}
public CodeMessageVO(String msgKey, String msgTxt) {
this.msgKey = msgKey;
this.msgTxt = msgTxt;
}
public void setMsgKey(String msgKey) {
this.msgKey = msgKey;
}
public String getMsgKey() {
return this.msgKey;
}
public void setMsgTxt(String msgTxt) {
this.msgTxt = msgTxt;
}
public String getMsgTxt() {
return this.msgTxt;
}
public void setMsgEtc(String msgEtc) {
this.msgEtc = msgEtc;
}
public String getMsgEtc() {
return NullControl.trimSpace(this.msgEtc);
}
public void setSmsSendType(String arg) {
this.smsSendType = arg;
}
public String getSmsSendType() {
return this.smsSendType;
}
public String getItsmObstclGrdDstcd() {
return itsmObstclGrdDstcd;
}
public void setItsmObstclGrdDstcd(String itsmObstclGrdDstcd) {
this.itsmObstclGrdDstcd = itsmObstclGrdDstcd;
}
}
@@ -0,0 +1,140 @@
//package com.eactive.eai.batch.common;
//
//import com.eactive.eai.common.dao.DAOFactory;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.util.ArrayList;
//
//public class BatchDirMakeUtil
//{
//
// //파일로거
// private static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_DEFAULT);
//
// private static String[] batchDirs;
//
// private static void setBatchDirs() throws Exception {
// BatchDirDAO dao = (BatchDirDAO)DAOFactory.newInstance().create(BatchDirDAO.class);
// ArrayList<String> aList = dao.getBatchDirList();
// batchDirs = new String[aList.size()];
// aList.toArray(batchDirs);
// }
//
// private static void makeDirBatch(String dirSuffix, boolean makeParent) throws Exception {
// int successCnt = 0;
// for (int i=0; i<batchDirs.length; i++) {
// if ( FileUtil.mkdir(batchDirs[i] +"/"+ dirSuffix, makeParent) ) successCnt++;
// }
// if (successCnt < batchDirs.length) throw new Exception("★★★★★ 배치 송수신 디렉토리 생성 실패 !! ★★★★★ ( 총 "+ batchDirs.length +" 개 중 "+ successCnt +" 개 생성됨 )");
// }
//
// private static void removeDirBatch(String dirSuffix, boolean removeChild) throws Exception {
// int successCnt = 0;
// for (int i=0; i<batchDirs.length; i++) {
// if ( FileUtil.rmdir(batchDirs[i] +"/"+ dirSuffix, removeChild) ) successCnt++;
// }
// if (successCnt < batchDirs.length) throw new Exception("★★★★★ 배치 송수신 디렉토리 삭제 실패 !! ★★★★★ ( 총 "+ batchDirs.length +" 개 중 "+ successCnt +" 개 삭제됨 )");
// }
//
// private static void renameDirBatch(String fromDirSuffix, String toDirSuffix, boolean makeDestDir) throws Exception {
// int successCnt = 0;
// for (int i=0; i<batchDirs.length; i++) {
// if ( FileUtil.move(batchDirs[i] +"/"+ fromDirSuffix, batchDirs[i] +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// }
// if (successCnt < batchDirs.length) throw new Exception("★★★★★ 배치 송수신 디렉토리명 변경 실패 !! ★★★★★ ( 총 "+ batchDirs.length +" 개 중 "+ successCnt +" 개 변경됨 )");
// }
//
// //==================================================================================================================
// public static void makeDirProcess(String processName, String processCode) throws Exception {
// logger.debug("■ 업무구분 디렉토리 생성 Start......");
// setBatchDirs();
// makeDirBatch(processName +"_"+ processCode, true); //true : 상위 디렉토리 미존재시 자동 생성함
// }
//
// public static void removeDirProcess(String processName, String processCode) throws Exception {
// logger.debug("■ 업무구분 디렉토리 삭제 Start......");
// setBatchDirs();
// removeDirBatch(processName +"_"+ processCode, false); //false : 하위 디렉토리 및 내용이 있으면 삭제 안함
// }
//
// public static void renameDirProcess(String fromProcessName, String fromProcessCode, String toProcessName, String toProcessCode) throws Exception {
// logger.debug("■ 업무구분 디렉토리명 변경 Start......");
// setBatchDirs();
// renameDirBatch(fromProcessName +"_"+ fromProcessCode, toProcessName +"_"+ toProcessCode, false); //false: 목적 경로 미존재시 생성 안함
// }
//
//
// //==================================================================================================================
// public static void makeDirOrgan(String processName, String processCode, String organName, String organCode) throws Exception {
// logger.debug("■ 대외기관 디렉토리 생성 Start......");
// setBatchDirs();
// makeDirBatch(processName +"_"+ processCode +"/"+ organName +"_"+ organCode, true); //true : 상위 디렉토리 미존재시 자동 생성함
//
// //생성된 대외기관 디렉토리 밑에 해당 업무의 전체 거래구분그룹 디렉토리도 함께 생성
// BatchDirDAO dao = (BatchDirDAO)DAOFactory.newInstance().create(BatchDirDAO.class);
// ArrayList<String[]> bizGroupList = dao.getBizGroupList(processCode);
//
// for (int i=0; i<bizGroupList.size(); i++) {
// String[] bizGroupInfo = (String[])bizGroupList.get(i); //0:거래구분그룹명, 1:거래구분그룹코드
// makeDirBatch(processName +"_"+ processCode +"/"+ organName +"_"+ organCode +"/"+ bizGroupInfo[0] +"_"+ bizGroupInfo[1], true); //true : 상위 디렉토리 미존재시 자동 생성함
// }
// }
//
// public static void removeDirOrgan(String processName, String processCode, String organName, String organCode) throws Exception {
// logger.debug("■ 대외기관 디렉토리 삭제 Start......");
// setBatchDirs();
// removeDirBatch(processName +"_"+ processCode +"/"+ organName +"_"+ organCode, false); //false : 하위 디렉토리 및 내용이 있으면 삭제 안함
// }
//
// public static void renameDirOrgan(String processName, String processCode, String fromOrganName, String fromOrganCode, String toOrganName, String toOrganCode) throws Exception {
// logger.debug("■ 대외기관 디렉토리명 변경 Start......");
// setBatchDirs();
// renameDirBatch(processName +"_"+ processCode +"/"+ fromOrganName +"_"+ fromOrganCode,
// processName +"_"+ processCode +"/"+ toOrganName +"_"+ toOrganCode, false); //false: 목적 경로 미존재시 생성 안함
// }
//
// //==================================================================================================================
// public static void makeDirBizGroup(String processName, String processCode, String bizGroupName, String bizGroupCode) throws Exception {
// logger.debug("■ 거래구분그룹 디렉토리 생성 Start......");
// setBatchDirs();
//
// //해당 업무의 모든 대외기관 디렉토리 밑에 거래구분그룹 디렉토리 생성
// BatchDirDAO dao = (BatchDirDAO)DAOFactory.newInstance().create(BatchDirDAO.class);
// ArrayList<String[]> organList = dao.getOrganList(processCode);
//
// for (int i=0; i<organList.size(); i++) {
// String[] organInfo = (String[])organList.get(i); //0:대외기관명, 1:대외기관코드
// makeDirBatch(processName +"_"+ processCode +"/"+ organInfo[0] +"_"+ organInfo[1] +"/"+ bizGroupName +"_"+ bizGroupCode, true); //true : 상위 디렉토리 미존재시 자동 생성함
// }
// }
//
// public static void removeDirBizGroup(String processName, String processCode, String bizGroupName, String bizGroupCode) throws Exception {
// logger.debug("■ 거래구분그룹 디렉토리 삭제 Start......");
// setBatchDirs();
//
// //해당 업무의 모든 대외기관 디렉토리 밑에 있는 거래구분그룹 디렉토리 삭제
// BatchDirDAO dao = (BatchDirDAO)DAOFactory.newInstance().create(BatchDirDAO.class);
// ArrayList<String[]> organList = dao.getOrganList(processCode);
//
// for (int i=0; i<organList.size(); i++) {
// String[] organInfo = (String[])organList.get(i); //0:대외기관명, 1:대외기관코드
// removeDirBatch(processName +"_"+ processCode +"/"+ organInfo[0] +"_"+ organInfo[1] +"/"+ bizGroupName +"_"+ bizGroupCode, false); //false : 하위 디렉토리 및 내용이 있으면 삭제 안함
// }
// }
//
// public static void renameDirBizGroup(String processName, String processCode, String fromBizGroupName, String fromBizGroupCode, String toBizGroupName, String toBizGroupCode) throws Exception {
// logger.debug("■ 거래구분그룹 디렉토리명 변경 Start......");
// setBatchDirs();
//
// //해당 업무의 모든 대외기관 디렉토리 밑에 있는 거래구분그룹 디렉토리명 변경
// BatchDirDAO dao = (BatchDirDAO)DAOFactory.newInstance().create(BatchDirDAO.class);
// ArrayList<String[]> organList = dao.getOrganList(processCode);
//
// for (int i=0; i<organList.size(); i++) {
// String[] organInfo = (String[])organList.get(i); //0:대외기관명, 1:대외기관코드
// renameDirBatch(processName +"_"+ processCode +"/"+ organInfo[0] +"_"+ organInfo[1] +"/"+ fromBizGroupName +"_"+ fromBizGroupCode,
// processName +"_"+ processCode +"/"+ organInfo[0] +"_"+ organInfo[1] +"/"+ toBizGroupName +"_"+ toBizGroupCode, false); //false: 목적 경로 미존재시 생성 안함
// }
// }
//}
@@ -0,0 +1,315 @@
package com.eactive.eai.batch.common;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.Logger;
public class BatchDirUtil
{
//파일로거
private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private static void makeDirBatch(String dirSuffix, boolean makeParent) throws Exception {
int successCnt = 0;
// if ( FileUtil.mkdir(getRequestRealDir() +"/"+ dirSuffix, makeParent) ) successCnt++;
// if ( FileUtil.mkdir(getRequestRootDir() +"/"+ dirSuffix, makeParent) ) successCnt++;
if ( FileUtil.mkdir(getRequestArchDir() +"/"+ dirSuffix, makeParent) ) successCnt++; //송신ARCH - /fepftp/fep/batch/SENDARCH
if ( FileUtil.mkdir(getRequestErrorDir() +"/"+ dirSuffix, makeParent) ) successCnt++; //송신ERROR - /fepftp/fep/batch/SENDERROR
if ( FileUtil.mkdir(getRequestRootDir() +"/"+ dirSuffix, makeParent) ) successCnt++; //송신 - /fepftp/fep/batch/snd
if ( FileUtil.mkdir(getResponseRealDir() +"/"+ dirSuffix, makeParent) ) successCnt++; //수신REAL - /fepftp/fep/batch/RECVREAL
if ( FileUtil.mkdir(getResponseRootDir() +"/"+ dirSuffix, makeParent) ) successCnt++; //수신ROOT - /fepftp/fep/batch/RECVROOT
if ( FileUtil.mkdir(getResponseArchDir() +"/"+ dirSuffix, makeParent) ) successCnt++; //수신ARCH - /fepftp/fep/batch/RECVARCH
if ( FileUtil.mkdir(getResponseErrorDir() +"/"+ dirSuffix, makeParent) ) successCnt++; //수신ERROR - /fepftp/fep/batch/RECVERROR
// if ( FileUtil.mkdir(getResponseNasDir() +"/"+ dirSuffix, makeParent) ) successCnt++;
// if ( FileUtil.mkdir(getResponseChkDir() +"/"+ dirSuffix, makeParent) ) successCnt++;
// if ( FileUtil.mkdir(getResSendRealDir() +"/"+ dirSuffix, makeParent) ) successCnt++; //
// if ( FileUtil.mkdir(getResSendArchDir() +"/"+ dirSuffix, makeParent) ) successCnt++;
// add by dhjeong at 2009.09.21
if ( FileUtil.mkdir(getReqRecvRootDir() +"/"+ dirSuffix, makeParent) ) successCnt++; //요구수신ROOT - /fepftp/fep/batch/REQROOT
if ( FileUtil.mkdir(getReqRecvErrorDir() +"/"+ dirSuffix, makeParent) ) successCnt++; //요구수신ERROR - /fepftp/fep/batch/REQERROR
if (successCnt < 8) logger.error("★★★★★ 배치 송수신 디렉토리 생성 실패 !! ★★★★★ ( 총 8 개 중 "+ successCnt +" 개 생성됨 )");
}
private static void removeDirBatch(String dirSuffix, boolean removeChild) throws Exception {
int successCnt = 0;
// if ( FileUtil.rmdir(getRequestRealDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
// if ( FileUtil.rmdir(getRequestRootDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
if ( FileUtil.rmdir(getRequestArchDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
if ( FileUtil.rmdir(getRequestErrorDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
if ( FileUtil.rmdir(getRequestRootDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
if ( FileUtil.rmdir(getResponseRealDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
if ( FileUtil.rmdir(getResponseRootDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
if ( FileUtil.rmdir(getResponseArchDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
if ( FileUtil.rmdir(getResponseErrorDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
// if ( FileUtil.rmdir(getResponseNasDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
// if ( FileUtil.rmdir(getResponseChkDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
// if ( FileUtil.rmdir(getResSendRealDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
// if ( FileUtil.rmdir(getResSendArchDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
// add by dhjeong at 2009.09.21
if ( FileUtil.rmdir(getReqRecvRootDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
if ( FileUtil.rmdir(getReqRecvErrorDir() +"/"+ dirSuffix, removeChild) ) successCnt++;
if (successCnt < 8) logger.error("★★★★★ 배치 송수신 디렉토리 삭제 실패 !! ★★★★★ ( 총 8 개 중 "+ successCnt +" 개 삭제됨 )");
}
// private static void renameDirBatch(String fromDirSuffix, String toDirSuffix, boolean makeDestDir) throws Exception {
// int successCnt = 0;
// if ( FileUtil.move(getRequestRealDir() +"/"+ fromDirSuffix, getRequestRealDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getRequestRootDir() +"/"+ fromDirSuffix, getRequestRootDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getRequestArchDir() +"/"+ fromDirSuffix, getRequestArchDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getRequestErrorDir() +"/"+ fromDirSuffix, getRequestErrorDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getResponseRealDir() +"/"+ fromDirSuffix, getResponseRealDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getResponseRootDir() +"/"+ fromDirSuffix, getResponseRootDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getResponseArchDir() +"/"+ fromDirSuffix, getResponseArchDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getResponseErrorDir() +"/"+ fromDirSuffix, getResponseErrorDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getResponseNasDir() +"/"+ fromDirSuffix, getResponseNasDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getResponseChkDir() +"/"+ fromDirSuffix, getResponseChkDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getResSendRealDir() +"/"+ fromDirSuffix, getResSendRealDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getResSendArchDir() +"/"+ fromDirSuffix, getResSendArchDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//
// // add by dhjeong at 2009.09.21
// if ( FileUtil.move(getReqRecvRootDir() +"/"+ fromDirSuffix, getReqRecvRootDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
// if ( FileUtil.move(getReqRecvErrorDir() +"/"+ fromDirSuffix, getReqRecvErrorDir() +"/"+ toDirSuffix, makeDestDir) ) successCnt++;
//
// if (successCnt < 14) logger.error("★★★★★ 배치 송수신 디렉토리명 변경 실패 !! ★★★★★ ( 총 14 개 중 "+ successCnt +" 개 변경됨 )");
// }
//==================================================================================================================
public static void makeDirProcess( String processCode ) throws Exception {
logger.debug("■ 업무구분 디렉토리 생성 Start......");
makeDirBatch(processCode, true); //true : 상위 디렉토리 미존재시 자동 생성함
}
public static void removeDirProcess(String processCode) throws Exception {
logger.debug("■ 업무구분 디렉토리 삭제 Start......");
removeDirBatch(processCode, false); //false : 하위 디렉토리 및 내용이 있으면 삭제 안함
}
// public static void renameDirProcess(String fromProcessCode, String toProcessCode) throws Exception {
// logger.debug("■ 업무구분 디렉토리명 변경 Start......");
// renameDirBatch(fromProcessCode, toProcessCode, false); //false: 목적 경로 미존재시 생성 안함
// }
//==================================================================================================================
public static void makeDirOrgan(String processCode, String organCode) throws Exception {
logger.debug("■ 대외기관 디렉토리 생성 Start......");
makeDirBatch(processCode +"/"+ organCode, true); //true : 상위 디렉토리 미존재시 자동 생성함
// //생성된 대외기관 디렉토리 밑에 해당 업무의 전체 거래구분그룹 디렉토리도 함께 생성
// ArrayList<DirInfoVO> bizGroupList = DirInfoManager.getInstance().getDirInfoByBatchCode(processCode);
// for (int i=0; i<bizGroupList.size(); i++) {
// DirInfoVO info = bizGroupList.get(i);
// makeDirBatch(processCode +"/"+ organCode +"/"+ info.getBizGroupCd(), true); //true : 상위 디렉토리 미존재시 자동 생성함
// }
}
public static void removeDirOrgan(String processCode, String organCode) throws Exception {
logger.debug("■ 대외기관 디렉토리 삭제 Start......");
removeDirBatch(processCode +"/"+ organCode, false); //false : 하위 디렉토리 및 내용이 있으면 삭제 안함
}
// public static void renameDirOrgan(String processCode, String fromOrganCode, String toOrganCode) throws Exception {
// logger.debug("■ 대외기관 디렉토리명 변경 Start......");
// renameDirBatch(processCode +"/"+ fromOrganCode, processCode +"/"+ toOrganCode, false); //false: 목적 경로 미존재시 생성 안함
// }
//==================================================================================================================
// public static void makeDirBizGroup(String processCode, String bizGroupCode) throws Exception {
// logger.debug("■ 거래구분그룹 디렉토리 생성 Start......");
// //해당 업무의 모든 대외기관 디렉토리 밑에 거래구분그룹 디렉토리 생성
// ArrayList<OutsideVO> organList = OutsideManager.getInstance().getOutsideInfo(processCode);
// for (int i=0; i<organList.size(); i++) {
// OutsideVO info = organList.get(i);
// makeDirBatch(processCode +"/"+ info.getOsdCode() +"/"+ bizGroupCode, true); //true : 상위 디렉토리 미존재시 자동 생성함
// }
// }
// public static void removeDirBizGroup(String processName, String processCode, String bizGroupName, String bizGroupCode) throws Exception {
// logger.debug("■ 거래구분그룹 디렉토리 삭제 Start......");
// //해당 업무의 모든 대외기관 디렉토리 밑에 있는 거래구분그룹 디렉토리 삭제
// ArrayList<OutsideVO> organList = OutsideManager.getInstance().getOutsideInfo(processCode);
// for (int i=0; i<organList.size(); i++) {
// OutsideVO info = organList.get(i);
// removeDirBatch(processName +"_"+ processCode +"/"+ info.getOsdName() +"_"+ info.getOsdCode() +"/"+ bizGroupName +"_"+ bizGroupCode, false); //false : 하위 디렉토리 및 내용이 있으면 삭제 안함
// }
// }
// public static void renameDirBizGroup(String processName, String processCode, String fromBizGroupName, String fromBizGroupCode, String toBizGroupName, String toBizGroupCode) throws Exception {
// logger.debug("■ 거래구분그룹 디렉토리명 변경 Start......");
// //해당 업무의 모든 대외기관 디렉토리 밑에 있는 거래구분그룹 디렉토리명 변경
// ArrayList<OutsideVO> organList = OutsideManager.getInstance().getOutsideInfo(processCode);
// for (int i=0; i<organList.size(); i++) {
// OutsideVO info = organList.get(i);
// renameDirBatch(processName +"_"+ processCode +"/"+ info.getOsdName() +"_"+ info.getOsdCode() +"/"+ fromBizGroupName +"_"+ fromBizGroupCode,
// processName +"_"+ processCode +"/"+ info.getOsdName() +"_"+ info.getOsdCode() +"/"+ toBizGroupName +"_"+ toBizGroupCode, false); //false: 목적 경로 미존재시 생성 안함
// }
// }
//요구송신 디렉토리 프라퍼티 키 정보
public static final String REQUEST_SND_DIR_INFO = "FileEventDirInfo";
// public static final String REQUEST_SND_REAL_DIR = "BASE_REAL_DIR";
public static final String REQUEST_SND_ROOT_DIR = "BASE_SEND_DIR";
public static final String REQUEST_SND_ARCH_DIR = "BASE_ARCH_DIR";
public static final String REQUEST_SND_ERROR_DIR = "BASE_ERROR_DIR";
public static final String REQUEST_SND_ROOT_EXT = "snd.root.ext";
//응답수신 디렉토리 프라퍼티 키 정보
public static final String RESPONSE_RCV_DIR_INFO = "ResponseRcvDirInfo";
public static final String RESPONSE_RCV_REAL_DIR = "rcv.real.directory";
public static final String RESPONSE_RCV_ROOT_DIR = "rcv.root.directory";
public static final String RESPONSE_RCV_ARCH_DIR = "rcv.arch.directory";
public static final String RESPONSE_RCV_ERROR_DIR = "rcv.error.directory";
// public static final String RESPONSE_RCV_NAS_DIR = "rcv.nas.directory";
// public static final String RESPONSE_RCV_CHK_DIR = "rcv.chk.directory";
public static final String RESPONSE_RCV_ROOT_EXT = "rcv.root.ext";
// 응답송신용 디렉토리 프라퍼티 키 정보 20060425 add by khs
// public static final String RESPONSE_SND_DIR_INFO = "ResponseSndDirInfo";
// public static final String RESPONSE_SND_REAL_DIR = "snd.real.directory";
// public static final String RESPONSE_SND_ARCH_DIR = "snd.arch.directory";
// // 요구송신 디렉토리 프라퍼티 키 정보 (이벤트 스케줄러의 스케줄 기반 요구송신 디렉토리)
// // add by kscheon at 2008.10.27
// public static final String SCH_REQUEST_SND_DIR_INFO = "SchedulerFileEventDirInfo";
// public static final String SCH_REQUEST_SND_REAL_DIR = "BASE_REAL_DIR";
// public static final String SCH_REQUEST_SND_ROOT_DIR = "BASE_ROOT_DIR";
// public static final String SCH_REQUEST_SND_ARCH_DIR = "BASE_ARCH_DIR";
// public static final String SCH_REQUEST_SND_ERROR_DIR = "BASE_ERROR_DIR";
// 요구수신용 디렉토리 프라퍼티 키 정보 20090921 add by dhjeong
public static final String REQUEST_RCV_DIR_INFO = "RequestRcvDirInfo";
public static final String REQUEST_RCV_ROOT_DIR = "req.root.directory";
public static final String REQUEST_RCV_ERROR_DIR = "req.error.directory";
private static String getBatchDir(String propGroupKey, String propKey) throws Exception {
String batchDir = PropManager.getInstance().getProperty(propGroupKey, propKey);
if (batchDir == null) {
if (propGroupKey.equals(REQUEST_SND_DIR_INFO)) {
// if (propKey.equals(REQUEST_SND_REAL_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"송신", "REAL" })); //배치 {1} {2} 디렉토리 정보를 프라퍼티에서 찾을 수 없습니다.
// else if (propKey.equals(REQUEST_SND_ROOT_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"송신", "ROOT" }));
// else
if (propKey.equals(REQUEST_SND_ARCH_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"송신", "ARCH" }));
else if (propKey.equals(REQUEST_SND_ERROR_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"송신", "ERROR"}));
} else if (propGroupKey.equals(RESPONSE_RCV_DIR_INFO)) {
if (propKey.equals(RESPONSE_RCV_REAL_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "REAL" }));
else if (propKey.equals(RESPONSE_RCV_ROOT_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "ROOT" }));
else if (propKey.equals(RESPONSE_RCV_ARCH_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "ARCH" }));
else if (propKey.equals(RESPONSE_RCV_ERROR_DIR)) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "ERROR"}));
// else if (propKey.equals(RESPONSE_RCV_NAS_DIR)) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "NAS"}));
// else if (propKey.equals(RESPONSE_RCV_CHK_DIR)) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"수신", "CHECK"}));
// } else if (propGroupKey.equals(RESPONSE_SND_DIR_INFO)) {
// if (propKey.equals(RESPONSE_SND_REAL_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"응답송신", "REAL" }));
// else if (propKey.equals(RESPONSE_SND_ARCH_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"응답송신", "ARCH" }));
}
//add by dhjeong at 2009.09.21
else if (propGroupKey.equals(REQUEST_RCV_DIR_INFO)) {
if (propKey.equals(REQUEST_RCV_ROOT_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"요구수신", "ROOT" })); //배치 {1} {2} 디렉토리 정보를 프라퍼티에서 찾을 수 없습니다.
else if (propKey.equals(REQUEST_RCV_ERROR_DIR )) throw new Exception(ExceptionUtil.getErrorCode("BECEAICUT009", new String[] {"요구수신", "ERROR" }));
}
}
//디렉토리 맨끝에 "/" 가 있으면 빼고 리턴
return batchDir.endsWith("/")? batchDir.substring(0, batchDir.length()-1) : batchDir;
}
// public static String getRequestRealDir() throws Exception {
// return getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_REAL_DIR);
// }
//
// public static String getRequestRootDir() throws Exception {
// return getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_ROOT_DIR);
// }
public static String getRequestArchDir() throws Exception {
return getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_ARCH_DIR);
}
public static String getRequestErrorDir() throws Exception {
return getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_ERROR_DIR);
}
public static String getResponseRealDir() throws Exception {
return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_REAL_DIR);
}
public static String getResponseRootDir() throws Exception {
return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_ROOT_DIR);
}
public static String getResponseArchDir() throws Exception {
return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_ARCH_DIR);
}
public static String getResponseErrorDir() throws Exception {
return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_ERROR_DIR);
}
//// add by dhjeong at 2012.10.17
// public static String getResponseNasDir() throws Exception {
// return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_NAS_DIR);
// }
//
//// add by dhjeong at 2012.10.17
// public static String getResponseChkDir() throws Exception {
// return getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_CHK_DIR);
// }
// public static String getResSendRealDir() throws Exception {
// return getBatchDir(RESPONSE_SND_DIR_INFO, RESPONSE_SND_REAL_DIR);
// }
//
// public static String getResSendArchDir() throws Exception {
// return getBatchDir(RESPONSE_SND_DIR_INFO, RESPONSE_SND_ARCH_DIR);
// }
// add by dhjeong at 2009.09.21
public static String getReqRecvRootDir() throws Exception {
return getBatchDir(REQUEST_RCV_DIR_INFO, REQUEST_RCV_ROOT_DIR);
}
public static String getReqRecvErrorDir() throws Exception {
return getBatchDir(REQUEST_RCV_DIR_INFO, REQUEST_RCV_ERROR_DIR);
}
public static String getRequestRootExt(){
String defaultExt = ".chk";
try {
String ext = getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_ROOT_EXT);
if ( ext == null )
ext = defaultExt;
return ext;
} catch (Exception e) {
return defaultExt;
}
}
public static String getResponseRootExt(){
String defaultExt = ".chk";
try {
String ext = getBatchDir(RESPONSE_RCV_DIR_INFO, RESPONSE_RCV_ROOT_EXT);
if ( ext == null )
ext = defaultExt;
return ext;
} catch (Exception e) {
return defaultExt;
}
}
/**
* snd 디렉토리
* @return
* @throws Exception
*/
public static String getRequestRootDir() throws Exception {
return getBatchDir(REQUEST_SND_DIR_INFO, REQUEST_SND_ROOT_DIR);
}
}
@@ -0,0 +1,88 @@
package com.eactive.eai.batch.common;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.SimpleTimeZone;
public class CalendarUtil
{
public static String getCurrentTime()
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
String curDate = formatter.format(Calendar.getInstance().getTime());
return curDate;
}
public static String getCurrentTimeNoDash()
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String curDate = formatter.format(Calendar.getInstance().getTime());
return curDate;
}
public static String getCurrentTimeNoDash(Date dt)
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String curDate = formatter.format(dt);
return curDate;
}
public static String getKSTDateTime()
{
// SimpleTimeZone simpletimezone = new SimpleTimeZone(0x1ee6280, "KST");
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return simpledateformat.format(date);
}
/**
* 1.기능: 스케쥴러에서 사용 (시작시각)
* - 시분을 입력받아서 현재의 년월 및 초,밀리세컨드(0000)를 추가한다.
*/
public static String setStartTime(String hhmm) throws Exception
{
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd");
Date date = new Date();
String rtTime = simpledateformat.format(date) + hhmm + "0000";
return rtTime;
}
/**
* 1.기능: 스케쥴러에서 사용 (종료시각)
* - 시분을 입력받아서 현재의 년월 및 초,밀리세컨드(0000)를 추가한다.
*/
public static String setEndTime(String hhmm) throws Exception
{
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat simpletimeformat = new SimpleDateFormat("HHmm");
Date date = new Date();
String systime = simpletimeformat.format(date);
//hhmm가 현재시간보다 클경우 현재날짜로
if ( StringUtil.stoi(hhmm) > StringUtil.stoi(systime)){
hhmm = simpledateformat.format(date) + hhmm + "0000";
}
//hhmm가 현재시간보다 크지않을경우 다음날짜로
else{
hhmm = getDatewithSpan(simpledateformat.format(date),1) + hhmm + "0000";
}
return hhmm;
}
public static String getDatewithSpan(String s, int i)
{
int j = 0x36ee80;
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd");
SimpleTimeZone simpletimezone = new SimpleTimeZone(9 * j, "KST");
simpledateformat.setTimeZone(simpletimezone);
int k = Integer.valueOf(s.substring(0, 4)).intValue();
int l = Integer.valueOf(s.substring(4, 6)).intValue() - 1;
int i1 = Integer.valueOf(s.substring(6, 8)).intValue() + i;
Calendar calendar = Calendar.getInstance();
calendar.set(k, l, i1);
return simpledateformat.format(calendar.getTime());
}
}
@@ -0,0 +1,58 @@
package com.eactive.eai.batch.common;
/**
* 1. 기능 : 배치프레임웍에서 공통으로 사용하는 상수를 정의한 Interface
* 2. 처리 개요 :
* -
* 3. 주의사항
*
* @author : YCLee 06/01/24
* @version : v 1.0.0
* @since :JDK v1.4.2
*/
public class CommonKeys
{
/* *******************************************************************
* Master Layer 구분 상수
******************************************************************* */
public static final String LAYER_USER_INTERFACE = "UI"; //UI (요구송신재처리,요구수신강제등록)
public static final String LAYER_FILE_EVENT = "FE"; //File Event
public static final String LAYER_SOCKET_SERVER = "SS"; //Socket Server
public static final String LAYER_SCHEDULER = "SC"; //Scheduler
public static final String LAYER_FLOW_CONTROLLER = "FC"; //Flow Controller
/* *******************************************************************
* Layer 구분 상수
******************************************************************* */
public static final String SUB_LAYER_USER_INTERFACE = "UI"; //UI (요구송신재처리,요구수신강제등록)
public static final String SUB_LAYER_FILE_EVENT = "FE"; //File Event
public static final String SUB_LAYER_SOCKET_SERVER = "SS"; //Socket Server
public static final String SUB_LAYER_SCHEDULER_QUEUE = "SQ"; //Scheduler Queue
public static final String SUB_LAYER_SCHEDULER_PROCESSING = "SP"; //Scheduler Processing
public static final String SUB_LAYER_FLOW_CONTROLLER = "FC"; //Flow Controller
public static final String SUB_LAYER_FLOW_PHASE_ST = "ST"; //Flow Controller 개시 [ST: Start ]
public static final String SUB_LAYER_FLOW_PHASE_FI = "FI"; //Flow Controller 파일정보교환 [FI: File Info ]
public static final String SUB_LAYER_FLOW_PHASE_DS = "DS"; //Flow Controller Data 송수신 [DS: Data Send ]
public static final String SUB_LAYER_FLOW_PHASE_MI = "MI"; //Flow Controller 결번정보교환 [MI: Missing Data Info]
public static final String SUB_LAYER_FLOW_PHASE_MS = "MS"; //Flow Controller 결번 송수신 [MS: Missing Data Send]
public static final String SUB_LAYER_FLOW_PHASE_UE = "UE"; //Flow Controller 단위업무종료 [UE: Unit End ]
public static final String SUB_LAYER_FLOW_PHASE_AE = "AE"; //Flow Controller 전업무종료 [AE: All End ]
public static final String SUB_LAYER_FLOW_PHASE_EX = "EX"; //Flow Controller 예외 [EX: Exception ]
public static final String SUB_LAYER_FLOW_PHASE_LT = "LT"; //Flow Controller 시스템회선상태확인(테스트) [LT: Line Test ]
public static final String SUB_LAYER_FLOW_PHASE_SE = "SE"; //Flow Controller 시스템장애통보 [SE: System Error ]
public static final String SUB_LAYER_FLOW_PHASE_SR = "SR"; //Flow Controller 시스템장애회복통보 [SR: System Recovery ]
public static final String SUB_LAYER_FLOW_PHASE_CK = "CK"; //Flow Controller 요구송신 테스트전문
/* *******************************************************************
* 업무 유형 구분 상수
******************************************************************* */
public static final String PROCESS_REQUEST_SEND = "RS"; //요구송신
public static final String PROCESS_REQUEST_RECEIVE = "RR"; //요구수신
public static final String PROCESS_RESPONSE_SEND = "AS"; //응답송신
public static final String PROCESS_RESPONSE_RECEIVE = "AR"; //응답수신
}
@@ -0,0 +1,273 @@
package com.eactive.eai.batch.common;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.Logger;
import com.sennet.gator.EzGatorFile;
import com.sennet.gator.JobType;
import com.sennet.gator.console.main.EzGatorExecutor;
public class EzgatorUtil {
private static String CBS_DIR_INFO = "CBSDirInfo";
private static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
public static EzGatorFile[] listFiles(String server, int port, String path, HashMap<Integer, String> extmap) throws IOException {
EzGatorExecutor executor = new EzGatorExecutor();
try {
Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO );
String keyPath = prop.getProperty("mft.key.path");
String username = prop.getProperty("mft.user.name");
executor.setIp(server); // API가 접속하는 서버, 송신할 파일이 있는 서버
executor.setPort(port);
executor.setUserId(username);
executor.setPassword("");
executor.setRemoteServerIp(server);
executor.setRemoteServerPort(port);
executor.setJobType(JobType.GETDIRINFO); // 작업 종류
executor.setSrcFile("");
if (extmap != null) {
executor.setOption("24h");
}
executor.setPrivateKeyPath(keyPath);
executor.init();
executor.connect();
executor.login();
EzGatorFile[] ezGatorFiles = null;
if (extmap == null) {
ezGatorFiles = executor.listFiles(path);
} else {
ArrayList<EzGatorFile> list = new ArrayList<EzGatorFile>();
for (int inx = 0; inx < extmap.size(); inx++) {
String ext = extmap.get(inx);
EzGatorFile[] ezGatorFilesTemp = executor.listFiles(path + "/*." + ext);
logger.debug("DHJEONG==>server:" + server + ",port:" + port + ",username:" + username + ",path:" + path + ";" + ext);
for (int jnx = 0; jnx < ezGatorFilesTemp.length; jnx++) {
list.add(ezGatorFilesTemp[jnx]);
}
}
ezGatorFiles = new EzGatorFile[list.size()];
list.toArray(ezGatorFiles);
}
logger.info("[MFT를 통해 검색된 체크파일 개수]server:" + server + ",port:" + port + ",path:" + path + ",files-->" + ezGatorFiles.length);
for (int inx = 0; inx < ezGatorFiles.length; inx++) {
logger.debug("[MFT를 통해 검색된 체크파일 목록]" + ezGatorFiles[inx].getRawListing());
}
return ezGatorFiles;
} catch (Throwable t) {
String arg[] = new String[2];
arg[0] = server;
arg[1] = "" + port;
String errMsg = ExceptionUtil.getErrorCode("BECEAIMEU017", arg);
logger.error(errMsg, t);
throw new IOException(t);
} finally {
executor.disconnect();
}
}
public static boolean retrieve(String server, int port, String remote, String localPath) throws Exception {
logger.info("[retrieve]remote ------->" + remote + ", localPath---->" + localPath);
File chkDir = new File(localPath);
chkDir.mkdirs(); // 상위 디렉토리 미 존재시에도 write 한다.
try {
chkDir.setReadable(true, false);
chkDir.setWritable(true, false);
chkDir.setExecutable(true, false);
File p1 = chkDir.getParentFile();
p1.setReadable(true, false);
p1.setExecutable(true, false);
p1.setWritable(true, false);
File p2 = p1.getParentFile();
p2.setReadable(true, false);
p2.setExecutable(true, false);
p2.setWritable(true, false);
File p3 = p2.getParentFile();
p3.setReadable(true, false);
p3.setExecutable(true, false);
p3.setWritable(true, false);
File p4 = p3.getParentFile();
p4.setReadable(true, false);
p4.setExecutable(true, false);
} catch (Exception e) {
//
}
String delimiter = StringUtil.getDirDelimiter(localPath);
String fName = remote.substring(remote.lastIndexOf(delimiter) + 1);
EzGatorExecutor executor = new EzGatorExecutor();
try {
Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO );
String localServer = prop.getProperty("mft.local.server");
String keyPath = prop.getProperty("mft.key.path");
String username = prop.getProperty("mft.user.name");
int localPort = Integer.parseInt(prop.getProperty("mft.local.port"));
executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버
executor.setPort(localPort);
executor.setUserId(username);
executor.setPassword("");
executor.setJobType(JobType.RECVFILE); // 작업 종류
executor.setPrivateKeyPath(keyPath);
executor.setRemoteServerIp(server); // 수신 서버
executor.setRemoteServerPort(port);
executor.setSrcFile(remote);
executor.setSrcSuffix(null);
executor.setOption("ir");
executor.setDestFile(localPath + fName); // 수신할 파일의 절대경로
executor.setDestSuffix(null);
executor.init();
executor.connect();
executor.login();
if (!executor.recvServerFile()) {
logger.warn("Command failed: " + executor.getErrorMsg());
throw new Exception(executor.getErrorMsg());
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new Exception(e.getMessage());
} finally {
executor.disconnect();
}
return true;
}
public static boolean store(String server, int port, String remote, String localPath) throws Exception {
EzGatorExecutor executor = new EzGatorExecutor();
try {
localPath = localPath.replace("\\r$", "");
Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO );
String localServer = prop.getProperty("mft.local.server");
int localPort = Integer.parseInt(prop.getProperty("mft.local.port"));
String keyPath = prop.getProperty("mft.key.path");
String username = prop.getProperty("mft.user.name");
executor.setPrivateKeyPath(keyPath);
executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버
executor.setPort(localPort);
executor.setUserId(username);
executor.setPassword("");
executor.setJobType(JobType.SENDFILE); // 작업 종류
executor.setRemoteServerIp(server); // 수신 서버
executor.setRemoteServerPort(port);
executor.setSrcFile(localPath);
executor.setSrcSuffix(null);
executor.setOption("ir");
executor.setDestFile(remote); // 수신할 파일의 절대경로
executor.setDestSuffix(null);
executor.init();
executor.connect();
executor.login();
boolean success = false;
try {
success = executor.sendServerFile();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new Exception(e.getMessage());
}
if (!success) {
logger.warn("Command failed: " + executor.getErrorMsg());
throw new Exception(executor.getErrorMsg());
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
throw new Exception(e.getMessage());
} finally {
executor.disconnect();
}
return true;
}
public static boolean delete(String server, int port, String fullfilename) throws IOException {
EzGatorExecutor executor = new EzGatorExecutor();
try {
fullfilename = fullfilename.replace("\\r$", "");
Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO );
String localServer = prop.getProperty("mft.local.server");
int localPort = Integer.parseInt(prop.getProperty("mft.local.port"));
String keyPath = prop.getProperty("mft.key.path");
String username = prop.getProperty("mft.user.name");
executor.setPrivateKeyPath(keyPath);
executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버
executor.setPort(localPort);
executor.setUserId(username);
executor.setPassword("");
executor.setRemoteServerIp(server); // 수신 서버
executor.setRemoteServerPort(port);
executor.setJobType(JobType.DELETEFILE); // 작업 종류
executor.setSrcFile(fullfilename);
executor.init();
executor.connect();
executor.login();
return executor.deleteServerFile();
} catch (Exception e) {
String arg[] = new String[2];
arg[0] = server;
arg[1] = "" + port;
String errMsg = ExceptionUtil.getErrorCode("BECEAIMEU017", arg);
logger.error(errMsg, e);
throw new IOException(e);
} finally {
executor.disconnect();
}
}
public static boolean rename(String server, int port, String srcname, String tarname) throws IOException {
EzGatorExecutor executor = new EzGatorExecutor();
try {
srcname = srcname.replace("\\r$", "");
tarname = tarname.replace("\\r$", "");
Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO );
String localServer = prop.getProperty("mft.local.server");
int localPort = Integer.parseInt(prop.getProperty("mft.local.port"));
String keyPath = prop.getProperty("mft.key.path");
String username = prop.getProperty("mft.user.name");
executor.setPrivateKeyPath(keyPath);
executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버
executor.setPort(localPort);
executor.setUserId(username);
executor.setPassword("");
executor.setRemoteServerIp(server); // 수신 서버
executor.setRemoteServerPort(port);
executor.setJobType(JobType.RENAMEFILE); // 작업 종류
executor.setSrcFile(srcname);
executor.setDestFile(tarname);
executor.setOption("ov");
executor.init();
executor.connect();
executor.login();
return executor.renameServerFile();
} catch (Exception e) {
String arg[] = new String[2];
arg[0] = server;
arg[1] = "" + port;
String errMsg = ExceptionUtil.getErrorCode("BECEAIMEU017", arg);
logger.error(errMsg, e);
throw new IOException(e);
} finally {
executor.disconnect();
}
}
}
@@ -0,0 +1,421 @@
package com.eactive.eai.batch.common;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.logger.LogManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
/**
* <pre>
* 디렉토리 또는 파일을 생성/삭제/이동/이름변경 하는 유틸리티이다.
* 참고) 윈도계열과 유닉스계열에 모두 적용된다.
* </pre>
*/
public class FileUtil {
//파일로거
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
/**
* 디렉토리를 생성한다.<br>
* 참고) 상위디렉토리가 이미 생성되어 있어야 한다.
* @param path 디렉토리 경로 문자열
* @return 성공시 리턴 true, 실패시 리턴 false
*/
public static boolean mkdir(String path) {
return mkdir(path, false);
}
/**
* 디렉토리를 생성한다.<br>
* 참고) 상위디렉토리가 미 존재시 상위디렉토리까지 생성할 수 있다.
* @param path 디렉토리 경로 문자열
* @param isRecursive 상위디렉토리 미 존재시 생성여부
* @return 성공시 리턴 true, 실패시 리턴 false
*/
public static boolean mkdir(String path, boolean isRecursive) {
if (path==null || (path=path.trim()).equals("")) return false;
return mkdir(new File(path.replace('\\', '/')), isRecursive);
}
/**
* 디렉토리를 생성한다.<br>
* 참고) 상위디렉토리가 미 존재시 상위디렉토리까지 생성할 수 있다.
* @param path 디렉토리 경로 File 객체
* @param isRecursive 상위디렉토리 미 존재시 생성여부
* @return 성공시 리턴 true, 실패시 리턴 false
*/
public static boolean mkdir(File f, boolean isRecursive) {
if (f==null) return false;
if (f.exists()) {
logger.debug(" - 디렉토리 생성...["+ f.getAbsolutePath() +"] -> true (이미존재함)");
setExecutable(f.getAbsolutePath());
return true;
}
boolean isSuccess = (isRecursive)? f.mkdirs() : f.mkdir();
logger.debug(" - 디렉토리 생성...["+ f.getAbsolutePath() +"] -> "+ isSuccess);
setExecutable(f.getAbsolutePath());
return isSuccess;
}
/**
* 디렉토리를 삭제한다.<br>
* 참고) 디렉토리 안에 내용이 없어야 한다.
* @param path 디렉토리 경로 문자열
* @return 성공시 리턴 true, 실패시 리턴 false
*/
public static boolean rmdir(String path) {
return rmdir(path, false);
}
/**
* 디렉토리를 삭제한다.<br>
* 참고) 디렉토리 안의 내용 존재시 모든 내용을 삭제할 수 있다.
* @param path 디렉토리 경로 문자열
* @param isRecursive 내용 존재시 삭제여부
* @return 성공시 리턴 true, 실패시 리턴 false
*/
public static boolean rmdir(String path, boolean isRecursive) {
if (path==null || (path=path.trim()).equals("")) return false;
return rmdir(new File(path.replace('\\', '/')), isRecursive);
}
/**
* 디렉토리를 삭제한다.<br>
* 참고) 디렉토리 안의 내용 존재시 모든 내용을 삭제할 수 있다.
* @param path 디렉토리 경로 File 객체
* @param isRecursive 내용 존재시 삭제여부
* @return 성공시 리턴 true, 실패시 리턴 false
*/
public static boolean rmdir(File f, boolean isRecursive) {
if (f==null) return false;
if (!f.exists()) {
logger.debug(" - 디렉토리 삭제...["+ f.getAbsolutePath() +"] -> true (존재안함)");
return true;
}
if (f.isFile()) {
logger.debug(" - 디렉토리 삭제...["+ f.getAbsolutePath() +"] -> false (파일임)");
return false;
}
if (isRecursive) { //디렉토리 내의 모든 내용도 삭제할때
File[] fl = f.listFiles();
for (int i=0; i<fl.length; i++) {
boolean isSuccess;
if (fl[i].isFile()) {
isSuccess = fl[i].delete();
logger.debug(" - 파일 삭제...["+ f.getAbsolutePath() +"] -> "+ isSuccess);
} else {
isSuccess = rmdir(fl[i], true);
}
if (!isSuccess) return false;
}
boolean isSuccess = f.delete();
logger.debug(" - 디렉토리 삭제...["+ f.getAbsolutePath() +"] -> "+ isSuccess);
return isSuccess;
} else {
boolean isSuccess = f.delete();
logger.debug(" - 디렉토리 삭제...["+ f.getAbsolutePath() +"] -> "+ isSuccess);
return isSuccess;
}
}
/**
* 파일을 삭제한다.
* @param path 파일 경로 문자열
* @return 성공시 리턴 true, 실패시 리턴 false
*/
public static boolean delete(String path) {
if (path==null || (path=path.trim()).equals("")) return false;
return delete(new File(path.replace('\\', '/')));
}
/**
* 파일을 삭제한다.
* @param path 파일 경로 File 객체
* @return 성공시 리턴 true, 실패시 리턴 false
*/
public static boolean delete(File f) {
if (f==null || !f.exists() || f.isDirectory()) return false; //존재하지 않거나 디렉토리면 리턴 true
return f.delete();
}
/**
* 파일 또는 디렉토리의 이름을 변경 또는 이동 시킨다.<br>
* 주의) 윈도계열에서 이동시 다른 드라이브로 이동할 수는 없다.
* @param pathFrom 원본 디렉토리 또는 파일 경로 문자열
* @param pathTo 목적 디렉토리 또는 파일 경로 문자열
* @return 성공시 리턴 true, 실패시 리턴 false
*/
public static boolean move(String pathFrom, String pathTo) {
return move(pathFrom, pathTo, false);
}
/**
* 파일 또는 디렉토리의 이름을 변경 또는 이동 시킨다.<br>
* 참고) 목적 경로의 상위디렉토리 미 존재시 상위디렉토리 생성 후 이름변경 또는 이동할 수 있다.
* 주의) 윈도계열에서 이동시 다른 드라이브로 이동할 수는 없다.
* @param pathFrom 원본 디렉토리 또는 파일 경로 문자열
* @param pathTo 목적 디렉토리 또는 파일 경로 문자열
* @param isMkdir 목적경로의 상위디렉토리 미 존재시 생성여부
* @return 성공시 리턴 true, 실패시 리턴 false
*/
public static boolean move(String pathFrom, String pathTo, boolean isMkdir) {
if (pathFrom==null || (pathFrom=pathFrom.trim()).equals("")) return false;
if (pathTo ==null || (pathTo =pathTo.trim() ).equals("")) return false;
return move(new File(pathFrom.replace('\\', '/')), pathTo.replace ('\\', '/'), isMkdir);
}
/**
* 파일 또는 디렉토리의 이름을 변경 또는 이동 시킨다.<br>
* 참고) 목적 경로의 상위디렉토리 미 존재시 상위디렉토리 생성 후 이름변경 또는 이동할 수 있다.
* 주의) 윈도계열에서 이동시 다른 드라이브로 이동할 수는 없다.
* @param pathFrom 원본 디렉토리 또는 파일 경로 File 객체
* @param pathTo 목적 디렉토리 또는 파일 경로 문자열
* @param isMkdir 목적경로의 상위디렉토리 미 존재시 생성여부
* @return 성공시 리턴 true, 실패시 리턴 false
*/
public static boolean move(File f, String pathTo, boolean isMkdir) {
if (f==null) return false;
if (!f.exists()) {
logger.debug(" - 디렉토리 이동...["+ f.getAbsolutePath() +"] to ["+ pathTo +"] -> false (존재안함)");
return false;
}
//목적경로가 없을경우 강제로 만듬
if (isMkdir) {
if (pathTo.endsWith("/")) pathTo = pathTo.substring(0, pathTo.length()-1); //맨끝 "/" 제거
boolean isSuccess = mkdir(pathTo.substring(0, pathTo.lastIndexOf("/")), true);
if (!isSuccess) {
logger.debug(" - 디렉토리 이동...["+ f.getAbsolutePath() +"] to ["+ pathTo +"] -> false (미존재Path생성실패)");
return false;
}
}
File f1 = new File(pathTo);
boolean isSuccess = f.renameTo(f1);
logger.debug(" - 디렉토리 이동...["+ f.getAbsolutePath() +"] to ["+ f1.getAbsolutePath() +"] -> "+ isSuccess);
setExecutable(pathTo);
return isSuccess;
}
public static boolean copyTransferFile(File sourceFile, File targetFile) throws IOException {
return copyTransferFile(sourceFile, targetFile, false);
}
public static boolean copyTransferFile(File sourceFile, File targetFile, boolean flag) throws IOException {
FileChannel inChannel = null;
FileChannel outChannel = null;
boolean success = true;
try {
inChannel = new FileInputStream(sourceFile).getChannel();
outChannel = new FileOutputStream(targetFile).getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
try {
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
} catch (IOException e) {
success = false;
logger.error( e.getMessage(), e);
}
}
if ( success && flag ){
try {
sourceFile.delete();
} catch (Exception e) {
success = false;
logger.error( e.getMessage(), e);
}
}
return success;
}
public static byte[] readLine( FileInputStream fin ){
byte[] fileLine = new byte[1024];
byte[] newLine = null;
int len = 0;
int buf;
try {
while (( buf = fin.read()) != -1) {
if ( buf == '\n' )
break;
if ( len == fileLine.length ){
byte[] tmpLine = fileLine;
fileLine = new byte[len + 1024];
System.arraycopy( tmpLine, 0, fileLine, 0, len );
}
fileLine[len] = (byte)buf;
len++;
}
if ( ( len > 0 ) && ( fileLine[len-1] == '\r' ) )
len--;
if ( len == 0 )
return null;
newLine = new byte[len];
System.arraycopy( fileLine, 0, newLine, 0, len );
} catch (Exception e) {
return null;
}
return newLine;
}
private static void setExecutable ( String path ){
String cmd1 = "chmod 775 " + path;
// String cmd2 = "chgrp ftp " + path;
// File dir = new File(path);
try {
Runtime.getRuntime().exec( cmd1 );
// Runtime.getRuntime().exec( cmd2 );
// dir.setExecutable(true, false);
// dir.setReadable(true, false);
// dir.setWritable(true, false);
} catch (Exception e) {
logger.error( e.getMessage(), e);
}
}
static public List<File> getFileList(File dir){
ArrayList<File> list = new ArrayList<File>();
File[] flist = dir.listFiles();
for (File file : flist) {
if ( file.isFile() ){
list.add(file);
}else if ( file.isDirectory()){
ArrayList<File> slist = (ArrayList<File>) getFileList(file);
for (File file2 : slist) {
list.add(file2);
}
}
}
return list;
}
static public List<File> getSendFileList(File dir){
// ArrayList<File> list = new ArrayList<File>();
// File[] deplist = dir.listFiles();
// for (File deps : deplist) {
// File sendDir = new File( deps.getAbsoluteFile()+ File.separator + "snd" );
// if ( sendDir.exists() && sendDir.isDirectory()){
// ArrayList<File> slist = (ArrayList<File>) getFileList(sendDir);
// for (File file : slist) {
// list.add(file);
// }
// }
// }
// return list;
ArrayList<File> list = new ArrayList<File>();
if ( dir.exists() && dir.isDirectory()){
ArrayList<File> slist = (ArrayList<File>) getFileList(dir);
for (File file : slist) {
list.add(file);
}
}
return list;
}
static public String getRecvFileName(String fileName, String pattern, BatchDoc batchDoc){
return getRecvFileName( fileName, pattern, batchDoc, true);
}
static public String getRecvFileName(String fileName, String pattern, BatchDoc batchDoc, boolean flag){
String rFileName = fileName + "";
String recvDate = null;
boolean useSeq = false;
if (pattern == null || pattern.trim().equals("")){
return rFileName;
}
if ( pattern.endsWith("001") ){
useSeq = true;
pattern = pattern.substring(0, pattern.length()-3);
if ( pattern.endsWith("_") ){
pattern = pattern.substring(0, pattern.length()-1);
}
}
String baseDate = batchDoc.getBatchMsg().getHeader().getBaseDate();
if ( baseDate == null || baseDate.trim().equals("") || !DatetimeUtil.isRightDate(baseDate)){
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
baseDate = formatter.format(Calendar.getInstance().getTime());
}
Calendar calendar = Calendar.getInstance();
calendar.set(Integer.parseInt(baseDate.substring(0,4)),Integer.parseInt(baseDate.substring(4,6))-1,Integer.parseInt(baseDate.substring(6)));
SimpleDateFormat sdf = new SimpleDateFormat( pattern );
recvDate = sdf.format(calendar.getTime());
if ( recvDate != null && !recvDate.equals("") ){
rFileName = rFileName + "_" + recvDate;
}
if ( !useSeq )
return rFileName;
String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode();
String instCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode();
String fileSeq = "001";
try {
fileSeq = LogManager.getInstance().getFileNameSeq(procCode, instCode, rFileName, flag);
} catch (Exception e) {
logger.error( e.getMessage(), e);
}
return rFileName + "_" + fileSeq;
}
public static byte[] readLine( BufferedInputStream bis ){
byte[] fileLine = new byte[1024];
byte[] newLine = null;
int len = 0;
int buf;
try {
while (( buf = bis.read()) != -1) {
if ( buf == '\n' )
break;
if ( len == fileLine.length ){
byte[] tmpLine = fileLine;
fileLine = new byte[len + 1024];
System.arraycopy( tmpLine, 0, fileLine, 0, len );
}
fileLine[len] = (byte)buf;
len++;
}
if ( ( len > 0 ) && ( fileLine[len-1] == '\r' ) )
len--;
if ( len == 0 )
return null;
newLine = new byte[len];
System.arraycopy( fileLine, 0, newLine, 0, len );
} catch (Exception e) {
return null;
}
return newLine;
}
}
@@ -0,0 +1,203 @@
//package com.eactive.eai.batch.common;
//
//import java.io.DataOutputStream;
//import java.net.Socket;
//import java.text.SimpleDateFormat;
//import java.util.Calendar;
//
//import com.eactive.eai.batch.code.CodeMessageManager;
//import com.eactive.eai.batch.code.CodeMessageVO;
//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.property.PropManager;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//public class ItmsSmsUtil {
//
// public static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_DEFAULT);
//
// public static final String SYSNOTIFYINFO = "SysNotifyInfo";
// public static final String HOST = "itsm.host";
// public static final String PORT = "itsm.port";
// public static final String MSG_GB = "msg.gb";
// public static final String MSG_DEL = "msg.del";
// public static final String REQ_BY_GROUP = "req.group";
// public static final String REQ_BY_TELNO = "req.telno";
// public static final String REQ_APPL_CD = "req.appl.cd";
//
// public static final String EAI_APPL_PREFIX = "eai.prefix";
// public static final String DEFAULT_APPL_CD = "appl.cd";
// public static final String CHECK_PERIOD = "check.period";
// public static final String CHECK_DELAY = "check.delay";
//
// public static final String EAI_SEND_YN = "eai.send.flag"; //업무팀에 보내고 나서 EAI 팀에도 보낼것인가?
//
//
// private ItmsSmsUtil(){
// }
//
// public static void sendSMS( String reqGb, String reqCont, String msg ){
//
// StringBuffer sb = new StringBuffer();
// try {
// String del = PropManager.getInstance().getProperty(SYSNOTIFYINFO, MSG_DEL);
// //PEM메시지구분 인터페이스대상 식별 코드 PEM_INFO 8
// sb.append(PropManager.getInstance().getProperty(SYSNOTIFYINFO, MSG_GB));
// sb.append(del);
//
// sb.append(reqGb); //
// sb.append(del);
//
// if ( PropManager.getInstance().getProperty(SYSNOTIFYINFO, REQ_BY_GROUP).equals(reqGb)){
// String eaiApplCd = reqCont;
// if ( eaiApplCd == null || eaiApplCd.trim().equals("")){
// eaiApplCd = PropManager.getInstance().getProperty(SYSNOTIFYINFO, DEFAULT_APPL_CD );
// }else{
// eaiApplCd = PropManager.getInstance().getProperty(SYSNOTIFYINFO, EAI_APPL_PREFIX) + eaiApplCd;
// }
// sb.append(eaiApplCd);
// }else{
// sb.append(reqCont);
// }
// sb.append(del);
//
// //발생시간 이벤트발생시간 YYYYMMDDhhmmss 2011030310153000
// SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
// String curDate = formatter.format(Calendar.getInstance().getTime());
// sb.append(curDate);
// sb.append(del);
//
// String reqGroup = PropManager.getInstance().getProperty(SYSNOTIFYINFO, REQ_APPL_CD );
// sb.append(reqGroup);
// sb.append(del);
//
// sb.append(msg);
//
// sendToSocket( new String(sb));
//
// } catch (Exception e) {
// logger.error("[ItmsSmsUtil][sendSMS]\n" + e.getMessage(),e);
// }
// return;
// }
//
// public static void sendToSocket( String msg ){
//
// Socket socket = null;
// try {
// logger.debug( "SMS MESSAGE :" + msg );
//
// if ( (socket = connect()) == null ) {
// return;
// }
//
// DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
// dout.write(msg.getBytes());
//
//
// } catch (Exception e) {
// logger.error("[ItmsSmsUtil][sendSMS]\n" + e.getMessage(),e);
// return;
// } finally {
// if ( socket != null ){
// try {
// socket.close();
// } catch (Exception e) {}
// }
// socket = null;
// }
// return;
// }
//
// private static Socket connect() throws Exception{
//
// String ipAdress = PropManager.getInstance().getProperty(SYSNOTIFYINFO, HOST);
// if (ipAdress == null)
// throw new Exception("'SMS서버 IP정보' 프라퍼티가 없습니다. (PropGroupName:"+ SYSNOTIFYINFO +", PropName:"+ HOST +")");
//
// String port = PropManager.getInstance().getProperty(SYSNOTIFYINFO, PORT);
// if (port == null)
// throw new Exception("'SMS서버 PORT정보' 프라퍼티가 없습니다. (PropGroupName:"+ SYSNOTIFYINFO +", PropName:"+ PORT +")");
// int nPortNum = -1;
// try {
// nPortNum = Integer.parseInt(port);
//
// } catch (Exception ex) {
// String errMsg = "소켓 포트 정보가 잘못되었습니다. (PortNo:{" + port + "})";
// throw new Exception(errMsg);
// }
//
// return socketInit(ipAdress, nPortNum);
// }
//
// private static Socket socketInit(String remoteIP, int remotePort) throws Exception
// {
// try {
// return new Socket(remoteIP, remotePort);
// } catch (Exception ex) {
// throw new Exception( "Socket 연결 에러 (IP:"+ remoteIP + ", Port:" + remotePort + ")," + ex.getMessage());
// }
// }
//
// public static void sendSMS(BatchDoc batchDoc){
//
// String errMsg = batchDoc.getBatchMsg().getBody().getErrorMsg();
// CodeMessageVO vo = null;
// CodeMessageVO nvo = null;
//
// for ( int inx=0; inx < errMsg.length()-12;inx++){
// if ( ( vo = CodeMessageManager.getInstance().getMessageVO(errMsg.substring(inx, inx+12))) != null ){
// try {
// nvo = vo;
// } catch (Exception e) {}
// }
// }
//
// String message = "[송신실패]";
// if ( "R".equals(batchDoc.getBatchMsg().getHeader().getProcessType().substring(1,2))){
// message = "[수신실패]";
// }
// message = message + "파일명:" + batchDoc.getBatchMsg().getHeader().getBizCode()
// + ",업무명:" + batchDoc.getBatchMsg().getHeader().getProcessName()
// + ",기관명:" + batchDoc.getBatchMsg().getHeader().getInstitutionName();
// if ( nvo != null ) {
// message = message + "," + nvo.getMsgEtc();
// }
//
// String procCode = batchDoc.getBatchMsg().getHeader().getProcessCode();
//// String organCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode();
// String bizCode = batchDoc.getBatchMsg().getHeader().getBizCode();
// BatchJobInfoVO jvo = DirInfoManager.getInstance().getFileInfoByDstcd( procCode, bizCode );
// String applCd = "";
// if ( jvo != null ){
// applCd = jvo.getUapplCd();
// }
// sendSMS( PropManager.getInstance().getProperty(SYSNOTIFYINFO, REQ_BY_GROUP), applCd, message);
//
// // 업무팀이 세팅 되어 있으면 EAI에도 한번 더 보낸다.
// if (applCd != null && !applCd.trim().equals("")){
// try {
// if (!PropManager.getInstance().getProperty(SYSNOTIFYINFO, EAI_SEND_YN).trim().equals("")){
// sendSMS( PropManager.getInstance().getProperty(SYSNOTIFYINFO, REQ_BY_GROUP), "", message);
// }
// } catch (Exception e) {} // 에러 무시
// }
//
//// // 이제 대외 기관에도 보내 보자.
//// try {
//// OutsideVO ovo = OutsideManager.getInstance().getOutsideInfo(procCode, organCode);
//// if ( ovo.getSMSDpstCnsntYn().equals("1") ){
//// String [] telnos = ovo.getOsidInstiTelno().split(",");
//// for (int i = 0; i < telnos.length; i++) {
//// String telno = telnos[i];
//// sendSMS( PropManager.getInstance().getProperty(SMSINFO, REQ_BY_TELNO), telno, message);
//// }
//// }
//// } catch (Exception e) {}
//
//
// }
//
//}
@@ -0,0 +1,93 @@
package com.eactive.eai.batch.common;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.logger.LogManager;
/**
* 1. 기능: JPD 및 Class에서 로깅을 위하여 호출하는 프로그램
* - LogUtil에서는 다음과 같은 태그로 각 로그를 구분한다.
* S: 시작로글
* C: 진행중인 로글
* E: 에러 종료 로그
* T: 정상 종료 로그
* - 본 프로그램에서는 호출된 프로그램으로부터 값을 추출하여 적절한 태그를 추가한 다음
* LogSender 프로그램을 호출한다.
*
* 2. 주의사항: LogUtil에서는 LogSender JPD에 연결이 안될 경우 별도의 로깅은 하지 않는다.
* 다만, File로 로깅 처리를 하도록 한다.
*/
public class LogUtil
{
/**
* 1.기능: LogUtil에서 실제 LogSender에 연결하는 메소드
*/
/* ============================================================================
* 아래의 메소드는 EAIBatchMessageDocument를 입력으로 받는 메소드
* - 최초 로그 생성시: setStartLog(BatchDoc)
* - 진행중인 로그: setLog(BatchDoc)
* - 에러로그: setLog(BatchDoc, ErrorMsg)
* - 종료로그: setEndLog(BatchDoc)
============================================================================ */
/**
* 1.기능: Log를 처음 만드는 프로그램에서 호출하는 Log 생성 메소드
*/
public static void setStartLog(BatchDoc doc) throws Exception
{
LogManager.getInstance().setLogStart(doc);
}
/**
* 1.기능: 진행중인 로그를 저장하는 메소드
*/
public static void setLog(BatchDoc doc) throws Exception
{
LogManager.getInstance().setLogStage(doc);
}
/**
* 1.기능: 에러 로그를 저장하는 메소드
*/
public static void setEndLog(BatchDoc doc) throws Exception
{
LogManager.getInstance().setLogEnd(doc);
}
/**
* 1.기능: 에러 로그를 저장하는 메소드
*/
public static void setErrorLog(BatchDoc doc, String errMsg) throws Exception
{
LogManager.getInstance().setLogError(doc, errMsg);
}
/**
* 1.기능: 사용자중지 로그를 저장하는 메소드
*/
public static void setCancelLog(BatchDoc doc, String errMsg) throws Exception
{
LogManager.getInstance().setLogCancel(doc, errMsg);
}
/**
* 1.기능: 단계 진행중 로그 Master의 필드가 결정되는 경우 로그 Master update
*/
public static void updateLogMaster(BatchDoc doc) throws Exception
{
LogManager.getInstance().updateLogMaster(doc);
}
public static void setLogFileStart(BatchDoc doc) throws Exception
{
LogManager.getInstance().setLogFileStart(doc);
}
public static void setLogFileEnd(BatchDoc doc) throws Exception
{
LogManager.getInstance().setLogFileEnd(doc);
}
}
@@ -0,0 +1,198 @@
package com.eactive.eai.batch.common;
public class LoggingUtil {
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];
private static final char[] HEX_CHAR_ARRAY = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/**
* BYTE ARRAY값을 HEXA STRING으로 변환하여 String을 리턴한다.
* @param abyte
* @return
*/
public static String byte2Hex(byte[] abyte) {
StringBuffer buf = new StringBuffer();
int len = abyte.length;
int high = 0;
int low = 0;
for (int i = 0; i < len; i++) {
high = ((abyte[i] & 0xf0) >> 4);
low = (abyte[i] & 0x0f);
buf.append(HEX_CHAR_ARRAY[high]);
buf.append(HEX_CHAR_ARRAY[low]);
}
return buf.toString();
}
/**
* 주어진 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();
}
}
/**
* 송수신전문에 대한 DUMP를 프린트할 수 있는 포맷으로 변환하여 String Array로 리턴한다.
* @param bytes
* @return
*/
public static String[] makeDumpFormat(byte[] bytes) {
if (bytes == null || bytes.length == 0)
return 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 sb = new StringBuffer();
sb.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(" ");
}
sb.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] = sb.append( stringFormat(new String(buf), false, SPACE, 16) ).append(" |").toString();
}
return dumps;
}
public static String hexDump(byte[] message) {
String[] dumpMsg = makeDumpFormat(message);
StringBuffer dump = new StringBuffer();
dump.append("byte[size=" + message.length + "]");
dump.append("\n");
for (int i = 0; i < dumpMsg.length; i++) {
dump.append(dumpMsg[i]);
if (i < dumpMsg.length - 1)
dump.append("\n");
}
return dump.toString();
}
/**
* byte[] 길이로 분리하여 출력한다. raw data 확인용
* @param message 송수신한 메시지
* @return Ascii로 변환한 문자열
*/
public static String asciiDump(byte[] message) {
int max = 140;
StringBuffer result = new StringBuffer().append(message.length).append(" bytes").append(System.lineSeparator());
int i = 0;
for (i = 0; i < (message.length) / max; i++) {
result.append(new String(message, i * max, max)).append(System.lineSeparator());
}
//남는 부분 처리
if (message.length > i * max) {
result.append(new String(message, i * max, message.length - (i * max))).append(System.lineSeparator());
}
return result.toString();
}
}
@@ -0,0 +1,52 @@
package com.eactive.eai.batch.common;
import java.io.IOException;
public class OSUtil
{
/** Operating system state flag for error. */
private static final int INIT_PROBLEM = -1;
/** Operating system state flag for neither Unix nor Windows. */
private static final int OTHER = 0;
/** Operating system state flag for Windows. */
private static final int WINDOWS = 1;
/** Operating system state flag for Unix. */
private static final int UNIX = 2;
public static int getOSType()
{
int os = OTHER;
try {
String osName = System.getProperty("os.name");
if (osName == null) {
throw new IOException("os.name not found");
}
osName = osName.toLowerCase();
// match
if (osName.indexOf("windows") != -1) {
os = WINDOWS;
} else if (osName.indexOf("linux") != -1
|| osName.indexOf("sun os") != -1
|| osName.indexOf("sunos") != -1
|| osName.indexOf("solaris") != -1
|| osName.indexOf("mpe/ix") != -1
|| osName.indexOf("hp-ux") != -1
|| osName.indexOf("aix") != -1
|| osName.indexOf("freebsd") != -1
|| osName.indexOf("irix") != -1
|| osName.indexOf("digital unix") != -1
|| osName.indexOf("unix") != -1
|| osName.indexOf("mac os x") != -1) {
os = UNIX;
} else {
os = OTHER;
}
} catch (Exception ex) {
os = INIT_PROBLEM;
}
return os;
}
}
@@ -0,0 +1,151 @@
package com.eactive.eai.batch.common;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.Logger;
public class SMSManager {
private static SMSManager instance = new SMSManager();
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
public static SMSManager getInstance() {
return instance;
}
private Socket socket = null;
private DataOutputStream dout = null;
public static final String SMSINFO = "SMSInfo";
public static final String IP = "ip";
public static final String PORT = "port";
public static final String SENDER = "sender";
public static final String PRIORITY = "priority";
private SMSManager(){
}
public boolean sendSMS( String telno, String msg ){
if ( socket != null){
return false;
}
try {
if ( !connect()) {
return false;
}
dout = new DataOutputStream(socket.getOutputStream());
byte[] reqData = new byte[137];
for ( int inx=0; inx < reqData.length; inx++){
reqData[inx] = ' ';
}
// SEND_REQUEST(문자전송요청)
// "01199714977 01199756577 가나다라마바사가나다라마바사가나다라마바사가나다라마바사가나다라마바사가나다라마 kbdbsvr1 120061107233027 "
// 받는이번호 (자릿수 13Byte Fix, 형태 “01199714977 “, Left Shift , space filling)
// 보낸이번호 (자릿수 13Byte Fix, 형태 “01199714977 “, Left Shift , space filling)
// 메시지 (자릿수 80Byte Fix, 형태:문자형, Left Shift , space filling)
// 호스트 명 (자릿수:15Byte Fix, 형태 “kbdbsvr1 “, Left Shift , space filling)
// 우선구분 (자릿수:1Byte Fix, 형태:0-보통,1-긴급,2-우선)
// 전송일시 (자릿수:14Byte Fix, 형태: yyyyMMddHHmmss(24h))
// 총 137 Byte Fix
// 받는이 전화 번호
System.arraycopy( telno.getBytes(), 0, reqData, 0, Math.min(telno.getBytes().length, 13));
// 보내는 사람 전화 번호 : Rule Property 에서 읽어 온다.
String sender = PropManager.getInstance().getProperty(SMSINFO, SENDER);
if (sender != null){
System.arraycopy( sender.getBytes(), 0, reqData, 13, Math.min(sender.getBytes().length, 13));
}
// 메시지
System.arraycopy( msg.getBytes(), 0, reqData, 26, Math.min(msg.getBytes().length, 80));
// 호스트명
String hostname = InetAddress.getLocalHost().getHostName();
System.arraycopy( hostname.getBytes(), 0, reqData, 106, Math.min(hostname.getBytes().length, 15));
// 우선구분 0을 디폴트로...
String priority = PropManager.getInstance().getProperty(SMSINFO, PRIORITY);
if ( priority == null ) priority = "0";
System.arraycopy( priority.getBytes(), 0, reqData, 121, Math.min(priority.getBytes().length, 1));
// 전송일시
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String curDate = formatter.format(Calendar.getInstance().getTime());
System.arraycopy( curDate.getBytes(), 0, reqData, 122, 14);
logger.debug( "SMS MESSAGE :" + new String (reqData));
dout.write(reqData);
} catch (Exception e) {
logger.error( e.getMessage(), e);
return false;
} finally {
if ( socket != null ){
try {
socket.close();
} catch (Exception e) {}
}
socket = null;
}
return true;
}
private boolean connect() throws Exception{
String ipAdress = PropManager.getInstance().getProperty(SMSINFO, IP);
if (ipAdress == null)
throw new Exception("'SMS서버 IP정보' 프라퍼티가 없습니다. (PropGroupName:"+ SMSINFO +", PropName:"+ IP +")");
String port = PropManager.getInstance().getProperty(SMSINFO, PORT);
if (port == null)
throw new Exception("'SMS서버 PORT정보' 프라퍼티가 없습니다. (PropGroupName:"+ SMSINFO +", PropName:"+ PORT +")");
int nPortNum = -1;
try {
nPortNum = Integer.parseInt(port);
} catch (Exception ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJC002", new String[] {port});
throw new Exception(errMsg);
}
socket = socketInit(ipAdress, nPortNum);
if (socket == null) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJC003");
throw new Exception(errMsg);
}
return true;
}
private Socket socketInit(String remoteIP, int remotePort) throws Exception
{
try {
return new Socket(remoteIP, remotePort);
} catch (UnknownHostException ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC001", new String[] {remoteIP, Integer.toString(remotePort)});
throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), 서버를 찾을 수 없습니다.
} catch (Exception ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC002", new String[] {remoteIP, Integer.toString(remotePort)});
throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), I/O Exception이 발생했습니다.
}
}
}
@@ -0,0 +1,487 @@
package com.eactive.eai.batch.common;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.util.StringTokenizer;
public class StringUtil
{
/**
* 1. 기능 : 주어진 문자열이 숫자로만 구성되어 있는지 확인한다.
* 공백이 있으면 false를 반환한다.
* 2. 처리 개요 :
* - char값이 48에서 57사이이면 숫자이다.
*
* @param str 문자열
* @return 문자열이 모두 숫자로만 이루어진경우 true
*/
public static boolean isNumeric(String str) {
if (str==null || str.equals("")) return false;
for (int i=0; i<str.length(); i++) {
if ((int)str.charAt(i) < 48 || (int)str.charAt(i) > 57) return false;
}
return true;
}
/**
* 1. 기능 : 주어진 문자열이 문자로만 구성되어 있는지 확인한다.
* 공백은 true를 반환한다.
* 2. 처리 개요 :
* - 입력된 String을 대문자로 모두 변환한다. (알파벳은 65(A)에서 90(Z)까지이다.)
* - char값이 65이상이면 문자이다.
*
* @param str 문자열
* @return 문자열이 모두 문자로만 이루어진경우 true
*/
public static boolean isAlpha(String str) {
if (str==null || str.equals("")) return true;
for (int i=0; i<str.length(); i++) {
if ((int)str.charAt(i) < 65 && ((int)str.charAt(i) != 32)) return false;
}
return true;
}
/**
* 1. 기능 : 구분자가 들어간 스트링을 구분자기준으로 잘라 String Array를 만들어주는 Method
* 2. 처리 개요 :
* - 구분자가 들어간 스트링을 구분자기준으로 잘라 String Array를 만들어주는 Method
* 3. 주의사항
*
* @param inStr 대상 스트링
* @param delim 잘라낼 때의 기준 구분자
* @return 잘라낸 스트링을 담고 있는 String Array
*/
public static String[] getStrArray(String inStr, String delim) {
String[] retStr = null;
if ( inStr == null || inStr.equals("") ) {
return (new String[] {});
} else {
retStr = inStr.split(delim);
}
return retStr;
}
/**
* 1.기능: Delimiter로 구분된 String을 받아들여 String[]을 반환한다.
*/
public String[] parseStringWithDelimiter(String str, String delim)
{
String[] rtArray = new String[getMissSeqNoCnt(str, delim.charAt(0))];
StringTokenizer st = new StringTokenizer(str, delim);
int i=0;
while (st.hasMoreTokens())
{
rtArray[i] = st.nextToken();
}
return rtArray;
}
private int getMissSeqNoCnt(String str, char delim)
{
/**
* 1.기능: 입력된 String에서 0의 갯수만 반환한다.
*/
int patternMatchCnt = 0;
for(int i=0; i<str.length(); i++)
{
if(str.charAt(i) == delim)
{
patternMatchCnt++;
}
}
return patternMatchCnt;
}
public static int stoi(String s)
{
if(s == null || s.equals(""))
return 0;
else
return Integer.valueOf(replaceStr(s, ",", "").trim()).intValue();
}
public static String itos(int i)
{
return (new Integer(i)).toString();
}
public static String replaceStr(String s, String s1, String s2) throws NullPointerException
{
if(s == null || s.length() == 0)
return "";
if(s1 == null || s1.equals("") || s2 == null)
return s;
int i = 0;
StringBuffer stringbuffer = new StringBuffer();
while((i = s.indexOf(s1)) >= 0)
{
stringbuffer.append(s.substring(0, i)).append(s2);
s = s.substring(i + s1.length());
}
stringbuffer.append(s);
return stringbuffer.toString();
}
public static String nvl(String str) {
return nvl(str, "");
}
public static String nvl(String str, String defaultValue) {
if (str == null || str.equals("")) return defaultValue;
return str;
}
public static String nvlTrim(String str) {
return nvlTrim(str, "");
}
public static String nvlTrim(String str, String defaultValue) {
if (str == null || str.trim().equals("")) return defaultValue;
return str.trim();
}
/**
* <pre>
* 문자열을 주어진 포맷으로 일치시킨다.
* 용례) matchFormat("20010101", "####/##/##") -> "2001/01/01"
* matchFormat("12345678", "##/## : ##") -> "12/34 : 56"
* </pre>
* @param str 원본문자열
* @param format 결과 포맷형태('#'문자에 원본 문자가 위치, 그외 문자는 그대로 표시)
* @return 포맷으로 변환된 문자열
*/
public static String matchFormat(String str, String format) {
if(str == null || str.length() == 0 ) return str;
int len = format.length();
char[] result = new char[len];
for(int i=0,j=0; i<len; i++,j++) {
if(format.charAt(i)=='#') {
try {
result[i]= str.charAt(j);
}catch(StringIndexOutOfBoundsException e) {
result[i]= '\u0000';
}
} else {
result[i]= format.charAt(i);
j--;
}
}
return new String(result);
}
public static boolean isCrackedHangleIndex(byte[] byteArr, int index) {
boolean crashFlag = false;
if (byteArr==null || byteArr.length==0 || byteArr.length<=index) return crashFlag;
for (int i=index-1; i>=0; i--) {
if (byteArr[i]>0) break;
crashFlag = !crashFlag;
}
return crashFlag;
}
public static String toCurFormat(double arg) {
return new DecimalFormat("###,##0").format(arg);
}
public static String getDirDelimiter(String path) {
return path.indexOf("/") >=0? "/" : //unix
path.indexOf("\\")>=0? "\\" : //windows
path.indexOf(".") >=0? "." : //host
"/"; //default(unix)
}
public static String getRandomDigit(long digitLen) {
if (digitLen <= 0) return "";
String format = "";
for (int i=0; i<digitLen; i++) format += "0";
DecimalFormat df = new DecimalFormat(format);
long randomDigit = (long) (Math.random() * Long.parseLong("1"+format));
return df.format(randomDigit);
}
public static String concateString(String[] valueArray) {
return concateString(valueArray, ",");
}
public static String concateString(String[] valueArray, String delimiter) {
if (valueArray == null || valueArray.length == 0) return "";
String concateStr = valueArray[0];
for (int i=1; i<valueArray.length; i++) {
concateStr += delimiter + valueArray[i];
}
return concateStr;
}
/**
* 1. 기능 : 주어진 문자열에서 지정된 문자를 잘라낸다.
* 2. 처리 개요 :
* - 주어진 문자열에서 끝에서 부터 지정된 문자를 반복되는 만큼 잘라낸다.
* 3. 주의사항
*
* @param inStr - 입력 문자열
* @param inChar - 잘라낼 문자
* @return 결과문자열
*/
public static String rtrimChar( String inStr, char inChar){
int len = inStr.getBytes().length;
byte newStr[]=null;
byte[] val = inStr.getBytes();
while ((0 < len) && (val[len -1] == inChar)) {
len--;
}
if (len > 0 ){
newStr = new byte[len];
System.arraycopy( val,0,newStr,0,len);
}
return newStr == null ? null : new String(newStr);// 20250910 npe
}
/**
* 1. 기능 : 주어진 문자열에서 지정된 문자를 잘라낸다.
* 2. 처리 개요 :
* - 주어진 문자열에서 끝에서 부터 지정된 문자를 반복되는 만큼 잘라낸다.
* 3. 주의사항
*
* @param inStr - 입력 문자열
* @param inChar - 잘라낼 문자
* @return 결과문자열
*/
public static byte[] rtrimChar( byte[] buf, char inChar){
int len = buf.length;
while ((0 < len) && ( (buf[len - 1] == inChar) || buf[len -1] == '\r' || buf[len -1] == '\n' )) {
len--;
}
if ( len > 0 ){
byte[] newBuf = new byte[len];
System.arraycopy( buf, 0, newBuf, 0, len);
return newBuf;
} else {
return null;
}
}
/**
* 1. 기능 : 주어진 스트링에 대해 offset 만큼의 byte 를 잘라내어 리턴한다.
* 2. 처리 개요 :
* - substring("1234",2) --> "34"
* 3. 주의사항
*
* @param inStr String Source
* @param offset offset
* @return String
*/
public static String substring( String inStr, int offset){
int len = inStr.getBytes().length - offset;
byte newStr[] = new byte[len];
System.arraycopy( inStr.getBytes(), offset, newStr, 0, len);
return new String (newStr);
}
/**
* 1. 기능 : 에러대신 Zero String을 리턴하는 substring method
* 2. 처리 개요 :
* - getSubstring("1234",4,2) --> ""
* 3. 주의사항
*
* @param Str String Source
* @param start start index.
* @param len length
* @return String
*/
public static String getSubstring(String Str, int start, int len)
{
if (Str == null) return "";
int slen = Str.length();
if ((slen < 1) || (start<0) || (len < 1)) return "";
if ((slen-1) < start) return "";
if (slen < (start+len)) {
return Str.substring(start,Str.length());
}
else {
return Str.substring(start,start+len);
}
}
/**
* 1. 기능 : 주어진 스트링에 대해 offset 만큼의 byte 를 잘라내어 리턴한다.
* 2. 처리 개요 :
* - substring("1234",2) --> "34"
* 3. 주의사항
*
* @param inStr String Source
* @param offset offset
* @return String
*/
public static byte[] split( byte[] str, int interval, byte[] del){
int offset1 = 0;
int offset2 = 0;
int len = str.length;
int delLen = del.length;
int newLen = len + ( ( ( ( len - 1)/interval ) + 1 )* delLen ) ;
byte[] newByte = new byte[newLen];
while ( offset1 < len - interval ){
System.arraycopy( str, offset1, newByte, offset2, interval);
offset1 += interval;
offset2 += interval;
System.arraycopy( del, 0, newByte, offset2, delLen);
offset2 += delLen;
}
System.arraycopy( str, offset1, newByte, offset2, len - offset1);
offset2 += len - offset1;
System.arraycopy( del, 0, newByte, offset2, delLen);
return newByte;
}
// public static String getCheckFileName( String realDirPath ){
// return realToRootDir( realDirPath );
// PropManager pmanager = PropManager.getInstance();
// String ext = ".chk";
// if ( realDirPath == null || realDirPath.equals(""))
// return realDirPath;
// try {
// String recvReal = BatchDirUtil.getResponseRealDir();
// ext = pmanager.getProperty("CBSDirInfo", "chk.ext");
// if (realDirPath.indexOf(recvReal) > -1 )
// return replaceStr( realDirPath, recvReal, BatchDirUtil.getResponseArchDir()) + ext;
//
// } catch (Exception e) {}
// return realDirPath + ext ;
// }
public static String realToRootDir( String realDirPath ){
if ( realDirPath == null || realDirPath.equals(""))
return realDirPath;
try {
String recvReal = BatchDirUtil.getResponseRealDir();
if (realDirPath.indexOf(recvReal) > -1 )
return replaceStr( realDirPath, recvReal, BatchDirUtil.getResponseRootDir() );
} catch (Exception e) {
return null;
}
return null;
}
public static String realToArchDir( String realDirPath ){
if ( realDirPath == null || realDirPath.equals(""))
return realDirPath;
try {
// String sendReal = BatchDirUtil.getRequestRealDir();
String recvReal = BatchDirUtil.getResponseRealDir();
// if ( realDirPath.indexOf(sendReal) > -1 )
// return replaceStr( realDirPath, sendReal, BatchDirUtil.getResponseArchDir() );
// else
if (realDirPath.indexOf(recvReal) > -1 )
return replaceStr( realDirPath, recvReal, BatchDirUtil.getResponseArchDir() );
} catch (Exception e) {
return null;
}
return null;
}
// public static String rootToArchDir( String rootDirPath ){
// if ( rootDirPath == null || rootDirPath.equals(""))
// return rootDirPath;
// try {
// String recvRoot = BatchDirUtil.getResponseRootDir();
// if ( rootDirPath.indexOf(recvRoot) > -1 )
// return replaceStr( rootDirPath, recvRoot, BatchDirUtil.getResponseArchDir() );
// } catch (Exception e) {
// return null;
// }
// return rootDirPath;
// }
// public static String rootToNasDir( String rootDirPath ){
// if ( rootDirPath == null || rootDirPath.equals(""))
// return rootDirPath;
// try {
// String recvRoot = BatchDirUtil.getResponseRootDir();
// if ( rootDirPath.indexOf(recvRoot) > -1 )
// return replaceStr( rootDirPath, recvRoot, BatchDirUtil.getResponseNasDir() );
// } catch (Exception e) {
// return null;
// }
// return rootDirPath;
// }
// public static String rootToChkDir( String rootDirPath ){
// if ( rootDirPath == null || rootDirPath.equals(""))
// return rootDirPath;
// try {
// String recvRoot = BatchDirUtil.getResponseRootDir();
// if ( rootDirPath.indexOf(recvRoot) > -1 )
// return replaceStr( rootDirPath, recvRoot, BatchDirUtil.getResponseChkDir() );
// } catch (Exception e) {
// return null;
// }
// return rootDirPath;
// }
public static String realToErrorDir( String realDirPath ){
if ( realDirPath == null || realDirPath.equals(""))
return realDirPath;
try {
// String sendReal = BatchDirUtil.getRequestRealDir();
String recvReal = BatchDirUtil.getResponseRealDir();
// if ( realDirPath.indexOf(sendReal) > -1 )
// return replaceStr( realDirPath, sendReal, BatchDirUtil.getResponseErrorDir() );
// else
if (realDirPath.indexOf(recvReal) > -1 )
return replaceStr( realDirPath, recvReal, BatchDirUtil.getResponseErrorDir() );
} catch (Exception e) {
return null;
}
return null;
}
public static long getTotRecCountFromHeader( String header ){
long cnt = -1;
try {
cnt = Long.parseLong(header.substring(27, 37));
} catch (Exception e) {
// e.printStackTrace();
}
return cnt;
}
public static String getBaseDateFromHeader( String header ){
String baseDate = null;
try {
baseDate = header.substring(19, 27);
} catch (Exception e) {
baseDate = CalendarUtil.getCurrentTimeNoDash().substring(0,8);
}
return baseDate;
}
public static String getDump(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
return sw.toString();
}
}
+181
View File
@@ -0,0 +1,181 @@
package com.eactive.eai.batch.doc;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import com.eactive.eai.common.util.Logger;
import com.jcraft.jsch.ChannelSftp;
public class BatchDoc implements Serializable{
private static final long serialVersionUID = 1L;
BatchMsg batchMsg;
/*** sFTP전송 종료 */
private ChannelSftp sftpChannel;
/*** 사용자 취소인 경우 true */
private boolean userCancel;
/** 기관별 로깅 */
Logger logger;
/**/
private Object bos;
private long currIODataByte;
public ChannelSftp getSftpChannel() {
return sftpChannel;
}
public void setSftpChannel(ChannelSftp sftpChannel) {
this.sftpChannel = sftpChannel;
}
public boolean isUserCancel() {
return userCancel;
}
public void setUserCancel(boolean userCancel) {
this.userCancel = userCancel;
}
public BatchMsg getBatchMsg() {
return batchMsg;
}
public void setBatchMsg(BatchMsg batchMsg) {
this.batchMsg = batchMsg;
}
public BatchMsg addNewBatchMsg(){
batchMsg = new BatchMsg();
return batchMsg;
}
@Override
public String toString() {
return batchMsg.toString();
}
public class BatchMsg implements Serializable
{
private static final long serialVersionUID = 1L;
Header header;
Body body;
Phaseinfo phaseinfo;
String telegramHeader;
String telegramBody;
String fileHeader;
String fileTrailer;
public void addNewHeader(){
header = new Header();
}
public void addNewBody(){
body = new Body();
}
public void addNewPhaseinfo(){
phaseinfo = new Phaseinfo();
}
public Header getHeader() {
return header;
}
public void setHeader(Header header) {
this.header = header;
}
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
public Phaseinfo getPhaseinfo() {
return phaseinfo;
}
public void setPhaseinfo(Phaseinfo phaseinfo) {
this.phaseinfo = phaseinfo;
}
public String getTelegramHeader() {
return telegramHeader;
}
public void setTelegramHeader(String telegramHeader) {
this.telegramHeader = telegramHeader;
}
public String getTelegramBody() {
return telegramBody;
}
public void setTelegramBody(String telegramBody) {
this.telegramBody = telegramBody;
}
public String getFileHeader() {
return fileHeader;
}
public void setFileHeader(String fileHeader) {
this.fileHeader = fileHeader;
}
public String getFileTrailer() {
return fileTrailer;
}
public void setFileTrailer(String fileTrailer) {
this.fileTrailer = fileTrailer;
}
@Override
public String toString() {
return "[BatchMsg]\n" + header + body + phaseinfo + "\nlogger=" + (logger == null ? "null" : logger.getName())
+ "\ntelegramHeader=" + telegramHeader + "\ntelegramBody=" + telegramBody
+ "\nfileHeader=" + fileHeader + "\nfileTrailer="
+ fileTrailer + "]";
}
}
/**
* 로거가 없을 경우 기본 로거를 ElinkLogger.LOGGER_DEFAULT로 얻는다.
*/
public Logger getLogger() {
if (logger == null) {
logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
logger.error("inst logger is null {}", batchMsg.toString());
}
return logger;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
/**
* 로거가 없을 경우 기본 로거를 loggerAdapter로 얻는다.
* @param loggerAdapter 로거가 없을 경우 기본 로거
* @return
*/
public Logger getLogger(String loggerAdapter) {
if (logger == null) {
logger = Logger.getLogger(loggerAdapter);
logger.error("inst logger is null {}", batchMsg.toString());
}
return logger;
}
public void setIOStream(Object bos) {
this.bos = bos;
}
public Object getIOStream() {
return this.bos;
}
public void setCurrIODataByte(long currIODataByte) {
this.currIODataByte = currIODataByte;
}
public long getCurrIODataByte() {
return this.currIODataByte ;
}
}
+397
View File
@@ -0,0 +1,397 @@
package com.eactive.eai.batch.doc;
import java.io.Serializable;
public class Body implements Serializable
{
private static final long serialVersionUID = 1L;
String subUUID ;
String subLayerCode ;
String wLIServerName ;
String portNo ;
int nodeCount ;
String flowPhaseCode ;
String lastPhaseCode ;
String nextPhaseCode ;
String phaseType ;
String lastPhaseType ;
String nextPhaseType ;
String sndMsgCode ;
String rcvMsgCode ;
String phaseStartTime ;
String phaseEndTime ;
String lastPhaseStartTime ;
String lastPhaseEndTime ;
String actionTag ;
String recallTag ;
String timeoutInterval ;
int retryCount ;
int blockNum ;
int seqNum ;
String missingNmField ;
int missingNmCount ;
long curFileSize ;
long recCnt ;
long curFileRecCnt ;
String lastResCode ;
int errorCode ;
String errorMsg ;
String recvedMsg ;
String sendSummary ;
byte[] sendBuffer ;
String instExt ;
String recvFld01 ;
String recvFld02 ;
String recvFld03 ;
String recvFld04 ;
String recvFld05 ;
String recvFld06 ;
String recvFld07 ;
String recvFld08 ;
String recvFld09 ;
String recvFld10 ;
public String getSubUUID() {
return subUUID;
}
public void setSubUUID(String subUUID) {
this.subUUID = subUUID;
}
public String getSubLayerCode() {
return subLayerCode;
}
public void setSubLayerCode(String subLayerCode) {
this.subLayerCode = subLayerCode;
}
public String getWLIServerName() {
return wLIServerName;
}
public void setWLIServerName(String wLIServerName) {
this.wLIServerName = wLIServerName;
}
public String getPortNo() {
return portNo;
}
public void setPortNo(String portNo) {
this.portNo = portNo;
}
public int getNodeCount() {
return nodeCount;
}
public void setNodeCount(int nodeCount) {
this.nodeCount = nodeCount;
}
public String getFlowPhaseCode() {
return flowPhaseCode;
}
public void setFlowPhaseCode(String flowPhaseCode) {
this.flowPhaseCode = flowPhaseCode;
}
public String getLastPhaseCode() {
return lastPhaseCode;
}
public void setLastPhaseCode(String lastPhaseCode) {
this.lastPhaseCode = lastPhaseCode;
}
public String getNextPhaseCode() {
return nextPhaseCode;
}
public void setNextPhaseCode(String nextPhaseCode) {
this.nextPhaseCode = nextPhaseCode;
}
public String getPhaseType() {
return phaseType;
}
public void setPhaseType(String phaseType) {
this.phaseType = phaseType;
}
public String getLastPhaseType() {
return lastPhaseType;
}
public void setLastPhaseType(String lastPhaseType) {
this.lastPhaseType = lastPhaseType;
}
public String getNextPhaseType() {
return nextPhaseType;
}
public void setNextPhaseType(String nextPhaseType) {
this.nextPhaseType = nextPhaseType;
}
public String getSndMsgCode() {
return sndMsgCode;
}
public void setSndMsgCode(String sndMsgCode) {
this.sndMsgCode = sndMsgCode;
}
public String getRcvMsgCode() {
return rcvMsgCode;
}
public void setRcvMsgCode(String rcvMsgCode) {
this.rcvMsgCode = rcvMsgCode;
}
public String getPhaseStartTime() {
return phaseStartTime;
}
public void setPhaseStartTime(String phaseStartTime) {
this.phaseStartTime = phaseStartTime;
}
public String getPhaseEndTime() {
return phaseEndTime;
}
public void setPhaseEndTime(String phaseEndTime) {
this.phaseEndTime = phaseEndTime;
}
public String getLastPhaseStartTime() {
return lastPhaseStartTime;
}
public void setLastPhaseStartTime(String lastPhaseStartTime) {
this.lastPhaseStartTime = lastPhaseStartTime;
}
public String getLastPhaseEndTime() {
return lastPhaseEndTime;
}
public void setLastPhaseEndTime(String lastPhaseEndTime) {
this.lastPhaseEndTime = lastPhaseEndTime;
}
public String getActionTag() {
return actionTag;
}
public void setActionTag(String actionTag) {
this.actionTag = actionTag;
}
public String getRecallTag() {
return recallTag;
}
public void setRecallTag(String recallTag) {
this.recallTag = recallTag;
}
public String getTimeoutInterval() {
return timeoutInterval;
}
public void setTimeoutInterval(String timeoutInterval) {
this.timeoutInterval = timeoutInterval;
}
public int getRetryCount() {
return retryCount;
}
public void setRetryCount(int retryCount) {
this.retryCount = retryCount;
}
public int getBlockNum() {
return blockNum;
}
public void setBlockNum(int blockNum) {
this.blockNum = blockNum;
}
public int getSeqNum() {
return seqNum;
}
public void setSeqNum(int seqNum) {
this.seqNum = seqNum;
}
public String getMissingNmField() {
return missingNmField;
}
public void setMissingNmField(String missingNmField) {
this.missingNmField = missingNmField;
}
public int getMissingNmCount() {
return missingNmCount;
}
public void setMissingNmCount(int missingNmCount) {
this.missingNmCount = missingNmCount;
}
public long getCurFileSize() {
return curFileSize;
}
public void setCurFileSize(long curFileSize) {
this.curFileSize = curFileSize;
}
public long getRecCnt() {
return recCnt;
}
public void setRecCnt(long recCnt) {
this.recCnt = recCnt;
}
public long getCurFileRecCnt() {
return curFileRecCnt;
}
public void setCurFileRecCnt(long curFileRecCnt) {
this.curFileRecCnt = curFileRecCnt;
}
public String getLastResCode() {
return lastResCode;
}
public void setLastResCode(String lastResCode) {
this.lastResCode = lastResCode;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getRecvedMsg() {
return recvedMsg;
}
public void setRecvedMsg(String recvedMsg) {
this.recvedMsg = recvedMsg;
}
public String getSendSummary() {
return sendSummary;
}
public void setSendSummary(String sendSummary) {
this.sendSummary = sendSummary;
}
public byte[] getSendBuffer() {
return sendBuffer;
}
public void setSendBuffer(byte[] sendBuffer) {
this.sendBuffer = sendBuffer;
}
public String getInstExt() {
return instExt;
}
public void setInstExt(String instExt) {
this.instExt = instExt;
}
public String getRecvFld01() {
return recvFld01;
}
public void setRecvFld01(String recvFld01) {
this.recvFld01 = recvFld01;
}
public String getRecvFld02() {
return recvFld02;
}
public void setRecvFld02(String recvFld02) {
this.recvFld02 = recvFld02;
}
public String getRecvFld03() {
return recvFld03;
}
public void setRecvFld03(String recvFld03) {
this.recvFld03 = recvFld03;
}
public String getRecvFld04() {
return recvFld04;
}
public void setRecvFld04(String recvFld04) {
this.recvFld04 = recvFld04;
}
public String getRecvFld05() {
return recvFld05;
}
public void setRecvFld05(String recvFld05) {
this.recvFld05 = recvFld05;
}
public String getRecvFld06() {
return recvFld06;
}
public void setRecvFld06(String recvFld06) {
this.recvFld06 = recvFld06;
}
public String getRecvFld07() {
return recvFld07;
}
public void setRecvFld07(String recvFld07) {
this.recvFld07 = recvFld07;
}
public String getRecvFld08() {
return recvFld08;
}
public void setRecvFld08(String recvFld08) {
this.recvFld08 = recvFld08;
}
public String getRecvFld09() {
return recvFld09;
}
public void setRecvFld09(String recvFld09) {
this.recvFld09 = recvFld09;
}
public String getRecvFld10() {
return recvFld10;
}
public void setRecvFld10(String recvFld10) {
this.recvFld10 = recvFld10;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Body\nsubUUID:");
builder.append(subUUID);
builder.append("\nsubLayerCode:");
builder.append(subLayerCode);
builder.append("\nwLIServerName:");
builder.append(wLIServerName);
builder.append("\nportNo:");
builder.append(portNo);
builder.append("\nnodeCount:");
builder.append(nodeCount);
builder.append("\nflowPhaseCode:");
builder.append(flowPhaseCode);
builder.append("\nlastPhaseCode:");
builder.append(lastPhaseCode);
builder.append("\nnextPhaseCode:");
builder.append(nextPhaseCode);
builder.append("\nphaseType:");
builder.append(phaseType);
builder.append("\nlastPhaseType:");
builder.append(lastPhaseType);
builder.append("\nnextPhaseType:");
builder.append(nextPhaseType);
builder.append("\nsndMsgCode:");
builder.append(sndMsgCode);
builder.append("\nrcvMsgCode:");
builder.append(rcvMsgCode);
builder.append("\nphaseStartTime:");
builder.append(phaseStartTime);
builder.append("\nphaseEndTime:");
builder.append(phaseEndTime);
builder.append("\nlastPhaseStartTime:");
builder.append(lastPhaseStartTime);
builder.append("\nlastPhaseEndTime:");
builder.append(lastPhaseEndTime);
builder.append("\nactionTag:");
builder.append(actionTag);
builder.append("\nrecallTag:");
builder.append(recallTag);
builder.append("\ntimeoutInterval:");
builder.append(timeoutInterval);
builder.append("\nretryCount:");
builder.append(retryCount);
builder.append("\nblockNum:");
builder.append(blockNum);
builder.append("\nseqNum:");
builder.append(seqNum);
builder.append("\nmissingNmField:");
builder.append(missingNmField);
builder.append("\nmissingNmCount:");
builder.append(missingNmCount);
builder.append("\ncurFileSize:");
builder.append(curFileSize);
builder.append("\nrecCnt:");
builder.append(recCnt);
builder.append("\nlastResCode:");
builder.append(lastResCode);
builder.append("\nerrorCode:");
builder.append(errorCode);
builder.append("\nerrorMsg:");
builder.append(errorMsg);
builder.append("\nrecvedMsg:");
builder.append(recvedMsg);
builder.append("\nsendSummary:");
builder.append(sendSummary);
builder.append("\ninstExt:");
builder.append(instExt);
return builder.toString();
}
}
+400
View File
@@ -0,0 +1,400 @@
package com.eactive.eai.batch.doc;
import java.io.Serializable;
public class Header implements Serializable
{
private static final long serialVersionUID = 1L;
String uUID ;
String tRX_ID ;
String layerCode ;
String processType ;
String processCode ;
String processName ;
String institutionCode ;
String institutionName ;
// String instituaionType ;
String jobCode ;
String scheduleCode ;
String fileName ;
String filePath ;
String userID ;
String userName ;
String userPassword ;
String scheduleSTime ;
String scheduleETime ;
String renamedFileName ;
String flowCode ;
String systemConnCode ;
long fileSize ;
int blockSize ;
int sequenceSize ;
String remoteIP ;
String port ;
String batchStartTime ;
String requestResponse ;
String sendRecv ;
String ruleCode ;
String ruleDesc ;
// String protocol ;
String bizCode ;
String fileErrorPath ;
int packetSize ;
int recLen ;
long totRecCnt ;
String baseDate ;
String eventScheduleID ;
String hdrInfoName ;
String recvUserID ;
String recvUserPassword ;
boolean reqSendRetryFlag ;
public String getUUID() {
return uUID;
}
public void setUUID(String uUID) {
this.uUID = uUID;
}
public String getTRXID() {
return tRX_ID;
}
public void setTRXID(String tRX_ID) {
this.tRX_ID = tRX_ID;
}
public String getLayerCode() {
return layerCode;
}
public void setLayerCode(String layerCode) {
this.layerCode = layerCode;
}
public String getProcessType() {
return processType;
}
public void setProcessType(String processType) {
this.processType = processType;
}
public String getProcessCode() {
return processCode;
}
public void setProcessCode(String processCode) {
this.processCode = processCode;
}
public String getProcessName() {
return processName;
}
public void setProcessName(String processName) {
this.processName = processName;
}
public String getInstitutionCode() {
return institutionCode;
}
public void setInstitutionCode(String institutionCode) {
this.institutionCode = institutionCode;
}
public String getInstitutionName() {
return institutionName;
}
public void setInstitutionName(String institutionName) {
this.institutionName = institutionName;
}
// public String getInstituaionType() {
// return instituaionType;
// }
// public void setInstituaionType(String instituaionType) {
// this.instituaionType = instituaionType;
// }
public String getJobCode() {
return jobCode;
}
public void setJobCode(String jobCode) {
this.jobCode = jobCode;
}
public String getScheduleCode() {
return scheduleCode;
}
public void setScheduleCode(String scheduleCode) {
this.scheduleCode = scheduleCode;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getScheduleSTime() {
return scheduleSTime;
}
public void setScheduleSTime(String scheduleSTime) {
this.scheduleSTime = scheduleSTime;
}
public String getScheduleETime() {
return scheduleETime;
}
public void setScheduleETime(String scheduleETime) {
this.scheduleETime = scheduleETime;
}
public String getRenamedFileName() {
return renamedFileName;
}
public void setRenamedFileName(String renamedFileName) {
this.renamedFileName = renamedFileName;
}
public String getFlowCode() {
return flowCode;
}
public void setFlowCode(String flowCode) {
this.flowCode = flowCode;
}
public String getSystemConnCode() {
return systemConnCode;
}
public void setSystemConnCode(String systemConnCode) {
this.systemConnCode = systemConnCode;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public int getBlockSize() {
return blockSize;
}
public void setBlockSize(int blockSize) {
this.blockSize = blockSize;
}
public int getSequenceSize() {
return sequenceSize;
}
public void setSequenceSize(int sequenceSize) {
this.sequenceSize = sequenceSize;
}
public String getRemoteIP() {
return remoteIP;
}
public void setRemoteIP(String remoteIP) {
this.remoteIP = remoteIP;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getBatchStartTime() {
return batchStartTime;
}
public void setBatchStartTime(String batchStartTime) {
this.batchStartTime = batchStartTime;
}
public String getRequestResponse() {
return requestResponse;
}
public void setRequestResponse(String requestResponse) {
this.requestResponse = requestResponse;
}
public String getSendRecv() {
return sendRecv;
}
public void setSendRecv(String sendRecv) {
this.sendRecv = sendRecv;
}
public String getRuleCode() {
return ruleCode;
}
public void setRuleCode(String ruleCode) {
this.ruleCode = ruleCode;
}
public String getRuleDesc() {
return ruleDesc;
}
public void setRuleDesc(String ruleDesc) {
this.ruleDesc = ruleDesc;
}
// public String getProtocol() {
// return protocol;
// }
// public void setProtocol(String protocol) {
// this.protocol = protocol;
// }
public String getBizCode() {
return bizCode;
}
public void setBizCode(String bizCode) {
this.bizCode = bizCode;
}
public String getFileErrorPath() {
return fileErrorPath;
}
public void setFileErrorPath(String fileErrorPath) {
this.fileErrorPath = fileErrorPath;
}
public int getPacketSize() {
return packetSize;
}
public void setPacketSize(int packetSize) {
this.packetSize = packetSize;
}
public int getRecLen() {
return recLen;
}
public void setRecLen(int recLen) {
this.recLen = recLen;
}
public long getTotRecCnt() {
return totRecCnt;
}
public void setTotRecCnt(long totRecCnt) {
this.totRecCnt = totRecCnt;
}
public String getBaseDate() {
return baseDate;
}
public void setBaseDate(String baseDate) {
this.baseDate = baseDate;
}
public String getEventScheduleID() {
return eventScheduleID;
}
public void setEventScheduleID(String eventScheduleID) {
this.eventScheduleID = eventScheduleID;
}
public String getHdrInfoName() {
return hdrInfoName;
}
public void setHdrInfoName(String hdrInfoName) {
this.hdrInfoName = hdrInfoName;
}
public String getRecvUserID() {
return recvUserID;
}
public void setRecvUserID(String recvUserID) {
this.recvUserID = recvUserID;
}
public String getRecvUserPassword() {
return recvUserPassword;
}
public void setRecvUserPassword(String recvUserPassword) {
this.recvUserPassword = recvUserPassword;
}
public boolean getReqSendRetryFlag() {
return reqSendRetryFlag;
}
public void setReqSendRetryFlag(boolean reqSendRetryFlag) {
this.reqSendRetryFlag = reqSendRetryFlag;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Header\nUUID:");
builder.append(uUID);
builder.append("\nTRX_ID:");
builder.append(tRX_ID);
builder.append("\nlayerCode:");
builder.append(layerCode);
builder.append("\nprocessType:");
builder.append(processType);
builder.append("\nprocessCode:");
builder.append(processCode);
builder.append("\nprocessName:");
builder.append(processName);
builder.append("\ninstitutionCode:");
builder.append(institutionCode);
builder.append("\ninstitutionName:");
builder.append(institutionName);
builder.append("\njobCode:");
builder.append(jobCode);
builder.append("\nscheduleCode:");
builder.append(scheduleCode);
builder.append("\nfileName:");
builder.append(fileName);
builder.append("\nfilePath:");
builder.append(filePath);
builder.append("\nuserID:");
builder.append(userID);
builder.append("\nuserName:");
builder.append(userName);
builder.append("\nuserPassword:");
builder.append(userPassword);
builder.append("\nscheduleSTime:");
builder.append(scheduleSTime);
builder.append("\nscheduleETime:");
builder.append(scheduleETime);
builder.append("\nrenamedFileName:");
builder.append(renamedFileName);
builder.append("\nflowCode:");
builder.append(flowCode);
builder.append("\nsystemConnCode:");
builder.append(systemConnCode);
builder.append("\nfileSize:");
builder.append(fileSize);
builder.append("\nblockSize:");
builder.append(blockSize);
builder.append("\nsequenceSize:");
builder.append(sequenceSize);
builder.append("\nremoteIP:");
builder.append(remoteIP);
builder.append("\nport:");
builder.append(port);
builder.append("\nbatchStartTime:");
builder.append(batchStartTime);
builder.append("\nrequestResponse:");
builder.append(requestResponse);
builder.append("\nsendRecv:");
builder.append(sendRecv);
builder.append("\nruleCode:");
builder.append(ruleCode);
builder.append("\nruleDesc:");
builder.append(ruleDesc);
// builder.append("\nprotocol:");
// builder.append(protocol);
builder.append("\nbizCode:");
builder.append(bizCode);
builder.append("\nfileErrorPath:");
builder.append(fileErrorPath);
builder.append("\npacketSize:");
builder.append(packetSize);
builder.append("\nrecLen:");
builder.append(recLen);
builder.append("\ntotRecCnt:");
builder.append(totRecCnt);
builder.append("\nbaseDate:");
builder.append(baseDate);
builder.append("\neventScheduleID:");
builder.append(eventScheduleID);
builder.append("\nhdrInfoName:");
builder.append(hdrInfoName);
builder.append("\nrecvUserID:");
builder.append(recvUserID);
builder.append("\nrecvUserPassword:");
builder.append(recvUserPassword);
builder.append("\nreqSendRetryFlag:");
builder.append(reqSendRetryFlag);
return builder.toString();
}
}
@@ -0,0 +1,158 @@
package com.eactive.eai.batch.doc;
import java.io.Serializable;
public class Phaseinfo implements Serializable
{
private static final long serialVersionUID = 1L;
String ruleCode ;
String phaseCode ;
String phaseType ;
String flowClassName ;
String lengthTelegramID ;
String lengthClassName ;
String lengthMsgCode ;
int lengthFieldIndex ;
String phaseSeq ;
String phaseTelegramID ;
String phaseClassName ;
String phaseMsgCode ;
String telegramTypeValue ;
String bizCodeValue ;
String controlCodeValue ;
String responseCodeValue ;
public String getRuleCode() {
return ruleCode;
}
public void setRuleCode(String ruleCode) {
this.ruleCode = ruleCode;
}
public String getPhaseCode() {
return phaseCode;
}
public void setPhaseCode(String phaseCode) {
this.phaseCode = phaseCode;
}
public String getPhaseType() {
return phaseType;
}
public void setPhaseType(String phaseType) {
this.phaseType = phaseType;
}
public String getFlowClassName() {
return flowClassName;
}
public void setFlowClassName(String flowClassName) {
this.flowClassName = flowClassName;
}
public String getLengthTelegramID() {
return lengthTelegramID;
}
public void setLengthTelegramID(String lengthTelegramID) {
this.lengthTelegramID = lengthTelegramID;
}
public String getLengthClassName() {
return lengthClassName;
}
public void setLengthClassName(String lengthClassName) {
this.lengthClassName = lengthClassName;
}
public String getLengthMsgCode() {
return lengthMsgCode;
}
public void setLengthMsgCode(String lengthMsgCode) {
this.lengthMsgCode = lengthMsgCode;
}
public int getLengthFieldIndex() {
return lengthFieldIndex;
}
public void setLengthFieldIndex(int lengthFieldIndex) {
this.lengthFieldIndex = lengthFieldIndex;
}
public String getPhaseSeq() {
return phaseSeq;
}
public void setPhaseSeq(String phaseSeq) {
this.phaseSeq = phaseSeq;
}
public String getPhaseTelegramID() {
return phaseTelegramID;
}
public void setPhaseTelegramID(String phaseTelegramID) {
this.phaseTelegramID = phaseTelegramID;
}
public String getPhaseClassName() {
return phaseClassName;
}
public void setPhaseClassName(String phaseClassName) {
this.phaseClassName = phaseClassName;
}
public String getPhaseMsgCode() {
return phaseMsgCode;
}
public void setPhaseMsgCode(String phaseMsgCode) {
this.phaseMsgCode = phaseMsgCode;
}
public String getTelegramTypeValue() {
return telegramTypeValue;
}
public void setTelegramTypeValue(String telegramTypeValue) {
this.telegramTypeValue = telegramTypeValue;
}
public String getBizCodeValue() {
return bizCodeValue;
}
public void setBizCodeValue(String bizCodeValue) {
this.bizCodeValue = bizCodeValue;
}
public String getControlCodeValue() {
return controlCodeValue;
}
public void setControlCodeValue(String controlCodeValue) {
this.controlCodeValue = controlCodeValue;
}
public String getResponseCodeValue() {
return responseCodeValue;
}
public void setResponseCodeValue(String responseCodeValue) {
this.responseCodeValue = responseCodeValue;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Phaseinfo\nruleCode:");
builder.append(ruleCode);
builder.append("\nphaseCode:");
builder.append(phaseCode);
builder.append("\nphaseType:");
builder.append(phaseType);
builder.append("\nflowClassName:");
builder.append(flowClassName);
builder.append("\nlengthTelegramID:");
builder.append(lengthTelegramID);
builder.append("\nlengthClassName:");
builder.append(lengthClassName);
builder.append("\nlengthMsgCode:");
builder.append(lengthMsgCode);
builder.append("\nlengthFieldIndex:");
builder.append(lengthFieldIndex);
builder.append("\nphaseSeq:");
builder.append(phaseSeq);
builder.append("\nphaseTelegramID:");
builder.append(phaseTelegramID);
builder.append("\nphaseClassName:");
builder.append(phaseClassName);
builder.append("\nphaseMsgCode:");
builder.append(phaseMsgCode);
builder.append("\ntelegramTypeValue:");
builder.append(telegramTypeValue);
builder.append("\nbizCodeValue:");
builder.append(bizCodeValue);
builder.append("\ncontrolCodeValue:");
builder.append(controlCodeValue);
builder.append("\nresponseCodeValue:");
builder.append(responseCodeValue);
return builder.toString();
}
}
@@ -0,0 +1,482 @@
package com.eactive.eai.batch.encrypt;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Hashtable;
/**
* 1. 기능 : 전문 생성시 사용자 암호를 생성한다.
* 2. 처리 개요 : CMS은행을 기준으로 암호화 및 복호화 알고리즘을 구현한다.
* 3. 주의사항
*
* @author : 이윤철 (2006/1/6)
* @version : v 1.0.0
* @see : 관련 기능을 참조
* @since :
*/
public class EncryptManager implements Lifecycle
{
//private static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_DEFAULT);
/**
* EncryptManager Single Instance
*/
private static EncryptManager instance = new EncryptManager();
/**
* LifeccyleSupport object
*/
private LifecycleSupport lifecycle = new LifecycleSupport(this);
/**
* 기동 여부
*/
private boolean started;
/**
* 암호화 테이블
*/
private static Hashtable<String, String> codeTable;
/**
* 1. 기능 : Default Constructor
* 2. 처리 개요 : Flow Rule 정보를 저장하기 위한 HashMap을 초기화한다.
* 3. 주의사항
*
**/
private EncryptManager() {
codeTable = new Hashtable<String, String>();
initTable();
}
// 암호화 대수 테이블 초기화
private static void initTable()
{
if(codeTable.isEmpty())
{
for(int i=65; i<91; i++)
{
String key = new Character((char)i).toString();
String value = new Integer(100 - i).toString();
codeTable.put(key, value);
codeTable.put(value, key);
}
for(int i=0; i<10; i++)
{
String key = new Integer(i).toString();
String value = new Integer(9-i).toString();
codeTable.put(key, value);
}
//logger.debug("** if Hashtable : A = : " + codeTable.get("A"));
//logger.debug("** Hashtable = : " + codeTable.toString());
}
else
{
//logger.debug("** else Hashtable : A = : " + codeTable.get("A"));
}
}
/**
* 1. 기능 : EncryptManager Singleton Object를 반환하는 getter method
* 2. 처리 개요 : EncryptManager Singleton Object를 반환한다.
* 3. 주의사항
*
* @return FlowRuleManager Singleton object
**/
public static EncryptManager getInstance() {
if(instance == null)
instance = new EncryptManager();
return instance;
}
/* ****************************************************************** */
/* EncryptManager 자체적인 메소드 정의 */
/* ****************************************************************** */
/**
* 1. 기능 : 암호화 알고리즘
* 2. 처리 개요 :
*
* 3. 주의사항
*
* @param 전송자명(영문), 전송자암호, 은행코드, 전송일(yymmdd)
* @return 사용자 암호 평문을 암호화하여 반환
* @exception
**/
public String getEncrypt(String transferName, String transferPwd, String bankCode, String transferDate) throws Exception
{
/**
* 1. 제한 조건
* - 거래일은 YYMMDD 형태(6자리)이다.
* 2. 입력문장 예시
* - transferName = "Kimchungjin"; //전송자명 (영문)
* transferPwd = "1234567890123456"; //전송자암호평문
* bankCode = "02"; //은행코드
* transferDate = "950815"; //전송년월일
*/
//logger.debug( "[EncryptManager][getEncrypt]:transferName(" + transferName + "), transferPwd(" + transferPwd
// + "), bankCode(" + bankCode + "), transferDate(" + transferDate + ")");
/* 변수 */
String encryptSeed = ""; // encryptSeed = 은행코드(2)+거래일(6, yymmdd)+전송자명 앞 8자리, 총16자리
String encryptMsg = ""; // 암호화된 결과를 보내는 문장
/* 전송자명 체크
* - 전송자명이 8자리보다 적으면 빈자리는 Z로 채운다.
* - 전송자명이 8자리보다 크면 앞의 8자리만 사용한다.
*/
transferName = transferName.toUpperCase();
if(transferName.length() > 8)
transferName = transferName.substring(0,8);
else
{
for(; transferName.length() < 8; )
{
transferName += "Z";
}
}
/* 전송자암호 체크 : 전송자 암호는 6자리이며 앞에서부터 반복해서 16자리로 만든다. */
// 암호에 공백이 들어 갈수 없다. 2009.01.08
if(transferPwd.trim().length() != 6)
throw new Exception("전송자 암호 평문은 반드시 6자리이어야합니다.(공백불가) : " + transferPwd);
transferPwd = transferPwd.toUpperCase();
for(int i=0; transferPwd.length() != 16; i++)
{
transferPwd += transferPwd.substring(i, i+1);
}
//transferPwd = "1234567890123456"; for test...
//logger.debug("transferPwd : " + transferPwd);
/* 전송일 체크 */
if(transferDate.length() != 6)
throw new Exception("전송일은 반드시 6자리(YYMMDD)이어야합니다. : " + transferDate);
/* 암호화 Seed를 생성한다. */
encryptSeed = bankCode + transferDate + transferName;
/* 암호화 문장 생성 */
for(int i=0; i<16; i++)
{
int m_Msg = new Integer((String)codeTable.get(transferPwd.substring(i, i+1))).intValue();
int m_Key = new Integer((String)codeTable.get(encryptSeed.substring(i, i+1))).intValue();
encryptMsg += (String)codeTable.get(new Integer((m_Msg + m_Key) % 36).toString());
}
return encryptMsg;
}
public String getEncryptForKCB(String transferName, String transferPwd, String bankCode, String transferDate) throws Exception
{
/**
* 1. 제한 조건
* - 거래일은 YYMMDD 형태(6자리)이다.
* 2. 입력문장 예시
* - transferName = "Kimchungjin"; //전송자명 (영문)
* transferPwd = "1234567890123456"; //전송자암호평문
* bankCode = "02"; //은행코드
* transferDate = "950815"; //전송년월일
* 적용 암호키 : A001050815Kimchu
*/
/* 변수 */
String encryptSeed = ""; // encryptSeed = 은행코드(A001)+거래일(6, yymmdd)+전송자명 앞 6자리, 총16자리
String encryptMsg = ""; // 암호화된 결과를 보내는 문장
/* 전송자명 체크
* - 전송자명이 6자리보다 적으면 빈자리는 Z로 채운다.
* - 전송자명이 6자리보다 크면 앞의 8자리만 사용한다.
*/
transferName = transferName.toUpperCase();
if(transferName.length() > 6)
transferName = transferName.substring(0,6);
else
{
for(; transferName.length() < 6; )
{
transferName += "Z";
}
}
/* 전송자암호 체크 : 전송자 암호는 6자리이며 앞에서부터 반복해서 16자리로 만든다. */
// 암호에 공백이 들어 갈수 없다. 2009.01.08
// if(transferPwd.trim().length() != 16)
// throw new Exception("전송자 암호 평문은 반드시 6자리이어야합니다.(공백불가) : " + transferPwd);
transferPwd = transferPwd.toUpperCase();
for(int i=0; transferPwd.length() != 16; i++)
{
transferPwd += transferPwd.substring(i, i+1);
}
//transferPwd = "1234567890123456"; for test...
//logger.debug("transferPwd : " + transferPwd);
/* 전송일 체크 */
if(transferDate.length() != 6)
throw new Exception("전송일은 반드시 6자리(YYMMDD)이어야합니다. : " + transferDate);
/* 암호화 Seed를 생성한다. */
encryptSeed = bankCode + transferDate + transferName;
/* 암호화 문장 생성 */
for(int i=0; i<16; i++)
{
int m_Msg = new Integer((String)codeTable.get(transferPwd.substring(i, i+1))).intValue();
int m_Key = new Integer((String)codeTable.get(encryptSeed.substring(i, i+1))).intValue();
encryptMsg += (String)codeTable.get(new Integer((m_Msg + m_Key) % 36).toString());
}
return encryptMsg;
}
/**
* 1. 기능 : 복호화 알고리즘 메인
* 2. 처리 개요 :
*
* 3. 주의사항
* @param 전달받은 사용자암호(암호화된것), 암호해독 seed
* @return
* @exception
**/
public String getDeEncrypt(String encryptMsg, String seed)
{
/* 변수 */
String normalMsg = "";
seed = seed.toUpperCase();
for(int i=0; i<16; i++)
{
int m_Msg = new Integer((String)codeTable.get(encryptMsg.substring(i, i+1))).intValue() + 36;
int m_Key = new Integer((String)codeTable.get(seed.substring(i, i+1))).intValue();
normalMsg += (String)codeTable.get(new Integer((m_Msg - m_Key) % 36).toString());
}
return normalMsg;
}
/**
* 1. 기능 : 복호화 알고리즘
* 복화화 알고리즘 Seed를 개별로 받아들임
* 2. 처리 개요 :
*
* 3. 주의사항
* @param 전달받은 사용자암호(암호화된것), 은행코드(2), 전송년월일(6), 전송자명(8)
* @return 사용자 암호 평문
* @exception
**/
public String getDeEncrypt(String encryptMsg, String bankCode, String transferDate, String transferName)
{
/* 전송자명 체크
* - 전송자명이 8자리보다 적으면 빈자리는 Z로 채운다.
* - 전송자명이 8자리보다 크면 앞의 8자리만 사용한다.
*/
transferName = transferName.toUpperCase();
if(transferName.length() > 8)
transferName = transferName.substring(0,8);
else
{
for(; transferName.length() < 8; )
{
transferName += "Z";
}
}
String seed = bankCode + transferDate + transferName;
return this.getDeEncrypt(encryptMsg, seed);
}
/**
* 1. 기능 : 암호화 알고리즘
* 2. 처리 개요 : this.getEncrypt(String, String, String, String)메소드는 코드내에 필요한 데이터를 추출(예. 전송자명 앞 8자리 추출)
* getEncryptPwd 메소드는 메소드를 호출하는 부분에서 필요한 모든 데이터의 값을 정의해서 호출하고,
* 해당 메소드내에서는 전달된 값으로 암호화하는 작업만 수행하도록 한다.
* 3. 주의사항
*
* @param 전송자명(영문), 전송자암호, 은행코드, 전송일(yymmdd)
* @return 사용자 암호 평문을 암호화하여 반환
* @exception
**/
public String getEncryptPwd(String transferName, String transferPwd, String bankCode, String transferDate) throws Exception
{
/**
* 1. 제한 조건
* - 거래일은 YYMMDD 형태(6자리)이다.
* 2. 입력문장 예시
* - transferName = "KIMHYUNKUK"; //전송자명 (영문)
* transferPwd = "1234567890123456"; //전송자암호평문
* bankCode = "004"; //은행코드
* transferDate = 2008년 11월 13일; //전송년월일
*/
/* 변수 */
String encryptSeed = ""; // 적용암호키
String encryptMsg = ""; // 암호화된 결과를 보내는 문장
transferName = transferName.toUpperCase();
/* 전송자암호 체크 : 전송자 암호는 6자리이며 앞에서부터 반복해서 16자리로 만든다. */
// 암호에 공백이 들어 갈수 없다. 2009.01.08
if(transferPwd.trim().length() != 6)
throw new Exception("전송자 암호 평문은 반드시 6자리이어야합니다.(공백불가) : " + transferPwd);
transferPwd = transferPwd.toUpperCase();
for(int i=0; transferPwd.length() != 16; i++)
{
transferPwd += transferPwd.substring(i, i+1);
}
/* 전송일 체크 */
if(transferDate.length() != 6)
throw new Exception("전송일은 반드시 6자리(YYMMDD)이어야합니다. : " + transferDate);
/* 암호화 Seed를 생성한다. */
encryptSeed = bankCode + transferDate + transferName;
/* 암호화 문장 생성 */
for(int i=0; i<transferPwd.length(); i++)
{
int m_Msg = new Integer((String)codeTable.get(transferPwd.substring(i, i+1))).intValue();
int m_Key = new Integer((String)codeTable.get(encryptSeed.substring(i, i+1))).intValue();
encryptMsg += (String)codeTable.get(new Integer((m_Msg + m_Key) % 36).toString());
}
return encryptMsg;
}
/**
* 1. 기능 : 복호화 알고리즘
* 복화화 알고리즘 Seed를 개별로 받아들임.
*
* 2. 처리 개요 :this.getDeEncrypt(String, String, String, String)메소드는 코드내에 필요한 데이터를 추출(예. 전송자명 앞 8자리 추출)
* getDeEncryptPwd 메소드는 메소드를 호출하는 부분에서 필요한 모든 데이터의 값을 정의해서 호출하고,
* 해당 메소드내에서는 전달된 값으로 암호화하는 작업만 수행하도록 한다.
*
* 3. 주의사항
* @param 전달받은 사용자암호(암호화된것), 은행코드(2), 전송년월일(6), 전송자명(8)
* @return 사용자 암호 평문
* @exception
**/
public String getDeEncryptPwd(String encryptMsg, String bankCode, String transferDate, String transferName)
{
/* 전송자명 체크
* - 전송자명이 8자리보다 적으면 빈자리는 Z로 채운다.
* - 전송자명이 8자리보다 크면 앞의 8자리만 사용한다.
*/
transferName = transferName.toUpperCase();
String seed = bankCode + transferDate + transferName;
return this.getDeEncrypt(encryptMsg, seed);
}
/* ****************************************************************** */
/* Lifecycle 인터페이스에 정의된 메소드 */
/* ****************************************************************** */
/**
* 1. 기능 : Lifecycle의 start 메서드로 EAIServerMangaer를 초기화하는 메서드
* 2. 처리 개요 : EAIServerDAO를 이용해 추출 Rule 정보 모두를 가져와 초기화한다.
* 3. 주의사항
*
* @exception LifecycleException 이미 시작되었거나,
* EAIServerDAO를 통해 Rule 정보를 가져온다.
* DAOExcepiton이 발생될 경우
**/
public void start() throws LifecycleException
{
if (started)
throw new LifecycleException("BECEAICEH001"); //EncryptManager 가 이미 시작 되었습니다.
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
// 암호화 테이블을 초기화 한다.
initTable();
started = true;
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
}
/**
* 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드
* 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다.
* 3. 주의사항
*
* @exception LifecycleException 이미 종료된 경우 발생
**/
public void stop() throws LifecycleException {
// Validate and update our current component state
if (!started)
throw new LifecycleException("BECEAICEH002"); //EncryptManager 가 이미 종료 되었습니다.
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
started = 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);
}
/**
* 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드
* 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다.
* 3. 주의사항
*
* @return 초기화 여부
**/
public boolean isStarted() {
return this.started;
}
}
@@ -0,0 +1,40 @@
package com.eactive.eai.batch.eventscheduler.holiday;
import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import java.sql.ResultSet;
import java.util.ArrayList;
public class HolidayDAO extends BaseDAO implements HolidayQuery
{
public HolidayDAO()
{
}
public ArrayList<HolidayVO> getAllHolidays() throws DAOException
{
ArrayList<HolidayVO> holidays = new ArrayList<HolidayVO>();
try
{
connect(GET_ALL_HOLIDAY);
ResultSet rs = executeQuery();
while(rs.next()) {
HolidayVO vo = new HolidayVO(rs.getString(1).trim(), rs.getString(2).trim(), rs.getString(3).trim());
holidays.add(vo);
}
return holidays;
}catch(Exception e){
throw new DAOException(ExceptionUtil.getErrorCode(e, "BECEAIMEH001"));
}
finally
{
disconnect();
}
}
}
@@ -0,0 +1,13 @@
package com.eactive.eai.batch.eventscheduler.holiday;
public final class HolidayKeys {
public static final String LEGAL_HOLIDAY_TYPE = "LH"; //공휴일
// public static final String TEMP_HOLIDAY_TYPE = "TH" ; //임시휴일
public static final String NATIONAL_HOLIDAY_TYPE = "NH"; //명절 즉, 음력휴일
public static final String[] HOLIDAY_TYPE_KEYS={"1", "2", "3"};
public static final String[] HOLIDAY_TYPE_VALUES={"LH", "TH", "NH"};
// public static final String[] HOLIDAY_TYPE_DESC={"공휴일", "임시휴일", "음력휴일"};
}
@@ -0,0 +1,298 @@
package com.eactive.eai.batch.eventscheduler.holiday;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.quartz.impl.calendar.AnnualCalendar;
import org.quartz.impl.calendar.WeeklyCalendar;
import com.eactive.eai.batch.eventscheduler.util.LunarCalendar;
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;
public class HolidayManager implements Lifecycle
{
static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER);
private static HolidayManager instance = new HolidayManager();
private LifecycleSupport lifecycle;
private boolean started;
private ArrayList<HolidayVO> holidays;
private AnnualCalendar hcal; //등록된 휴일, 토, 일
private AnnualCalendar scal; //등록된 휴일, 일
private HolidayManager(){
lifecycle = new LifecycleSupport(this);
holidays = new ArrayList<HolidayVO>();
}
public static HolidayManager getInstance(){
return instance;
}
public void start() throws LifecycleException{
if(started){
throw new LifecycleException("BECEAIMEH201");
} else{
lifecycle.fireLifecycleEvent("starting", this);
DAOFactory daoFactory = DAOFactory.newInstance();
HolidayDAO dao = null;
try {
dao = (HolidayDAO)daoFactory.create(HolidayDAO.class);
holidays = dao.getAllHolidays();
makeCalendar();
} catch(DAOException e) {
throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMEH202"));
} catch (Exception e){
throw new LifecycleException(ExceptionUtil.getErrorCode(e,"BECEAIMEH202"));
}
started = true;
lifecycle.fireLifecycleEvent("started", this);
return;
}
}
public void stop() throws LifecycleException{
if(!started){
throw new LifecycleException("BECEAIMEH203");
} else {
lifecycle.fireLifecycleEvent("stoping", this);
holidays = null;
started = false;
lifecycle.fireLifecycleEvent("stopped", this);
return;
}
}
public void addLifecycleListener(LifecycleListener listener){
lifecycle.addLifecycleListener(listener);
}
public LifecycleListener[] findLifecycleListeners(){
return lifecycle.findLifecycleListeners();
}
public void removeLifecycleListener(LifecycleListener listener){
lifecycle.removeLifecycleListener(listener);
}
public boolean isStarted(){
return started;
}
public void removeHoliday(HolidayVO vo){
String rymd = vo.getHoliday();
String rtype = vo.getHolidayType();
try{
for (int i=0; i<holidays.size(); i++){
HolidayVO ivo = (HolidayVO)holidays.get(i);
String cymd = ivo.getHoliday();
String ctype = ivo.getHolidayType();
if (rymd.equals(cymd) && rtype.equals(ctype)){
holidays.remove(i);
break;
}
}
this.makeCalendar();
}catch (Exception e){
throw new RuntimeException ("occur RuntimeException at HolidayManager.removeHoliday ");
}
}
public void setHoliday(HolidayVO vo){
holidays.add(vo);
try{
this.makeCalendar();
}catch (Exception e){
throw new RuntimeException ("occur RuntimeException at HolidayManager.removeHoliday ");
}
}
public ArrayList<HolidayVO> getAllHoliday(){
return holidays;
}
public AnnualCalendar getCalendar (){
return this.hcal;
}
public void setCalendar (AnnualCalendar cal){
this.hcal = cal;
}
public boolean isAllHoliday(String day){
if (hcal == null){ //휴일 Calendar가 null이면 휴일 없음.
return false;
}
boolean result = false;
try {
Calendar dcal = createCalendar(day);
result = hcal.isDayExcluded(dcal);
int dow = dcal.get(Calendar.DAY_OF_WEEK);
if (result==false){ //등록된 휴일 목록에 없으면 주말휴일에 포함되는지 확인
WeeklyCalendar wcal = (WeeklyCalendar)hcal.getBaseCalendar();
result = wcal.isDayExcluded(dow);
}
}catch (Exception e){
throw new RuntimeException ("occur RuntimeException at HolidayManager.isAllHoliday - "+day);
}
return result;
}
public boolean isHoliday(String day){
if (scal == null){ //휴일 Calendar가 null이면 휴일 없음.
return false;
}
boolean result = false;
try {
Calendar dcal = createCalendar(day);
result = scal.isDayExcluded(dcal);
int dow = dcal.get(Calendar.DAY_OF_WEEK);
if (result==false){ //등록된 휴일 목록에 없으면 일요일에 포함되는지 확인
WeeklyCalendar wcal = (WeeklyCalendar)scal.getBaseCalendar();
result = wcal.isDayExcluded(dow);
}
}catch (Exception e){
logger.error(e.getMessage(), e);
throw new RuntimeException ("occur RuntimeException at HolidayManager.isHoliday - "+day + "\n" + e.getMessage());
}
return result;
}
/*
public String[] getHolidayNm(){
Iterator it = holidays.keySet().iterator();
String eaiIns[] = new String[holidays.size()];
for(int i = 0; it.hasNext(); i++)
eaiIns[i] = (String)it.next();
Arrays.sort(eaiIns);
return eaiIns;
}
public HolidayVO[] getHolidayVos(){
Iterator it = holidays.values().iterator();
HolidayVO vos[] = new HolidayVO[holidays.size()];
for(int i = 0; it.hasNext(); i++){
vos[i] = (HolidayVO)it.next();
}
return vos;
}
*/
public void makeCalendar() throws Exception{
TimeZone tz = TimeZone.getTimeZone("Asia/Seoul");
WeeklyCalendar weeklys = new WeeklyCalendar(tz);
weeklys.setDayExcluded(Calendar.SUNDAY, true); //일요일
weeklys.setDayExcluded(Calendar.SATURDAY, true); //토요일
WeeklyCalendar sunweek = new WeeklyCalendar(tz);
sunweek.setDayExcluded(Calendar.SUNDAY, true); //일요일
AnnualCalendar aholidays = new AnnualCalendar(weeklys);
scal = new AnnualCalendar(sunweek);
Calendar cal = null;
Calendar c = new GregorianCalendar();
int year = c.get(Calendar.YEAR);
if (holidays.size()>0){
for (int i=0; i<holidays.size(); i++){
HolidayVO vo = (HolidayVO)holidays.get(i);
String days = vo.getHoliday();
String type = vo.getHolidayType();
try{
if (HolidayKeys.NATIONAL_HOLIDAY_TYPE.equals(type)){//명절
String lunar = "";
String day = days.substring(4,8);
if ("1230".equals(day)){
lunar = (year-1)+day; //음력 12월 30일은 전년도로 계산해야 함.
}
else {
lunar = year+day;
}
String toSolar = LunarCalendar.toSolarOfNationalHoliday(lunar);
cal = createCalendar(toSolar);
aholidays.setDayExcluded(cal, true); //토,일을 포함한 전체 휴일
scal.setDayExcluded(cal, true); //일요일을 포함한 휴일
}
else {
if (HolidayKeys.LEGAL_HOLIDAY_TYPE.equals(type)){//공휴일
String calDays = year+days.substring(4,8);
cal = createCalendar(calDays);
}else {//임시휴일
int tyear = Integer.parseInt(days.substring(0, 4));
if (year <= tyear){ //임시휴일의 년도가 현재 년도 이후이면 셋팅
cal = createCalendar(days);
}
}
aholidays.setDayExcluded(cal, true);//토,일을 포함한 전체 휴일
scal.setDayExcluded(cal, true);//일요일을 포함한 전체 휴일
}
}catch (Exception e){
logger.error("HolidayManager ] makeCalendar - Holiday set failed - "+e.getMessage(),e);
throw new Exception(ExceptionUtil.getErrorCode(e,"BECEAIMEH204"));
}
}
}
setCalendar(aholidays);
}
private Calendar createCalendar(String days) throws Exception{
Calendar cal = null;
try{
int year = Integer.parseInt(days.substring(0, 4));
int month = Integer.parseInt(days.substring(4,6));
int day = Integer.parseInt(days.substring(6,8));
cal = new GregorianCalendar(year, month-1, day);
return cal;
} catch (Exception e){
logger.error("HolidayManager ] createCalendar - createCalendar failed - "+e.getMessage(),e);
String arg[] = new String[1];
arg[0] = days;
throw new Exception(ExceptionUtil.getErrorCode(e, "BECEAIMEH205", arg));
}
}
}
@@ -0,0 +1,11 @@
package com.eactive.eai.batch.eventscheduler.holiday;
import com.eactive.eai.common.dao.Keys;
public interface HolidayQuery
{
public static final String GET_ALL_HOLIDAY =
"SELECT HoldyDstcd, HoldyYmd, EvntSchdrHoldyCtnt \n"
+"FROM " + Keys.TABLE_OWNER + "TSEAIBE02 \n";
}
@@ -0,0 +1,64 @@
package com.eactive.eai.batch.eventscheduler.holiday;
import java.io.Serializable;
public class HolidayVO implements Serializable
{
private static final long serialVersionUID = 1L;
private String holidayType;
private String holiday;
private String description;
public HolidayVO(){
}
public HolidayVO(String type, String day, String desc){
this.holiday = day;
this.description = desc;
int typeLength = HolidayKeys.HOLIDAY_TYPE_KEYS.length;
for(int i=0; i<typeLength; i++){
if (HolidayKeys.HOLIDAY_TYPE_KEYS[i].equals(type)){
this.holidayType=HolidayKeys.HOLIDAY_TYPE_VALUES[i];
}
}
}
public void setHolidayType(String type){
this.holidayType = type;
}
public String getHolidayType(){
return holidayType;
}
public void setHoliday(String day){
this.holiday = day;
}
public String getHoliday(){
return holiday;
}
public void setDescription(String desc){
this.description = desc;
}
public String getDescription(){
return description;
}
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append("HolidayVO - [ ");
sb.append(", holidayType=").append(holidayType);
sb.append(", holiday=").append(holiday);
sb.append(", description=").append(description);
sb.append(" ]");
return sb.toString();
}
}
@@ -0,0 +1,63 @@
package com.eactive.eai.batch.eventscheduler.management;
import java.util.TimerTask;
import com.eactive.eai.batch.eventscheduler.holiday.HolidayManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
public class HolidayChecker extends TimerTask{
/**
* EAI FRAMEWORK DEFAULT FILE LOGGER
*/
static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER);
/**
* 일일 초기화를 위해 현재 날짜와 비교하기 위한 이전날짜
*/
private String prevYear;
/**
* 1. 기능 : Default 생성자
* 2. 처리 개요 :
* 3. 주의사항
**/
public HolidayChecker() {
prevYear = DatetimeUtil.getCurrentDate().substring(0,4);
logger.debug("HolidayChecker ] run .. currentYear - ["+prevYear+"]/["+DatetimeUtil.getCurrentDate()+"]");
}
/**
* 1. 기능 : 정해진시간에 초기화 수행
* 2. 처리 개요 :
* - DatetimeUtil로부터 현재 일자를 얻어 비교하여 일자가 변경된 경우 reset
* - 최근시간(10분 또는 1시간) 마다 reset
* 3. 주의사항
**/
public void run()
{
String currentYear = DatetimeUtil.getCurrentDate().substring(0,4);
logger.debug("HolidayChecker ] run .. currentYear - ["+currentYear+"]/["+DatetimeUtil.getCurrentDate()+"]");
if (!(currentYear.equals(prevYear))){
HolidayManager hmanager = HolidayManager.getInstance();
try{
hmanager.makeCalendar();
}catch (Exception e){
logger.error("HolidayChecker ] HolidayCalendar를 재구성하는데 에러가 발생했습니다. - "+e.getMessage());
}
prevYear = currentYear;
}
}
}
@@ -0,0 +1,208 @@
package com.eactive.eai.batch.eventscheduler.management;
import java.util.Timer;
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.property.PropManager;
import com.eactive.eai.common.util.Logger;
public class HolidayMonitor implements Lifecycle{
/**
* EAI FRAMEWORK DEFAULT FILE LOGGER
*/
static Logger logger = Logger.getLogger(Logger.LOGGER_SCHEDULER);
/**
* EAIServiceMonitor의 Singleton object
*/
private static HolidayMonitor instance = new HolidayMonitor();
/**
* EAIServiceMonitor의 Lifecycle Event 처리를 위한 LifecycleSupport object
*/
private LifecycleSupport lifecycle = new LifecycleSupport(this);
/**
* EAIServiceMonitor에서 사용하는 Poprties Group의 Key
*/
public static final String PROP_GROUP = "HolidayMonitor";
/**
* EAIServiceMonitor에서 사용하는 Property Key : MonitorChecker의 동작 주기
*/
public static final String PROP_PERIOD = "monitor.checker.period";
/**
* 일일, 최근시간별 데이터 저장을 위해 주기적으로 실행 Monitor check를 하는 TimerTask object
*/
private HolidayChecker checker;
/**
* MonitorChecker를 실제 실행하는 Timer object - add 20080618 by kscheon
*/
private Timer timer;
/**
* EAIServiceMonitor starting 여부를 체크하는 flag 변수
*/
private boolean started;
/**
* 1. 기능 : Default 생성자
* 2. 처리 개요 :
* -
* 3. 주의사항
*
* @param
* @return
* @exception
**/
private HolidayMonitor() {
}
/**
* 1. 기능 : EAIServiceMonitor Singleton object를 반환하는 메서드
* 2. 처리 개요 :
* - EAIServiceMonitor Singleton object의 reference 반환
* 3. 주의사항
*
*@return EAIServiceMonitor Singleton object
**/
public static HolidayMonitor getInstance() {
if(instance==null) {
synchronized(HolidayMonitor.class) {
if(instance==null) {
instance = new HolidayMonitor();
}
}
}
return instance;
}
/**
* 1. 기능 : EAIServiceMonitor의 초기화 작업을 실행하는 메서드
* 2. 처리 개요 :
* - MonitorChecker객체를 생성해 Timer에 등록 실행한다.
* 3. 주의사항
*
*@exception LifecycleException EAIServiceMonitor 초기화 실패 시 발생
**/
public void start() throws LifecycleException {
if (started) {
throw new LifecycleException("BECEAIMEH201");
}
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
PropManager pmanager = PropManager.getInstance();
long period = 1000*60*60*1; //10분은 1000*60*10
try {
period = Long.parseLong(pmanager.getProperty(PROP_GROUP, PROP_PERIOD));
} catch(Exception e) {}
this.checker = new HolidayChecker();
this.timer = new Timer();
this.timer.schedule(this.checker, period, period);
started = true;
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
}
/**
* 1. 기능 : EAIServiceMonitor의 종료시 undo 작업을 실행하는 메서드
* 2. 처리 개요 :
* - 초기화 작업 시 생성한 MonitorChecker객체를 종료한다.
* 3. 주의사항
*
*@exception LifecycleException EAIServiceMonitor undo 작업 실패 시 발생
**/
public void stop() throws LifecycleException {
// Validate and update our current component state
if(!started){
throw new LifecycleException("BECEAIMEH203");
} else {
lifecycle.fireLifecycleEvent("stoping", this);
started = false;
this.timer.cancel();
this.timer = null;
this.checker = null;
lifecycle.fireLifecycleEvent("stopped", this);
return;
}
}
/**
* 1. 기능 : LifecycleListener를 등록하는 메서드
* 2. 처리 개요 :
* - LifecycleListener를 등록한다.
* 3. 주의사항
*
*@param listener Lifecycle Evnet를 받을 LifecycleListener
**/
public void addLifecycleListener(LifecycleListener listener)
{
lifecycle.addLifecycleListener(listener);
}
/**
* 1. 기능 : 등록된 LifecycleListener를 반환하는 메서드
* 2. 처리 개요 :
* - 등록된 LifecycleListener를 반환한다.
* 3. 주의사항
*
*@return 등록된 LifecycleListner들
**/
public LifecycleListener[] findLifecycleListeners()
{
return lifecycle.findLifecycleListeners();
}
/**
* 1. 기능 : 등록된 LifecycleListener 중 특정 LifecyleListener를 삭제하는 메서드
* 2. 처리 개요 :
* - 등록된 특정 LifecycleListener를 삭제한다.
* 3. 주의사항
*
*@param listener 삭제할 LifecycleListener
**/
public void removeLifecycleListener(LifecycleListener listener)
{
lifecycle.removeLifecycleListener(listener);
}
/**
* 1. 기능 : EAIServiceMonitor의 start 여부를 반환하는 getter method
* 2. 처리 개요 :
* - EAIServiceMonitor의 start 여부를 반환한다.
* 3. 주의사항
*
*@return EAIServiceMonitor의 start 여부
**/
public boolean isStarted() {
return this.started;
}
}
@@ -0,0 +1,18 @@
package com.eactive.eai.batch.eventscheduler.management;
public class SchedulerEventException extends Exception
{
public SchedulerEventException()
{
super("SchedulerEventException is occured.");
}
public SchedulerEventException(String msg)
{
super(msg);
}
private static final long serialVersionUID = 1L;
}
@@ -0,0 +1,252 @@
//package com.eactive.eai.batch.eventscheduler.management;
//
//import java.io.Serializable;
//import java.util.Date;
//
//import com.eactive.eai.inbound.remote.RemoteServerVO;
//
//
//public class SchedulerEventVO implements Serializable
//{
// private static final long serialVersionUID = 1L;
// private String schedulerEndTime;
// private String schedulerStartTime;
//
// private String type;
// private String excuteJobClass;
// private String propGroupName;
// private String description;
//
// private String bjobMsgScheID;
// private String rmtSevrJobID;
// private boolean isholidaySend;
// private String cronExpression;
//
// private Date startDate;
// private Date endDate;
//
// private String schedulerId;
// private String schedulerName;
// private String status;
// private String sendRecvType; //스케줄러에서 파일의 송신(S)/수신(R) 타입
// private String fileLocation; //스케줄 기반 요구 송신에서 파일을 가져올 위치. 리모트 : R, 로칼 : L
//
// private boolean isFirst;
//
// /**
// * 프러퍼티의 HashMap 형태
// */
//
// private RemoteServerVO rsvo;
//
//
// public SchedulerEventVO(){
// }
//
// public SchedulerEventVO(String id){
// schedulerId = id;
// }
//
// public SchedulerEventVO(String id, String type, String cronExpression,
// String scheduleName, String thisSchUseYn, boolean isholidaySend, String propGroupName,
// String rmtSevrJobID, String bjobMsgScheID, String sendRecvType, String fileLocation,
// String description, String excuteJobClass){
//
// this.schedulerId = id;
//
// this.excuteJobClass = excuteJobClass;
// this.propGroupName = propGroupName;
// this.description = description;
// this.bjobMsgScheID = bjobMsgScheID;
// this.rmtSevrJobID = rmtSevrJobID;
// this.isholidaySend = isholidaySend;
// this.cronExpression = cronExpression;
// this.schedulerName = scheduleName;
// this.status = thisSchUseYn;
// this.sendRecvType = sendRecvType;
// this.fileLocation = fileLocation;
//
// int typeLength = SchedulerKeys.EVENT_SCHEDULER_TYPE_KEYS.length;
//
// for(int i=0; i<typeLength; i++){
// if (SchedulerKeys.EVENT_SCHEDULER_TYPE_KEYS[i].equals(type)){
// this.type=SchedulerKeys.EVENT_SCHEDULER_TYPE_VALUES[i];
// }
// }
// }
//
// public String getSchedulerId(){
// return schedulerId;
// }
//
// public void setSchedulerId(String schedulerId){
// this.schedulerId = schedulerId;
// }
//
// public String getSchedulerName(){
// return schedulerName;
// }
//
// public void setSchedulerName(String schedulerName){
// this.schedulerName = schedulerName;
// }
//
// public void setStatus(String status){
// this.status = status;
// }
//
// public String getStatus(){
// return status;
// }
//
// public String getSchedulerEndTime(){
// return schedulerEndTime;
// }
//
// public void setSchedulerEndTime(String schedulerEndTime){
// this.schedulerEndTime = schedulerEndTime;
// }
//
// public String getSchedulerStartTime(){
// return schedulerStartTime;
// }
//
// public void setSchedulerStartTime(String schedulerStartTime){
// this.schedulerStartTime = schedulerStartTime;
// }
//
// public Date getEndDate(){
// return this.endDate;
// }
//
// public void setEndDate(Date date){
// this.endDate = date;
// }
//
// public Date getStartDate(){
// return startDate;
// }
//
// public void setStartDate(Date date){
// this.startDate = date;
// }
//
// public void setType(String type){
// this.type = type;
// }
//
// public String getType(){
// return type;
// }
//
// public void setExcuteJobClass(String excuteJobClass){
// this.excuteJobClass = excuteJobClass;
// }
//
// public String getExcuteJobClass(){
// return excuteJobClass;
// }
//
// public void setPropGroupName(String name){
// this.propGroupName = name;
// }
//
// public String getPropGroupName(){
// return propGroupName;
// }
//
// public void setDescription(String description){
// this.description = description;
// }
//
// public String getDescription(){
// return description;
// }
//
// public void setBjobMsgScheID(String bjobMsgScheID){
// this.bjobMsgScheID = bjobMsgScheID;
// }
//
// public String getBjobMsgScheID(){
// return bjobMsgScheID;
// }
//
// public void setRmtSevrJobID(String rmtSevrJobID){
// this.rmtSevrJobID = rmtSevrJobID;
// }
//
// public String getRmtSevrJobID(){
// return rmtSevrJobID;
// }
//
// public void setHolidaySend(boolean isholidaySend){
// this.isholidaySend = isholidaySend;
// }
//
// public boolean isHolidaySend(){
// return isholidaySend;
// }
//
//
// public String getCronExpression(){
// return cronExpression;
// }
//
// public void setCronExpression(String cronExpression){
// this.cronExpression = cronExpression;
// }
//
//
// public RemoteServerVO getRemoteServerVO(){
// return rsvo;
// }
//
// public void setRemoteServerVO(RemoteServerVO vo){
// this.rsvo = vo;
// }
//
// public void setFirst(boolean flag){
// this.isFirst = flag;
// }
//
// public boolean isFirst(){
// return isFirst;
// }
//
// public void setSendRecvType(String type){
// this.sendRecvType = type;
// }
//
// public String getSendRecvType(){
// return sendRecvType;
// }
//
// public void setFileLocation(String location){
// this.fileLocation = location;
// }
//
// public String getFileLocation(){
// return fileLocation;
// }
//
// public String toString(){
// StringBuffer sb = new StringBuffer();
// sb.append("ScedulerEventVO [ schedulerId=").append(schedulerId);
// sb.append(", status=").append(status);
// sb.append(", type=").append(type);
// sb.append(", cronExpression=").append(cronExpression);
// sb.append(", excuteJobClass=").append(excuteJobClass);
// sb.append(", propGroupName=").append(propGroupName);
// sb.append(", bjobMsgScheID=").append(bjobMsgScheID);
// sb.append(", rmtSevrJobID=").append(rmtSevrJobID);
// sb.append(", schedulerStartTime=").append(schedulerStartTime);
// sb.append(", schedulerEndTime=").append(schedulerEndTime);
// sb.append(", isholidaySend=").append(isholidaySend);
// sb.append(", sendRecvType=").append(sendRecvType);
// sb.append(", fileLocation=").append(fileLocation);
// sb.append(", description=").append(description);
// sb.append(" ]");
// return sb.toString();
// }
//
//}
@@ -0,0 +1,53 @@
//package com.eactive.eai.batch.eventscheduler.management;
//
//public final class SchedulerKeys
//{
//
// public SchedulerKeys(){
// }
//
// public static final String DEFAULT_JOB_GROUP = "DEFAULT_JOB_GROUP";
// public static final String DEFAULT_JOB_DETAIL_NAME = "SCHEDULER";
// public static final String START_SCHEDULER_ID_PREFIX = "start_";
// public static final String STOP_SCHEDULER_ID_PREFIX = "stop_";
//
//
// //for file eventgen prop
// public static final String REMOTE_IP = "REMOTE_IP";
// public static final String REMOTE_PORT = "REMOTE_PORT";
// public static final String USER = "USER";
// public static final String PASSWORD = "PASSWORD";
// public static final String REMOTE_DIR = "REMOTE_DIR";
// public static final String FILE_PATTERN = "FILE_PATTERN";
// public static final String LOCAL_DIR = "LOCAL_DIR";
// public static final String LOCAL_FILE = "LOCAL_FILE";
// public static final String POST_ACTION_TYPE = "POST_ACTION_TYPE"; //A|D|N
// public static final String ARCH_DIR = "ARCH_DIR";
// public static final String ERROR_DIR = "ERROR_DIR";
// public static final String PASSIVE_MODE = "PASSIVE_MODE";
// public static final String POLLING_INTERVAL = "POLLING_INTERVAL";
// public static final String JPD_CALL_WAIT_TIME = "JPD_CALL_WAIT_TIME";
//
// //for timer eventgen prop
// public static final String MESSAGE = "MESSAGE";
//
// public static final String SERIVCE_URI = "SERIVCE_URI";
//
// //for Remote FTP/NDM type
// public static final String REMOTE_FTP_TYPE = "RF";
// public static final String REMOTE_NDM_TYPE = "RN";
//
//
// public static final String REQ_SEND_TYPE = "RS";
// public static final String REQ_SEND_REMOTE = "R";
// public static final String REQ_SEND_LOCAL = "L";
//
// public static final String POST_ACTION_DELETE = "D";
// public static final String POST_ACTION_ARCH = "A";
// public static final String POST_ACTION_NONE = "N";
//
// public static final String EVENT_SCHEDULER_TYPE_KEYS[] = {"01", "02", "03", "04", "05", "06", "07", "08"};
// public static final String EVENT_SCHEDULER_TYPE_VALUES[] = {"RF", "RN", "LR", "LA", "RR", "TM", "RH", "RS"};
//
//
//}
@@ -0,0 +1,43 @@
//package com.eactive.eai.batch.eventscheduler.util;
//
///**
// * 설명 : 디렉토리명 관련 유틸리티 클래스<BR>
// * 사용법 : <BR>
// * 작성 날짜 : 2008.02.27
// * @author 천기숙
// * @version 1.0
// */
//public class DirectoryUtil {
//
// public final static String DILIMITER = "/";
//
// /**
// * 사용목적 : 메인디렉토리명과 서브 디렉토리명을 받아 전체 경로 반환<BR>
// * 사용법 : <BR>
// * 구현 설명 : <BR>
// * 유효 리턴 값 : 디렉토리의 전체 경로<BR>
// * 유효 인자 값 : baseDir - 메인디렉토리명,
// * subDir - 서브디렉토리명<BR>
// * 작성 날짜 : (05-01-12 오후 03:36:00)
// */
// public static String getDir(String baseDir, String subDir){
// String dir = baseDir+DILIMITER+subDir;
//
// return dir;
//
// }
//
// /**
// * 사용목적 : 윈도우 디렉토리 구분자를 유닉스 디렉토리 구분자로 변경<BR>
// * 사용법 : <BR>
// * 구현 설명 : <BR>
// * 유효 리턴 값 : 유닉스 디렉토리 구분자<BR>
// * 유효 인자 값 : dir - 디렉토리<BR>
// * 작성 날짜 : (05-01-12 오후 03:36:00)
// */
// public static String replaceDilimiter (String dir){
// String strBaseDir = dir.replaceAll("\\\\", DILIMITER);
//
// return strBaseDir;
// }
//}
@@ -0,0 +1,116 @@
//package com.eactive.eai.batch.eventscheduler.util;
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
///**
//* 1. 기능 : Scheduler의 CronExpression을 조립 및 파싱하기 위한 클래스
//* 2. 처리 개요 :
//* - 스케줄러 정보를 CronTrigger에서 사용될 Expression으로 조립
//* - CronTrigger에서 사용되는 Expression을 사용자가 이해하기 쉬운 형태로 파싱
//* 3. 주의사항
//*
//* @author : kscheon
//* @version : v 1.0.0
//*/
//public final class ExpressionParser {
//
// /**
// * Default Logger
// */
// static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_SCHEDULER);
//
// public final static String EXP_ALL = "*";
// public final static String EXP_RANGE = "-";
// public final static String EXP_ADD = ",";
// public final static String EXP_INCREMENT = "/";
// public final static String EXP_LAST = "L";
// public final static String EXP_NTH = "#";
//
// public final static String assembleExpression(String[] token){
// int length = token.length;
// if (length != 6){
// logger.error("ExpressionParser ] assembleExpression - argument length is not 6 - "+length);
// }
// String expression = "";
//
// for (int i=0; i< length; i++){
// expression = expression+token[i];
//
// if (i <length-1){
// expression = expression + " ";
// }
// }
//
// return expression;
// }
//
// public final static String assembleExpressionByDate(String date){
// String expression = "";
// int length = 7;
//
// String token[] = new String[length];
//
// token[0] = date.substring(12, 14);
// token[1] = date.substring(10,12);
// token[2] = date.substring(8,10);
// token[3] = date.substring(6,8);
// token[4] = date.substring(4,6);
// token[5] = "?"; // Day-of-Week (1-7 or SUN-SAT)
// token[6] = date.substring(0,4);
//
// for (int i=0; i< length; i++){
// if("00".equals(token[i])){ //00초, 00분, 00시 이면 0으로 대체
// token[i] = "0";
// }
// expression = expression+token[i];
//
// if (i <length-1){
// expression = expression + " ";
// }
// }
// return expression;
// }
//
// public final static String[] parseExpression (String exp){
// return new String[6];
// }
//
//
//
// public final static String getCronExpByPollTime(String pollTime)throws Exception{
// String token[] = new String[]{"*", "*", "*", "*", "*", "?"};
//
// String parseResult[] = pollTime.split(":");
// System.out.println("ExpressionParser ] pollTime ["+pollTime+"]");
// if (parseResult.length !=4){
// logger.error("ExpressionParser ] Pollling Time 오류");
// throw new Exception("ExpressionParser ] Pollling Time 오류");
// }
// //초, 분, 시, 일로 만들것...
// for (int i=0; i<parseResult.length-1; i++){
// if("0".equals(parseResult[i])){
// token[i] = parseResult[i];
// } else {
// token[i] = "0/"+parseResult[i];
// break;
// }
// }
// if (!"0".equals(parseResult[parseResult.length-1])){
// token[parseResult.length-1] = "0/"+parseResult[parseResult.length-1];
// }
//
// String exp = "";
// for (int j=0; j<token.length-1; j++){
// exp = exp + token[j]+" ";
//
// }
// exp = exp +token[token.length-1];
//
// logger.debug("ExpressionParser ] setCronExpByPollTime - cronExpression["+exp+"]");
// return exp;
//
//
// }
//
//}
@@ -0,0 +1,186 @@
//package com.eactive.eai.batch.eventscheduler.util;
//
//import java.io.File;
//
//import com.eactive.eai.batch.common.StringUtil;
//import com.eactive.eai.batch.eventscheduler.management.SchedulerEventVO;
//import com.eactive.eai.batch.eventscheduler.management.SchedulerKeys;
//import com.eactive.eai.common.exception.ExceptionUtil;
//import com.eactive.eai.common.property.PropManager;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.util.Properties;
//import java.util.HashMap;
//
//
//public class LocalFileUtil {
//
//// private String propFile = "";
// private String propLocalDir = "";
// private String delimiter ="";
// private String searchFileName;
// private String posActionType = "";
// private String propArchiveDir = "";
//
// private HashMap<String, String[]> fileInfos;
//
// public LocalFileUtil(){
// fileInfos = new HashMap<String, String[]>();
// }
//
// static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_SCHEDULER);
//
// public HashMap<String, String[]> searchFileInfo(SchedulerEventVO vo, String searchFile) throws Exception {
//
//
// //Properties mapProp = vo.getEventPropMap();
//
// String propGroup = vo.getPropGroupName();
// Properties mapProp = null;
//
// try{
// if(propGroup !=null && propGroup.length() > 0){
// PropManager pmanager = PropManager.getInstance();
// mapProp = pmanager.getPropGroupVO(propGroup).getProperties();
// }
//
// }catch (Exception e){
// e.printStackTrace();
// logger.error("LocalFileUtil ] searchFileInfo - 프로퍼티 정보를 설정하는데 오류가 발생했습니다. - "+e.getMessage());
// }
//
// searchFileName = searchFile;
//
// //propFile = ((String)mapProp.get(SchedulerKeys.FILE_PATTERN)).trim();
// propLocalDir = ((String)mapProp.get(SchedulerKeys.LOCAL_DIR)).trim();
//
// delimiter = StringUtil.getDirDelimiter(propLocalDir);
//
// posActionType = (String)(mapProp.get(SchedulerKeys.POST_ACTION_TYPE)==null?SchedulerKeys.POST_ACTION_DELETE:mapProp.get(SchedulerKeys.POST_ACTION_TYPE));
// propArchiveDir = (String)mapProp.get(SchedulerKeys.ARCH_DIR);
//
// File f = new File(propLocalDir);
// String fileName = "";
//
// if (f != null && f.exists()){
// File[] fileList = f.listFiles();
//
//
// if ((fileList != null) && (fileList.length != 0)) {
// for (int i=0; i<fileList.length; i++) {
// fileName = fileList[i].getName();
// if (fileName.length() > propLocalDir.length()) {
// fileName = fileName.substring(propLocalDir.getBytes().length);
// }
// //첫번째 목록이 파일 타입인지 확인한다.
// if (fileList[i].isFile()){
// String[] fileInfo = new String[2];
//
// if (searchFileName !=null && searchFileName.length()>0){
// if (fileName.indexOf(searchFileName)>0){ //탐색하고자 하는 파일명(BJ01의 BjobTranDstcdName값 참조
// fileInfo[0] = propLocalDir;
// fileInfo[1] = fileName;
// fileInfos.put(fileName, fileInfo);
//
// logger.debug("LocalFileUtil ] 탐색하고자 하는 파일이 생성되었습니다. - searchFileName ["+searchFileName+"] - localFileName ["+fileName+"]");
//
// postAction(fileList[i], fileName);
//
// }
// }else {
// fileInfo[0] = propLocalDir;
// fileInfo[1] = fileName;
// fileInfos.put(fileName, fileInfo);
//
// postAction(fileList[i], fileName);
//
// logger.debug("LocalFileUtil ] 파일이 생성되었습니다. - searchFileName ["+searchFileName+"] - localFileName ["+fileName+"]");
// }
//
// } else {
// reDirectory(propLocalDir+delimiter+fileName);
// }
// }
// }
// }
// return fileInfos;
// }
//
// private void reDirectory (String currentDir) throws Exception {
//
// try {
//
// File rf = new File(currentDir);
// if (rf != null){
//
//
//
// File[] subFile = rf.listFiles();
//
// String localFileName = "";
//
// if ((subFile != null) && (subFile.length != 0)) {
// for (int i=0; i<subFile.length; i++) {
// localFileName = subFile[i].getName();
// if (localFileName.length() > currentDir.length()) {
// localFileName = localFileName.substring(currentDir.getBytes().length);
// }
//
// if(subFile[i].isDirectory()) { //directory type이면
// reDirectory(currentDir+delimiter+localFileName);
//
// } else if(subFile[i].isFile()) {
// String[] fileInfo = new String[2];
//
//
// if (searchFileName !=null && searchFileName.length()>0){
// if (localFileName.indexOf(searchFileName)>0){ //탐색하고자 하는 파일명(BJ01의 BjobTranDstcdName값 참조
// fileInfo[0] = currentDir;
// fileInfo[1] = localFileName;
// fileInfos.put(localFileName, fileInfo);
//
// logger.debug("LocalFileUtil ] 탐색하고자 하는 파일이 생성되었습니다. - searchFileName ["+searchFileName+"] - localFileName ["+localFileName+"]");
//
// postAction(subFile[i], localFileName);
//
// }
// }else {
// fileInfo[0] = currentDir;
// fileInfo[1] = localFileName;
// fileInfos.put(localFileName, fileInfo);
//
// postAction(subFile[i], localFileName);
//
// logger.debug("LocalFileUtil ] 파일이 생성되었습니다. - searchFileName ["+searchFileName+"] - localFileName ["+localFileName+"]");
// }
//
// }
// }
// }
// rf = null;
// subFile = null;
// }
// } catch (Exception f) {
// String arg[] = new String[1];
// arg[0] = currentDir;
// throw new Exception(ExceptionUtil.getErrorCode(f, "BECEAIMEU001",arg));
// }
// }
//
// private void postAction(File f, String fineName){
// if (SchedulerKeys.POST_ACTION_ARCH.equals(posActionType)){
// File af = new File(propArchiveDir);
// if (!af.exists()){
// if(!af.mkdir()){
// logger.error("LocalFileUtil ] searchFileInfo - Arch Directory 생성 실패");
// }
// }
// //File af2 = new File(af, fineName+"_" +CalendarUtil.getCurrentTimeNoDash());
// File af2 = new File(af, fineName);
// f.renameTo(af2);
// }else if (SchedulerKeys.POST_ACTION_DELETE.equals(posActionType)){
// f.delete();
// }
// }
//}
@@ -0,0 +1,152 @@
package com.eactive.eai.batch.eventscheduler.util;
import com.ibm.icu.util.Calendar ;
import com.ibm.icu.util.ChineseCalendar ;
public final class LunarCalendar {
private static final int CHINESE_DIFF = 2637;
public LunarCalendar() {
//
}
/**
* 양력을 음력으로 변환
*
*/
public static String toLunar( String lunarDateStr ) {
if( lunarDateStr == null || lunarDateStr.length() !=8 ) {
return "" ;
}
Calendar cal = Calendar.getInstance() ;
ChineseCalendar cc = new ChineseCalendar();
cal.set( Calendar.YEAR, Integer.parseInt(lunarDateStr.substring(0,4)) ) ;
cal.set( Calendar.MONTH, Integer.parseInt(lunarDateStr.substring(4,6))-1 ) ;
cal.set( Calendar.DAY_OF_MONTH, Integer.parseInt(lunarDateStr.substring(6)) ) ;
cc.setTimeInMillis( cal.getTimeInMillis() ) ;
int y = cc.get(ChineseCalendar.EXTENDED_YEAR)- CHINESE_DIFF ;
int m = cc.get(ChineseCalendar.MONTH)+1 ;
int d = cc.get(ChineseCalendar.DAY_OF_MONTH) ;
StringBuffer sb = new StringBuffer() ;
sb.append( y ) ;
if( m < 10 ) sb.append( "0" ) ;
sb.append( m ) ;
if( d < 10 ) sb.append( "0" ) ;
sb.append( d ) ;
return sb.toString() ;
}
/**
* 음력을 양력으로 변환
*
*/
public static String toSolar( String solarDateStr ) {
if( solarDateStr == null || solarDateStr.length() !=8 ) {
return "" ;
}
Calendar cal = Calendar.getInstance() ;
ChineseCalendar cc = new ChineseCalendar();
cc.set( ChineseCalendar.EXTENDED_YEAR, Integer.parseInt(solarDateStr.substring(0,4)) + CHINESE_DIFF ) ;
cc.set( ChineseCalendar.MONTH, Integer.parseInt(solarDateStr.substring(4,6))-1 ) ;
cc.set( ChineseCalendar.DAY_OF_MONTH, Integer.parseInt(solarDateStr.substring(6)) ) ;
cal.setTimeInMillis( cc.getTimeInMillis() ) ;
int y = cal.get(Calendar.YEAR) ;
int m = cal.get(Calendar.MONTH) + 1 ;
int d = cal.get(Calendar.DAY_OF_MONTH) ;
StringBuffer sb = new StringBuffer() ;
sb.append( y ) ;
if( m < 10 ) sb.append( "0" ) ;
sb.append( m ) ;
if( d < 10 ) sb.append( "0" ) ;
sb.append( d ) ;
return sb.toString() ;
}
/**
public static String[] toSolarOfNationalHoliday (String date){
String[] nholiday = new String[3];
int dateInt = (Integer.parseInt(date))-1; //음력날짜 -1
try {
}catch (Exception e){
e.printStackTrace();
}
//지정된 음력날짜 앞뒤까지 휴일로 설정하기 위함.
for (int i=0; i<nholiday.length; i++){
nholiday[i]=toSolar(""+dateInt);
dateInt++;
}
return nholiday;
}*/
public static String toSolarOfNationalHoliday (String date){
String nholiday = new String();
try {
nholiday=toSolar(date);
}catch (Exception e){
e.printStackTrace();
}
return nholiday;
}
// public static void main(String args[]) throws Exception {
//// LunarCalendar lc = new LunarCalendar() ;
//// String lunarDate = lc.toLunar("20080627") ;
//// String date = lc.toSolar("20080524") ;
//// System.out.println("음력으로 20080627 ->"+lunarDate);
//// System.out.println("양력으로 20080524 ->"+date);
//
//// MultiThread Test
// new Thread("T1") {
// public void run() {
// for(int i=0; i<100; i++) {
// LunarCalendar lc = new LunarCalendar() ;
// String lunarDate = lc.toLunar("20080627") ;
// String date = lc.toSolar("20080524") ;
// System.out.println("T1 음력으로 20080627 ->"+lunarDate);
// System.out.println("T1 양력으로 20080524 ->"+date);
// }
// }
// }.start(); // T1 쓰레드 시작
//
// new Thread("T2") {
// public void run() {
// for(int i=0; i<100; i++) {
// LunarCalendar lc = new LunarCalendar() ;
// String lunarDate = lc.toLunar("20080626") ;
// String date = lc.toSolar("20080523") ;
// System.out.println("T2 음력으로 20080626 ->"+lunarDate);
// System.out.println("T2 양력으로 20080523 ->"+date);
// }
// }
// }.start(); // T2 쓰레드 시작
// }
}
@@ -0,0 +1,57 @@
//package com.eactive.eai.batch.eventscheduler.util;
//
//import org.apache.commons.logging.Log;
//
//import org.apache.commons.net.ProtocolCommandEvent;
//import org.apache.commons.net.ProtocolCommandListener;
//
///**
// * 사용목적 : 모든 command/reply traffic를 print하는 ProtocolCommandListener interface를
// * 구현한 간단하게 클래스이다.<BR>
// * 사용법 : <BR>
// * 작성 날짜 : (05-01-11 오전 18:35:00)
// * @author 김철성
// * @version 1.0
// */
//public class PrintCommandListener implements ProtocolCommandListener
//{
// private Log writer;
//
// /**
// * 사용목적 : 생성자<BR>
// * 사용법 : <BR>
// * 구현 설명 : <BR>
// * 유효 리턴 값 : <BR>
// * 유효 인자 값 : <BR>
// * 작성 날짜 : (05-01-11 오전 18:35:00)
// */
// public PrintCommandListener(Log writer) {
// this.writer = writer;
// }
//
// /**
// * 사용목적 : ProtocolCommandEvent의 내용을 멤버 변수 PrintWriter 객체의
// * print 메소드를 호출하는 메소드이다.<BR>
// * 사용법 : <BR>
// * 구현 설명 : <BR>
// * 유효 리턴 값 : <BR>
// * 유효 인자 값 : <BR>
// * 작성 날짜 : (05-01-11 오전 18:35:00)
// */
// public void protocolCommandSent(ProtocolCommandEvent event) {
// this.writer.debug(event.getMessage());
// }
//
// /**
// * 사용목적 : ProtocolCommandEvent의 내용을 멤버 변수 PrintWriter 객체의
// * print 메소드를 호출하는 메소드이다.<BR>
// * 사용법 : <BR>
// * 구현 설명 : <BR>
// * 유효 리턴 값 : <BR>
// * 유효 인자 값 : <BR>
// * 작성 날짜 : (05-01-11 오전 18:35:00)
// */
// public void protocolReplyReceived(ProtocolCommandEvent event) {
// this.writer.debug(event.getMessage());
// }
//}
@@ -0,0 +1,312 @@
//package com.eactive.eai.batch.eventscheduler.util;
//
//import java.io.IOException;
//import java.io.OutputStream;
//import java.util.Properties;
//import java.util.Vector;
//
//import org.apache.commons.net.ftp.FTPClient;
//import org.apache.commons.net.ftp.FTPConnectionClosedException;
//import org.apache.commons.net.ftp.FTPFile;
//import org.apache.commons.net.ftp.FTPReply;
//
//import com.eactive.eai.batch.common.StringUtil;
//import com.eactive.eai.batch.eventscheduler.management.SchedulerEventVO;
//import com.eactive.eai.batch.eventscheduler.management.SchedulerKeys;
//import com.eactive.eai.common.exception.ExceptionUtil;
//import com.eactive.eai.common.property.PropManager;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import com.eactive.eai.inbound.remote.RemoteServerVO;
//
//public class RemoteFTPUtil {
//
// private Vector<String[]> fileInfos;
//
//
// private FTPClient ftp = null;
//
// private OutputStream output = null;
// private String propIp = "";
// private String propPort = "21";
// private String propUser = "";
// private String propPassword = "";
// private String propRemoteDir = "";
// private String propPassive = "active";
// private String propArchiveDir = "";
// private String searchFileName = "";
// private String posActionType = "";
//
// private String delimiter ="";
//
// static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_SCHEDULER);
//
// public RemoteFTPUtil() {
// fileInfos = new Vector<String[]>();
// }
//
// public Vector<String[]> searchFileInfo(SchedulerEventVO vo, String searchFile) throws Exception {
//
// searchFileName = searchFile;
// //Properties mapProp = vo.getEventPropMap();
// String propGroup = vo.getPropGroupName();
// Properties mapProp = null;
//
// try{
// if(propGroup !=null && propGroup.length() > 0){
// PropManager pmanager = PropManager.getInstance();
// mapProp = pmanager.getPropGroupVO(propGroup).getProperties();
// }
//
// }catch (Exception e){
// e.printStackTrace();
// logger.error("RemoteFTPUtil ] searchFileInfo - 프로퍼티 정보를 설정하는데 오류가 발생했습니다. - "+e.getMessage());
// }
// try {
//
// //RemoteDirectoryVO rdvo = vo.getRemoteDirectoryVO();
// RemoteServerVO rsvo = vo.getRemoteServerVO();
//
// propPassive = (String)(mapProp.get(SchedulerKeys.PASSIVE_MODE)==null?"active":mapProp.get(SchedulerKeys.PASSIVE_MODE));
//
// propIp = rsvo.getRemoteServerIP();
// propPort = rsvo.getRemoteFtpPort();
// propUser = rsvo.getRemoteUserId();
// propPassword = rsvo.getRemotePassword();
// //propRemoteDir = rdvo.getRemoteDirName();
// propRemoteDir = mapProp.getProperty(SchedulerKeys.REMOTE_DIR);
//
// /*
// propIp = mapProp.getProperty(SchedulerKeys.REMOTE_IP);
// propUser = mapProp.getProperty(SchedulerKeys.USER);
// propPassword = mapProp.getProperty(SchedulerKeys.PASSWORD);
// propRemoteDir = mapProp.getProperty(SchedulerKeys.REMOTE_DIR);
// propPort = mapProp.getProperty(SchedulerKeys.REMOTE_PORT);
// */
// delimiter = StringUtil.getDirDelimiter(propRemoteDir);
// posActionType = (String)(mapProp.get(SchedulerKeys.POST_ACTION_TYPE)==null?SchedulerKeys.POST_ACTION_NONE:mapProp.get(SchedulerKeys.POST_ACTION_TYPE));
// propArchiveDir = (String)mapProp.get(SchedulerKeys.ARCH_DIR);
//
//
//
// if (propRemoteDir == null || propRemoteDir.length() <=0){
// throw new Exception(ExceptionUtil.getErrorCode("BECEAIMEU011"));
// }
//
// String remoteFileName = "";
//
// logger.debug("RemoteFTPUtil ] propIp:propPort:propUser:propPassword - "+propIp+":"+propPort+":"+propUser+":"+propPassword );
// ftp = connect(propIp, Integer.parseInt(propPort), propUser, propPassword, Boolean.getBoolean(propPassive));
//
// // 디렉토리 변경
// boolean result = ftp.changeWorkingDirectory(propRemoteDir);
//
// if (!result){
// String arg[] = new String[1];
// arg[0] = propRemoteDir;
// throw new Exception(ExceptionUtil.getErrorCode("BECEAIMEU012", arg));
// }
//
// FTPFile[] ftpFiles = ftp.listFiles(propRemoteDir);
//
// if ((ftpFiles != null) && (ftpFiles.length != 0)) {
// for (int i=0; i<ftpFiles.length; i++) {
// remoteFileName = ftpFiles[i].getName();
//
// if (remoteFileName.length() > propRemoteDir.length()) {
// remoteFileName = remoteFileName.substring(propRemoteDir.getBytes().length);
// }
//
// // 첫번째 목록이 파일 타입인지 확인한다.
// if (ftpFiles[i].isFile()){
// String[] fileInfo = new String[2];
//
// if (searchFileName !=null && searchFileName.length()>0){
// if (remoteFileName.indexOf(searchFileName)>0){ //탐색하고자 하는 파일명(BJ01의 BjobTranDstcdName값 참조
//
// fileInfo[0] = propRemoteDir;
// fileInfo[1] = remoteFileName;
// fileInfos.add(fileInfo);
//
// logger.debug("RemoteFTPUtil ] 지정된 파일을 찾았습니다. searchFileName - ["+searchFileName+"] - remoteFileName ["+remoteFileName+"]");
//
// postAction(ftp, propRemoteDir, remoteFileName);
//
// }
// }else {
// fileInfo[0] = propRemoteDir;
// fileInfo[1] = remoteFileName;
// fileInfos.add(fileInfo);
//
// postAction(ftp, propRemoteDir, remoteFileName);
//
// }
// }else {
// reDirectory(ftp, propRemoteDir+delimiter+remoteFileName);
// }
// }
// }
// ftp.logout();
// return fileInfos;
// } catch (FTPConnectionClosedException e) {
// e.printStackTrace();
// String arg[] = new String[2];
// arg[0] = propIp;
// arg[1] = ""+propPort;
// throw new IOException(ExceptionUtil.getErrorCode(e, "BECEAIMEU013", arg));
// } catch (IOException e) {
// e.printStackTrace();
// throw new IOException(ExceptionUtil.getErrorCode(e, "BECEAIMEU014"));
// } catch (Exception e) {
// e.printStackTrace();
// throw new Exception(ExceptionUtil.getErrorCode(e, "BECEAIMEU014"));
// } finally {
// if (output != null) {
// try {
// output.close();
// } catch (Exception e) {
// // do nothing
// }
// }
// if (ftp != null && ftp.isConnected()) {
// try {
// ftp.disconnect();
// } catch (IOException f) {
// // do nothing
// }
// }
// ftp = null;
// }
// }
//
//
// private FTPClient connect(String server, int port, String username,
// String password, boolean passive) throws IOException {
// FTPClient ftpClient = new FTPClient();
//
// try {
//
// if (passive) {
// ftpClient.enterLocalPassiveMode();
// } else {
// ftpClient.enterLocalActiveMode();
// }
//
// ftpClient.setControlEncoding("euc-kr");
//
// int reply;
// ftpClient.connect(server, port);
//
// reply = ftpClient.getReplyCode();
//
// if (!FTPReply.isPositiveCompletion(reply)) {
// ftpClient.disconnect();
// throw new IOException(ExceptionUtil.getErrorCode("BECEAIMEU015"));
// }
//
// if (!ftpClient.login(username, password)) {
// ftpClient.logout();
// String arg[] = new String[0];
// arg[0] = username;
// throw new IOException(ExceptionUtil.getErrorCode("BECEAIMEU016", arg));
// }
// return ftpClient;
// } catch (IOException ie) {
// try {
// String arg[] = new String[2];
// arg[0] = server;
// arg[1] = ""+port;
// throw new IOException(ExceptionUtil.getErrorCode("BECEAIMEU017", arg));
// } catch (Exception ex) {
// }
// throw ie;
// } finally {
// try {
// if (ftp.isConnected()) {
// ftp.disconnect();
// }
// } catch (Exception f) {
// // do nothing
// }
// }
// }
//
//
// private void reDirectory (FTPClient ftp, String currentDir) throws Exception {
//
//
// try {
// // 디렉토리 변경
// boolean isChange = ftp.changeWorkingDirectory(currentDir);
// if (!isChange) {
// String arg[] = new String[1];
// arg[0]=currentDir;
// throw new Exception(ExceptionUtil.getErrorCode("BECEAIMEU018", arg));
// }
//
// FTPFile[] subFile = ftp.listFiles(currentDir);
//
// String remoteFile = "";
//
// if ((subFile != null) && (subFile.length != 0)) {
// for (int i=0; i<subFile.length; i++) {
// remoteFile = subFile[i].getName();
// if (remoteFile.length() > currentDir.length()) {
// remoteFile = remoteFile.substring(currentDir.getBytes().length);
// }
//
// // 파일 타입인지 확인한다.
// if(subFile[i].isDirectory()) { //directory type이면
// reDirectory(ftp, currentDir+delimiter+remoteFile);
//
// } else if(subFile[i].isFile()) {
// String[] fileInfo = new String[2];
//
//
// if (searchFileName !=null && searchFileName.length()>0){
// if (remoteFile.indexOf(searchFileName)>0){ //탐색하고자 하는 파일명(BJ01의 BjobTranDstcdName값 참조
// fileInfo[0] = currentDir;
// fileInfo[1] = remoteFile;
// fileInfos.add(fileInfo);
//
// logger.debug("RemoteFTPUtil ] 지정된 파일을 찾았습니다. searchFileName - ["+searchFileName+"] - remoteFileName ["+remoteFile+"]");
//
// postAction(ftp, currentDir, remoteFile );
// }
// }else {
// fileInfo[0] = currentDir;
// fileInfo[1] = remoteFile;
// fileInfos.add(fileInfo);
//
// postAction(ftp, currentDir, remoteFile );
// }
//
// }
// }
// }
// subFile = null;
//
// } catch (Exception f) {
// String arg[] = new String[1];
// arg[0]=currentDir;
// throw new Exception(ExceptionUtil.getErrorCode(f, "BECEAIMEU019", arg));
// }
// }
//
// private void postAction(FTPClient ftp, String dirName, String fileName) throws Exception{
// if (SchedulerKeys.POST_ACTION_ARCH.equals(posActionType)){
//
// //if (!ftp.rename(dirName+delimiter+fileName, propArchiveDir+delimiter+fileName+"_" +CalendarUtil.getCurrentTimeNoDash())){
// if (!ftp.rename(dirName+delimiter+fileName, propArchiveDir+delimiter+fileName)){
// logger.error("RemoteFTPUtil ] File remane failed");
// logger.error(" : org -["+dirName+delimiter+fileName+"], new-["+propArchiveDir+delimiter+fileName+"]");
// }else {
// logger.debug("RemoteFTPUtil ] File rename : org -["+dirName+delimiter+fileName+"], new-["+propArchiveDir+delimiter+fileName+"]");
// }
// }else if (SchedulerKeys.POST_ACTION_DELETE.equals(posActionType)){
// ftp.deleteFile(dirName+delimiter+fileName);
// }
//
// }
//
//}
@@ -0,0 +1,140 @@
package com.eactive.eai.batch.flowController;
import com.eactive.eai.batch.common.StringUtil;
import java.io.Serializable;
/**
* 1. 기능 : 하나의 배치작업 업무를 나타내는 Value Object
* 즉, CMS은행, CMS업체등이 해당된다.
* 관련 테이블 - TSEAIBJ02, TSEAIBJ05
* 2. 처리 개요 :
*
* 3. 주의사항
*
* @author : YCLee
* @version : v 1.0.0
* @see :
* @since :JDK v1.4.2
*/
public class BatchTargetVO implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 업무코드
*/
private String processCode; // 예, CMSBK
/**
* 대외기관코드
*/
private String organCode; // 예, IL03
/**
* 대외기관명
*/
private String organName; // 예, 삼성생명
/**
* 업무명
*/
private String processName; // 예, CMS은행
/**
* 요구송수신 연결 정보
*/
private DemandTargetVO[] demandTagetVOs;
/**
* 1. 기능 : Defualt Constructor
* 2. 처리 개요 :
* - Defualt Constructor
* 3. 주의사항
*
**/
public BatchTargetVO() {
}
/**
* 1. 기능 : 대외기관 정보를 저장하는 생성자 함수
* 2. 처리 개요 :
* 3. 주의사항
*
* @param
**/
public BatchTargetVO(String processCode, String processName, String organCode, String organName) {
this.processCode = StringUtil.nvlTrim(processCode);
this.processName = StringUtil.nvlTrim(processName);
this.organCode = StringUtil.nvlTrim(organCode);
this.organName = StringUtil.nvlTrim(organName);
}
/**
* 1. 기능: processCode를 반환하는 getter 메소드
*/
public String getProcessCode()
{
return this.processCode;
}
/**
* 1. 기능: organCode를 반환하는 getter 메소드
*/
public String getOrganCode()
{
return this.organCode;
}
/**
* 1. 기능: organName를 반환하는 getter 메소드
*/
public String getOrganName()
{
return this.organName;
}
/**
* 1. 기능: processName을 반환하는 getter 메소드
*/
public String getProcessName()
{
return this.processName;
}
/**
* 1. 기능 : 요구송수신 연결정보 리스트를 반환하는 getter 메소드
* 2. 처리 개요 :
* 3. 주의사항
*
* @param ruleKey rule의 PK
**/
public DemandTargetVO[] getDemadnTargets() {
return this.demandTagetVOs;
}
/**
* 1. 기능 : 요구송수신 연결정보 리스트를 저장하는 setter 메소드
* 2. 처리 개요 :
* - Rule Key를 저장한다.
* 3. 주의사항
*
* @param ruleKey rule의 PK
**/
public int setDemadnTargets(DemandTargetVO[] demandTargetVOs) {
this.demandTagetVOs = new DemandTargetVO[demandTargetVOs.length];
this.demandTagetVOs = demandTargetVOs;
return this.demandTagetVOs.length;
}
}
@@ -0,0 +1,154 @@
package com.eactive.eai.batch.flowController;
import com.eactive.eai.batch.common.StringUtil;
import java.io.Serializable;
/**
* 1. 기능 : 요구송수신을 위한 연결정보를 나타내는 Value Object
*
* 2. 처리 개요 :
*
* 3. 주의사항
*
* @author : YCLee 2006/1/11
* @version : v 1.0.0
* @see :
* @since :JDK v1.4.2
*/
public class DemandTargetVO implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
//대외기관 연결 상태 상수 설정
public static final String ORGAN_SOCKET_STATUS_NORNAL = "1"; //정상 (DB에 저장되는 값임)
public static final String ORGAN_SOCKET_STATUS_ERROR = "0"; //장애 (DB에 저장되는 값임)
private String systemConnCode;
/**
* 연결기관의 IP
*/
private String ipAddress;
/**
* 연결기관의 port number
*/
private String portNumber;
/**
* 소켓연결시 사용하는 ID
*/
private String socketID;
/**
* 소켓연결시 사용하는 패스워드
*/
private String socketPwd;
/**
* 연결 Timeout 간격
*/
private String timeoutInterval;
//대외기관 망상태
private String organSocketStatus;
public void setOrganSocketStatus(String arg) { organSocketStatus = arg; }
public String getOrganSocketStatus() { return organSocketStatus; }
/**
* 1. 기능 : Defualt Constructor
* 2. 처리 개요 :
* - Defualt Constructor
* 3. 주의사항
*
**/
public DemandTargetVO() {
}
/**
* 1. 기능 : IP, Port만 입력받는 생성자
* 2. 처리 개요 :
* 3. 주의사항
*
* @param IP, Port
**/
public DemandTargetVO(String systemConnCode, String ipAddress, String portNumber, String socketID, String socketPwd, String timeoutInterval, String organSocketStatus) {
this.systemConnCode = StringUtil.nvlTrim(systemConnCode);
this.ipAddress = StringUtil.nvlTrim(ipAddress);
this.portNumber = StringUtil.nvlTrim(portNumber);
this.socketID = StringUtil.nvlTrim(socketID);
this.socketPwd = StringUtil.nvlTrim(socketPwd);
this.timeoutInterval = StringUtil.nvlTrim(timeoutInterval);
this.organSocketStatus = StringUtil.nvlTrim(organSocketStatus);
}
public void setSystemConnCode(String systemConnCode)
{
this.systemConnCode = systemConnCode;
}
public String getSystemConnCode()
{
return this.systemConnCode;
}
public void setIpAddress(String ipAddress)
{
this.ipAddress = ipAddress;
}
public String getIpAddress()
{
return this.ipAddress;
}
public void setPortNumber(String portNumber)
{
this.portNumber = portNumber;
}
public String getPortNumber()
{
return this.portNumber;
}
public void setSocketID(String socketID)
{
this.socketID = socketID;
}
public String getSocketID()
{
return this.socketID;
}
public void setSocketPwd(String socketPwd)
{
this.socketPwd = socketPwd;
}
public String getSocketPwd()
{
return this.socketPwd;
}
public void setTimeoutInterval(String timeoutInterval)
{
this.timeoutInterval = timeoutInterval;
}
public String getTimeoutInterval()
{
return this.timeoutInterval;
}
}
@@ -0,0 +1,229 @@
package com.eactive.eai.batch.flowController;
import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
/**
* 1. 기능 : EAI서버 정보 테이블에 대한 Data Access Object 이다.
* 2. 처리 개요 : EAI서버 정보 테이블에 대한 Create, Read, Update, Delete 를 처리한다.
*
* 3. 주의사항
*
*/
public class FlowControllerDAO extends BaseDAO implements FlowControllerQuery
{
/**
* 1. 기능 : 업무별 기본 정보 전체를 메모리에 로딩하기 위해 테이블 전체 내용을 SELECT해서
* BatchTargetVO 객체 리스트로 생성 반환하는 메서드.
* 2. 처리 개요 : TSEAIBJ02 테이블을 조회해서 각 업무 기본 정보를 가져오고, 해당 업무별 연결 정보를
* TSEAIBJ05 테이블에서 조회하여 연결 정보들을 DemandTargetVO[]로 만든 다음, processCode를 key로 하여
* 전체를 hashmap의 형태로 반환한다.
* 3. 주의사항
*
* @return Flow Rule 정보 전체데이터로 FlowRuleVO Collection
* @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 EAI서버 정보를 가져오다 발생되는 모든 에러
**/
public HashMap<String, BatchTargetVO> getAllTargets() throws DAOException
{
ResultSet rs = null;
try {
this.connect(GET_ALL_TARGETS);
//logger.debug("FlowControllerDAO.getAllTargets() >>> 수행 SQL 문 : \n"+ GET_ALL_TARGETS);
rs = executeQuery();
HashMap<String, BatchTargetVO> all = new HashMap<String, BatchTargetVO>();
while (rs.next()) {
BatchTargetVO vo = new BatchTargetVO(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
logger.debug(" - 대외기관 정보 로딩됨 ("+ vo.getProcessCode() +": "+ vo.getProcessName() +", "+ vo.getOrganCode() +": "+ vo.getOrganName() +")");
vo.setDemadnTargets(this.getDemandTartgetArray(vo.getProcessCode(), vo.getOrganCode()));
all.put(vo.getProcessCode() + vo.getOrganCode(), vo);
}
return all;
} catch (DAOException ex) {
throw ex;
} catch (Exception ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIMFC001");
throw new DAOException(errMsg); //요구송신 전체 대외기관 연결정보 로딩시 오류가 발생하였습니다.
} finally {
this.disconnect();
}
}
private DemandTargetVO[] getDemandTartgetArray(String processCode, String organCode) throws DAOException {
ResultSet rs = null;
int index = 0;
try {
super.preparedStatement = conn.prepareStatement(GET_DETAIL_DEMAND_TARGETS);
//logger.debug("FlowControllerDAO.getDemandTartgetArray() >>> 수행 SQL 문 : \n"+ GET_DETAIL_DEMAND_TARGETS);
index = 1;
this.preparedStatement.setString(index++, processCode); //logger.debug("FlowControllerDAO.getDemandTartgetArray() >>> 바인드("+(index-1)+") : ["+ processCode +"]");
this.preparedStatement.setString(index++, organCode ); //logger.debug("FlowControllerDAO.getDemandTartgetArray() >>> 바인드("+(index-1)+") : ["+ organCode +"]");
rs = executeQuery();
ArrayList<DemandTargetVO> aList = new ArrayList<DemandTargetVO>();
while (rs.next()) {
DemandTargetVO vo = new DemandTargetVO(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7));
logger.debug(" > 대외기관 요구송수신 연결 정보 ☞ (IP: "+ vo.getIpAddress() +", Port: "+ vo.getPortNumber() +", ID: "+ vo.getSocketID() +", PW: "+ vo.getSocketPwd() +", Timeout: "+ vo.getTimeoutInterval() +", OrganStatus: "+ vo.getOrganSocketStatus() +")");
aList.add(vo);
}
//logger.debug("FlowControllerDAO.getDemandTartgetArray() >>> 요구송수신 시스템 연결정보 건수: "+ aList.size());
if (aList.size() == 0) {
logger.debug(" > 대외기관 요구송수신 연결 정보 없음");
return new DemandTargetVO[0];
}
DemandTargetVO[] demandTargetArray = new DemandTargetVO[aList.size()];
aList.toArray(demandTargetArray);
return demandTargetArray;
} catch (DAOException ex) {
throw ex;
} catch (Exception ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIMFC002", new String[] {processCode, organCode});
throw new DAOException(errMsg); //요구송신 업무구분(%1) 대외기관(%2)에 해당하는 연결정보 로딩시 오류가 발생하였습니다.
} finally {
//ResultSet 과 PreparedStatement 만 close. Connection 은 Close 하면 안됨
try { if (rs!=null) rs.close(); } catch (Exception e) {throw new DAOException("BECEAICDB106");}
super.closeStatement();
}
}
public BatchTargetVO getBatchTargetVO(String processCode, String organCode) throws DAOException {
ResultSet rs = null;
int index = 0;
try {
this.connect(GET_BATCH_TARGETS);
//logger.debug("FlowControllerDAO.getBatchTargetVO() >>> 수행 SQL 문 : \n"+ GET_BATCH_TARGETS);
index = 1;
this.preparedStatement.setString(index++, processCode); //logger.debug("FlowControllerDAO.getBatchTargetVO() >>> 바인드("+(index-1)+") : ["+ processCode +"]");
this.preparedStatement.setString(index++, organCode ); //logger.debug("FlowControllerDAO.getBatchTargetVO() >>> 바인드("+(index-1)+") : ["+ organCode +"]");
rs = executeQuery();
if (rs.next() == false) {
//logger.debug("ResponseFlowDAO.getBatchTargetVO() >>> 요구송수신 시스템정보 건수: 0");
String errMsg = ExceptionUtil.getErrorCode("BECEAIMFC003", new String[] {processCode, organCode});
throw new DAOException(errMsg); //업무구분(%1)의 대외기관(%2) 정보가 등록되지 않았습니다.
}
//logger.debug("ResponseFlowDAO.getBatchTargetVO() >>> 요구송수신 시스템정보 건수: 1");
BatchTargetVO vo = new BatchTargetVO(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
logger.debug(" - 대외기관 정보 로딩됨 ("+ vo.getProcessCode() +": "+ vo.getProcessName() +", "+ vo.getOrganCode() +": "+ vo.getOrganName() +")");
vo.setDemadnTargets(this.getDemandTartgetArray(vo.getProcessCode(), vo.getOrganCode()));
return vo;
} catch (DAOException ex) {
throw ex;
} catch (Exception ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIMFC002", new String[] {processCode, organCode});
throw new DAOException(errMsg); //요구송신 업무구분(%1) 대외기관(%2)에 해당하는 연결정보 로딩시 오류가 발생하였습니다.
} finally {
disconnect();
}
}
/**
* 1. 기능 : 전달된 UUID에 해당하는 MsgPrcssStusCd 정보를 반환한다.
* 2. 처리 개요 : 전달된 UUID에 해당하는 MsgPrcssStusCd 정보를 읽어온다.
* 3. 주의사항
*
* @return
* @exception DAOExcepiton DB SELECT 관련 SQLException을 포함한 전문 정보를 가져오다 발생되는 모든 에러
**/
public String getStatusCode(String uuid) throws DAOException
{
try
{
ResultSet rs = null;
String statusCode = "";
// 연결정보의 전체 갯수를 읽어온다.
this.connect(GET_STATUS_CODE);
this.preparedStatement.setString(1, uuid);
rs = this.executeQuery();
if(rs.next()) {
statusCode = rs.getString(1);
} else {
String errMsg = ExceptionUtil.getErrorCode("BECEAIMFC008", new String[] {uuid});
throw new DAOException(errMsg); //작업진행 테이블에 해당 정보가 없습니다. (UUID: %1)
}
rs.close();
return statusCode;
} catch(Exception e) {
String errMsg = ExceptionUtil.getErrorCode(e, "BECEAIMFC009", new String[] {uuid});
throw new DAOException(errMsg); //작업진행 테이블에서 해당 작업의 상태 정보 조회시 오류가 발생하였습니다. (UUID: %1)
} finally {
this.disconnect();
}
}
public int updateSystemConnLineStatus(String processCode, String organCode, String lineStatus) throws DAOException {
int retValue = 0;
int index = 0;
try {
this.connect(UPDATE_SYSTEM_CONN_LINE_STATUS);
//logger.debug("FlowControllerDAO.updateSystemConnLineStatus() >>> 수행 SQL 문 : \n"+ ResponseFlowQuery.UPDATE_SYSTEM_CONN_LINE_STATUS);
index = 1;
this.preparedStatement.setString(index++, lineStatus ); //logger.debug("ResponseFlowDAO.updateSystemConnLineStatus() >>> 바인드("+(index-1)+") : ["+ lineStatus +"]");
this.preparedStatement.setString(index++, processCode); //logger.debug("ResponseFlowDAO.updateSystemConnLineStatus() >>> 바인드("+(index-1)+") : ["+ processCode +"]");
this.preparedStatement.setString(index++, organCode ); //logger.debug("ResponseFlowDAO.updateSystemConnLineStatus() >>> 바인드("+(index-1)+") : ["+ organCode +"]");
retValue = this.executeUpdate();
logger.debug("FlowControllerDAO.updateSystemConnLineStatus() >>> 연결 회선 상태 UPDATE 건 수 : "+ retValue);
if (retValue == 0) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIFRF010", new String[] {lineStatus});
throw new DAOException(errMsg); //대외기관 연결정보 테이블에 회선 상태 update 건수가 0 건입니다. (회선상태: {1})
}
} catch (DAOException ex) {
throw ex;
} catch (Exception ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFRF011", new String[] {lineStatus});
throw new DAOException(errMsg); //대외기관 연결정보 테이블에 회선 상태 update 시 오류가 발생하였습니다.(회선상태: {1})
} finally {
disconnect();
}
return retValue;
}
}
@@ -0,0 +1,251 @@
package com.eactive.eai.batch.flowController;
import java.util.HashMap;
import java.util.Iterator;
import com.eactive.eai.agent.AgentUtil;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.flowController.UpdateBatchTargetCommand;
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. 기능 : Flow Controller에서 사용하는 메소드들의 모임
* 2. 처리 개요 : 대부분의 값은 메모리에 로딩하지 않는 것으로 한다.
* 3. 주의사항
*
* @author : YCLee 2006/1/11
* @version : v 1.0.0
* @see : 관련 기능을 참조
* @since :
*/
public class FlowControllerManager implements Lifecycle
{
//파일로거
private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
/**
* EAIServerManager Single Instance
*/
private static FlowControllerManager instance = new FlowControllerManager();
/**
* LifeccyleSupport object
*/
private LifecycleSupport lifecycle = new LifecycleSupport(this);
/**
* 기동 여부
*/
private boolean started;
/**
* BatchTargetVO들을 저장하는 HashMap
*/
private HashMap<String, BatchTargetVO> targets;
/**
* 1. 기능 : Default Constructor
* 2. 처리 개요 : Flow Rule 정보를 저장하기 위한 HashMap을 초기화한다.
* 3. 주의사항
*
**/
private FlowControllerManager() {
targets = new HashMap<String, BatchTargetVO>();
}
/**
* 1. 기능 : FlowControllerManager Singleton Object를 반환하는 getter method
* 2. 처리 개요 : FlowControllerManager Singleton Object를 반환한다.
* 3. 주의사항
*
* @return FlowControllerManager Singleton object
**/
public static FlowControllerManager getInstance() {
return instance;
}
/* ****************************************************************** */
/* FlowControllerManager 자체적인 메소드 정의 */
/* ****************************************************************** */
/**
* 1. 기능 : 요구 송수신에서 사용할 대외기관의 연결 정보를 반환한다.
* 2. 처리 개요 :
*
* 3. 주의사항
*
* @return XML을 담고 있는 String 객체 반환
* @exception
**/
public DemandTargetVO[] getRemoteHostInfo(String processCode, String organCode)
{
if((BatchTargetVO)targets.get(processCode + organCode) == null)
return null;
else
return ((BatchTargetVO)targets.get(processCode + organCode)).getDemadnTargets();
}
public BatchTargetVO getBatchTargetInfo(String processCode, String organCode)
{
return (BatchTargetVO)targets.get(processCode + organCode);
}
public HashMap<String, BatchTargetVO> getTargets()
{
return targets;
}
/**
* 1.기능: F/C에서 요청 처리중 운영자에 의해서 해당 건이 취소되었는지를 확인하는 메소드
*/
public boolean getStatusCode(String uuid) throws Exception
{
FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class);
//반환값이 C(사용자취소)인 경우만 false로 반환한다.
if (dao.getStatusCode(uuid).equals("C"))
return false;
else
return true;
}
/* ****************************************************************** */
/* Lifecycle 인터페이스에 정의된 메소드 */
/* ****************************************************************** */
/**
* 1. 기능 : Lifecycle의 start 메서드로 FlowControllerManager 초기화하는 메서드
* 2. 처리 개요 : FlowControllerDAO를 이용해 대상 기관의 정보 모두를 가져와 초기화한다.
* 3. 주의사항
*
* @exception LifecycleException 이미 시작되었거나,
* DAOExcepiton이 발생될 경우
**/
public void start() throws LifecycleException
{
if (started) throw new LifecycleException("BECEAIMFC010"); //FlowControllerManager 가 이미 시작되었습니다.
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
try {
FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class);
this.targets = dao.getAllTargets();
} catch (DAOException e) {
String errMsg = ExceptionUtil.getErrorCode(e, "BECEAIMFC011");
throw new LifecycleException(errMsg); //Lifecycle 에서 FlowControllerManager 시작 시 (대외기관 별 연결정보 로딩) 오류가 발생하였습니다.
}
started = true;
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
}
/**
* 1. 기능 : Lifecycle의 stop 메서드로 EAIServerManager를 종료하는 메서드
* 2. 처리 개요 : 멤버에 캐싱항 EAIServer Rule 정보를 clear한다.
* 3. 주의사항
*
* @exception LifecycleException 이미 종료된 경우 발생
**/
public void stop() throws LifecycleException {
// Validate and update our current component state
if (!started)
throw new LifecycleException("BECEAIMFC012"); //FlowControllerManager 가 이미 종료되었습니다.
this.targets.clear();
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
started = 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);
}
/**
* 1. 기능 : FlowRuleManager의 초기화 여부를 반환하는 getter 메서드
* 2. 처리 개요 : FlowRuleManager의 초기화 여부를 반환한다.
* 3. 주의사항
*
* @return 초기화 여부
**/
public boolean isStarted() {
return this.started;
}
public int updateSystemConnLineStatus(String processCode, String organCode, String lineStatus) throws Exception {
logger.debug("▣▣▣▣▣ ==================================================================================");
logger.debug("▣▣▣▣▣ ★ 응답수신 '회선 "+ (lineStatus.equals(DemandTargetVO.ORGAN_SOCKET_STATUS_NORNAL)? "장애회복" : "장애") +" 통보 전문' 처리 Start......");
logger.debug("▣▣▣▣▣ - 업무구분코드 : ["+ processCode +"]");
logger.debug("▣▣▣▣▣ - 대외기관코드 : ["+ organCode +"]");
logger.debug("▣▣▣▣▣ ① 해당 대외기관의 전체 연결정보 DB Update......");
FlowControllerDAO dao = (FlowControllerDAO)DAOFactory.newInstance().create(FlowControllerDAO.class);
int resultCnt = dao.updateSystemConnLineStatus(processCode, organCode, lineStatus);
logger.debug("▣▣▣▣▣ ② Agent를 통한 모든 서버의 연결정보 HashMap Update......");
Command command = new UpdateBatchTargetCommand();
String[] args = new String[] {processCode, organCode, lineStatus};
command.setArgs(args);
HashMap<String, Object> map = AgentUtil.broadcast(command);
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String svrName = it.next();
String resultStr = (String) map.get(svrName);
logger.debug("▣▣▣▣▣ - '"+ svrName +"' 서버 호출 결과: "+ resultStr);
}
logger.debug("▣▣▣▣▣ ==================================================================================");
return resultCnt;
}
}
@@ -0,0 +1,69 @@
package com.eactive.eai.batch.flowController;
import com.eactive.eai.common.dao.Keys;
/**
* 1. 기능 : FlowControllerDAO에서 사용하는 SQL Query를 정의한 Interface
* 2. 처리 개요 :
* - FlowControllerDAO에서 사용하는 SQL Query를 정의한 Interface
* 3. 주의사항
*
* @author : YCLee 05/12/22
* @version : v 1.0.0
* @see :
* @since :JDK v1.4.2
*/
public interface FlowControllerQuery
{
/**
* 업무 기본 정보를 조회하는 Query
*/
public static final String GET_ALL_TARGETS = "select A.BjobBzwkDstcd, A.BjobBzwkName, LTRIM(RTRIM(B.OsidInstiDstcd)) AS OsidInstiDstcd, B.OsidInstiName \n" +
"from " + Keys.TABLE_OWNER + "TSEAIBJ02 A, " + Keys.TABLE_OWNER + "TSEAIBJ06 B \n" +
"where A.BjobBzwkDstcd = B.BjobBzwkDstcd \n" +
"and A.ThisMsgUseYn = '1' \n" +
"and B.ThisMsgUseYn = '1' \n";
/**
* 업무 기본 정보를 조회하는 Query
*/
public static final String GET_BATCH_TARGETS = "select A.BjobBzwkDstcd, A.BjobBzwkName, LTRIM(RTRIM(B.OsidInstiDstcd)) AS OsidInstiDstcd, B.OsidInstiName \n" +
"from " + Keys.TABLE_OWNER + "TSEAIBJ02 A, " + Keys.TABLE_OWNER + "TSEAIBJ06 B \n" +
"where A.BjobBzwkDstcd = B.BjobBzwkDstcd \n" +
"and B.BjobBzwkDstcd like ?||'%' \n" +
"and LTRIM(RTRIM(B.OsidInstiDstcd)) = ? \n"+
"and A.ThisMsgUseYn = '1' \n" +
"and B.ThisMsgUseYn = '1' \n";
/**
* 업무별 요구송수신 상세 연결 정보를 조회하는 Query
*/
public static final String GET_DETAIL_DEMAND_TARGETS =
"select SysLnkgDstcd, LnkgIPInfoName, LnkgPortInfoName, LnkgID, LnkgPwd, ToutVal, TCirtLnkgStusCd \n" +
"from " + Keys.TABLE_OWNER + "TSEAIBJ05 \n" +
"where BjobBzwkDstcd like ?||'%' \n" +
"and LTRIM(RTRIM(OsidInstiDstcd)) = ? \n"+
"and RqstRspnsDstcd = 'R' \n" +
"and ThisMsgUseYn = '1' ";
/**
* 해당 요청의 현재 status를 반환한다.
*/
public static final String GET_STATUS_CODE = "select MsgPrcssStusCd "+
"from " + Keys.TABLE_OWNER + "TSEAIBS04 \n" +
"where BjobDmndMsgID = ? ";
/**
* 응답수신 Flow Controller에서 시스템 장애 통보 및 회복 통보 전문을 받았을때 회선 상태를 update 한다.
* 해당 대외기관의 요구송수신 연결정보 전체 update
*/
public static final String UPDATE_SYSTEM_CONN_LINE_STATUS =
"UPDATE " + Keys.TABLE_OWNER + "TSEAIBJ05 \n"
+ "SET TCirtLnkgStusCd = ? \n"
+ "WHERE BjobBzwkDstcd LIKE ?||'%' \n"
+ "AND LTRIM(RTRIM(OsidInstiDstcd)) = ? \n"
+ "AND RqstRspnsDstcd = 'R'";
}
@@ -0,0 +1,24 @@
package com.eactive.eai.batch.flowController;
/**
* 1. 기능 : server 패키지에서 사용하는 상수를 정의한 Interface
* 2. 처리 개요 :
* - server 패키지에서 사용하는 상수를 정의한 Interface
* 3. 주의사항
*
* @author : YCLee 05/12/22
* @version : v 1.0.0
* @see : TestCallRunner, TestCallManager
* @since :JDK v1.4.2
*/
public class Keys
{
/**
* EAI 배치 프레임웍에서 임시로 사용하는 기본 DataSource에 대한 JNDI 이름
*/
public static final String EAI_BATCH_TEMP_DATASOURCE = "SONGDataSource";
}
@@ -0,0 +1,692 @@
package com.eactive.eai.batch.ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;
public class FTPAdaptor {
// private static Logger logger = LoggerFactory.getLogger(ElinkLogger.LOGGER_ADAPTER);
protected static FTPFile[] listFiles(String server, int port, String username, String password, String path, HashMap<Integer, String> extmap, Logger logger) throws IOException {
logger.debug("[FTP connect]server -->" + server);
logger.debug("[FTP connect]port -->" + port);
logger.debug("[FTP connect]username-->" + username);
logger.debug("[FTP connect]password-->" + password);
logger.debug("[FTP listFiles]path-->" + path);
FTPClient ftpClient = new FTPClient();
try {
ftpClient.setControlEncoding("euc-kr");
ftpClient.connect(server, port);
ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!ftpClient.login(username, password)) {
ftpClient.logout();
String arg[] = new String[1];
arg[0] = username;
throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
}
if (extmap == null) {
FTPFile[] tmpfiles = ftpClient.listFiles(path);
for (int jnx = 0; jnx < tmpfiles.length; jnx++) {
String filename = tmpfiles[jnx].getName();
tmpfiles[jnx].setName(filename.replace(path, ""));
}
return tmpfiles;
} else {
ArrayList<FTPFile> list = new ArrayList<FTPFile>();
int returnCnt = 0;
for (int inx = 0; inx < extmap.size(); inx++) {
String ext = extmap.get(inx);
FTPFile[] tmpfiles = ftpClient.listFiles(path + "/*." + ext);
for (int jnx = 0; jnx < tmpfiles.length; jnx++) {
String filename = tmpfiles[jnx].getName();
tmpfiles[jnx].setName(filename.replace(path, ""));
list.add(tmpfiles[jnx]);
returnCnt++;
}
}
FTPFile[] files = new FTPFile[returnCnt];
list.toArray(files);
return files;
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new IOException(e.getMessage());
} finally {
ftpClient.quit();
}
}
// 20241008 FTPFileObject 사용
protected static FTPFileObject[] listFiles2(String server, int port, String username, String password, String path, Logger logger) throws IOException {
logger.debug("[FTP connect]server -->" + server);
logger.debug("[FTP connect]port -->" + port);
logger.debug("[FTP connect]username-->" + username);
logger.debug("[FTP connect]password-->" + password);
logger.debug("[FTP listFiles]path-->" + path);
FTPClient ftpClient = new FTPClient();
try {
ftpClient.setControlEncoding("euc-kr");
ftpClient.connect(server, port);
ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!ftpClient.login(username, password)) {
ftpClient.logout();
String arg[] = new String[1];
arg[0] = username;
throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
}
FTPFile[] tmpfiles = ftpClient.listFiles(path);
for (int jnx = 0; jnx < tmpfiles.length; jnx++) {
String filename = tmpfiles[jnx].getName();
tmpfiles[jnx].setName(filename.replace(path, ""));
}
ArrayList<FTPFileObject> oFiles = new ArrayList<FTPFileObject>();
FTPFileObject[] rFiles = new FTPFileObject[tmpfiles.length];
FTPFileObject nFile;
for(FTPFile file :tmpfiles){
nFile = new FTPFileObject();
nFile.setFile(file.isFile());
nFile.setName(file.getName());
nFile.setSize(file.getSize());
oFiles.add(nFile);
}
oFiles.toArray(rFiles);
return rFiles;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new IOException(e.getMessage());
} finally {
ftpClient.quit();
}
}
protected static long retrieve(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String localPath, int bandWidthLimit, Logger logger, String ftpFileType) throws Exception {
logger.debug("[FTP retrieve]remote-->" + remote);
logger.debug("[FTP retrieve]localPath-->" + localPath);
long size = -1;
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.setControlEncoding("euc-kr");
ftpClient.connect(server, port);
if("ASCII".equals(ftpFileType))
ftpClient.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE);
else
ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!ftpClient.login(username, password)) {
ftpClient.logout();
String arg[] = new String[1];
arg[0] = username;
throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
}
File chkDir = new File(localPath);
String delimiter = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(localPath);
String fName = remote.substring(remote.lastIndexOf(delimiter) + 1);
logger.debug("[retrieve]fName ------->" + fName);
if (!chkDir.exists() && !chkDir.mkdirs()) {
logger.error("[체크파일을 생성할 수 없습니다.]"); // 상위 디렉토리 미 존재시에도 write 한다.
return -1;
}
File file = new File(localPath + delimiter + fName);
OutputStream output = new FileOutputStream(file);
if(bandWidthLimit > 0){
/**
* 대역폭 콘트롤 bis 512bps -> 512/8=64bytes/second, (1Byte=8bit),
*/
//Buffer buffer = new Buffer(1024);
//int bandWidth = 1024*8;
long bufferSize = bandWidthLimit/8;
byte[] bufferArr = new byte[(int)bufferSize];
try {
bos = new BufferedOutputStream(output);
bis = new BufferedInputStream(ftpClient.retrieveFileStream(remote));
batchDoc.setIOStream(bis);
int readCount = 0;
int lootCnt = 0;
long[] timeMillis = new long[2];
timeMillis[0] = System.currentTimeMillis();
long rtt = 0;//round trip time 1회 전송시간 millisecond
long rttMax = 0;
long rttMin = 0;
double rttAve = 0;
long rttSum = 0;
long realBandWidth = 0;
long realBandWidthMax = 0;
long realBandWidthMin = 0;
double realBandWidthAve = 0;
long realBandWidthSum = 0;
long readByteSum = 0;
long sizeStartTime = 0;
long sizePerSecond = 0;
int sleepTimeCriteria = 990;
while (true){
lootCnt++;
sleepTimeCriteria = 990; //여유 10milli
//강제중지 설정시
if (batchDoc.isUserCancel()){
throw new Exception("사용자가 전송을 중지 했습니다.");
}
timeMillis[0] = System.currentTimeMillis();
readCount = bis.read(bufferArr);
timeMillis[1] = System.currentTimeMillis();
if(readCount<=0) break;
bos.write(bufferArr,0,readCount);
readByteSum += readCount;
batchDoc.setCurrIODataByte(readByteSum);
if (sizePerSecond > 0){
rtt = timeMillis[1] - sizeStartTime;
} else {
rtt = timeMillis[1] - timeMillis[0];
}
if(rtt<=0 ){
//rtt=1;//local test시 0이 발생 divide by zero오류 발생, 방어코드
if(sizeStartTime==0)sizeStartTime = timeMillis[0];
sizePerSecond += readCount;
if(sizePerSecond >= bufferArr.length){
logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] rtt<=0 SLEEP 990 sec, readCount["+readCount+"]sizePerSecond["+sizePerSecond+"]readByteSum["+readByteSum+"] rtt["+rtt+"] sizeStartTime[,"+sizeStartTime+"] bufferSize["+bufferSize+"]");
Thread.sleep(990);
sizePerSecond = 0;
sizeStartTime = 0;
} else {
logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] rtt<=0 SLEEP 0 sec, readCount["+readCount+"]sizePerSecond["+sizePerSecond+"] readByteSum["+readByteSum+"] rtt["+rtt+"] sizeStartTime[,"+sizeStartTime+"] bufferSize["+bufferSize+"]");
}
continue;
}
if ( readCount < bufferArr.length || sizePerSecond> 0){
if(sizeStartTime==0)sizeStartTime = timeMillis[0];
sizePerSecond += readCount;
if(sizePerSecond>0 && sizePerSecond < bufferArr.length){
logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] SLEEP 0 sec readCount["+readCount+"] sizePerSecond["+sizePerSecond+"] readByteSum["+readByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]");
continue;
}
}
if (sizePerSecond > 0){
realBandWidth = (long) (sizePerSecond * 8 * 1000 / rtt);
} else {
realBandWidth = (long) (bufferSize * 8 * 1000 / rtt);
}
//min, max, sum
rttSum += rtt;
if (rtt > rttMax)rttMax = rtt;
else if (rtt < rttMin)rttMin = rtt;
realBandWidthSum += realBandWidth;
if(realBandWidth>realBandWidthMax)realBandWidthMax=realBandWidth;
else if(realBandWidth<realBandWidthMin)realBandWidthMin=realBandWidth;
if (sizePerSecond > 0 && sizePerSecond>bufferSize){
sleepTimeCriteria = (int) (sleepTimeCriteria*sizePerSecond/bufferSize);
}
if(rtt < sleepTimeCriteria){
logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] readByteSum["+readByteSum+"] sizePerSecond["+sizePerSecond+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep["+(sleepTimeCriteria-rtt)+"]sleepTimeCriteria["+sleepTimeCriteria+"]");
Thread.sleep((long) (sleepTimeCriteria-rtt));
} else {
logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] readByteSum["+readByteSum+"] sizePerSecond["+sizePerSecond+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep[0]sleepTimeCriteria["+sleepTimeCriteria+"]");
}
sizePerSecond = 0;
sizeStartTime = 0;
}
realBandWidthAve = realBandWidthSum/lootCnt;
rttAve = rttSum/lootCnt;
logger.info("SFTPAdaptor] ####Statistics : bufferSize["+bufferSize
+"] loopCnt["+lootCnt
+"] readByteSum["+readByteSum
+"] rttAve["+rttAve
+"] rttMax["+rttMax
+"] rttMin["+rttMin
+"] bandWidthLimit["+bandWidthLimit
+"] realBandWidthAve["+realBandWidthAve
+"] realBandWidthMax["+realBandWidthMax
+"] realBandWidthMin["+realBandWidthMin
+"]");
} finally {
if (bos != null){
bos.flush();
bos.close();
}
if (bis != null)bis.close();
if(output!=null) output.close();
}
} else {
ftpClient.retrieveFile(remote, output);
if(output!=null) output.close();
}
if ( file.exists() )
size = file.length();
// check the reply code to verify success
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
logger.warn("Command failed: " + ftpClient.getReplyString());
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new Exception(e.getMessage());
} finally {
if (ftpClient != null)
ftpClient.quit();
}
return size;
}
protected static long retrieve(String server, int port, String username, String password, String remote, String localPath, Logger logger) throws Exception {
logger.debug("[FTP retrieve]remote-->" + remote);
logger.debug("[FTP retrieve]localPath-->" + localPath);
long size = -1;
//BufferedOutputStream bos = null;// 20250910
//BufferedInputStream bis = null;// 20250910
FTPClient ftpClient = new FTPClient();
try {
ftpClient.setControlEncoding("euc-kr");
ftpClient.connect(server, port);
ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!ftpClient.login(username, password)) {
ftpClient.logout();
String arg[] = new String[1];
arg[0] = username;
throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
}
File chkDir = new File(localPath);
String delimiter = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(localPath);
String fName = remote.substring(remote.lastIndexOf(delimiter) + 1);
logger.debug("[retrieve]fName ------->" + fName);
if (!chkDir.exists() && !chkDir.mkdirs()) {
logger.error("[체크파일을 생성할 수 없습니다.]"); // 상위 디렉토리 미 존재시에도 write 한다.
return -1;
}
File file = new File(localPath + delimiter + fName);
OutputStream output = new FileOutputStream(file);
ftpClient.retrieveFile(remote, output);
output.close();
if ( file.exists() )
size = file.length();
// check the reply code to verify success
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
logger.warn("Command failed: " + ftpClient.getReplyString());
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new Exception(e.getMessage());
} finally {
if (ftpClient != null)
ftpClient.quit();
}
return size;
}
protected static boolean store(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String localPath, int bandWidthLimit, Logger logger) throws Exception {
logger.debug("[FTP store]remote-->" + remote);
logger.debug("[FTP store]localPath-->" + localPath);
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
FileInputStream input = null;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.setControlEncoding("euc-kr");
ftpClient.connect(server, port);
ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!ftpClient.login(username, password)) {
ftpClient.logout();
String arg[] = new String[1];
arg[0] = username;
throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
}
File file = new File(localPath);
String delimiter = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(remote);
String remotePath = remote.substring(0,remote.lastIndexOf(delimiter));
String fileName = remote.substring(remote.lastIndexOf(delimiter) + 1);
logger.debug("[FTP store]remotePath-->" + remotePath);
logger.debug("[FTP store]fileName-->" + fileName);
boolean cd = ftpClient.changeWorkingDirectory(remotePath);
if ( !cd ){
ftpClient.makeDirectory(remotePath);
ftpClient.changeWorkingDirectory(remotePath);
}
input = new FileInputStream(file);
if(bandWidthLimit > 0){
/**
* 대역폭 콘트롤 bis 512bps -> 512/8=64bytes/second, (1Byte=8bit),
*/
//Buffer buffer = new Buffer(1024);
//int bandWidth = 1024*8;
long bufferSize = bandWidthLimit/8;
byte[] bufferArr = new byte[(int)bufferSize];
try {
bos = new BufferedOutputStream(ftpClient.storeFileStream(remote));
bis = new BufferedInputStream(input);
batchDoc.setIOStream(bos);
int readCount = 0;
int lootCnt = 0;
long[] timeMillis = new long[2];
timeMillis[0] = System.currentTimeMillis();
long rtt = 0;//round trip time 1회 전송시간 millisecond
long rttMax = 0;
long rttMin = 0;
double rttAve = 0;
long rttSum = 0;
long realBandWidth = 0;
long realBandWidthMax = 0;
long realBandWidthMin = 0;
double realBandWidthAve = 0;
long realBandWidthSum = 0;
long writeByteSum = 0;
long sizeStartTime = 0;
long sizePerSecond = 0;
while (true){
lootCnt++;
//강제중지 설정시
if (batchDoc.isUserCancel()){
throw new Exception("사용자가 전송을 중지 했습니다.");
}
readCount = bis.read(bufferArr);
if(readCount<=0) break;
//****sftp send......
timeMillis[0] = System.currentTimeMillis();
bos.write(bufferArr,0,readCount);
timeMillis[1] = System.currentTimeMillis();
writeByteSum += readCount;
batchDoc.setCurrIODataByte(writeByteSum);
if (sizePerSecond > 0){
rtt = timeMillis[1] - sizeStartTime;
} else {
rtt = timeMillis[1] - timeMillis[0];
}
if(rtt<=0){
if(sizeStartTime==0)sizeStartTime = timeMillis[0];
sizePerSecond += readCount;
realBandWidth = 0;
}else {
//rtt가 0보다 커야 bandwidth계산
realBandWidth = (long) ((sizePerSecond+bufferSize) * 8 * 1000 / rtt);
sizeStartTime = 0;
sizePerSecond = 0;
}
realBandWidthSum += realBandWidth;
if(realBandWidth>realBandWidthMax)realBandWidthMax=realBandWidth;
else if(realBandWidth<realBandWidthMin)realBandWidthMin=realBandWidth;
rttSum += rtt;
if (rtt > rttMax)rttMax = rtt;
else if (rtt < rttMin)rttMin = rtt;
//1초이내로 처리가 된경우sleep,, 여유 10milli
if(rtt < 990){ //여유 10milli
logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] writeByteSum["+writeByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep["+(990-rtt)+"]");
Thread.sleep((long) (990-rtt));
} else {
logger.debug("SFTPAdaptor]lootCnt["+(lootCnt)+"] readCount["+readCount+"] writeByteSum["+writeByteSum+"] rtt["+rtt+"] bandWidthLimit["+bandWidthLimit+"] realBandWidth["+realBandWidth+"] bufferSize["+bufferSize+"]sleep[0]");
}
}
realBandWidthAve = realBandWidthSum/lootCnt;
rttAve = rttSum/lootCnt;
logger.info("SFTPAdaptor] ####Statistics : bufferSize["+bufferSize
+"] loopCnt["+lootCnt
+"] writeByteSum["+writeByteSum
+"] rttAve["+rttAve
+"] rttMax["+rttMax
+"] rttMin["+rttMin
+"] bandWidthLimit["+bandWidthLimit
+"] realBandWidthAve["+realBandWidthAve
+"] realBandWidthMax["+realBandWidthMax
+"] realBandWidthMin["+realBandWidthMin
+"]");
} finally {
try {
if (bos != null){
bos.flush();
bos.close();
}
if (bis != null)bis.close();
if(input!=null) input.close();
} catch (Throwable t){
logger.error("Closing Error:"+t.getMessage());
}
}
} else {
ftpClient.storeFile(fileName, input);
if(input!=null) input.close();// 20250910 obl
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new Exception(e.getMessage());
} finally {
if (ftpClient != null) ftpClient.disconnect();
}
return true;
}
protected static boolean store(String server, int port, String username, String password, String remote, String localPath, Logger logger) throws Exception {
logger.debug("[FTP store]remote-->" + remote);
logger.debug("[FTP store]localPath-->" + localPath);
FTPClient ftpClient = new FTPClient();
try {
ftpClient.setControlEncoding("euc-kr");
ftpClient.connect(server, port);
ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!ftpClient.login(username, password)) {
ftpClient.logout();
String arg[] = new String[1];
arg[0] = username;
throw new IOException(ExceptionUtil.getErrorCode( "BECEAIMEU016", arg ));
}
File file = new File(localPath);
String delimiter = com.eactive.eai.batch.common.StringUtil.getDirDelimiter(remote);
String remotePath = remote.substring(0,remote.lastIndexOf(delimiter));
String fileName = remote.substring(remote.lastIndexOf(delimiter) + 1);
logger.debug("[FTP store]remotePath-->" + remotePath);
logger.debug("[FTP store]fileName-->" + fileName);
boolean cd = ftpClient.changeWorkingDirectory(remotePath);
if ( !cd ){
ftpClient.makeDirectory(remotePath);
ftpClient.changeWorkingDirectory(remotePath);
}
FileInputStream input = new FileInputStream(file);
ftpClient.storeFile(fileName, input);
input.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new Exception(e.getMessage());
} finally {
if (ftpClient != null)
ftpClient.quit();
}
return true;
}
protected static boolean rename(String server, int port, String username, String password, String srcname, String tarname, Logger logger) throws Exception {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.setControlEncoding("euc-kr");
ftpClient.connect(server, port);
ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!ftpClient.login(username, password)) {
ftpClient.logout();
String arg[] = new String[1];
arg[0] = username;
throw new IOException(ExceptionUtil.getErrorCode(
"BECEAIMEU016", arg));
}
ftpClient.rename(srcname, tarname);
ftpClient.quit();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new Exception(e.getMessage());
} finally {
if (ftpClient != null)
ftpClient.quit();
}
return true;
}
protected static boolean delete(String server, int port, String username, String password, String srcname, Logger logger) throws Exception {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.setControlEncoding("euc-kr");
ftpClient.connect(server, port);
ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!ftpClient.login(username, password)) {
ftpClient.logout();
String arg[] = new String[1];
arg[0] = username;
throw new IOException(ExceptionUtil.getErrorCode(
"BECEAIMEU016", arg));
}
ftpClient.deleteFile(srcname);
ftpClient.quit();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new Exception(e.getMessage());
} finally {
if (ftpClient != null)
ftpClient.quit();
}
return true;
}
}
@@ -0,0 +1,29 @@
package com.eactive.eai.batch.ftp;
public class FTPFileObject {
private boolean file ;
private String name ;
private long size;
public boolean isFile() {
return file;
}
public void setFile(boolean file) {
this.file = file;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
}
+106
View File
@@ -0,0 +1,106 @@
package com.eactive.eai.batch.ftp;
import java.io.IOException;
import java.util.HashMap;
import org.apache.commons.net.ftp.FTPFile;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.batch.doc.BatchDoc;
public class FTPUtil {
public static FTPFile[] listFiles(String server, int port, String username, String password, String path, HashMap<Integer, String> extmap, boolean isSftp, Logger logger, String authType)
throws IOException {
if ( isSftp ){
return SFTPAdaptor.listFiles(server, port, username, password, path, extmap, logger, authType);
}else{
return FTPAdaptor.listFiles(server, port, username, password, path, extmap, logger);
}
}
// 20241008 sftp jsch 방식 list
public static FTPFileObject[] listFilesJSCH(String server, int port, String username, String password, String path, boolean isSftp, Logger logger, String authType)
throws IOException {
if ( isSftp ){
return SFTPAdaptor.listFilesJSCH(server, port, username, password, path, logger, authType);
}else{
return FTPAdaptor.listFiles2(server, port, username, password, path, logger);
}
}
public static long retrieve(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String remoteFileName, String localPath,
int connTimeout, int setTimeout, boolean isSftp, int bandWidth, Logger logger, String authType) throws Exception {
if ( isSftp ){
return SFTPAdaptor.retrieveJSCH(batchDoc, server, port, username, password, remote, remoteFileName, localPath, connTimeout, setTimeout, bandWidth, logger, authType);
}else{
return FTPAdaptor.retrieve(batchDoc,server, port, username, password, remote+remoteFileName, localPath, bandWidth, logger, "");
}
}
public static long retrieve(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String remoteFileName, String localPath,
int connTimeout, int setTimeout, int bandWidth, Logger logger, String authType, String fileType) throws Exception {
if ( "0".equals(authType)) {
return FTPAdaptor.retrieve(batchDoc,server, port, username, password, remote+remoteFileName, localPath, bandWidth, logger, fileType);
}else {
return SFTPAdaptor.retrieveJSCH(batchDoc, server, port, username, password, remote, remoteFileName, localPath, connTimeout, setTimeout, bandWidth, logger, authType);
}
}
public static long retrieve(String server, int port, String username, String password, String remote, String localPath, boolean isSftp, Logger logger, String authType) throws Exception {
if ( isSftp ){
return SFTPAdaptor.retrieve(server, port, username, password, remote, localPath, logger, authType);
}else{
return FTPAdaptor.retrieve(server, port, username, password, remote, localPath, logger);
}
}
public static boolean store(BatchDoc batchDoc, String server, int port, String username, String password, String remote, String remoteFileName, String localPath,
int connTimeout, int setTimeout, boolean isSftp, int bandWidth, Logger logger, String authType) throws Exception {
if ( isSftp ){
return SFTPAdaptor.storeJSCH(batchDoc, server, port, username, password, remote, remoteFileName, localPath, connTimeout, setTimeout, bandWidth, logger, authType);
}else{
return FTPAdaptor.store(batchDoc,server, port, username, password, remote+remoteFileName, localPath, bandWidth, logger);
}
}
/**
*
* @param authType 1: ID 인증, 2: 키인증
*/
public static boolean store(String server, int port, String username, String password, String remote, String localPath, boolean isSftp, Logger logger, String authType) throws Exception {
if ( isSftp ){
return SFTPAdaptor.store(server, port, username, password, remote, localPath, logger, authType);
}else{
return FTPAdaptor.store(server, port, username, password, remote, localPath, logger);
}
}
public static boolean rename(String server, int port, String username, String password, String srcname, String tarname, boolean isSftp, Logger logger, String authType) throws Exception {
if ( isSftp ){
return SFTPAdaptor.rename(server, port, username, password, srcname, tarname, logger, authType);
}else{
return FTPAdaptor.rename(server, port, username, password, srcname, tarname, logger);
}
}
/**
* KED backup을 위해서 만듬
*/
public static boolean renameWithMkdirs(String server, int port, String username, String password, String srcname, String tarname, String filename, boolean isSftp, Logger logger, String authType) throws Exception {
return SFTPAdaptor.renameWithMkdirs(server, port, username, password, srcname, tarname, filename, logger, authType);
}
// public static boolean delete(String server, int port, String username, String password, String srcname, boolean isSftp) throws Exception {
// if ( isSftp ){
// return SFTPAdaptor.delete(server, port, username, password, srcname);
// }else{
// return FTPAdaptor.delete(server, port, username, password, srcname);
// }
// }
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,134 @@
package com.eactive.eai.batch.job.jobComm;
import java.io.File;
import com.eactive.eai.batch.job.jobHandle.JobFinishHandler;
import com.eactive.eai.adapter.ftp.Transfer;
import com.eactive.eai.batch.common.CalendarUtil;
import com.eactive.eai.batch.common.CommonKeys;
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.Logger;
public class OutboundFTPHandle {
private BatchDoc batchDoc;
private String logHeader;
private String strUUID;
private Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
public void proc( BatchDoc recvBatchDoc ){
batchDoc = recvBatchDoc;
logger = recvBatchDoc.getLogger();
init();
try {
callScript();
closeAndRemove();
} catch (Exception e) {
handleException(e);
}
}
private void init()
{
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
logHeader = "["+ batchDoc.getBatchMsg().getHeader().getUUID() +" / "+
batchDoc.getBatchMsg().getHeader().getProcessCode() +" / "+
batchDoc.getBatchMsg().getHeader().getInstitutionName() +" / "+
batchDoc.getBatchMsg().getHeader().getProcessType() +" / "+
batchDoc.getBatchMsg().getHeader().getFileName() +" / "+
batchDoc.getBatchMsg().getHeader().getRuleCode() +"] [OutboundFTPHandle] ";
strUUID = batchDoc.getBatchMsg().getHeader().getUUID();
logger.info("{"+logHeader+"} start OutboundFTPHandle ... " );
logger.info("{"+logHeader+"} [JUNGFOX]################ 요구송수신 FTP 핸들러 시작 BatchMessageDoc: \n"+ batchDoc.toString());
logger.info("{"+logHeader+"} >> BatchRunningJobManager 등록시작 ");
BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, null, batchDoc);
logger.info("{"+logHeader+"} >> BatchRunningJobManager 등록완료 ");
}
public void callScript() throws Exception {
logger.info("[OutboundFTPHandle] =========================================================================");
String dirPath = batchDoc.getBatchMsg().getHeader().getFilePath();
String fileName = batchDoc.getBatchMsg().getHeader().getFileName();
String renamedFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName();
String processType = batchDoc.getBatchMsg().getHeader().getProcessType();
if ( processType.equalsIgnoreCase("RS") ){
File file = new File( dirPath + File.separatorChar + renamedFileName);
if ( !file.exists()){
throw new Exception();
}
long fileLen = file.length();
batchDoc.getBatchMsg().getHeader().setFileSize( fileLen );
logger.info("[OutboundFTPHandle] ※ 송신 디렉토리 : [" + dirPath +"]");
logger.info("[OutboundFTPHandle] ※ 송신 파일명 : [" + fileName +"]");
logger.info("[OutboundFTPHandle] ※ 송신 파일크기 : [" + fileLen +"]");
logger.info("[OutboundFTPHandle] =========================================================================");
//VAN사 제공 모듈을 이용하여 로컬의 송신_Arch 에 있는 파일을 해당 밴사로 전송
try {
logger.info("FTP 스크립트가 호출되었습니다.");
Transfer.sendFileByEvent(batchDoc);
} catch (Throwable t) {
String errMsg = ExceptionUtil.getErrorCode(t, "BECEAIFJC008" );
throw new Exception(errMsg); //VAN사 송수신 모듈 이용 전송 시 오류가 발생하였습니다.
}
new JobFinishHandler(batchDoc).handleSuccessEnd();
} else if ( processType.equalsIgnoreCase(CommonKeys.PROCESS_REQUEST_RECEIVE) ){
logger.info("[OutboundFTPHandle] ※ 수신 디렉토리 : [" + dirPath +"]");
logger.info("[OutboundFTPHandle] ※ 수신 파일명 : [" + fileName +"]");
logger.info("[OutboundFTPHandle] =========================================================================");
//VAN사 제공 모듈을 이용하여 로컬의 송신_Arch 에 있는 파일을 해당 밴사로 전송
try {
logger.info("FTP 스크립트가 호출되었습니다.");
Transfer.recvFileByEvent(batchDoc);
} catch (Throwable t) {
String errMsg = ExceptionUtil.getErrorCode(t, "BECEAIFJC008" );
throw new Exception(errMsg); //VAN사 송수신 모듈 이용 전송 시 오류가 발생하였습니다.
}
new JobFinishHandler(batchDoc).handleSuccessEnd();
} else {
}
}
private void closeAndRemove() throws Exception
{
logger.info("{"+logHeader+"} >> BatchRunningJobManager 에서 Socket 연결정보 제거 시작......");
BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID);
logger.info("{"+logHeader+"} >> BatchRunningJobManager Socket 연결정보 제거 완료.");
}
private void handleException(Exception ex)
{
try {
if (BatchRunningJobManager.getInstance().isSocketClosed(strUUID) == false) BatchRunningJobManager.getInstance().closeRunningSocket(strUUID);
} catch (Exception e) {
logger.error("{"+logHeader+"} ★★★★★ OutboundFTPHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n"+ e.getMessage());
}
try {
if (BatchRunningJobManager.getInstance().isJobRunning(strUUID) == true) BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID);
} catch (Exception e) {
logger.error("{"+logHeader+"} ★★★★★ OutboundFTPHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n" + e.getMessage());
}
try {
// 파일로그 처리
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJC005");
logger.error("{"+errMsg+"} {"+logHeader+"} \r\n"+ex.getMessage());
// DB로그 처리
new JobFinishHandler(batchDoc).handleErrorEnd(errMsg);
} catch (Exception e) {
logger.error("{"+logHeader+"} ★★★★★ OutboundFTPHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n" + e.getMessage());
}
}
}
@@ -0,0 +1,148 @@
package com.eactive.eai.batch.job.jobComm;
import java.net.Socket;
import java.net.UnknownHostException;
import com.eactive.eai.batch.job.jobHandle.FlowController;
import com.eactive.eai.batch.job.jobHandle.JobFinishHandler;
import com.eactive.eai.adapter.socket.outbound.OutboundSocketClient;
import com.eactive.eai.batch.common.CalendarUtil;
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.Logger;
public class OutboundSocketHandle {
private BatchDoc batchDoc;
private String logHeader;
private String strUUID;
private Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
public void proc( BatchDoc recvBatchDoc ){
batchDoc = recvBatchDoc;
init();
try {
connect();
FlowController flowController = new FlowController();
batchDoc = flowController.clientRequestwithReturn(batchDoc);
closeAndRemove();
} catch (Exception e) {
handleException(e);
}
}
private void init()
{
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
logHeader = "["+ batchDoc.getBatchMsg().getHeader().getUUID() +" / "+
batchDoc.getBatchMsg().getHeader().getProcessCode() +" / "+
batchDoc.getBatchMsg().getHeader().getInstitutionName() +" / "+
batchDoc.getBatchMsg().getHeader().getProcessType() +" / "+
batchDoc.getBatchMsg().getHeader().getFileName() +" / "+
batchDoc.getBatchMsg().getHeader().getRuleCode() +"] [OutboundSocketHandle] ";
strUUID = batchDoc.getBatchMsg().getHeader().getUUID();
logger = batchDoc.getLogger();
logger.info("{"+logHeader+"} start OutboudnSocketHandle ... " );
logger.info("{"+logHeader+"} [JUNGFOX]################ 요구송신 소켓연결 JPD 시작 BatchMessageDoc: \n"+ batchDoc.toString());
}
private void connect() throws Exception{
// 새로운 connection 만들기
// *** 소켓연결은 상대방 서버 소켓의 IP+PORT 당 하나의 연결만을 가지는 것을 가정한다.
// 2. 연결 가능 IP 주소 구하기
// 조건 : 현재 사용중이 아니고, 장애통보 혹은 장애 상태가 아닌 경우...
//
// 사용가능한 소켓 자원이 구해졌으면
//
logger.info("{"+logHeader+"} SOCKET TARGET IP = [" + batchDoc.getBatchMsg().getHeader().getRemoteIP()+"]" );
logger.info("{} SOCKET PORT = [" + batchDoc.getBatchMsg().getHeader().getPort()+"]");
// 소켓을 만들고
logger.info("{"+logHeader+"} Socket connection try to the ["+batchDoc.getBatchMsg().getHeader().getRemoteIP()+"] starting");
int nPortNum = -1;
try {
nPortNum = Integer.parseInt(batchDoc.getBatchMsg().getHeader().getPort());
} catch (Exception ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJC002", new String[] {batchDoc.getBatchMsg().getHeader().getPort()});
throw new Exception(errMsg);
}
Socket socket = socketInit(batchDoc.getBatchMsg().getHeader().getRemoteIP(), nPortNum);
if (socket == null) {
// String errMsg = "setSocketConnection : SocketClientControl socketInit return null";
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJC003");
throw new Exception(errMsg);
}
logger.info("{"+logHeader+"} Socket connection success");
logger.info("{"+logHeader+"} >> BatchRunningJobManager 등록시작 ");
OutboundSocketClient socketClient = new OutboundSocketClient(socket);
BatchRunningJobManager.getInstance().addRunningJobInfo(strUUID, socketClient, batchDoc);
logger.info("{"+logHeader+"} >> BatchRunningJobManager 등록완료 ");
}
private Socket socketInit(String remoteIP, int remotePort) throws Exception
{
try {
return new Socket(remoteIP, remotePort);
} catch (UnknownHostException ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC001", new String[] {remoteIP, Integer.toString(remotePort)});
throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), 서버를 찾을 수 없습니다.
} catch (Exception ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIASC002", new String[] {remoteIP, Integer.toString(remotePort)});
throw new Exception(errMsg); //Socket 연결 에러 (IP: %1, Port: %2), I/O Exception이 발생했습니다.
}
}
private void closeAndRemove() throws Exception
{
//Outbound Socket Close
BatchRunningJobManager.getInstance().closeRunningSocket(strUUID);
logger.info("{"+logHeader+"} >> BatchRunningJobManager 에서 Socket 연결정보 제거 시작......" );
BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID);
logger.info("{"+logHeader+"} >> BatchRunningJobManager Socket 연결정보 제거 완료.");
}
private void handleException(Exception ex)
{
try {
if (BatchRunningJobManager.getInstance().isSocketClosed(strUUID) == false) BatchRunningJobManager.getInstance().closeRunningSocket(strUUID);
} catch (Exception e) {
logger.error("{"+logHeader+"} ★★★★★ OutboundSocketHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n" + e.getMessage());
}
try {
if (BatchRunningJobManager.getInstance().isJobRunning(strUUID) == true) BatchRunningJobManager.getInstance().removeRunningJobInfo(strUUID);
} catch (Exception e) {
logger.error("{"+logHeader+"} ★★★★★ OutboundSocketHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n"+ e.getMessage());
}
try {
// = this.context.getExceptionInfo().getException();
// 파일로그 처리
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJC005");
logger.error("{"+logHeader+"}"+" {"+errMsg+"}"+ ex.getMessage());
// DB로그 처리
new JobFinishHandler(batchDoc).handleErrorEnd(errMsg);
} catch (Exception e) {
logger.error("{} ★★★★★ OutboundSocketHandle JPD 예외 처리 중 에러 !! ★★★★★ \r\n", logHeader, e);
}
}
}
@@ -0,0 +1,32 @@
package com.eactive.eai.batch.job.jobConstant;
public class ErrorKeys
{
public static final String ERROR_UNEXPECTED_TELEGRAM_IGNORE = "BWCEAIFJM001"; //Rule에 정의되지 않은 전문종별코드[{1}] 가 도착하였습니다. 당 전문을 무시하고 다음 전문을 수신합니다.
public static final String ERROR_NO_SOCKET = "BECEAIFJM001"; //해당 배치 작업의 전문 송수신 시 필요한 Socket 정보를 BatchRunningJobManager에서 찾을 수 없습니다. 내부 로직 검토가 필요합니다. (UUID:{1})
public static final String ERROR_NO_PROCDATA = "BECEAIFJM002"; //해당 배치 작업의 진행 정보를 JobProcessData 에서 찾을 수 없습니다. 내부 로직 검토가 필요합니다. (UUID:{1})
public static final String ERROR_NO_NEXTSTAGE = "BECEAIFJM003"; //해당 배치 작업의 진행 정보 중 현재 단계 정보를 찾을 수 없습니다. TSEAIBR02 테이블에 해당 단계 정보를 등록하세요. (RuleCode:{1}, PhaseCode:{2})
public static final String ERROR_NO_TELEGRAM_ID = "BECEAIFJM004"; //수행 중인 단계의 텔레그램ID 정보를 텔레그램 정의 테이블(TSEAIBR05) 에서 찾을 수 없습니다. TSEAIBR05 테이블에 해당 텔레그램 정보를 등록하세요. (RuleCode:{1}, PhaseCode:{2}, TelegramID:{3})
public static final String ERROR_NO_CLASS_DEFINITION = "BECEAIFJM005"; //텔레그램 클래스를 동적으로 생성시 실패하였습니다. 해당 클래스 파일이 존재하는지 확인하세요. (TelegramID:{1}, ClassName:{2})
public static final String ERROR_RECV_PRE_LENGTH = "BECEAIFJM006"; //(전문 송수신 전) 텔레그램 클래스의 수행 전처리 실행이 실패하였습니다. 해당 클래스의 doPreExecute 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2})
public static final String ERROR_ERR_TELEGRAM_META = "BECEAIFJM007"; //전문헤더 수신 시 비정형 전문필드(길이가 XX) 가 존재합니다. 전문헤더 텔레그램ID 의 비정형 전문필드를 제거하세요. (TelegramID:{1}, ClassName:{2})
public static final String ERROR_TIMEOUT_OVER = "BECEAIFJM008"; //대외기관으로부터 전문 수신 시 Timeout 이 발생하였습니다 (읽어들인 데이터 없음). 해당 대외기관에 연락바랍니다. [Timeout회수:{1}, soTimeout:{2}초]
public static final String ERROR_RECV_ERROR = "BECEAIFJM009"; //대외기관으로부터 전문 수신 시 오류가 발생하였습니다.(소켓 IOException) 파일로그의 상세오류 검토가 필요합니다. (ClassName:{1})
public static final String ERROR_END_OF_STREAM = "BECEAIFJM010"; //대외기관으로부터 전문 수신 시 End-Of-Stream 에 도착하여 읽어들일 데이터가 없습니다. 해당 대외기관에 연락바랍니다.
public static final String ERROR_EXCEPTION = "BECEAIFJM011"; //대외기관으로부터 전문 수신 시 Socket 오류가 발생하여 데이터를 읽어들일 수 없습니다.
public static final String ERROR_RECV_SHORT_LENGTH = "BECEAIFJM012"; //대외기관으로부터 전문 수신 시 전체 전문을 수신하지 못했습니다. 파일로그에서 읽어 들인 전문필드 확인 후 해당 대외기관에 연락바랍니다.
public static final String ERROR_UNEXPECTED_TELEGRAM = "BECEAIFJM013"; //수신전문의 '전문종별코드' 값({1})에 해당하는 단계 정보를 JobProcessData 에서 찾을 수 없습니다. TSEAIBR02 테이블에서 해당 단계의 'CndnTelgmPtrnCd' 값을 확인하세요. (RuleCode:{1}, PhaseCode:{2})
public static final String ERROR_EXECUTION = "BECEAIFJM014"; //(전문 송수신 전) 텔레그램 클래스의 전문조립 또는 전문해체(doExecute) 함수 실행이 실패하였습니다. 해당 클래스의 doExecute 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2})
public static final String ERROR_RECV_VALIDATION = "BECEAIFJM015"; //대외기관으로부터 수신된 전문의 Validatioin 체크가 실패하였습니다. 오류전문을 보내지 않고 작업을 종료합니다.
public static final String ERROR_POST_EXECUTION = "BECEAIFJM016"; //(전문 송수신 후) 텔레그램 클래스의 수행 후처리 실행이 실패하였습니다. 해당 클래스의 doPostExecute 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2})
public static final String ERROR_INFORMAL_FIELD_LENGTH = "BECEAIFJM017"; //데이터 전문의 송수신 시 비정형 전문필드의 길이 계산이 실패하였습니다. 해당 클래스의 getCalculatedLength 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2})
public static final String ERROR_INFORMAL_ACTION = "BECEAIFJM018"; //데이터 수신전문의 비정형 전문필드 수신 중 수신 데이터 처리가(doInformalField) 실패하였습니다. 파일로그에서 상세오류 확인 후 로직 검토가 필요합니다. (TelegramID:{1}, ClassName:{2})
public static final String ERROR_NOTFOUND_NEXTSTAGE = "BECEAIFJM019"; //다음 원인에 의해 다음 단계 정보를 찾을 수 없습니다. (하위 원인이 없을경우 TSEAIBR02 테이블에서 해당 Rule 정보가 올바른지 확인이 필요합니다.) (RuleCode:{1}, PhaseCode:{2})
public static final String ERROR_SEND_VALIDATION = "BECEAIFJM020"; //대외기관으로 전송할 송신전문의 Validation 체크가 실패하였습니다.
public static final String ERROR_READ_FILE = "BECEAIFJM021"; //데이터 송신전문의 비정형 전문필드 데이터를 읽어오는데 실패하였습니다. 해당 클래스의 doInformalFieldSendData 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2})
public static final String ERROR_WRITE_ERROR = "BECEAIFJM022"; //대외기관에 전문 송신 시 오류가 발생하였습니다. 해당 대외기관에서 소켓 연결을 종료하였거나 파일로그 확인 후 로직 수정이 필요합니다.
public static final String ERROR_SHORT_WRITE_ERROR = "BECEAIFJM023"; //대외기관에 송신할 전문의 사이즈가 다릅니다. 파일로그 확인 후 로직 수정이 필요합니다. (TelegramID:{1}, ClassName:{2}, 보낼Size:{3}, 실제Size:{4})
public static final String ERROR_RECV_PRE_AFTER_COPY = "BECEAIFJM024"; //전문 Body 수신 전에 텔레그램 클래스의 수행 전처리 실행이 실패하였습니다. 해당 클래스의 doPreExecuteAfterCopy 메소드 검토가 필요합니다. (TelegramID:{1}, ClassName:{2})
}
@@ -0,0 +1,641 @@
package com.eactive.eai.batch.job.jobConstant;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class TelegramKeys
{
/**
* 자료구분
*/
public static final String RPS_HBD_DAT_GBN_TEST = "T"; //테스트데이터
public static final String RPS_HBD_DAT_GBN_REAL = "R"; //실데이터
public static final String RPS_HBD_DAT_GBN_PASS = "B"; //ByPass데이터
public static String getRPS_HDB_DAT_GBN(String s)
{
if (s.equals("test")) // Test Data
return "T";
else if (s.equals("real")) // Real Data
return "R";
else if (s.equals("pass")) // By Pass
return "B";
else
return "E"; // Error: 위의 문자가 아닌 경우
}
/**
* 송수신 Flag (HDB_TRA_FLAG)
*/
public static final String RPS_HDB_TRA_FLAG_CLIENT = "1"; // Client --> Server 1, Server --> Client 2
public static final String RPS_HDB_TRA_FLAG_SERVER = "2";
/**
* 응답코드 (HDB_RET_CODE), 3자리
*/
public static final String RPS_HDB_RET_CODE_SUCCESS = "000"; //정상
public static final String RPS_HDB_RET_CODE_ALREADY_RECEIVED = "101"; //기수신완료
public static final String RPS_HDB_RET_CODE_FORMAT_ERROR = "201"; //Format오류
public static final String RPS_HDB_RET_CODE_CODE_ERROR = "202"; //기관코드오류
public static final String RPS_HDB_RET_CODE_FILENAME_ERROR = "203"; //파일명오류
public static final String RPS_HDB_RET_CODE_UNCOMPLETED_ERROR = "901"; //파일전송미완료
public static final String RPS_HDB_RET_CODE_OTHER_ERROR = "999"; //기타오류
public static String getName_RPS_HDB_RET_CODE(String code) {
return code==null ? "null" :
code.equals(RPS_HDB_RET_CODE_SUCCESS )? "정상" :
code.equals(RPS_HDB_RET_CODE_ALREADY_RECEIVED )? "기수신완료" :
code.equals(RPS_HDB_RET_CODE_FORMAT_ERROR )? "Format오류" :
code.equals(RPS_HDB_RET_CODE_CODE_ERROR )? "기관코드오류" :
code.equals(RPS_HDB_RET_CODE_FILENAME_ERROR )? "파일명오류" :
code.equals(RPS_HDB_RET_CODE_UNCOMPLETED_ERROR)? "파일전송미완료" :
code.equals(RPS_HDB_RET_CODE_OTHER_ERROR )? "기타오류" : code;
}
/**
* 응답코드 (KFB_RET_CODE), 3자리
*/
public static final String KFB_RET_CODE_SUCCESS = "000"; //정상
public static final String KFB_RET_CODE_NO_FILE = "101"; //해당일자 전송자료 없음
public static final String KFB_RET_CODE_ALREADY_RECEIVED = "102"; //해당일자 정보 기수신 완료
public static final String KFB_RET_CODE_ORGN_CODE_ERROR = "401"; //참가기관코드 Error
public static final String KFB_RET_CODE_TGRAM_CODE_ERROR = "402"; //전문종별코드 Error
public static final String KFB_RET_CODE_TRX_GBN_CODE_ERROR = "403"; //거래구분코드 Error
public static final String KFB_RET_CODE_SND_RCV_FLAG_ERROR = "404"; //송수신 Flag Error
public static final String KFB_RET_CODE_FILE_TRANS_NO_END = "610"; //파일전송 미완료
public static String getName_KFB_RET_CODE(String code) {
return code==null ? "null" :
code.equals(KFB_RET_CODE_SUCCESS )? "정상" :
code.equals(KFB_RET_CODE_NO_FILE )? "해당일자 전송자료 없음" :
code.equals(KFB_RET_CODE_ALREADY_RECEIVED )? "해당일자 정보 기수신 완료" :
code.equals(KFB_RET_CODE_ORGN_CODE_ERROR )? "참가기관코드 Error" :
code.equals(KFB_RET_CODE_TGRAM_CODE_ERROR )? "전문종별코드 Error" :
code.equals(KFB_RET_CODE_TRX_GBN_CODE_ERROR)? "거래구분코드 Error" :
code.equals(KFB_RET_CODE_SND_RCV_FLAG_ERROR)? "송수신 Flag Error" :
code.equals(KFB_RET_CODE_FILE_TRANS_NO_END )? "파일전송 미완료" : code;
}
/**
* 응답코드 (BOKJJ_RET_CODE), 3자리
*/
public static final String BOKJJ_RET_CODE_SUCCESS = "000"; //정상
public static final String BOKJJ_RET_CODE_PROTO = "210"; //전문흐름순서 오류
public static final String BOKJJ_RET_CODE_ALREADY_RECEIVED = "220"; //기수신 자료임
public static final String BOKJJ_RET_CODE_DATE_ERROR = "230"; //헤더 전문 내 날짜 오류
public static final String BOKJJ_RET_CODE_REC_COUNT_ERROR = "240"; //수신건수와 헤더 또는 트레일러건수 불일치
public static final String BOKJJ_RET_CODE_ID_ERROR = "310"; //참가기관ID 오류
public static final String BOKJJ_RET_CODE_PASSWORD_ERROR = "320"; //비밀번호 오류
public static final String BOKJJ_RET_CODE_OPCODE_ERROR = "330"; //업무관리정보 오류
public static final String BOKJJ_RET_CODE_HDTLER_ERROR = "340"; //헤더/트레일러 구분 코드 오류
public static final String BOKJJ_RET_CODE_JOBCODE_ERROR = "910"; //업무구분코드 오류
public static final String BOKJJ_RET_CODE_TEL_CODE_ERROR = "920"; //전문종별코드 오류
public static final String BOKJJ_RET_CODE_TRX_GBN_CODE_ERROR = "930"; //거래구분코드 오류
public static final String BOKJJ_RET_CODE_SND_RCV_FLAG_ERROR = "940"; //송수신 FLAG 오류
public static final String BOKJJ_RET_CODE_RTN_CODE_ERROR = "950"; //응답코드 오류
public static final String BOKJJ_RET_CODE_SND_RCV_JOBCODE_ERROR = "960"; //송수신 업무구분 코드 오류
public static final String BOKJJ_RET_CODE_FILE_TRANS_DUP_ERROR = "630"; //파일중복 수신 오류
public static String getName_BOKJJ_RET_CODE(String code) {
return code==null ? "null" :
code.equals(BOKJJ_RET_CODE_SUCCESS )? "정상" :
code.equals(BOKJJ_RET_CODE_PROTO )? "전문흐름순서 오류 " :
code.equals(BOKJJ_RET_CODE_ALREADY_RECEIVED )? "기수신 자료임 " :
code.equals(BOKJJ_RET_CODE_DATE_ERROR )? "헤더 전문 내 날짜 오류 " :
code.equals(BOKJJ_RET_CODE_REC_COUNT_ERROR )? "수신건수와 헤더 또는 트레일러건수 불일치" :
code.equals(BOKJJ_RET_CODE_ID_ERROR )? "참가기관ID 오류 " :
code.equals(BOKJJ_RET_CODE_PASSWORD_ERROR )? "비밀번호 오류 " :
code.equals(BOKJJ_RET_CODE_OPCODE_ERROR )? "업무관리정보 오류 " :
code.equals(BOKJJ_RET_CODE_HDTLER_ERROR )? "헤더/트레일러 구분 코드 오류 " :
code.equals(BOKJJ_RET_CODE_JOBCODE_ERROR )? "업무구분코드 오류 " :
code.equals(BOKJJ_RET_CODE_TEL_CODE_ERROR )? "전문종별코드 오류 " :
code.equals(BOKJJ_RET_CODE_TRX_GBN_CODE_ERROR )? "거래구분코드 오류 " :
code.equals(BOKJJ_RET_CODE_SND_RCV_FLAG_ERROR )? "송수신 FLAG 오류 " :
code.equals(BOKJJ_RET_CODE_RTN_CODE_ERROR )? "응답코드 오류 " :
code.equals(BOKJJ_RET_CODE_SND_RCV_JOBCODE_ERROR)? "송수신 업무구분 코드 오류 " :
code.equals(BOKJJ_RET_CODE_FILE_TRANS_DUP_ERROR )? "파일중복 수신 오류 " : code;
}
public static final long BOKJJ_DELAY_MILISEC = 1000;
/**
* 응답코드 (BOKNG_RET_CODE), 3자리
*/
public static final String BOKNG_RET_CODE_000 = "000"; //정상
public static final String BOKNG_RET_CODE_210 = "210"; //거래구분코드 불일치 오류
public static final String BOKNG_RET_CODE_220 = "220"; //블록번호 오류
public static final String BOKNG_RET_CODE_230 = "230"; //중복수신 오류
public static final String BOKNG_RET_CODE_240 = "240"; //데이터 시퀀스 오류 / 데이터 건수 오류
public static final String BOKNG_RET_CODE_250 = "250"; //데이터 수신 Timeout 오류
public static final String BOKNG_RET_CODE_260 = "260"; //결번확인 오류
public static final String BOKNG_RET_CODE_270 = "270"; //업무 개시전 오류
public static final String BOKNG_RET_CODE_280 = "280"; //집계 응답전문 미수신(한은망 집계 처리시)
public static final String BOKNG_RET_CODE_310 = "310"; //송신자 ID 오류
public static final String BOKNG_RET_CODE_320 = "320"; //송신자 Password 오류
public static final String BOKNG_RET_CODE_330 = "330"; //수신구분 오류
public static final String BOKNG_RET_CODE_340 = "340"; //전문전송일시 오류
public static final String BOKNG_RET_CODE_350 = "350"; //파일명 오류
public static final String BOKNG_RET_CODE_360 = "360"; //Data구분 오류
public static final String BOKNG_RET_CODE_370 = "370"; //처리기준일 오류
public static final String BOKNG_RET_CODE_910 = "910"; //업무코드 오류
public static final String BOKNG_RET_CODE_920 = "920"; //기관코드 오류
public static final String BOKNG_RET_CODE_930 = "930"; //전문종별코드 오류
public static final String BOKNG_RET_CODE_940 = "940"; //수신FLAG 오류
public static final String BOKNG_RET_CODE_950 = "950"; //응답코드 오류
public static String getName_BOKNG_RET_CODE(String code) {
return code==null ? "null" :
code.equals(BOKNG_RET_CODE_000)? "정상" :
code.equals(BOKNG_RET_CODE_210)? "거래구분코드 불일치 오류" :
code.equals(BOKNG_RET_CODE_220)? "블록번호 오류" :
code.equals(BOKNG_RET_CODE_230)? "중복수신 오류" :
code.equals(BOKNG_RET_CODE_240)? "데이터 시퀀스 오류 / 데이터 건수 오류" :
code.equals(BOKNG_RET_CODE_250)? "데이터 수신 Timeout 오류" :
code.equals(BOKNG_RET_CODE_260)? "결번확인 오류" :
code.equals(BOKNG_RET_CODE_270)? "업무 개시전 오류" :
code.equals(BOKNG_RET_CODE_280)? "집계 응답전문 미수신(한은망 집계 처리시)" :
code.equals(BOKNG_RET_CODE_310)? "송신자 ID 오류" :
code.equals(BOKNG_RET_CODE_320)? "송신자 Password 오류" :
code.equals(BOKNG_RET_CODE_330)? "수신구분 오류" :
code.equals(BOKNG_RET_CODE_340)? "전문전송일시 오류" :
code.equals(BOKNG_RET_CODE_350)? "파일명 오류" :
code.equals(BOKNG_RET_CODE_360)? "Data구분 오류" :
code.equals(BOKNG_RET_CODE_370)? "처리기준일 오류" :
code.equals(BOKNG_RET_CODE_910)? "업무코드 오류" :
code.equals(BOKNG_RET_CODE_920)? "기관코드 오류" :
code.equals(BOKNG_RET_CODE_930)? "전문종별코드 오류" :
code.equals(BOKNG_RET_CODE_940)? "수신FLAG 오류" :
code.equals(BOKNG_RET_CODE_950)? "응답코드 오류" : code;
}
/*******************************************************************************
* 금융정보분석원 사용 코드
*******************************************************************************/
public static final String FIUSC_RES_CODE_SUCESS = "00"; //정상, 시퀀스와 크기 둘다 일치
public static final String FIUSC_RES_CODE_ERROR = "11"; //오류, 시퀀그와 크기 둘다 불일치
public static final String FIUSC_RES_CODE_ERROR_SEQ = "01"; //오류, 시퀀스 불일치
public static final String FIUSC_RES_CODE_ERROR_SIZE = "10"; //오류, 크기 불일치
public static final String FIUSC_DATA_FLAG_BIN = "B"; //바이너리 모드
public static final String FIUSC_RESUME_YN = "N"; //이어받기 사용안함
public static final String FIUSC_EAI_CD = "eai.cd"; //중계기관코드
/**
* 전문전송일 (HDB_SND_DATE): YYYYMMDD 형태의 값을 전달하여야 한다.
*/
public static String getYYYYMMDD()
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String curDate = formatter.format(Calendar.getInstance().getTime());
return curDate;
}
/**
* 전문전송일 (HDB_SND_DATE): YYYYMMDD 형태의 값을 전달하여야 한다.
*/
public static String getYYYYMMDD( int days )
{
Calendar temp = Calendar.getInstance ( );
StringBuffer sbDate = new StringBuffer ( );
temp.add ( Calendar.DAY_OF_MONTH, days );
int nYear = temp.get ( Calendar.YEAR );
int nMonth = temp.get ( Calendar.MONTH ) + 1;
int nDay = temp.get ( Calendar.DAY_OF_MONTH );
sbDate.append ( nYear );
if ( nMonth < 10 )
sbDate.append ( "0" );
sbDate.append ( nMonth );
if ( nDay < 10 )
sbDate.append ( "0" );
sbDate.append ( nDay );
return sbDate.toString ( );
}
/**
* 전문전송시간 (HDB_SND_TIME): HHMMSS 형태의 값을 전달하여야 한다.
*/
public static String getHHMMSS()
{
SimpleDateFormat formatter = new SimpleDateFormat("hhmmss");
String curDate = formatter.format(Calendar.getInstance().getTime());
return curDate;
}
/**
* 수신기관 전문 번호 (HDB_RSV_DOCSEQ) 8자리, 송신측에서는 null이나 0으로 채워서 보낼 수 있다.
*/
public static final String RPS_HDB_RSV_DOCSEQ = "00000000";
/**
* 전체 파일 수 (HDB_TOT_FILE), 사용안함, 여기서는 00으로 세팅
*/
public static final String RPS_HDB_TOT_FILE = "00";
/**
* 현재 파일 순번(HDB_CUR_FILE), 사용안함, 여기서는 00으로 세팅
*/
public static final String RPS_HDB_CUR_FILE = "00";
/**
* 현재 파일명 (HDB_DOC_NAME), 30자리, --> 실행시간에 만들어짐.
*/
/**
* 현재파일전체전문수 (HDB_CUR_TOT), 사용안함, 여기서는 00으로 세팅
*/
public static final String RPS_HDB_CUR_TOT = "00";
/**
* 현재파일현재순번 (HDB_CUR_NOW), 사용안함, 여기서는 00으로 세팅
*/
public static final String RPS_HDB_CUR_NOW = "00";
/**
* 전문CASE명 (HDB_DOC_CASE), 사용안함, 여기서는 000000으로 세팅
*/
public static final String RPS_HDB_DOC_CASE = "000000";
/**
* 송신자 추가정의 (HDB_SND_EXT), FILLER, 여기서는 공백으로 채움
*/
public static final String RPS_HDB_SND_EXT = " ";
/**
* 수신자 추가정의 (HDB_RSV_EXT), FILLER, 여기서는 공백으로 채움
*/
public static final String RPS_HDB_RSV_EXT = " ";
public static final String CMS_BIZ_GBN = "";
public static final String CMS_TRA_FLAG_BANK = "";
/**
* CMS에서 사용되는 응답코드
**/
public static final String RES_CODE_SUCESS = "000"; //정상
public static final String RES_CODE_SYSTEM_ERROR = "090"; //시스템장애
public static final String RES_CODE_SENDER_NAME_ERROR = "310"; //송신자명오류
public static final String RES_CODE_SENDER_PWD_ERROR = "320"; //송신자암호오류
public static final String RES_CODE_ALREADY_RECEIVED = "630"; //기전송 완료
public static final String RES_CODE_NOT_REGISTERED = "631"; //해당은행 미등록 업무
public static final String RES_CODE_FILENAME_ERROR = "632"; //비정상 화일명
public static final String RES_CODE_BYTE_ERROR = "633"; //비정상전문 BYTE수
public static final String RES_CODE_FILE_ORDER_ERROR = "634"; //파일 전송 순서 오류
public static final String RES_CODE_FORMAT_ERROR = "800"; //FORMAT 오류
public static String getCmsRetDescription(String code) {
return code==null ? "null" :
code.equals(RES_CODE_SUCESS )? "정상" :
code.equals(RES_CODE_SYSTEM_ERROR )? "시스템장애" :
code.equals(RES_CODE_SENDER_NAME_ERROR )? "송신자명오류" :
code.equals(RES_CODE_SENDER_PWD_ERROR )? "송신자암호오류" :
code.equals(RES_CODE_ALREADY_RECEIVED )? "기전송 완료" :
code.equals(RES_CODE_NOT_REGISTERED )? "해당은행 미등록 업무" :
code.equals(RES_CODE_FILENAME_ERROR )? "비정상 화일명" :
code.equals(RES_CODE_BYTE_ERROR )? "비정상전문 BYTE수" :
code.equals(RES_CODE_FILE_ORDER_ERROR )? "파일 전송 순서 오류" :
code.equals(RES_CODE_FORMAT_ERROR )? "FORMAT 오류" :code;
}
/**
*
* CMS에서 사용되는 전문 전송 일시 : MMDDhhmmss 형태의 값을 전달하여야 한다.
*/
public static String getMMddHHmmss()
{
SimpleDateFormat formatter = new SimpleDateFormat("MMddHHmmss");
String curDate = formatter.format(Calendar.getInstance().getTime());
return curDate;
}
/**
*
* 신한은망에서 사용되는 전문 전송 일시 : YYYYMMDDhhmmss 형태의 값을 전달하여야 한다.
*/
public static String getYYYYMMddHHmmss()
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String curDate = formatter.format(Calendar.getInstance().getTime());
return curDate;
}
/**
* 1. 기능 : 현재 요일을 숫자로 리턴하는 Method
* 2. 처리 개요 :
* - 현재 요일을 숫자로 리턴하는 Method
* 3. 주의사항
*
* @return 현재 요일 숫자
* @exception
**/
public static int getDayOfWeekNum() {
Calendar c = Calendar.getInstance();
return c.get ( Calendar.DAY_OF_WEEK );
}
/**
* 트랜잭션 코드
*/
public static final String TRANSACTION_CODE = "transaction_code";
/**
* 업무구분코드
*/
public static final String BIZ_GBN = "biz.gbn";
/**
* 자료구분코드
*/
public static final String DAT_GBN = "data.gbn";
/**
* 은행/센타 코드
*/
public static final String BANK_CODE = "bank.code"; //은행코드
public static final String CENTER_CODE = "center.code"; //센타코드
/**
* 송수신 플래그
* "C" - 센터에서 전문을 발생할 시, "B" - 은행 및 기관 에서 전문을 발생할 시
*/
public static final String TRA_FLAG_CENTER = "tra.flag.center";
public static final String TRA_FLAG_BANK = "tra.flag.bank";
public static final String TRA_FLAG_SEND = "tra.flag.send";
public static final String TRA_FLAG_RECV = "tra.flag.recv";
/**
* 퇴직연금 송신 기관 관련
* 송신기관 구분 (HDB_SND_CLS) : 1:운영, 2:기록, 3:자산, 4:상품, 5:자산운영
* 송신기관 코드 (HDB_SND_ID)
*/
public static final String HDB_SND_CLS = "send.class";
public static final String HDB_SND_ID = "send.id";
public static final String HDB_RCV_CLS = "rcv.cls";
/**
* CMS 방식의 다양한 TR code, 기관코드, ll 필드등을 위해 다음을 추가함.
*/
public static final String ORGN_CD_LEN = "bank.code.len";
public static final String TRCD_LEN = "tr.code.len";
public static final String FILE_NAME_LEN = "file.name.len";
public static final String CMS_CIPHER_USE = "cipher.yn";
public static final String TRAN_GBN_SEND = "send.tran.gbn";
public static final String TRAN_GBN_RECV = "recv.tran.gbn";
public static final String SLEEP_TIME = "sleep.time";
public static final String SLEEP_TIME_0620 = "sleep.time.0620";
public static final String SLEEP_TIME_POST = "sleep.time.post";
public static final String LENGTH_OFFSET = "length.offset";
public static final String IGNORE_DATA_LEN = "ignore.data.len";
public static final String FILLER_LEN_0600 = "fill.len.0600";
public static final String APPEND_LL_LEN = "append.ll.len";
public static final String SKIP_LF = "skip.lf";
public static final String SKIP_SUMMARY = "skip.sum";
public static final String DEBUG = "debug.yn";
// 여신금융협회
public static final String BLOCKING_COUNT = "blocking.count"; // 파일별로 블러킹 개수가 정해져 있음
public static final String PADDING_LEN = "padding.len"; // 파일별로 블러킹 하고 나서 추가 패딩하는 길이
public static final String RECV_REC_LEN = "recv.rec.len"; // 해당 파일의 수신시 레코드 크기
/**
* 프로퍼티 그룹을 가져오기 위한 PREFIX
* 프로퍼티 그룹은 REFIX+배치 업무 코드
*/
public static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo";
/**
* 조건문장
*/
public final static String BLOCKEND = "BLOCKEND";
public final static String COMPARE = "COMPARE";
public final static String LOSS = "LOSS";
public final static String EOF = "EOF";
public final static String LOSSEND = "LOSSEND";
public final static String TIMEOUT = "TIMEOUT";
public final static String ERROR = "ERROR";
public final static String SEND = "SEND";
public final static String RECV = "RECV";
public final static String NOFILE = "NOFILE";
public final static String NOBODY = "NOBODY";
public final static String DUP = "DUP";
public final static String IGNORE = "IGNORE";
/**
* 어음이미지 시스템에서 사용되는 응답코드
**/
public static final String BI_RES_CODE_SUCESS = "000"; //정상
public static final String BI_RES_CODE_SYSTEM_ERROR = "090"; //시스템장애
public static final String BI_RES_CODE_BEFORE_FILE = "110"; //작업시작파일 처리전 수신요청
public static final String BI_RES_CODE_AFTER_FILE = "120"; //작업시작파일 처리후 수신요청
public static final String BI_RES_CODE_SENDER_NAME_ERROR = "210"; //송신자명오류
public static final String BI_RES_CODE_SENDER_PWD_ERROR = "220"; //송신자암호오류
public static final String BI_RES_CODE_ALREADY_RECEIVED = "410"; //기전송 완료
public static final String BI_RES_CODE_NOT_REGISTERED = "420"; //해당은행 미등록 업무
public static final String BI_RES_CODE_FILENAME_ERROR = "430"; //비정상 화일명
public static final String BI_RES_CODE_BYTE_ERROR = "440"; //비정상전문 BYTE수
public static final String BI_RES_CODE_FILE_SIZE_ERROR = "710"; //파일 사이즈 오류
public static final String BI_RES_CODE_FORMAT_ERROR = "800"; //FORMAT 오류
public static final String BI_RES_CODE_ETC_ERROR = "900"; //기타 오류
public static final String BI_TR_CLASS_RECV = "R";
public static final String BI_TR_CLASS_SEND = "S";
public static String[] BIIMG_RES_CODES ={"000", "101", "102", "401", "402", "403", "404", "610", "800", "900"};
public static boolean isDefinedBiImgResCode (String code){
int len = BIIMG_RES_CODES.length;
for (int i=0; i<len; i++){
if(BIIMG_RES_CODES[i].equals(code)){
return true;
}
}
return false;
}
public static String getBiImgRetDescription(String code) {
return code==null ? "null" :
code.equals(BI_RES_CODE_SUCESS )? "정상" :
code.equals(BI_RES_CODE_SYSTEM_ERROR )? "시스템장애" :
code.equals(BI_RES_CODE_BEFORE_FILE )? "작업시작파일 처리전 수신요청" :
code.equals(BI_RES_CODE_AFTER_FILE )? "작업시작파일 처리후 수신요청" :
code.equals(BI_RES_CODE_SENDER_NAME_ERROR )? "송신자명오류" :
code.equals(BI_RES_CODE_SENDER_PWD_ERROR )? "송신자암호오류" :
code.equals(BI_RES_CODE_ALREADY_RECEIVED )? "기전송 완료" :
code.equals(BI_RES_CODE_NOT_REGISTERED )? "해당은행 미등록 업무" :
code.equals(BI_RES_CODE_FILENAME_ERROR )? "비정상 화일명" :
code.equals(BI_RES_CODE_BYTE_ERROR )? "비정상전문 BYTE수" :
code.equals(BI_RES_CODE_FILE_SIZE_ERROR )? "파일 사이즈 오류" :
code.equals(BI_RES_CODE_FORMAT_ERROR )? "FORMAT 오류" :
code.equals(BI_RES_CODE_ETC_ERROR )? "기타 오류": code;
}
/*******************************************************************************
* KED 사용 코드
*******************************************************************************/
public static final String KED_SEND_TRCODE = "CB02";
public static final String KED_RECV_TRCODE = "RB02";
public static final String KED_DATA_OFFSET = "data.offset";
public static final String KED_RES_CODE_SUCESS = "000"; //정상
public static final String KED_RES_CODE_NOFILE = "101"; //해당일자 전송 자료 없음
public static final String KED_RES_CODE_ALREADY_RECEIVED = "102"; //기 전송 완료
public static final String KED_RES_CODE_NOT_REGISTERED = "401"; //해당회원사 미등록 업무
public static final String KED_RES_CODE_TELTYPE_ERROR = "402"; //전문 종별코드 Error
public static final String KED_RES_CODE_FILENAME_ERROR = "403"; //비정상 화일명
public static final String KED_RES_CODE_BYTE_ERROR = "404"; //비정상전문 BYTE수
public static final String KED_RES_CODE_NOEND_FILE_RECV = "610"; //화일 수신 미완료
public static final String KED_RES_CODE_SYSTEM_ERROR = "800"; //시스템장애
public static final String KED_RES_CODE_ETC_ERROR = "900"; //기타 오류
/**
* 정의된 전문종별인지 확인한다.
*/
public static String[] KED_TELTYPE = {"0600", "0610", "0700", "0710", "0320", "0620", "0300", "0310", "0720", "0730", "0800", "0810" };
public static boolean isKedTelType (String code){
int len = KED_TELTYPE.length;
for (int i=0; i<len; i++){
if(KED_TELTYPE[i].equals(code)){
return true;
}
}
return false;
}
/**
* 정의된 응답코드인지 확인한다.
**/
public static String[] KED_RES_CODES ={"000", "101", "102", "401", "402", "403", "404", "610", "800", "900"};
public static boolean isDefinedKedResCode (String code){
int len = KED_RES_CODES.length;
for (int i=0; i<len; i++){
if(KED_RES_CODES[i].equals(code)){
return true;
}
}
return false;
}
/*******************************************************************************
* 한은 외환망 사용 코드
*******************************************************************************/
// public static final String BOKEX_DATA_FLAG_BIN = "B"; //바이너리 모드
// public static final String BOKEX_RESUME_YN = "N"; //이어받기 사용안함
public static final String DATA_FLAG = "data.flag"; //바이너리 모드
public static final String RESUME_YN = "resume.yn"; //이어받기 사용안함
/*******************************************************************************
* DACOM MAGIC LINK 프로토콜
*******************************************************************************/
public static final int MAGICLINK_TELEGRAM_LENGTH = 150; //전문길이
public static final String MAGICLINK_NEXT = "NXT"; //다음 파일 있음
public static final String MAGICLINK_END = "END"; //다음 파일 없음
public static final String MAGICLINK_NEW = "NEW"; //새로운 파일 전송
public static final String MAGIC_RES_CODE_SUCESS = "000"; // 정상
public static final String MAGIC_RES_CODE_SYSTEM_ERROR = "001"; // 시스템 장애
public static final String MAGIC_RES_CODE_USERID_ERROR = "002"; // USER ID 오류
public static final String MAGIC_RES_CODE_PASSWD_ERROR = "003"; // PASSWORD 오류
public static final String MAGIC_RES_CODE_JOBTYPE_ERROR = "004"; // JOB TYPE 오류
public static final String MAGIC_RES_CODE_NO_DATA = "005"; // 조건에 맞는 자료 없음
public static final String MAGIC_RES_CODE_TELEGRAM_TYPE_ERROR = "006"; // 전문 종류 오류
public static final String MAGIC_RES_CODE_SEND_BYTE_ERROR = "007"; // 전송 Bytes오류
public static final String MAGIC_RES_CODE_PROTOCOL_ERROR = "008"; // 전문 형식 오류
public static final String MAGIC_RES_CODE_PASSWD_CHG_ERROR = "009"; // PASSWORD Change오류
public static final String MAGIC_RES_CODE_ETC_ERROR = "099"; // 기타 오류
/*******************************************************************************
* DACOM 매직링크 사용 코드
*******************************************************************************/
public static final String MLINK_PROCESS_SEND = "SD"; //자료송신
public static final String MLINK_PROCESS_RECV = "RD"; //자료수신
public static final String MLINK_FILENAME = "file.name"; //수신 요청 파일 명
public static final String MLINK_RECV_FLAG = "E"; //수신 플래그
public static final String MLINK_DOC_RECV_ID = "recv.id"; //수신자ID
public static final int MLINK_HEADER_LEN = 63; //파일 헤더 길이
/*******************************************************************************
* 구 DACOM (KSNET) 사용 코드
*******************************************************************************/
public static final int KSNET_HEADER_LEN = 38; //파일 헤더 길이
/*******************************************************************************
* 삼성네트웍스 X.25 송수신 사용코드
*******************************************************************************/
public static final String SSNET_GROUP_ID = "group.id"; //그룹 ID
public static final String SSNET_USER_ID = "user.id"; //USER ID
public static final String SSNET_DEST_TYPE = "D"; //수신자 TYPE
public static final String SSNET_CODE_CONV_DEFAULT = "A"; //코드변환여부
public static final String SSNET_CODE_CONV_OPT = "code.conv"; //코드변환여부
public static final String SSNET_MISS_CHK_REQ = "Y"; //결번 CHK요구표시
public static final String SSNET_SEND_MSG_ID = "send.msg.id"; //SUBJECT(Msg ID)
public static final String SSNET_RECV_MSG_ID = "recv.msg.id"; //SUBJECT(Msg ID)
public static final String SSNET_SEND = "S"; //송수신 업무구분 (송신)
public static final String SSNET_MISS_REQ = "C"; //결번전문확인 요구 전문
public static final String SSNET_MISS_RES = "E"; //결번 확인 완료(결번이 없을때)
public static final String SSNET_MISS_RES_CODE = "001"; //*001 : 최종번호 틀림
/*******************************************************************************
* 한국은행 국고 프로토콜
*******************************************************************************/
public static final String BOKGG_RES_CODE_SUCESS = "000"; // 정상
public static final String BOKGG_RES_CODE_ERROR = "009"; // 오류
public static String getBokGGRetDescription(String code) {
return code==null ? "null" :
code.equals(BOKGG_RES_CODE_SUCESS )? "정상" :
code.equals(BOKGG_RES_CODE_ERROR )? "오류" : code;
}
/*******************************************************************************
* 신용회복위원회 프로토콜
*******************************************************************************/
public static final String CCRSF_RES_CODE_SUCESS = "000"; // 정상
public static String getCCRSFRetDescription(String code) {
return code==null ? "null" :
code.equals(CCRSF_RES_CODE_SUCESS )? "정상" :
code.equals( "910" )? "시스템 명칭 오류" :
code.equals( "911" )? "헤더 길이 오류" :
code.equals( "912" )? "전문길이 오류" :
code.equals( "920" )? "전문코드 오류" :
code.equals( "930" )? "업무구분코드 오류" :
code.equals( "940" )? "전문 생성기관 오류" :
code.equals( "950" )? "응답코드 오류" :
code.equals( "960" )? "송수신 구분 오류" :
code.equals( "970" )? "해당 파일 없음" :
code.equals( "990" )? "기타 오류" :
code.equals( "210" )? "전문 흐름순서 오류" :
code.equals( "220" )? "이미 수신한 자료의 중복수신" :
code.equals( "230" )? "헤더 레코드 전문의 날짜 오류" :
code.equals( "240" )? "헤더 및 트레일러에 기록된 데이터 수와 실제 수신한 데이터 수의 불일치" :
code.equals( "330" )? "업무관리정보 오류" :
code.equals( "340" )? "헤더, 데이터, 트레일러 구분 오류" :
code.equals( "350" )? "조회 데이터 없음" :
code.equals( "360" )? "조회조건 오류" : code;
}
// public static int getLlStart(BatchDoc batchDoc) {
// try {
// int llStart = 1;
// String propName = PROP_GROUP_NAME_PREFIX + "{" +
// batchDoc.getBatchMsg().getHeader().getProcessCode() + "_" +
// batchDoc.getBatchMsg().getHeader().getInstitutionCode() + "}";
// PropManager pmanager = PropManager.getInstance();
// llStart = Integer.parseInt(pmanager.getProperties(propName).getProperty("ll.start"));
// return llStart;
// } catch (Exception e) {
// return 1;
// }
// }
}
@@ -0,0 +1,308 @@
package com.eactive.eai.batch.job.jobHandle;
import java.util.ArrayList;
import java.util.HashMap;
import com.eactive.eai.batch.job.jobModule.Component.JobComponentService;
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.message.EAIBatchMsgManager;
import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager;
import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO;
import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoManager;
import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.routing.Process;
import com.eactive.eai.common.util.Logger;
public class FlowController extends Process
{
public BatchDoc batchDoc;
// FileLoger
protected Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
public String logHeader;
private String strUUID;
public final static String PHASECODE_START = "START";
public final static String PHASECODE_NORMAL_END = "END";
public final static String PHASECODE_ERROR_END = "EEND";
public BatchDoc clientRequestwithReturn( BatchDoc batchDoc)
{
this.batchDoc = batchDoc;
logger = batchDoc.getLogger();
try {
init();
while (checkNextStage()) {
excutePhaseStage();
}
end();
} catch (Exception e) {
handleException(e);
}
return batchDoc;
}
public void clientRequest() {
// do noting
}
public void init() throws Exception
{
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
logHeader = "["+ batchDoc.getBatchMsg().getHeader().getUUID() +" / "+
batchDoc.getBatchMsg().getHeader().getProcessCode() +" / "+
batchDoc.getBatchMsg().getHeader().getInstitutionName() +" / "+
batchDoc.getBatchMsg().getHeader().getProcessType() +" / "+
batchDoc.getBatchMsg().getHeader().getFileName() +" / "+
batchDoc.getBatchMsg().getHeader().getRuleCode() +"] ";
strUUID = batchDoc.getBatchMsg().getHeader().getUUID();
logger.info("{} ================================================================================================="+ logHeader);
logger.info("{} ▷▷▷▷▷ FlowController 시작 : "+ batchDoc.getBatchMsg().getHeader().getRuleCode() +" ("+ batchDoc.getBatchMsg().getHeader().getRuleDesc() +")"+ logHeader);
logger.info("{} ================================================================================================="+ logHeader);
//logger.info("{} ▷ Batch Socket Count : " + BatchRunningJobManager.getInstance().getRunningJobCount(), logHeader);
//logger.info("{} ▷ Job Process Data Count : " + JobProcessData.getInstance().getBatchStageDataCount(), logHeader);
//logger.info("{} =================================================================================================", logHeader);
//BatchRunningJobManager 에서 진행중인 BatchMessageDocument 를 update
BatchRunningJobManager.getInstance().updateRunningDocument(strUUID, batchDoc);
//LayerCode, SubLayerCode 설정
EAIBatchMsgManager.updateBatchMsg(batchDoc, CommonKeys.LAYER_FLOW_CONTROLLER, CommonKeys.SUB_LAYER_FLOW_CONTROLLER);
// Flow Rule 의 시작단계를 지정한다. (반드시 'START' 이어야함)
batchDoc.getBatchMsg().getBody().setNextPhaseCode(PHASECODE_START);
}
/**
* WhleDo 문의 조건처리 함수
*/
public boolean checkNextStage()
{
//단계 시작시간 설정
batchDoc.getBatchMsg().getBody().setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash());
String nextPhaseCode = batchDoc.getBatchMsg().getBody().getNextPhaseCode();
logger.info("{} ▶ 다음 수행 단계: ["+ nextPhaseCode +"]"+ logHeader);
if (nextPhaseCode.equalsIgnoreCase(PHASECODE_NORMAL_END)) {
new JobFinishHandler(batchDoc).handleSuccessEnd();
logger.info("{} ▷ 정상종료 단계("+ PHASECODE_NORMAL_END +"') 가 수행되었습니다. FlowController 를 종료합니다."+ logHeader);
return false;
} else if (nextPhaseCode.equalsIgnoreCase(PHASECODE_ERROR_END)) {
new JobFinishHandler(batchDoc).handleErrorEnd("");
logger.info("{} ▷ 에러종료 단계("+ PHASECODE_ERROR_END +") 가 수행되었습니다. FlowController 를 종료합니다."+ logHeader);
return false;
} else {
return true;
}
}
public void excutePhaseStage() throws Exception
{
String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode();
String execPhaseCode = batchDoc.getBatchMsg().getBody().getNextPhaseCode();
try {
// 이전 단계 정보를 유지하기위해 현 단계 정보를 저장한다. (현재는 이전 단계 정보를 사용하는 곳 없음)
batchDoc.getBatchMsg().getBody().setLastPhaseCode (batchDoc.getBatchMsg().getBody().getFlowPhaseCode());
batchDoc.getBatchMsg().getBody().setLastPhaseType (batchDoc.getBatchMsg().getBody().getPhaseType());
batchDoc.getBatchMsg().getBody().setLastPhaseStartTime(batchDoc.getBatchMsg().getBody().getPhaseStartTime());
batchDoc.getBatchMsg().getBody().setLastPhaseEndTime (batchDoc.getBatchMsg().getBody().getPhaseEndTime());
// 다음 단계 코드를 이용하여 필요한 정보를 조회하고 저장해 준다.
logger.debug("{} ■ 단계 Logging 시작... [RuleCode: " + strRuleCode + "] [NextPhaseCode: "+ execPhaseCode +"]"+ logHeader);
logger.debug("{} >> Node Manager (TSEAIBR03) 에서 해당 Node 정보 조회...\r\n"+logHeader);
NodeInfoVO nvo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, execPhaseCode);
if (nvo == null) {
//실행대상 단계코드를 TSEAIBR03 테이블에서 찾을 수 없음 (RuleCode:{1}, PhaseCode:{2})
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJH002", new String[] {strRuleCode, execPhaseCode});
throw new Exception(errMsg);
//setNextPhaseAsError(strRuleCode, errMsg); //다음 단계를 'EEND' 노드로 설정
}
String execPhaseClassName = nvo.getFlowComp();
logger.debug("{} => [RuleCode: "+ nvo.getRuleCode() +"] "+
"[PhaseCode: "+ nvo.getPhaseCode() +"] "+
"[PhaseType: "+ nvo.getPhaseType() +"] "+
"[ClassName: "+ nvo.getFlowComp() +"] "+
"[TelegramID: "+ nvo.getTelegramID() +"]"+ logHeader);
//Flow Component 클래스명 값이 있는지 체크
if (execPhaseClassName==null || execPhaseClassName.equals("")) {
// 실행대상 단계코드의 해당 FlowComponent 클래스이름이 지정되어 있지 않음 (RuleCode:{1}, PhaseCode:{2})
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJH003", new String[] {strRuleCode, execPhaseCode});
throw new Exception(errMsg);
//setNextPhaseAsError(strRuleCode, errMsg); //다음 단계를 'EEND' 노드로 설정
} else {
// body 쪽 NEXT 설정
batchDoc.getBatchMsg().getBody().setFlowPhaseCode(execPhaseCode);
batchDoc.getBatchMsg().getBody().setPhaseType(nvo.getPhaseType()); //단계 타입 (SEND, RECV, END, EEND 중 하나)
// PhaseInfo 설정 by Node Info
batchDoc.getBatchMsg().getPhaseinfo().setRuleCode (strRuleCode);
batchDoc.getBatchMsg().getPhaseinfo().setPhaseCode (execPhaseCode);
batchDoc.getBatchMsg().getPhaseinfo().setPhaseType (nvo.getPhaseType());
batchDoc.getBatchMsg().getPhaseinfo().setFlowClassName (nvo.getFlowComp());
batchDoc.getBatchMsg().getPhaseinfo().setLengthFieldIndex (nvo.getLengthField());
batchDoc.getBatchMsg().getPhaseinfo().setLengthTelegramID (nvo.getTelegramID());
batchDoc.getBatchMsg().getPhaseinfo().setLengthClassName ("");
batchDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode ("");
batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq ("");
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 ("");
}
// 1. JobProcessData와 관련된 작업 수행
// 1-1 JobProcessData에서 이전단계에서 사용했던 '다음단계'결정용 Stage변환룰 정보를 삭제해준다.
HashMap<String, Object> curr_job_data = JobProcessData.getInstance().getBatchStageData(strUUID);
//Flow 최초 단계 수행시 해당 UUID의 HashMap 생성함
if (curr_job_data == null) curr_job_data = new HashMap<String, Object>();
curr_job_data.remove(JobProcessData.PROCDATA_NEXTSTAGE);
// 1-2 TSEAIBR02 테이블에서 현재 Node의 가능 Stage를 모두 구해서 JobProcessData에 할당
// Next Possible Stage 가 없으면, 현재 지정된 단계가 최종이라는 뜻.
logger.debug("{} >> Phase Manager (TSEAIBR02) 에서 해당 Node의 수행 가능 Phase 목록 조회... [RuleCode: " + strRuleCode + "] [PhaseCode: "+ execPhaseCode +"]"+ logHeader);
ArrayList<PhaseInfoVO> al = PhaseInfoManager.getInstance().getPhaseInfo(strRuleCode, execPhaseCode);
if (al.size() > 0) {
//NEXT Stage 목록 debug logging...
for (int i=0; i< al.size(); i++) {
PhaseInfoVO pvo = (PhaseInfoVO) al.get(i);
logger.debug("{} => "+ (i+1) +". [PhaseCode: "+ pvo.getPhaseCode() +"] [PhaseSeq: "+ pvo.getPhaseSeq() +"] [TelegramID: "+ pvo.getTelegramID() +"] [NextPahseCode: "+ pvo.getNextPhaseCode() +"]"+ logHeader);
}
// END, EEND 단계인 경우 TSEAIBR02 테이블에 단계 정보가 없어도 해당 단계를 수행함
//} else if (execPhaseCode.trim().equalsIgnoreCase("END") || execPhaseCode.trim().equalsIgnoreCase("EEND")) {
// logger.debug("{} => 'END' 또는 'EEND' 단계임. 해당 종료 단계를 수행 후 배치 작업을 종료함.", logHeader);
// NEXT Stage가 없고, "END" 나 "EEND" 가 아닌 경우에는 에러 처리함
} else {
//실행대상 단계코드를 TSEAIBR02 (Phase) 테이블에서 찾을 수 없음 (RuleCode:{1}, PhaseCode:{2})
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJH004", new String[] {strRuleCode, execPhaseCode});
throw new Exception(errMsg);
//setNextPhaseAsError(strRuleCode, errMsg); //다음 단계를 'EEND' 노드로 설정
}
curr_job_data.put(JobProcessData.PROCDATA_NEXTSTAGE, al);
JobProcessData.getInstance().setBatchStageData(strUUID, curr_job_data);
// 2. 클래스 생성
logger.info("{} >> 수행할 단계 클래스 생성 및 execute() 호출...\r\n"+ logHeader);
JobComponentService phaseStage = (JobComponentService)Class.forName(execPhaseClassName).newInstance();
phaseStage.setEAIBatchMessage(batchDoc);
// 3. 해당 클래스를 호출한다.
logger.info("{} => ############################ ClassName: [" + execPhaseClassName + "] ############################"+ logHeader);
//========================================================================
batchDoc = phaseStage.execute();
//========================================================================
logHeader = "["+ batchDoc.getBatchMsg().getHeader().getUUID() +" / "+
batchDoc.getBatchMsg().getHeader().getProcessCode() +" / "+
batchDoc.getBatchMsg().getHeader().getInstitutionName() +" / "+
batchDoc.getBatchMsg().getHeader().getProcessType() +" / "+
batchDoc.getBatchMsg().getHeader().getFileName() +" / "+
batchDoc.getBatchMsg().getHeader().getRuleCode() +"] ";
//단계 종료시간 설정
batchDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
//현 단계 DB 로깅
LogUtil.setLog(batchDoc);
logger.debug("{} ■ 단계 Logging 종료 !! [RuleCode: " + strRuleCode + "] [PhaseCode: "+ execPhaseCode +"]"+ logHeader);
} catch (Exception ex) {
//FlowController 에서 해당 단계 수행시 Exception 발생. (RuleCode:{1}, PhaseCode:{2})
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJH001", new String[] {strRuleCode, execPhaseCode});
throw new Exception(errMsg);
//setNextPhaseAsError(strRuleCode, errMsg); //다음 단계를 'EEND' 노드로 설정
}
}
public void end() throws Exception
{
logger.info("{} ================================================================================================="+ logHeader);
logger.info("{} ▷▷▷▷▷ FlowController 종료 : "+ batchDoc.getBatchMsg().getHeader().getRuleCode() +" ("+ batchDoc.getBatchMsg().getHeader().getRuleDesc() +")"+ logHeader);
logger.info("{} ================================================================================================="+ logHeader);
//logger.info("{} ▷ Batch Socket Count : " + BatchRunningJobManager.getInstance().getRunningJobCount(), logHeader);
//logger.info("{} ▷ Job Process Data Count : " + JobProcessData.getInstance().getBatchStageDataCount(), logHeader);
//logger.info("{} =================================================================================================", logHeader);
}
public void handleException(Exception ex)
{
try {
//Exception ex = this.context.getExceptionInfo().getException();
// 파일로그 처리
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJH006");
logger.error("{"+logHeader+"}" + " {"+"logHeader"+"}" + errMsg, ex);
// DB로그 처리
new JobFinishHandler(batchDoc).handleErrorEnd(errMsg);
} catch (Exception e) {
logger.error("{"+logHeader+"} ★★★★★ FlowController JPD 예외 처리 중 에러 !! ★★★★★\r\n"+ e.getMessage());
}
}
/*
private void setNextPhaseAsError(String strRuleCode, String strErrMsg) throws Exception
{
NodeInfoVO err_nvo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, this.PHASECODE_ERROR_END);
// body 쪽 NEXT 설정
batchDoc.getEAIBatchMessage().getBody().setFlowPhaseCode(this.PHASECODE_ERROR_END);
batchDoc.getEAIBatchMessage().getBody().setPhaseType("");
// PhaseInfo 설정 by Node Info
batchDoc.getEAIBatchMessage().getPhaseinfo().setRuleCode (strRuleCode);
batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseCode (this.PHASECODE_ERROR_END);
batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseType (err_nvo.getPhaseType());
batchDoc.getEAIBatchMessage().getPhaseinfo().setFlowClassName (err_nvo.getFlowComp());
batchDoc.getEAIBatchMessage().getPhaseinfo().setLengthFieldIndex (err_nvo.getLengthField());
batchDoc.getEAIBatchMessage().getPhaseinfo().setLengthTelegramID (err_nvo.getTelegramID());
batchDoc.getEAIBatchMessage().getPhaseinfo().setLengthClassName ("");
batchDoc.getEAIBatchMessage().getPhaseinfo().setLengthMsgCode ("");
batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseSeq ("");
batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseTelegramID ("");
batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseClassName ("");
batchDoc.getEAIBatchMessage().getPhaseinfo().setPhaseMsgCode ("");
batchDoc.getEAIBatchMessage().getPhaseinfo().setTelegramTypeValue ("");
batchDoc.getEAIBatchMessage().getPhaseinfo().setBizCodeValue ("");
batchDoc.getEAIBatchMessage().getPhaseinfo().setControlCodeValue ("");
batchDoc.getEAIBatchMessage().getPhaseinfo().setResponseCodeValue ("");
Logging(ERROR, strErrMsg);
batchDoc.getEAIBatchMessage().getBody().setErrorMsg(strErrMsg);
}
*/
public void procFileEvent(String recvdirPath, String recvfileName, String lines)
throws Exception {
}
}
@@ -0,0 +1,185 @@
package com.eactive.eai.batch.job.jobHandle;
//import com.eactive.eai.batch.running.BatchRunningJobManager;
//import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobModule.Component.JobComponentService;
import com.eactive.eai.batch.common.CalendarUtil;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager;
import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO;
import com.eactive.eai.batch.scheduler.SchedulerMessageManager;
import com.eactive.eai.common.util.Logger;
public class JobFinishHandler
{
protected Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private String logHeader = "";
private BatchDoc batchMsgDoc;
private String gUUID = "";
private String subUUID = "";
private String gRuleCode = "";
public JobFinishHandler(BatchDoc batchMsgDoc) {
this.batchMsgDoc = batchMsgDoc;
this.gUUID = batchMsgDoc.getBatchMsg().getHeader().getUUID();
this.subUUID = batchMsgDoc.getBatchMsg().getBody().getSubUUID();
this.gRuleCode = batchMsgDoc.getBatchMsg().getHeader().getRuleCode();
logger = batchMsgDoc.getLogger();
logHeader = "["+ batchMsgDoc.getBatchMsg().getHeader().getUUID() +" / "+
batchMsgDoc.getBatchMsg().getHeader().getProcessCode() +" / "+
batchMsgDoc.getBatchMsg().getHeader().getInstitutionName() +" / "+
batchMsgDoc.getBatchMsg().getHeader().getProcessType() +" / "+
batchMsgDoc.getBatchMsg().getHeader().getFileName() +" / "+
batchMsgDoc.getBatchMsg().getHeader().getRuleCode() +"] ";
}
//FlowController 관련 JPD 에서 오류 발생시 오류를 처리한다.
public void handleErrorEnd(String errMsg) {
try {
//1. 에러메시지 설정
if (errMsg != null && !errMsg.equals("")) {
if (!batchMsgDoc.getBatchMsg().getBody().getErrorMsg().equals("")) {
errMsg += "\n caused by..." + batchMsgDoc.getBatchMsg().getBody().getErrorMsg();
}
batchMsgDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
}
//2. 에러종료 단계 수행
executeFlowErrorEndPhase();
//3. 작업 진행정보 제거
deleteProcessingInfo();
//4. 에러종료 DB Log
batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setErrorLog(batchMsgDoc, batchMsgDoc.getBatchMsg().getBody().getErrorMsg());
} catch (Exception e) {
logger.error("[handleErrorEnd]처리 중 오류 발생 -" + e.getMessage(),e );
}
}
public void handleSuccessEnd() {
try {
//1. 정상종료 단계 수행
executeFlowSuccessEndPhase();
//2. 작업 진행정보 제거
deleteProcessingInfo();
//3. 정상종료 DB Log
batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash());
LogUtil.setLog(batchMsgDoc);
LogUtil.setEndLog(batchMsgDoc);
} catch (Exception e) {
logger.error("[handleSuccessEnd]처리 중 오류 발생 -" + e.getStackTrace() );
}
}
/**
* Exception을 throw 하지 않는다.
*/
private void executeFlowErrorEndPhase() {
logger.info("{"+logHeader+"}"+" ▷ 에러종료 단계("+ FlowController.PHASECODE_ERROR_END +") 수행......");
NodeInfoVO nodeInfo = null;
try {
nodeInfo = NodeInfoManager.getInstance().getNodeInfo(gRuleCode, FlowController.PHASECODE_ERROR_END);
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
}
//해당 RuleCode에 에러종료 단계가 없으면 디폴트 에러종료 단계 설정
try {
if (nodeInfo == null) {
logger.info("{"+logHeader+"}"+ " => 해당 Rule 정보에 에러종료 단계 없음. 디폴트 에러종료 단계를 설정함.");
nodeInfo = new NodeInfoVO();
nodeInfo.setRuleCode(gRuleCode);
nodeInfo.setPhaseCode(FlowController.PHASECODE_ERROR_END);
nodeInfo.setPhaseType(FlowController.PHASECODE_ERROR_END);
nodeInfo.setDesc("디폴트 에러종료 단계");
nodeInfo.setLengthField(0);
nodeInfo.setTelegramID("");
nodeInfo.setFlowComp("com.eactive.eai.batch.job.jobModule.Component.EEND");
}
setPhaseInfoToBatchMsgDoc(nodeInfo);
executeFlowPhase(nodeInfo.getFlowComp());
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
}
}
/**
* Exception을 throw 하지 않는다.
*/
private void executeFlowSuccessEndPhase() {
logger.info("{"+"logHeader"+"}"+" ▷ 정상종료 단계("+ FlowController.PHASECODE_NORMAL_END +") 수행......");
NodeInfoVO nodeInfo = null;
try {
nodeInfo = NodeInfoManager.getInstance().getNodeInfo(gRuleCode, FlowController.PHASECODE_NORMAL_END);
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
}
//해당 RuleCode에 에러종료 단계가 없으면 디폴트 에러종료 단계 설정
try {
if (nodeInfo == null) {
logger.info("{"+"logHeader"+"}"+" 해당 Rule 정보에 정상종료 단계 없음. 디폴트 정상종료 단계를 설정함.");
nodeInfo = new NodeInfoVO();
nodeInfo.setRuleCode(gRuleCode);
nodeInfo.setPhaseCode(FlowController.PHASECODE_NORMAL_END);
nodeInfo.setPhaseType(FlowController.PHASECODE_NORMAL_END);
nodeInfo.setDesc("디폴트 정상종료 단계");
nodeInfo.setLengthField(0);
nodeInfo.setTelegramID("");
nodeInfo.setFlowComp("com.eactive.eai.batch.job.jobModule.Component.END");
}
setPhaseInfoToBatchMsgDoc(nodeInfo);
executeFlowPhase(nodeInfo.getFlowComp());
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
}
}
private void setPhaseInfoToBatchMsgDoc(NodeInfoVO nodeInfo) {
//body 쪽 단계정보 설정
batchMsgDoc.getBatchMsg().getBody().setFlowPhaseCode(nodeInfo.getPhaseCode());
batchMsgDoc.getBatchMsg().getBody().setPhaseType(nodeInfo.getPhaseType());
//Phase 쪽 단계정보 설정
batchMsgDoc.getBatchMsg().getPhaseinfo().setRuleCode (nodeInfo.getRuleCode());
batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseCode (nodeInfo.getPhaseCode());
batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseType (nodeInfo.getPhaseType());
batchMsgDoc.getBatchMsg().getPhaseinfo().setFlowClassName (nodeInfo.getFlowComp());
batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthFieldIndex (nodeInfo.getLengthField());
batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthTelegramID (nodeInfo.getTelegramID());
batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthClassName ("");
batchMsgDoc.getBatchMsg().getPhaseinfo().setLengthMsgCode ("");
batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseSeq ("");
batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID ("");
batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseClassName ("");
batchMsgDoc.getBatchMsg().getPhaseinfo().setPhaseMsgCode ("");
batchMsgDoc.getBatchMsg().getPhaseinfo().setTelegramTypeValue ("");
batchMsgDoc.getBatchMsg().getPhaseinfo().setBizCodeValue ("");
batchMsgDoc.getBatchMsg().getPhaseinfo().setControlCodeValue ("");
batchMsgDoc.getBatchMsg().getPhaseinfo().setResponseCodeValue ("");
}
private void executeFlowPhase(String className) throws Exception {
JobComponentService phaseExecuteObj = (JobComponentService) Class.forName(className).newInstance();
phaseExecuteObj.setEAIBatchMessage(batchMsgDoc);
//해당 클래스를 수행
logger.info("{"+"logHeader"+"} => ############################ ClassName: [" + className + "] ############################");
batchMsgDoc = phaseExecuteObj.execute();
}
private void deleteProcessingInfo() throws Exception {
logger.info("{"+logHeader+"} ▷ JobProcessData 에서 해당 UUID 정보 삭제... [UUID: "+ gUUID +"]" );
JobProcessData.getInstance().delBatchStageData(gUUID);
logger.info("{"+logHeader+"} ▷ Schedule Processing 테이블 (TSEAIBS04) 에서 해당 UUID 정보 삭제... [UUID: "+ gUUID +"]");
SchedulerMessageManager.getInstance().deleteJobFromProcessing(gUUID, subUUID);
}
}
@@ -0,0 +1,65 @@
package com.eactive.eai.batch.job.jobHandle;
//import com.eactive.eai.batch.doc.BatchDoc;
import java.util.ArrayList;
import java.util.HashMap;
import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO;
import com.eactive.eai.common.util.Logger;
public class JobProcessData
{
//파일로거
private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
private static JobProcessData instance = new JobProcessData();
public static final String PROCDATA_PRE_TELEGRAM = "PRE_TELEGRAM";
public static final String PROCDATA_NEXTSTAGE = "NEXT_STAGE";
public static final String PROCDATA_BLOCKDATA = "PROCDATA_BLOCKDATA";
public static final String PROCDATA_MISSDATA = "PROCDATA_MISSDATA";
public static final String PROCDATA_FIRST_MISS = "PROCDATA_FIRST_MISS";
public static final String PROCDATA_LAST_MISS = "PROCDATA_LAST_MISS";
private HashMap<String, Object> hm_batchData;
private JobProcessData() {
hm_batchData = new HashMap<String, Object>();
}
public static JobProcessData getInstance() {
return instance;
}
public synchronized void addBatchStageData(String strUUID, HashMap<String, ArrayList<PhaseInfoVO>> hmData)
{
Object obj = hm_batchData.get(strUUID);
if (obj != null) {
logger.warn("[JobProcessData] addBatchMsgDoc >> UUID["+strUUID+"] 에 이미 데이터가 있습니다." + obj);
hm_batchData.remove(strUUID);
}
hm_batchData.put(strUUID, hmData);
}
@SuppressWarnings("unchecked")
public synchronized HashMap<String, Object> getBatchStageData(String strUUID)
{
return (HashMap<String, Object>)hm_batchData.get(strUUID);
}
public synchronized void setBatchStageData(String strUUID, HashMap<String, Object> hm)
{
hm_batchData.remove(strUUID);
hm_batchData.put(strUUID, hm);
}
public synchronized void delBatchStageData(String strUUID)
{
this.hm_batchData.remove(strUUID);
}
public synchronized int getBatchStageDataCount() {
return hm_batchData.size();
}
}
@@ -0,0 +1,955 @@
package com.eactive.eai.batch.job.jobItem;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.common.StringUtil;
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.batch.rule.phaseinfo.PhaseInfoVO;
import com.eactive.eai.batch.telegram.TelegramManager;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.Logger;
public class DefaultTelegram implements TelegramService
{
//Telegram 전문구조를 나타내는 MsgMetaDstcd
protected String TELEGRAM_META_CODE = "";
protected BatchDoc batchDoc;
// FileLoger
protected Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
public String logHeader;
public String logNodeCount;
public String ErrorMsg = "";
public int nFileHeadTailLogSize = 500;
/**
* Stage 변경 참조용 ArrayList : 실제 FlowComponent에서 조회해서 텔레그램쪽으로 지정해 줘야 한다.
*/
public ArrayList<PhaseInfoVO> al_NextStage = new ArrayList<PhaseInfoVO>();
/**
* 필드를 저장한 Array List : 각각은 Byte Array로 이루어진다.
*/
public ArrayList<byte []> al_Field = new ArrayList<byte []>();
/**
* 필드의 Property를 String배열로 가진다. 각 필드 처리시 alignment결정을 위한 것이다.
* TSEAIBM02의 각 필드에 대한 필드 특성치 (TSEAIBM01참조) 에 대한 배열이다.
* EX> AN : 좌측정렬, NN : 우측정렬
*/
public String[] al_FieldProps ;
/**
* 문자열로 각 필드의 실질적인 길이를 나타낸다.
* 길이값으로 'XX'가 들어 있는 경우가 비정형 필드가 된다.
*/
public String[] al_FieldLength;
public String[] al_FieldIDs;
public String[] al_FieldNames;
/**
* Telegram Class의 상태에 따른 KEY WORD 저
*/
public String conditionTxt = "";
/**
* 모든 Send/Recv 에 사용될 공통 필드 선언 --> SEND TelegramClass 에서 전문 조립시 사용
* DB에서 읽어들인 값...
*/
// 전문 종별 : 룰 DB (TSEAIBR02) 의 SEND 단계에 들어 있는 해당 전문 송신에 사용될 전문종별 값이다.
public String fldTelegramType = "";
// 업무관리 코드 : 룰 DB (TSEAIBR02) 의 SEND 단계에 들어 있는 해당 전문 송신에 사용될 업무관리코드 값이다.
public String fldOpCode = "";
// 거래구분코드 : 룰 DB (TSEAIBR02) 의 SEND 단계에 들어 있는 해당 전문 송신에 사용될 거래구분코드 값이다.
public String fldTrClass = "";
//이전 단계 RECV 텔레그램 전문 해석 후 응답코드 값 저장.
//기본값은 TelegramKeys.RPS_HDB_RET_CODE_SUCCESS (000) 값을 가짐.
public String resolveResponseCode = TelegramKeys.RPS_HDB_RET_CODE_SUCCESS;
public String telegramType = "";
/**
* SEND 단계에서 사용될 함수 : 룰에 있던 값
*/
public String getFldTelegramType()
{
return this.fldTelegramType;
}
/**
* SEND 단계에서 사용될 함수 : 룰에 있던 값
*/
public void setFldTelegramType(String strTelegramType)
{
this.fldTelegramType = strTelegramType;
}
/**
* SEND 단계에서 사용될 함수 : 룰에 있던 값
*/
public String getFldOpCode()
{
return this.fldOpCode;
}
/**
* SEND 단계에서 사용될 함수 : 룰에 있던 값
*/
public void setFldOpCode(String strOpCode)
{
this.fldOpCode = strOpCode;
}
/**
* SEND 단계에서 사용될 함수 : 룰에 있던 값
*/
public String getFldTrClass()
{
return this.fldTrClass;
}
/**
* SEND 단계에서 사용될 함수 : 룰에 있던 값
*/
public void setFldTrClass(String strTrClass)
{
this.fldTrClass = strTrClass;
}
/**
* BatchDoc 인스탄스 지정
*/
public void setEAIBatchMessage(BatchDoc pBatchDoc)
{
batchDoc = pBatchDoc;
logger = batchDoc.getLogger();
}
public BatchDoc getEAIBatchMessage()
{
return batchDoc;
}
/**
* Telegram 전문별 특별한 수행기능 처리
*/
/**
* boolean doPreExecution
* 지정된 전문의 구성 필드 배열 선언
*/
public boolean doPreExecute()
{
try {
/* 1. 단계 기본 정보 추출*/
TelegramManager telegramManager = TelegramManager.getInstance();
/* 2. 전문 입력값 생성
* - [0]에서 [7]까지는 공통부 (CMS은행 기준)
* - 나머지는 개별부
* - 주의사항: 전문의 길이를 정의하는 필드는 모든 값을 입력한 다음에 정의되어야 한다.
* 예, CMS은행의 경우 제일 첫 필드가 전문의 길이를 저장하는 필드이이다. objs[0] 참조
*/
// 전문필드의 갯수만큼 임시변수 생성
this.al_FieldLength = telegramManager.getTelegramFieldLengthsArray(this.TELEGRAM_META_CODE);
this.al_FieldProps = telegramManager.getTelegramFieldTypesArray (this.TELEGRAM_META_CODE);
this.al_FieldIDs = telegramManager.getTelegramFieldIDsArray (this.TELEGRAM_META_CODE);
this.al_FieldNames = telegramManager.getTelegramFieldNamesArray (this.TELEGRAM_META_CODE);
logger.info("{"+logHeader+"} 전문 [" + TELEGRAM_META_CODE + "] 의 필드 수 = " + this.al_FieldLength.length );
this.al_Field = new ArrayList<byte []>();
for (int i=0; i<this.al_FieldLength.length ; i++)
{
String strLength = this.al_FieldLength[i];
int nLength ;
if (!strLength.equalsIgnoreCase(DefaultTelegram.FIELD_NO_LENGTH)) {
try {
nLength = Integer.parseInt(strLength);
} catch(Exception e) {
ErrorMsg = "수신용 길이결정 전문에 길이가 지정되어 있지 않습니다.";
logger.info("{"+logHeader+"} 전문[" + TELEGRAM_META_CODE + "] 는 길이결정용 전문구조체이며, 여기에 지정된 필드에 길이가 지정되지 않은 것이 있습니다.");
return false;
}
} else {
nLength = 1;
}
byte[] field = new byte[nLength];
this.al_Field.add(field);
}
return true;
} catch (Exception e) {
ErrorMsg = "수신용 길이 결정 중 장애 발생 ";
logger.error("{} 전문[" + TELEGRAM_META_CODE + "] 용 byte array 를 ArrayList 에 할당 중 장애 발생 >> ", logHeader, e);
}
return false;
}
public boolean doPreExecuteAfterCopy()
{
return true;
}
/**
* 전문 조립하기 / 헤체하기
*/
public boolean doExecute()
{
return true;
}
/**
* 전문 Validation : 송신할 전문, 수시한 전문 Validation
*/
public boolean doValidation()
{
return true;
}
/**
* SEND 단계 : doPreExecute -> doExecute -> dePostExecute 순서로 호출
* RECV 단계 : doPreExecute -> doExecute -> doPostExecute 순서로 호출
*/
public boolean doPostExecute()
{
return true;
}
/**
* 해당 전문의 총 길이값을 리턴해주는 함수 : 비정형 필드에 대한 고려를 하지 못했다.
* 사용안함.
*/
public int getTelegramLength()
{
int nTotalLength =0;
for (int i=0; i< al_Field.size(); i++) {
byte[] t_field = (byte[]) al_Field.get(i);
nTotalLength = nTotalLength + t_field.length;
}
return nTotalLength;
}
/**
* byte 배열로 받은 데이터를 한꺼번에 필드에 지정해 줄때 사용하는 함수. 비정형필드에 대한 고려가 없다.
* RECV 방식이 바뀌면서 사용안함.
* 단순 byte 배열보다는 각 필드별로 데이터를 사용함.
*/
public void setReceiveData(byte[] recvByteArray)
{
ByteArrayInputStream bin = new ByteArrayInputStream(recvByteArray);
for (int i=0; i<al_Field.size(); i++) {
byte[] aField = (byte[]) al_Field.get(i);
bin.read(aField, 0, aField.length);
}
// 이것은 업무별로 구현하는 수 밖에는 없다...
byte[] lenField = (byte[]) al_Field.get(batchDoc.getBatchMsg().getPhaseinfo().getLengthFieldIndex());
String strRemainLength = new String(lenField);
int nTotalLength = 0;
try {
nTotalLength = Integer.parseInt(strRemainLength);
} catch (Exception e) {
logger.debug("{"+logHeader+"} LENGTH FIELD["+strRemainLength+"] conversion failed : "+e.getMessage() );
return ;
}
int nReceivedLength = 0;
for (int i=2; i<al_Field.size(); i++) {
byte[] aField = (byte[]) al_Field.get(i);
nReceivedLength = nReceivedLength + aField.length;
}
logger.info("{"+logHeader+"} 총 수신 전문 길이 : " + nTotalLength);
logger.info("{"+logHeader+"} 기 수신 전문 길이 : " + nReceivedLength);
}
/**
* byte[] getFieldDataByIndex(int idx)
* 해당 필드(idx)의 byte 배열을 리턴해 주는 함수.
* 인덱스가 해당 전문의 필드 수를 넘어가는 경우는 null을 리턴해 준다.
*/
public byte[] getFieldDataByIndex(int idx)
{
if (this.al_Field.size() > idx) {
byte[] aField = (byte[]) al_Field.get(idx);
return aField;
}
return null;
}
/**
* byte[] getSendData()
* 각 필드 byte배열을 한꺼번에 조립하여 하나의 byte 배열로 리턴해주는 함수. 비정형 필드에 대해 고려하지 못했다.
* 사용안함.
*/
public byte[] getSendData()
{
ByteArrayOutputStream ba_out = new ByteArrayOutputStream();
try {
for (int i=0; i < al_Field.size(); i++)
{
byte[] aField = (byte[]) al_Field.get(i);
ba_out.write(aField);
}
return ba_out.toByteArray();
} catch (Exception ex) {
logger.debug("{"+logHeader+"} getSendData : Exception >> " + ex.getMessage());
return null;
}
}
/**
* Field Array ( al_Field )에서 지정된 인덱스의 값을 교체해 준다.
*
* 지정된 필드의 값을 변경해 준다.
*/
public void setFieldDataByIndex(int idx, byte[] buf)
{
if (this.al_Field.size() > idx) {
byte[] aField = (byte[]) al_Field.get(idx);
int len = aField.length;
if ( ( len == 1 ) && buf.length > 1) {
// XX인 경우
len = (buf.length > 100) ? 100: buf.length;
aField = new byte[len];
} else {
len = (len < buf.length)? len : buf.length;
}
for (int i=0; i<len; i++)
aField[i] = buf[i];
al_Field.set(idx, aField);
}
}
/**
* 해당 텔레그램 클래스에 실질적인 전문구조를 나타내는 Meta코드를 지정해 준다.
* 파라미터 strMsgMetaDstcd는 TSEAIBM02에 들어있는 각 전문구조를 표시하는 MsgMetaDstcd 필드 값이다.
*/
public void setTelegramCode(String strMsgMetaDstcd)
{
this.TELEGRAM_META_CODE = strMsgMetaDstcd;
//batchMsgDoc 이 먼저 설정되어 있어야함.
logHeader = "["+ batchDoc.getBatchMsg().getHeader().getUUID() +" / "+
batchDoc.getBatchMsg().getHeader().getProcessCode() +" / "+
batchDoc.getBatchMsg().getHeader().getInstitutionName() +" / "+
batchDoc.getBatchMsg().getHeader().getProcessType() +" / "+
batchDoc.getBatchMsg().getHeader().getFileName() +" / "+
batchDoc.getBatchMsg().getHeader().getRuleCode() +" / "+
batchDoc.getBatchMsg().getPhaseinfo().getPhaseCode() +" / "+
batchDoc.getBatchMsg().getPhaseinfo().getPhaseType() +"] ";
logNodeCount = "[NodeCnt-"+ batchDoc.getBatchMsg().getBody().getNodeCount() +" / "+
this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".")+1) +" / "+
strMsgMetaDstcd +"] ";
}
/**
* SEND/RECV단계 처리 종료 후, 다음 단계 결정을 하기전에 다음단계(Phase)결정의 기본 자료로
* 현 단계(Phase)에서 가능한 다음 단계 리스트를 지정해 준다. (TSEAIBR02테이블에서 읽어들인 LIST 값)
*/
public void setNextStageInfo(ArrayList<PhaseInfoVO> stageList)
{
this.al_NextStage = stageList;
}
/**
* SEND/RECV 단계에서 사용될 getNextStage 함수구현 ( Child Telegram Class 에서 공통으로 사용 )
*
* 다섯개의 조건으로 다음 단계를 결정한다.
* 1. 전문종별 조건 : RECV단계에서 수신한 전문종별 조건값
* 2. 업무관리코드 조건 : RECV단계에서 수신한 전문의 업무관리 코드 조건값
* 3. 거래구분코드 조건 : RECV단계에서 수신한 전문의 거래구분코드 조건값
* 4. 응답코드 조건 : RECV단계에서 수신한 전문의 응답코드 조건 값
* 5. KeyWord 조건 : SEND/RECV 단계의 ConditionTxt로 지정되어 있는 KEY 조건 문장
*
* 단계(Phase)변환 룰(TSEAIBR02)의 각 레코드에 위의 조건 필드값이 지정되어 있지 않는 경우, 해당 조건은 당연 TRUE 처리한다.
* KEYWORD 조건 값 중, 'TIMEOUT' 과 'ERROR'는 SEND/RECV의 단계 처리 중, 이미 처리된 부분이므로 여기에서는 고려대상이 안된다.
* 따라서 이 두 (TIMEOUT, ERROR)에 대한 부분은 무조건 false를 리턴할 것이다.
*
* 주의>> 조건이 지정되는 않은 레코드가 PhaseSeq상 앞에 있다면, 항상 해당 레코드의 다음 단계(Phase)가 다음 단계로 결정될 것이다.
*
* SEND 단계 :
* SEND 단계의 룰정보는 조건전문종별값,조건업무관리코드값,조건거래구분코드값,조건응답코드값 이 지정되어 있으면 안된다.
* SEND단계에서 상대방에게 통보하는 응답코드에 따른 룰분기를 할 경우, 상태변환 룰을 적용하고, 해당 텔레그래에서 getResCode를 구현하도록 한다.
* KeyWord 조건 값 사용 :
* RECV 단계 :
* 위의 다섯 가지 조건이 다 지정될 수도 있다.
*/
public PhaseInfoVO getNextStage() {
String strRecvTelegramType = this.getTelegramType();
String strRecvOpCode = this.getOpCode();
String strRecvTrClass = this.getTrClass();
String strRecvResCode = this.getResCode();
boolean bCondition_TelegramType = false; //전문종류
boolean bCondition_OpCode = false; //업무관리코드
boolean bCondition_TrClass = false; //거래구분코드
boolean bCondition_ResCode = false; //응답코드
boolean bCondition_ConditionText= false; //배치 일괄처리 KEY WORD 처리용
logger.debug("{"+logHeader+"} getNextStage - strRecvTelegramType : "+strRecvTelegramType);
logger.debug("{"+logHeader+"} getNextStage - strRecvOpCode : "+strRecvOpCode);
logger.debug("{"+logHeader+"} getNextStage - strRecvTrClass : "+strRecvTrClass);
logger.debug("{"+logHeader+"} getNextStage - strRecvResCode : "+strRecvResCode);
logger.debug("{"+logHeader+"} getNextStage - ConditionTxt : " + this.getConditionTxt());
logger.debug("{"+logHeader+"} this.al_NextStage.size() : " + this.al_NextStage.size());
//일단 상태변경 규칙 DB Table에 값이 없으면 해당 조건은 true로 처리해 준다.
int i;
for (i=0; i < this.al_NextStage.size(); i++) {
PhaseInfoVO phase_vo = this.al_NextStage.get(i);
// 1 전문종별 비교
if (phase_vo.getCTelegramType().trim().length() == 0) {
bCondition_TelegramType = true;
} else {
if (phase_vo.getCTelegramType().trim().equalsIgnoreCase(strRecvTelegramType.trim()))
bCondition_TelegramType = true;
else
bCondition_TelegramType = false;
}
// 2 업무관리코드 비교
if (phase_vo.getCOpCode().trim().length() == 0) {
bCondition_OpCode = true;
} else {
if (phase_vo.getCOpCode().trim().equalsIgnoreCase(strRecvOpCode))
bCondition_OpCode = true;
else
bCondition_OpCode = false;
}
// 3 거래구분코드 비교
if (phase_vo.getCTrClass().trim().length() == 0) {
bCondition_TrClass = true;
} else {
if (phase_vo.getCTrClass().trim().equalsIgnoreCase(strRecvTrClass))
bCondition_TrClass = true;
else
bCondition_TrClass = false;
}
// 4 응답코드 비교
if (phase_vo.getCResCode().trim().length() == 0) {
bCondition_ResCode = true;
} else {
if (phase_vo.getCResCode().trim().equalsIgnoreCase(strRecvResCode))
bCondition_ResCode = true;
else
bCondition_ResCode = false;
}
// 5 CondtionTxt (KeyWord) 조건 비교
if (phase_vo.getConditionTxt().trim().compareToIgnoreCase(this.getConditionTxt().trim()) == 0)
bCondition_ConditionText = true;
else
bCondition_ConditionText = false;
// 네가지 모든 조건이 일치하면 .. 다시 Condition Text를 체크해 보아야 한다.
if (bCondition_TelegramType && bCondition_OpCode && bCondition_TrClass && bCondition_ResCode
&& bCondition_ConditionText )
{
break;
}
}
if (i < this.al_NextStage.size()) {
logger.info("{"+logHeader+"} 다음 단계를 찾았습니다.-->" + (PhaseInfoVO)this.al_NextStage.get(i));
return (PhaseInfoVO)this.al_NextStage.get(i);
} else {
logger.debug("{"+logHeader+"} 다음 단계를 찾을 수 없습니다.-->["+this.al_NextStage.size()+"]");
for (i=0; i < this.al_NextStage.size(); i++) {
PhaseInfoVO phase_vo = (PhaseInfoVO) this.al_NextStage.get(i);
String strRuleCTelegramType = phase_vo.getCTelegramType().trim();
String strRuleCOpCode = phase_vo.getCOpCode().trim();
String strRuleCTrClass = phase_vo.getCTrClass().trim();
String strRuleCResCode = phase_vo.getCResCode().trim();
String strRuleConditionTxt = phase_vo.getConditionTxt().trim();
logger.debug("{"+logHeader+"} index =["+ ( i + 1 ) +"]["+ phase_vo.getPhaseSeq()+"]strRuleCTelegramType-->["
+ strRuleCTelegramType+ "]strRuleCOpCode-->["
+strRuleCOpCode + "]strRuleCTrClass-->["+strRuleCTrClass+"]strRuleCResCode-->["
+strRuleCResCode+ "]strRuleConditionTxt-->["+strRuleConditionTxt+ "]");
}
return null;
}
}
/**
* RULE의 TelegramType만 가지고, 다음 텔레그램의 ID를 결정한다.
*/
public String getRealRecvTelegram() {
//전문헤더의 {전문종별코드} 값
String strRecvTelegramType = this.getTelegramType();
//일단 상태변경 규칙 DB Table에 값이 없으면 해당 조건은 true로 처리해 준다.
for (int i=0; i<this.al_NextStage.size(); i++) {
PhaseInfoVO info = (PhaseInfoVO) this.al_NextStage.get(i);
//전문종별코드 비교
if (info.getCTelegramType().trim().equals("") ||
info.getCTelegramType().trim().equalsIgnoreCase(strRecvTelegramType.trim())) {
batchDoc.getBatchMsg().getPhaseinfo().setPhaseSeq (info.getPhaseSeq() ); //Stage Logging 용
batchDoc.getBatchMsg().getPhaseinfo().setPhaseTelegramID(info.getTelegramID()); //Stage Logging 용
return info.getTelegramID();
}
}
return "";
}
/**
* 현재 전문의 ConditionTxt에 지정되어 있는 값과, 텔레그램에서 체크할 수 있는 상태를 가지고
* 조건 성립여부를 체크한다. --> 다음 진행 Stage 결정을 위해서
*
* 각 Telegram Class에서 오버라이드 구현 할 수도 있다.
*/
public boolean checkNextStageConditionTxt(String pConditionTxt)
{
logger.info("{"+logHeader+"} Function called : checkNextStageConditionTxt ");
if (pConditionTxt.equalsIgnoreCase(TelegramKeys.TIMEOUT) ||
pConditionTxt.equalsIgnoreCase(TelegramKeys.ERROR) )
{
// 이 두가지 경우는 이미 RECV단계에서 처리되므로 별도 처리하지 않는다.
return false;
}
return true;
}
/**
* 상대방에게 보낼 응답코드값을 계산하도록 한다.
* 이전단계의 텔레그램을 찾아 이전 단계의 응답코드를 반환한다.
*
*/
public String getSendResponseCode() throws Exception
{
try {
//처음 업무개시 텔레그램이면 TelegramKeys.RPS_HDB_RET_CODE_SUCCESS (000)을 반환
if (this.batchDoc.getBatchMsg().getBody().getNodeCount() == 1 )
{
return resolveResponseCode;
} else
{
// 이전 전문을 구한다.
String strUUID = this.batchDoc.getBatchMsg().getHeader().getUUID();
HashMap<String, Object> hm_job = JobProcessData.getInstance().getBatchStageData(strUUID);
TelegramService prevTelegram = (TelegramService) hm_job.get(JobProcessData.PROCDATA_PRE_TELEGRAM);
if (prevTelegram == null) {
throw new Exception("not found previous telegram instance : needed in compiling of response telegram");
}
return prevTelegram.getResolveResponseCode();
}
} catch (Exception ex) {
throw new Exception(ex);
}
}
public String getConditionTxt()
{
return this.conditionTxt;
}
public void setConditionTxt(String strConsitionTxt)
{
this.conditionTxt = strConsitionTxt;
}
/**
* SEND 단계에서 전체 송신 전문의 길이를 구할 때 사용
* 전문에 따라, 전체 전문의 길이를 포함하는 경우(퇴직연금)도 있고, 특정필드 이후 (길이값 필드 미포함) 의
* 필드 길이에 대한 것만 전문길이로 표시하는 경우도 있으나,
* 이 함수는 실질적으로 통신 IO를 일으킬 때, 대상 송신 Bytes수를 리턴하도록 한다.
*
* 각 SEND Telegram 에서 개별 구현하도록 한다.
*/
public int getSendLength()
{
return 0;
}
public String toString()
{
StringBuffer sb = new StringBuffer();
// 여기서 텔레그램 클래스 인스탄스로 스트링으로 만들어준다.
return sb.toString();
}
/**
* 수신받은 전문구조에서 '전문종별' 값을 리턴한다.
* 각 TelegramClass에서 오버라이드 구현하도록 한다.
* RECV telegram 에서 구현
*/
public String getTelegramType()
{
return this.telegramType;
}
public void setTelegramType(String telegramType)
{
this.telegramType = telegramType;
}
/**
* 수신받은 전문구조에서 '거래구분코드' 값을 리턴한다.
* 각 TelegramClass에서 오버라이드 구현하도록 한다.
* RECV telegram 에서 구현
*/
public String getTrClass()
{
return "";
}
/**
* 수신받은 전문구조에서 '응답코드' 값을 리턴한다.
* 각 TelegramClass에서 오버라이드 구현하도록 한다.
* RECV telegram 에서 구현
*/
public String getResCode()
{
return "";
}
/**
* 수신받은 전문구조에서 '업무관리코드' 값을 리턴한다.
* 각 TelegramClass에서 오버라이드 구현하도록 한다.
* RECV telegram 에서 구현
*/
public String getOpCode()
{
return "";
}
/**
* Default 구현으로 사용가능한 함수
*
* 지정된 필드(idx)에 파라미터 값 (strValue)을 저장해 준다.
* 세번째 파라미터 Alignment 의 값이 ALIGNMENT_RIGHT("NN") 이면, 오른쪽정렬을 해주고
* 아니면 왼쪽 정렬 해준다.
*
* 오른쪽 정렬일때는 필드값이 필드길이보다 짧을때 '0'을 채워넣어주고
* 왼쪽 정렬일때 필드값이 필드길이보다 짧을때 ' '(SPACE)를 채워넣어준다.
*/
public void compileField(int idx, String strValue, String Alignment) throws Exception {
if (this.al_Field.size() > idx) {
int aFieldLength = ((byte[])this.al_Field.get(idx)).length;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
if ( strValue == null ) strValue = "";
byte[] bValue = strValue.getBytes("KSC5601");
if (!Alignment.equalsIgnoreCase(ALIGNMENT_RIGHT)) {
if (aFieldLength> bValue.length) {
int n= aFieldLength - bValue.length;
for (int i=0; i<bValue.length; i++) bout.write(bValue[i]);
for (int i=0; i<n; i++) bout.write(' ');
} else {
for (int i=0; i<aFieldLength; i++) bout.write(bValue[i]);
}
}
else {
if (aFieldLength > bValue.length) {
int n = aFieldLength - bValue.length;
for (int i=0; i<n; i++) bout.write('0');
for (int i=0; i<bValue.length ; i++) bout.write(bValue[i]);
} else {
for (int i=0; i<aFieldLength; i++) bout.write(bValue[i]);
}
}
al_Field.set(idx, bout.toByteArray());
} catch (Exception ex) {
throw new Exception(ex);
}
} else {
throw new Exception("Telegram compile : overflow index " + idx);
}
}
/**
* 해당 텔레그램 클래스가 가지고 있는 총 필드의 갯수를 리턴해 준다.
* 가능하면 필드를 나타내는 ArrayList인 al_Field는 밖으로 안 보여주 위해....
*
* default 구현으로 사용가능.
*/
public int getFieldCount()
{
return this.al_Field.size();
}
/**
* 특정 필드(idx)의 필드 길이를 리턴해준다.
*
* default 구현으로 사용가능.
*/
public String getFieldLength(int idx)
{
if (this.al_Field.size() > idx) {
return this.al_FieldLength[idx];
} else {
return null;
}
}
/**
* 특정필드 (idx)의 필드 property (AN, NN, ...)를 리턴해 준다.
* default 구현으로 사용가능
*/
public String getFieldProperty(int idx)
{
if (this.al_Field.size() > idx) {
return this.al_FieldProps[idx];
} else {
return null;
}
}
/**
* 비정형 필드에 대한 송수신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx)
{
return -1;
}
/**
* return value : 0 no left data to be sent
* -1 error
* >0 data copied to the data field
*
* 비정형 필드를 가지는 송신전문 처리 Telegram Class 에서 오버라이드 되어야 한다.
* SEND/RECV 단계에서, 각 비정형 필드(idx) 의 실질적인 처리대상 길이를 getCalculatedLength() 로 구한 다음,
* 이 함수를 반복적을 호출하여 해당 비정형필드 처리완료를 위한 데이터를 얻어낸다.
* 파라미터 data에 매번 호출 될 때, 비정형 필드 처리를 위한 적절한 데이터를 실어 주도록 한다.
* 리턴값은 실질적으로 파라미터 data에 실린 데이터의 길이 이다.
*/
public int getInformalFieldSendData(int idx, byte[] data) {
return 0;
}
/**
* RECV단계에서 비정형 필드(idx)의 값을 통신 IO 를 통해 읽고, 그 결과를 텔레그램클래스로 넘겨주는 함수이다.
* 비정형 필드를 가지는 개별 Telegram Class 는 이 함수를 통해 각각 클래스가 가지는 비정형 필드(예> 파일 내용 등...)에 대한
* 처리를 완료해 줘야 한다.
*
* 비정형 필드를 가지는 개별 Telegram Class에서 오버라이드 필요
*/
public boolean doInformalField(int idx, byte[] data, int length)
{
return true;
}
// 전문 해체 후 응답코드
public String getResolveResponseCode()
{
return resolveResponseCode;
}
//전문 해체 후 응답코드
public void setResolveResponseCode(String code)
{
this.resolveResponseCode = code;
}
//파일 송수신 시 파일의 헤더, 트레일러 값을 배치메시지에 설정
public void setFileHeaderAndTrailer(File f) {
//파일이 존재하지 않거나 디렉토리면 리턴
if (f == null || !f.exists() || f.isDirectory()) {
logger.info("{"+logHeader+"} ["+ (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()+2;
}
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);
}
}
byte[] bufTrailer2 = new byte[(int)fileTrailerSize-2];
int startIndex = 0;
if ( bufTrailer[bufTrailer.length-2] == '\r' && bufTrailer[bufTrailer.length-1] == '\n'){
startIndex = 0;
}else if ( bufTrailer[bufTrailer.length-1] == '\r' || bufTrailer[bufTrailer.length-1] == '\n'){
startIndex = 1;
}else{
startIndex = 2;
}
System.arraycopy(bufTrailer, startIndex, bufTrailer2, 0, bufTrailer2.length);
batchDoc.getBatchMsg().setFileHeader(new String(bufHeader));
batchDoc.getBatchMsg().setFileTrailer(new String(bufTrailer2));
} catch (Exception ex) {
logger.error("{} ★★★★★ 파일내용 헤더, 트레일러 DB로그 설정시 오류 발생 !! ★★★★★", logHeader, ex);
} finally {
try { if (fin != null) fin.close(); } catch (Exception e) {}
}
}
/**
* 전문결정용 텔레그램에서 사용하도록 한다.
* 전문결정용 텔레그램 클래스를 이용하여, 수신단계 처리시에 예상치 못한 전문종별 수신시 남아있는 전문을 받아 통신 자원에서
* 없애기 위해 사용하는 함수이다. --> RECV2 에서 사용
*/
public int getRemainDataLength()
{
return -1;
}
protected boolean checkType(String type, String value)
{
return (type.equalsIgnoreCase("AA") || type.equalsIgnoreCase("A"))? StringUtil.isAlpha(value) :
(type.equalsIgnoreCase("NN") || type.equalsIgnoreCase("N"))? StringUtil.isNumeric(value) :
(type.equalsIgnoreCase("AN"))? true : false;
}
//특정 필드 Index (base 0) 의 값을 문자열로 리턴
protected String getFieldValueString(int columnIndex) {
if (al_Field.size() <= columnIndex) return "";
return new String( (byte[]) al_Field.get(columnIndex) );
}
protected String getFieldValueString(String fieldID){
int inx = 0;
for ( inx=0; inx < al_FieldIDs.length; inx++){
if ( al_FieldIDs[inx].equals(fieldID) )
break;
}
return getFieldValueString(inx);
}
/**
* 총길이에 맞게 String 앞을 0으로 채워주는 함수 <BR>
* (예) makeFSpace("1234",6) --> "001234" <BR>
* @param String String Source
* @param int 총길이
* @return String
*/
protected String makeZero(String Str, int totlen)
{
String retStr = "";
if(Str == null) return "";
byte[] b_data = Str.getBytes();
int slen = b_data.length;
if( (totlen < 1) || (slen >= totlen) ) return Str;
for(int i=0; i< (totlen-slen); i++) {
retStr += "0";
}
retStr += Str;
return retStr;
}
/**
* 총길이에 맞게 String 앞을 Space로 채워주는 함수 <BR>
* (예) makeFSpace("1234",6) --> " 1234" <BR>
* @param String String Source
* @param int 총길이
* @return String
*/
protected String makeSpace(String Str, int totlen)
{
String retStr = "";
if(Str == null) return "";
byte[] b_data = Str.getBytes();
int slen = b_data.length;
if( (totlen < 1) || (slen >= totlen) ) return Str;
for(int i=slen; i< (totlen); i++) {
retStr += " ";
}
retStr = Str + retStr;
return retStr;
}
protected String substring(byte[] src, int offset, int len){
try {
byte[] temp = new byte[len];
System.arraycopy(src, offset, temp, 0, len);
return new String(temp);
} catch (Exception e) {
return null;
}
}
protected Properties getTelegramInfo() throws Exception {
//BATCH작업구분코드 (processCode)와 기관코드(institutionCode)에 따른 프로퍼티 정보 가져오기
String propName = TelegramKeys.PROP_GROUP_NAME_PREFIX +
"{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getInstitutionCode() +
"}";
PropManager pmanager = PropManager.getInstance();
return pmanager.getProperties(propName);
}
protected Properties getJobInfo() throws Exception {
//BATCH작업구분코드 (processCode)와 업무구분코드(BizCode)에 따른 프로퍼티 정보 가져오기
String propName = TelegramKeys.PROP_GROUP_NAME_PREFIX +
"{" +
batchDoc.getBatchMsg().getHeader().getProcessCode() +
"_" +
batchDoc.getBatchMsg().getHeader().getBizCode() +
"}";
PropManager pmanager = PropManager.getInstance();
return pmanager.getProperties(propName);
}
public String getSeparator() {
return File.separator;
}
}
@@ -0,0 +1,102 @@
package com.eactive.eai.batch.job.jobItem;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO;
import java.util.ArrayList;
public interface TelegramService
{
public final String ALIGNMENT_RIGHT = "NN";
public final String FIELD_NO_LENGTH = "XX";
public void setEAIBatchMessage(BatchDoc pBatchDoc) ;
public BatchDoc getEAIBatchMessage();
/**
* Telegram 전문별 특별한 수행기능 처리
*/
public boolean doPreExecute();
public boolean doPreExecuteAfterCopy();
public boolean doPostExecute();
public boolean doExecute();
public boolean doValidation();
public int getTelegramLength();
public void setReceiveData(byte[] recvByteArray);
public byte[] getFieldDataByIndex(int idx);
public byte[] getSendData();
public void setFieldDataByIndex(int idx, byte[] buf);
public int getFieldCount();
public String getFieldLength(int idx);
/**
* parameter로 전달되는 인덱스가 비정형 필드인지 체크하고,
* SEND : 해당 비정형 필드의 송신 길이를 리턴
* RECV : 해당 비정형 필드의 수신 길이를 리턴
*/
public int getCalculatedLength(int idx);
public String getFieldProperty(int idx);
public void setTelegramCode(String strTelegramCode);
public void setNextStageInfo(ArrayList<PhaseInfoVO> stageList);
public PhaseInfoVO getNextStage() ;
public String getRealRecvTelegram();
public boolean doInformalField(int idx, byte[] data, int length);
public int getSendLength();
public int getInformalFieldSendData(int idx, byte[] data);
public String getConditionTxt() ;
public void setConditionTxt(String strConsitionTxt);
/**
* 각 전문이 응답전문일 때, 전문에 조립된 응답코드를 구하는 함수
* 각 Telegram 클래스에서 구현되어야 함. 기본은 '000'으로 정상처리 응답코드를 리턴해주도록 한다.
*/
public String getSendResponseCode() throws Exception ;
public String toString();
//------------------------------------------------------------------------------------
public int getRemainDataLength(); //<-- 전문결정용 텔레그램에서 통신 자원상에 남아있는 전문의 남아있는 데이터 수를 계산한다.
//-------------------------------------------------- 실제전문 내용을 읽어들이는 곳...
public String getFldTelegramType();
public void setFldTelegramType(String strTelegramType);
public String getFldOpCode();
public void setFldOpCode(String strOpCode);
public String getFldTrClass();
public void setFldTrClass(String strTrClass);
// 전문종별
public String getTelegramType();
public void setTelegramType(String telegramType);
// 거래 구분코드
public String getTrClass() ;
// 응답코드
public String getResCode();
// 업무관리코드
public String getOpCode();
// 전문 해체 후 응답코드
public String getResolveResponseCode();
//전문 해체 후 응답코드
public void setResolveResponseCode(String code);
}
@@ -0,0 +1,139 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.encrypt.EncryptManager;
import com.eactive.eai.common.exception.ExceptionUtil;
public class RECV_BI0200 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BI0200() {
//업무개시요구 및 업무개시통보
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
try{
//송신자 암호 유효성 확인
String sendPwd = new String ((byte[]) al_Field.get(10));
if (sendPwd == null || sendPwd.length() <= 0) {
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_SENDER_PWD_ERROR);
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI010";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return false;
}
//요구송수신 테스트를 위해 암호 복호화
//결재원과 테스트시에는 해당 클래스는 실행되지 않음.
Properties telegramInfo = getTelegramInfo();
String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE);
if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) {
//전송자명은 앞에서 7자리이며 7자리 미만은 Z로 채움..
String passwd = EncryptManager.getInstance().getDeEncryptPwd(sendPwd,
telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1,3),
TelegramKeys.getYYYYMMddHHmmss().substring(2,8),
(batchDoc.getBatchMsg().getHeader().getUserID()+"ZZZZZZZ").substring(0,8)
);
logger.debug("{"+logHeader+"} RECV_BI0200 ] PASSWD : ["+passwd+"], getUserPassword : ["+batchDoc.getBatchMsg().getHeader().getUserPassword()+"]");
if (!passwd.startsWith(batchDoc.getBatchMsg().getHeader().getUserPassword())){
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_SENDER_PWD_ERROR);
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI010";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return false;
}
}
}catch(Exception e){
String errMsg = ExceptionUtil.getErrorCode ("RECV_BI0200] occure exception at doValidation ");
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,90 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.lang.String;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BI0210 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BI0210() {
// 업무개시통보
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,92 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.lang.String;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BI0220 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BI0220() {
//업무종료 지시
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,90 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.lang.String;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BI0230 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BI0230() {
//업무종료보고
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,210 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.lang.String;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.ByteArrayOutputStream;
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.common.exception.ExceptionUtil;
import java.io.File;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BI0400 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BI0400() {
//화일정보수신요구
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
try{
//파일구분 (6)+은행코드(3)+블럭번호(3)+전송일자(8)
//파일명 파싱해서 유효성 검사가 필요한 경우 .....
//해당 내용 추가할것 by kscheon
String fName = new String ((byte[]) al_Field.get(6));
long fSize = Long.parseLong(new String ((byte[]) al_Field.get(8)));
batchDoc.getBatchMsg().getHeader().setFileName(fName);
//파일명으로 부터 거래 구분 코드 추출
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 = (OutsideVO)organList.get(i);
if ( institutionCode.equals(organInfo.getOsdCode()) ) {
bizCodeStartIndex = organInfo.getBizCdStartIdx();
bizCodeEndIndex = organInfo.getBizCdEndIdx();
break;
}
}
if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= fName.length()) bizCodeStartIndex = 0;
if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fName.length()) bizCodeEndIndex = fName.length();
String bizCode = fName.substring(bizCodeStartIndex, bizCodeEndIndex);
BatchJobInfoVO bJobInfo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode);
if ( bJobInfo == null || !bJobInfo.getRecvUseYN().equals("1") ){
logger.debug("[RECV_BI0400][doExecute]processCode(" + processCode + "), bizCode(" + bizCode + ")");
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_NOT_REGISTERED);
return true;
}
long recLen = bJobInfo.getFileRecSize();
batchDoc.getBatchMsg().getHeader().setBizCode(bizCode);
//파일이 1024(byte)xn으로 구성되므로
String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath();
logger.debug("{"+logHeader+"} DIR = <<"+fileDir+">> FILE >> Tele FName <<"+fName+">>");
if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) {
fileDir = fileDir + File.separator;
}
String fileFullName = fileDir + fName;
File f = new File(fileFullName);
if (f.exists() && f.length() > 0) {
long file_size = f.length();
if (file_size >= fSize ){
//기수신완료
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ALREADY_RECEIVED);
batchDoc.getBatchMsg().getBody().setCurFileSize(file_size);
} else {
int seq_size = this.batchDoc.getBatchMsg().getHeader().getSequenceSize();
int seq_no = (int)file_size/seq_size;
if (seq_no > 0){
batchDoc.getBatchMsg().getBody().setCurFileSize(file_size);
batchDoc.getBatchMsg().getBody().setSeqNum(seq_no);
JobProcessData job = JobProcessData.getInstance();
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
@SuppressWarnings("unchecked")
HashMap<Integer, String> miss_data = (HashMap<Integer, String>) hm.get(JobProcessData.PROCDATA_MISSDATA); //결번여부 저장..
if (miss_data == null) {
miss_data = new HashMap<Integer, String>();
}
for (int i=0; i<seq_no; i++){
miss_data.put(new Integer(i), "1");
}
hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
} else {//수신된 데이터가 seq크기만큼 안되면 처음부터 다시..
batchDoc.getBatchMsg().getBody().setCurFileSize(0);
batchDoc.getBatchMsg().getBody().setSeqNum(0);
}
}
} else {//최초 파일 수신시
batchDoc.getBatchMsg().getBody().setCurFileSize(0);
batchDoc.getBatchMsg().getBody().setSeqNum(0);
}
batchDoc.getBatchMsg().getHeader().setFileSize(fSize);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(fSize/recLen);
} catch ( Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
String fName = new String ((byte[]) al_Field.get(6));
if (fName == null || fName.length() <= 0) {
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FILENAME_ERROR);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = fName;
String errCode = "BECEAIFJI007";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return false;
}
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,208 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.lang.String;
import java.util.HashMap;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.running.BatchOpenFileManager;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BI0410 extends DefaultTelegram implements TelegramService
{
private BufferedInputStream bis;
/**
* 생성자
*/
public RECV_BI0410() {
// 화일정보수신보고
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
if (!createFile()) {
logger.error("{} file open failed", logHeader);
setConditionTxt(TelegramKeys.ERROR);
return false;
}
try{
long rSize = Long.parseLong(new String ((byte[]) al_Field.get(8)));
if (getResCode().equalsIgnoreCase(TelegramKeys.BI_RES_CODE_ALREADY_RECEIVED)) { //기송신 파일이면
this.setConditionTxt(TelegramKeys.COMPARE);
} else {
int seqSize = batchDoc.getBatchMsg().getHeader().getSequenceSize();
int totSeqSizeOffSize = 0;
if (rSize >= batchDoc.getBatchMsg().getHeader().getFileSize()){
logger.debug("{"+logHeader+"} doExecute ] recive file size is bigger than current file size ");
this.batchDoc.getBatchMsg().getBody().setErrorMsg("RECV_BI0410 - doExecute ] recive file size is bigger than current file size");
setConditionTxt(TelegramKeys.ERROR);
return false;
}
if (rSize > 0) { //기 송신된 파일이면서 미완료 파일이면
totSeqSizeOffSize = (int)(rSize / seqSize);
if (totSeqSizeOffSize > 0 ) { //
batchDoc.getBatchMsg().getBody().setSeqNum(totSeqSizeOffSize);
batchDoc.getBatchMsg().getBody().setCurFileSize(rSize);
byte[] fileData = new byte[seqSize];
for (int i=0; i<totSeqSizeOffSize; i++){
bis.read(fileData);
// 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다.
JobProcessData job = JobProcessData.getInstance();
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
@SuppressWarnings("unchecked")
HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>) hm.get(JobProcessData.PROCDATA_BLOCKDATA);
if (block_data == null) {
block_data = new HashMap<Integer, byte[]>();
}
block_data.put( new Integer(i) , fileData);
hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);
}
}
else {//기전송된 파일의 사이즈가 seqSize보다 작으면 처음부터 다시 송신
batchDoc.getBatchMsg().getBody().setSeqNum(0);
}
} else { //최초 송신이면
batchDoc.getBatchMsg().getBody().setSeqNum(0);
}
}
} catch ( Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
String fName = new String ((byte[]) al_Field.get(6));
if (fName == null || fName.length() <= 0) {
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FILENAME_ERROR);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = fName;
String errCode = "BECEAIFJI007";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return false;
}
// String filegbn = fName.substring(0, 6).trim();
// String fbankcd = fName.substring(6, 9).trim();
// int fblockno = Integer.parseInt(fName.substring(9, 12));
// String senddate = fName.substring(12, 20);
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
LogUtil.setLogFileStart(batchDoc);
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
private boolean createFile ()
{
try {
bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID() );
if (bis == null){
logger.warn("FILE정보가 NULL입니다.");
return false;
}
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI028";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
}
@@ -0,0 +1,176 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.lang.String;
import java.util.HashMap;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BI0420 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
private int recv_seq_no=0;
public RECV_BI0420() {
// 결번확인지시
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
String _seq_no = new String ((byte[]) al_Field.get(8));
recv_seq_no = Integer.parseInt(_seq_no);
int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum();
if (recv_seq_no < seq_no){
// 0410으로 받은 SEQ_NO가 EAIBatchMessage의 SEQ_NO 보다 작으면 EEND처리 해야 함.
this.setConditionTxt(TelegramKeys.ERROR);
logger.debug("{"+logHeader+"} current block_no is bigger than received block_no");
String[] msgArgs = new String[3];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = _seq_no;
msgArgs[2] = ""+seq_no;
String errCode = "BECEAIFJI024";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return false;
}
if (recv_seq_no > seq_no){
batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no);
JobProcessData job = JobProcessData.getInstance();
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
// HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA); //결번이후에 수신된 데이터 보관..
// if (block_data == null) {
// block_data = new HashMap();
// }
@SuppressWarnings("unchecked")
HashMap<Integer, String> miss_data = (HashMap<Integer, String>) hm.get(JobProcessData.PROCDATA_MISSDATA); //결번여부 저장..
if (miss_data == null) {
miss_data = new HashMap<Integer, String>();
}
@SuppressWarnings("unchecked")
HashMap<String, Integer> first_miss_field = (HashMap<String, Integer>) hm.get(JobProcessData.PROCDATA_FIRST_MISS); //첫번째 결번
@SuppressWarnings("unchecked")
HashMap<String, Integer> last_miss_field = (HashMap<String, Integer>) hm.get(JobProcessData.PROCDATA_LAST_MISS); //마지막 결번 위치 저장
int missCount = this.batchDoc.getBatchMsg().getBody().getMissingNmCount();
if (first_miss_field == null){
first_miss_field = new HashMap<String, Integer>();
first_miss_field.put(JobProcessData.PROCDATA_FIRST_MISS, new Integer(seq_no+1));
hm.put(JobProcessData.PROCDATA_FIRST_MISS, first_miss_field);
for (int i=seq_no; i<recv_seq_no; i++){//중간에 결번이 생긴 부분은 결번으로 셋팅
miss_data.put(new Integer(i), "0");
hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
last_miss_field = new HashMap<String, Integer>();
last_miss_field.put(JobProcessData.PROCDATA_LAST_MISS, new Integer(i));
hm.put(JobProcessData.PROCDATA_LAST_MISS, last_miss_field);
missCount = missCount+1;
}
this.batchDoc.getBatchMsg().getBody().setMissingNmCount(missCount);
} else { //이전에 miss_field가 있으면
for (int i=seq_no; i<recv_seq_no; i++){//중간에 결번이 생긴 부분은 결번으로 셋팅
miss_data.put(new Integer(i), "0");
hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
last_miss_field = new HashMap<String, Integer>();
last_miss_field.put(JobProcessData.PROCDATA_LAST_MISS, new Integer(i));
hm.put(JobProcessData.PROCDATA_LAST_MISS, last_miss_field);
missCount = missCount+1;
}
this.batchDoc.getBatchMsg().getBody().setMissingNmCount(missCount);
}
}
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,193 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.lang.String;
import java.util.HashMap;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BI0430 extends DefaultTelegram implements TelegramService
{
private int INFORMALFIELD_INDEX = 10;
private ByteArrayOutputStream bout;
/**
* 생성자
*/
public RECV_BI0430() {
// 결번확인지시
bout = new ByteArrayOutputStream();
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
String _missing_count = new String ((byte[]) al_Field.get(9));
String missing_field = bout.toString();
al_Field.set(INFORMALFIELD_INDEX, missing_field.getBytes());
int recv_migging_count = Integer.parseInt(_missing_count);
if (recv_migging_count == 0 ) {
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
JobProcessData job = JobProcessData.getInstance();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화
} else if (recv_migging_count > 0) {
this.setConditionTxt(TelegramKeys.LOSS);
}
this.batchDoc.getBatchMsg().getBody().setMissingNmCount(recv_migging_count);
this.batchDoc.getBatchMsg().getBody().setMissingNmField(missing_field);
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size()-1; i++) {//마지막 결번확인 부분은 로그로 남기지 않는다.
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
/**
* int getCalculatedLength(int idx)
* --------------------------------------------------------------------------------------
* 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다.
* 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다.
* SEND : 송신 길이 계산
* RECV : 수신 길이 계산
*/
public int getCalculatedLength(int idx) {
if (idx >= this.getFieldCount()) {
//logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
setConditionTxt(TelegramKeys.ERROR);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
String byte_size = new String ((byte[]) al_Field.get(8)); // 최종 seqquence-no가 결번확인 길이임.
logger.info("{"+logHeader+"} the sum of definite field length [" + byte_size + "]");
try {
return Integer.parseInt(byte_size);
} catch(Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e );
setConditionTxt(TelegramKeys.ERROR);
return -1;
}
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
setConditionTxt(TelegramKeys.ERROR);
return -1;
}
}
public boolean doInformalField(int idx, byte[] data, int length)
{
try {
if (idx == INFORMALFIELD_INDEX) {
logger.debug("{"+logHeader+"} 결번 데이터 : [" + new String(data) + "]");
bout.write(data, 0, length);
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
setConditionTxt(TelegramKeys.ERROR);
}
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI004";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
return true;
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,92 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.common.exception.ExceptionUtil;
public class RECV_BI0440 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BI0440() {
//화일송신완료지시
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,112 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.lang.String;
import java.io.ByteArrayOutputStream;
import java.io.File;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BI0450 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BI0450() {
//화일송신완료보고
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
String strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath();
String fileName = batchDoc.getBatchMsg().getHeader().getFileName();
String dirDelimiter = StringUtil.getDirDelimiter(strFullPathName);
strFullPathName = strFullPathName+dirDelimiter+fileName;
File rcvRealFile = null;
try {
rcvRealFile = new File( strFullPathName );
if (rcvRealFile.exists()) {
super.setFileHeaderAndTrailer(rcvRealFile);
}
} catch (Exception ex) {
batchDoc.getBatchMsg().getBody().setErrorMsg("해당경로에 파일이 존재하지 않습니다. - "+strFullPathName);
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR); //기타 에러 999
return false;
}
LogUtil.setLogFileEnd(batchDoc);
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,335 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.lang.String;
import java.util.HashMap;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BI0700 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
private int INFORMALFIELD_INDEX = 10;
private ByteArrayOutputStream bout;
private int recv_seq_no = 0;
private int seq_no = 0;
private File f;
private FileOutputStream fout;
public RECV_BI0700() {
//data 송신
bout = new ByteArrayOutputStream();
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
try {
String _seq_no = new String ((byte[]) al_Field.get(8));
recv_seq_no = Integer.parseInt(_seq_no);
seq_no = batchDoc.getBatchMsg().getBody().getSeqNum();
//지금까지 수신한 시퀀스의 크기가 현재 받은 시퀀스의 크기보다 크면 Error
if ((recv_seq_no - seq_no) < 0 ){
logger.debug("{"+logHeader+"} doExecute >> current seq_no is bigger than recived seq_no");
this.setConditionTxt(TelegramKeys.ERROR);
String[] msgArgs = new String[3];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = _seq_no;
msgArgs[2] = ""+seq_no;
String errCode = "BECEAIFJI024";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return false;
}
batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no);
return true;
} catch ( Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e );
this.setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
JobProcessData job = JobProcessData.getInstance();
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
@SuppressWarnings("unchecked")
HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>) hm.get(JobProcessData.PROCDATA_BLOCKDATA); //결번이후에 수신된 데이터 보관..
if (block_data == null) {
block_data = new HashMap<Integer, byte[]>();
}
@SuppressWarnings("unchecked")
HashMap<Integer, String> miss_data = (HashMap<Integer, String>) hm.get(JobProcessData.PROCDATA_MISSDATA); //결번여부 저장..
if (miss_data == null) {
miss_data = new HashMap<Integer, String>();
}
@SuppressWarnings("unchecked")
HashMap<String, Integer> first_miss_field = (HashMap<String, Integer>) hm.get(JobProcessData.PROCDATA_FIRST_MISS); //첫번째 결번
@SuppressWarnings("unchecked")
HashMap<String, Integer> last_miss_field = (HashMap<String, Integer>) hm.get(JobProcessData.PROCDATA_LAST_MISS); //마지막 결번 위치 저장
int missCount = this.batchDoc.getBatchMsg().getBody().getMissingNmCount();
if (first_miss_field == null){
if ((recv_seq_no - seq_no)==1){ //순차적인 seq를 수신하면.. 파일에 write
if (!createFile()) {
return false;
}
fout.write(bout.toByteArray());
miss_data.put(new Integer(recv_seq_no-1), "1");
hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
}else { //결번이 발생한 경우이면 메모리에 저장.
first_miss_field = new HashMap<String, Integer>();
first_miss_field.put(JobProcessData.PROCDATA_FIRST_MISS, new Integer(seq_no+1));
hm.put(JobProcessData.PROCDATA_FIRST_MISS, first_miss_field);
last_miss_field = new HashMap<String, Integer>();
last_miss_field.put(JobProcessData.PROCDATA_LAST_MISS, new Integer(seq_no+1));
hm.put(JobProcessData.PROCDATA_LAST_MISS, last_miss_field);
for (int i=seq_no+1; i<recv_seq_no; i++){//중간에 결번이 생긴 부분은 결번으로 셋팅
miss_data.put(new Integer(i-1), "0");
hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
missCount = missCount+1;
}
this.batchDoc.getBatchMsg().getBody().setMissingNmCount(missCount);
block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray());
hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);
miss_data.put(new Integer(recv_seq_no-1), "1");
hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
}
} else { //이전에 miss_field가 있으면 현재 수신한 seq에 data set
for (int i=seq_no+1; i<recv_seq_no; i++){//중간에 결번이 생긴 부분은 결번으로 셋팅
miss_data.put(new Integer(i-1), "0");
hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
missCount = missCount+1;
}
this.batchDoc.getBatchMsg().getBody().setMissingNmCount(missCount);
block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray());
hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);
miss_data.put(new Integer(recv_seq_no-1), "1");
hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
}
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
if (fout != null) {
fout.close();
}
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
this.setConditionTxt(TelegramKeys.ERROR);
return false;
}finally{
try{
if (fout != null) {
fout.close();
}
}catch(Exception e){
}
}
}
/**
* int getCalculatedLength(int idx)
* --------------------------------------------------------------------------------------
* 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다.
* 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다.
* SEND : 송신 길이 계산
* RECV : 수신 길이 계산
*/
public int getCalculatedLength(int idx) {
if (idx >= this.getFieldCount()) {
logger.debug("{"+logHeader+"} getCalculatedLength> parameter is bigger than field count");
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
this.setConditionTxt(TelegramKeys.ERROR);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
String byte_size = new String ((byte[]) al_Field.get(9)); //실 DATA Byte수
logger.info("{"+logHeader+"} the sum of definite field length [" + byte_size + "]");
try {
return Integer.parseInt(byte_size);
} catch(Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e );
this.setConditionTxt(TelegramKeys.ERROR);
return -1;
}
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
this.setConditionTxt(TelegramKeys.ERROR);
return -1;
}
}
public boolean doInformalField(int idx, byte[] data, int length)
{
try {
if (idx == INFORMALFIELD_INDEX) {
bout.write(data, 0, length);
//전송상태처리
long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+length;
batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize);
} else {
logger.debug("{"+logHeader+"} doInformalField >> index of informal action error : " + idx);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
this.setConditionTxt(TelegramKeys.ERROR);
return false;
}
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI004";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex );
this.setConditionTxt(TelegramKeys.ERROR);
return false;
}
return true;
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
private boolean createFile () {
try {
String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath();
if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) {
strFullPath = strFullPath + File.separator;
}
strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName();
logger.info("{"+logHeader+"} getCalculatedLength >> File full-path [" + strFullPath + "]");
f = new File(strFullPath);
fout = new FileOutputStream(f, true); //bytes will be written to the end of the file rather than the beginning
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI028";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e );
this.setConditionTxt(TelegramKeys.ERROR);
return false;
}
return true;
}
}
@@ -0,0 +1,316 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.lang.String;
import java.util.HashMap;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BI0710 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
private int INFORMALFIELD_INDEX = 10;
private int recv_seq_no;
private ByteArrayOutputStream bout;
private File f;
private FileOutputStream fout;
public RECV_BI0710() {
//data 송신
bout = new ByteArrayOutputStream();
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
try {
String _seq_no = new String ((byte[]) al_Field.get(8));
recv_seq_no = Integer.parseInt(_seq_no);
return true;
} catch ( Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e );
return false;
}
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
JobProcessData job = JobProcessData.getInstance();
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
@SuppressWarnings("unchecked")
HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>)hm.get(JobProcessData.PROCDATA_BLOCKDATA);
if (block_data == null ){
block_data = new HashMap<Integer, byte[]>();
}
@SuppressWarnings("unchecked")
HashMap<Integer, String> miss_data = (HashMap<Integer, String>) hm.get(JobProcessData.PROCDATA_MISSDATA); //결번여부 저장..
if (miss_data == null) {
miss_data = new HashMap<Integer, String>();
}
@SuppressWarnings("unchecked")
HashMap<String, Integer> last_miss_field = (HashMap<String, Integer>) hm.get(JobProcessData.PROCDATA_LAST_MISS); //마지막 결번 위치 저장
@SuppressWarnings("unchecked")
HashMap<String, Integer> first_miss_field = (HashMap<String, Integer>) hm.get(JobProcessData.PROCDATA_FIRST_MISS); //첫번째 결번
Integer firstMiss = (Integer) first_miss_field.get(JobProcessData.PROCDATA_FIRST_MISS);
int missingCount = batchDoc.getBatchMsg().getBody().getMissingNmCount();
logger.info("{"+logHeader+"} doPostExecute> RECV recv_seq_no [" + recv_seq_no + "] ");
byte[] _missing_field = new byte[miss_data.size()];
for (int j = 0; j<miss_data.size(); j++) { //받은 seq_no만큼만 데이터 확인
String field = (String) miss_data.get( new Integer(j) );
_missing_field[j] = field.getBytes()[0]; //결번이 발생한 seq만 '0' 설정
if ((recv_seq_no-1) == j && _missing_field[j] == '0' ){
_missing_field[recv_seq_no-1] = '1';
missingCount -= 1;
miss_data.put(new Integer(j), "1");
hm.put(JobProcessData.PROCDATA_MISSDATA, miss_data);
}
}
batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing_field));
batchDoc.getBatchMsg().getBody().setMissingNmCount(missingCount);
if (firstMiss != null && firstMiss.intValue() == recv_seq_no){//첫번째 결번 필드와 현재 수신된 seq가 같으면.. file write
if (!createFile()) {
return false;
}
fout.write(bout.toByteArray());
hm.put(JobProcessData.PROCDATA_FIRST_MISS, null );
for (int i =0; i < _missing_field.length; i++){
if (_missing_field[i]=='0'){
first_miss_field.put(JobProcessData.PROCDATA_FIRST_MISS, new Integer(i+1)); // 첫번째 결번
hm.put(JobProcessData.PROCDATA_FIRST_MISS, first_miss_field );
last_miss_field = new HashMap<String, Integer>();
last_miss_field.put(JobProcessData.PROCDATA_LAST_MISS, new Integer(i+1));
hm.put(JobProcessData.PROCDATA_LAST_MISS, last_miss_field);
for (int n = recv_seq_no; n<i; n++){//현재 받은 결번 데이터와 다음 결번 사이에 seq data를 write한다.
byte[] data = (byte[]) block_data.get(new Integer(n));
fout.write(data);
block_data.remove(new Integer(n));
}
break;
}
}
}else {//같지 않으면 메모리에 저장..
logger.info("{} doInformalField >> missing telegram receive : [" + (recv_seq_no-1) + "]", logHeader);
if (block_data.get(new Integer(recv_seq_no-1)) == null) {
block_data.put(new Integer(recv_seq_no-1), bout.toByteArray());
hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);
}
}
logger.info("{} doPostExecute> RECV missing telegram [" + recv_seq_no + "] missing field - [" + new String(_missing_field), logHeader);
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
if (fout != null) {
fout.close();
}
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}finally{
try{
if (fout != null) {
fout.close();
}
}catch(Exception e){
}
}
}
/**
* int getCalculatedLength(int idx)
* --------------------------------------------------------------------------------------
* 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다.
* 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다.
* SEND : 송신 길이 계산
* RECV : 수신 길이 계산
*/
public int getCalculatedLength(int idx) {
if (idx >= this.getFieldCount()) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
String byte_size = new String ((byte[]) al_Field.get(9)); //실 DATA Byte수
logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader);
try {
return Integer.parseInt(byte_size);
} catch(Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
}
public boolean doInformalField(int idx, byte[] data, int length)
{
try {
if (idx == INFORMALFIELD_INDEX) {
bout.write(data, 0, length);
//전송상태처리
long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+length;
batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize);
} else {
logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return false;
}
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI004";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
return true;
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
private boolean createFile () {
try {
String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath();
if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) {
strFullPath = strFullPath + File.separator;
}
strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName();
logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader);
f = new File(strFullPath);
fout = new FileOutputStream(f, true); //bytes will be written to the end of the file rather than the beginning
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI028";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e );
return false;
}
return true;
}
}
@@ -0,0 +1,319 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager;
import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO;
import com.eactive.eai.common.exception.ExceptionUtil;
/**
* TSEAIBR03 의 각 노드 정보에 지정되는 클래스 이다.
* RECV 액션을 수행하는 노드에 대해, 해당 노드에서 수행할 전문수신작업의 수신길이를 결정하기 위해 사용된다.
*/
public class RECV_BILLIMG extends DefaultTelegram implements TelegramService
{
private final int MAX_TCP_BYTES = 8232; //업무구분코드 이후의 송신할 전문길이의 최대값은 8232 BYTES이다.
private Properties telegramInfo;
/**
* 생성자 : 어음이미지 길이 결정용 텔레그램 클래스 이다.
*/
public RECV_BILLIMG() {
}
public boolean doValidation()
{
if (!super.doValidation()) return false;
try {
int currFiledIndex = 0;
String currFieldValue = "";
//1. 어음이미지수신 전문의 전문필드 개수 체크
logger.info("{} >>>>> 수신 전문의 전문필드 개수 Checking......", logHeader);
if (al_FieldProps == null || al_Field == null || al_FieldProps.length != al_Field.size()) {
String errMsg = "전문필드 값 Validation 체크를 위한 데이터 불량.";
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FORMAT_ERROR);
super.setConditionTxt(TelegramKeys.ERROR);
return false;
}
//2. 어음이미지수신 전문의 전체 전문필드 타입 체크
logger.info("{} >>>>> 수신 전문의 전체 전문필드 타입 Checking......", logHeader);
for(int i=1; i<al_Field.size(); i++) { //트랜잭션 코드는 확인하지 않음..
if ( !this.checkType(al_FieldProps[i], new String((byte[])al_Field.get(i))) ) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIMTM010", new String[] {al_FieldNames[i], (i+1)+"", new String((byte[])al_Field.get(i)), al_FieldProps[i]});
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 정의된 타입 '{4}' 에 맞지 않습니다.
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FORMAT_ERROR);
super.setConditionTxt(TelegramKeys.ERROR);
return false;
}
}
logger.info("{} >>>>> TCP/IP 전문 송신 BYTE 수 Checking......", logHeader);
String tcpBytes = new String ((byte[]) al_Field.get(1));
try{
int bytes = Integer.parseInt(tcpBytes);
if (bytes > MAX_TCP_BYTES){
String errMsg = "TCPIP 전문 송신 BYTES는 8232 를 초과할 수 없습니다. - ["+bytes+"]";
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_BYTE_ERROR);
super.setConditionTxt(TelegramKeys.ERROR);
return false;
}
}catch (NumberFormatException ne){
logger.error( ne.getMessage(), ne);
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_BYTE_ERROR);
super.setConditionTxt(TelegramKeys.ERROR);
return false;
}
logger.info("{} >>>>> 업무구분코드 Checking......", logHeader);
currFiledIndex = 2;
currFieldValue = new String((byte[])al_Field.get(currFiledIndex));
if (!currFieldValue.equals(telegramInfo.getProperty(TelegramKeys.BIZ_GBN))) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR006", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue, telegramInfo.getProperty(TelegramKeys.BIZ_GBN)});
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 이 아닙니다.
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FORMAT_ERROR);
super.setConditionTxt(TelegramKeys.ERROR);
return false;
}
logger.info("{} >>>>> 거래구분코드 Checking......", logHeader);
currFiledIndex = 4;
currFieldValue = new String((byte[])al_Field.get(currFiledIndex));
if (!(currFieldValue.equals(TelegramKeys.BI_TR_CLASS_RECV)
|| currFieldValue.equals(TelegramKeys.BI_TR_CLASS_SEND))) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR007", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue,
TelegramKeys.BI_TR_CLASS_RECV, TelegramKeys.BI_TR_CLASS_SEND});
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 값들 중 하나이어야 합니다.
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FORMAT_ERROR);
super.setConditionTxt(TelegramKeys.ERROR);
return false;
}
logger.info("{} >>>>> 송수신 FLAG Checking......", logHeader);
currFiledIndex = 5;
currFieldValue = new String((byte[])al_Field.get(currFiledIndex));
if (!(currFieldValue.equals(telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK))
|| currFieldValue.equals(telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER)))) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIFAR007", new String[] {al_FieldNames[currFiledIndex], (currFiledIndex+1)+"", currFieldValue,
telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), telegramInfo.getProperty(TelegramKeys.TRA_FLAG_CENTER)});
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신전문의 {1} 필드(Index:{2}) 값 '{3}' 이 '{4}' 값들 중 하나이어야 합니다.
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_FORMAT_ERROR);
super.setConditionTxt(TelegramKeys.ERROR);
return false;
}
logger.info("{} >>>>> 응답코드 Checking......", logHeader);
currFiledIndex = 7;
currFieldValue = new String((byte[])al_Field.get(currFiledIndex));
if (!(currFieldValue.equals(TelegramKeys.BI_RES_CODE_SUCESS) || currFieldValue.equals(TelegramKeys.BI_RES_CODE_ALREADY_RECEIVED))) {
String errMsg = "정상거래 응답코드를 수신하지 못했습니다. 수신된 응답코드 ["+currFieldValue+"]-"+TelegramKeys.getBiImgRetDescription(currFieldValue);
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR);
super.setConditionTxt(TelegramKeys.ERROR);
return false;
}
}catch (Exception e){
logger.error( e.getMessage(), e);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(e.toString());
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR);
super.setConditionTxt(TelegramKeys.ERROR);
return false;
}
return true;
}
public boolean doExecute() {
return true;
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
/**
* 20060417 add by khs : 원치 않는 전문종별 도착시, 소켓에 있는 garvage 데이터를 없애기 위해 사용한다.
*
* return value : <0 계산 할 수 없거나 장애이다.
* >0 해당 데이터를 소켓에서 더 읽어들인다.
*/
public int getRemainDataLength()
{
try {
int idx;
String strLength;
String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode();
String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode();
NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode);
idx = vo.getLengthField();
if (idx == 0) return -1;
strLength = new String((byte[])this.al_Field.get(idx-1));
int nDocLen = Integer.parseInt(strLength);
int nReceivedLen = 0;
for (int i=2; i<this.al_FieldLength.length ; i++) {
nReceivedLen = nReceivedLen + Integer.parseInt(this.al_FieldLength[i]);
}
return (nDocLen-nReceivedLen);
} catch (Exception ex) {
this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString());
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
this.setConditionTxt(TelegramKeys.ERROR);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
this.setConditionTxt(TelegramKeys.ERROR);
return -1;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
this.setConditionTxt(TelegramKeys.ERROR);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
default:
break;
}
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
this.setConditionTxt(TelegramKeys.ERROR);
return -1;
}
}
}
@@ -0,0 +1,292 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.encrypt.EncryptManager;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0200 extends DefaultTelegram implements TelegramService
{
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BI0200() {
//업무개시요구 및 업무개시통보
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, " ", this.al_FieldProps[6]);
//응답코드
compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]);
//전문 전송 일시 (MMddhhmmss)
compileField(8, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[8]);
//송신자명 (어음이미지시스템의 책임자 ID)
compileField(9, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[9]);
//송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호
//compileField(10, batchDoc.getEAIBatchMessage().getHeader().getUserPassword(), this.al_FieldProps[10]);
String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE);
if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) {
//전송자명은 앞에서 8자리이며 8자리 미만은 Z로 채움..
String passwd = EncryptManager.getInstance().getEncryptPwd((batchDoc.getBatchMsg().getHeader().getUserID()+"ZZZZZZZ").substring(0,8),
(batchDoc.getBatchMsg().getHeader().getUserPassword() + "ZZZZZZ").substring(0,6),
telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1,3),
TelegramKeys.getYYYYMMddHHmmss().substring(2,8));
compileField(10, passwd, this.al_FieldProps[10]);
logger.debug("{} SEND_BI0200 ] PASSWD : "+passwd, logHeader);
}else{
compileField(10, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[10]);
}
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH; //실 DATA BYTE수
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
default:
break;
}
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,333 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0210 extends DefaultTelegram implements TelegramService
{
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BI0210() {
//업무개시통보
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
// if (CommonKeys.PROCESS_RESPONSE_SEND.equalsIgnoreCase(this.batchDoc.getBatchMsg().getHeader().getProcessType())){
// // 응답송신 이면
// String strPathName = BatchDirUtil.getResSendRealDir();
// if ( strPathName.charAt(strPathName.length()-1) != '/' ) {
// strPathName = strPathName + '/';
// }
//
// BatchTargetVO btVO = FlowControllerManager.getInstance().getBatchTargetInfo(this.batchDoc.getBatchMsg().getHeader().getProcessCode(), this.batchDoc.getBatchMsg().getHeader().getInstitutionCode());
// StringBuffer sb = new StringBuffer();
//
// sb.append(btVO.getProcessCode());
// sb.append("/");
// sb.append(btVO.getOrganCode());
// strPathName = strPathName + sb.toString();
// Logging(INFO, "[응답송신] PATH NAME = [" + strPathName + "]");
//
// File ff = new File(strPathName);
// if (!ff.exists()) {
// Logging(WARN, "응답송신용 디렉토리 [" + strPathName + "] 이 없습니다.");
// String[] msgArgs = new String [2];
// msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
// msgArgs[1] = ff.getName();
// String errCode = "BECEAIFJI022";
// String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
// this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
// return false;
// }
// File[] fileList = ff.listFiles();
// String strFileName = "";
// this.setConditionTxt(TelegramKeys.NOFILE);
// if (fileList.length> 0) {
// for (int i1=0; i1<fileList.length; i1++) {
// if ( fileList[i1].isFile()) {
// strFileName = fileList[i1].getName();
// break;
// }
// }
//
// if ( !strFileName.equals("")){
// this.setConditionTxt("");
// batchDoc.getBatchMsg().getHeader().setFilePath(strPathName);
// batchDoc.getBatchMsg().getHeader().setFileName(strFileName);
// batchDoc.getBatchMsg().getHeader().setRenamedFileName(strFileName);
// File logFile = new File(strPathName+'/'+strFileName);
// if (logFile.exists()) {
// logger.info("{} FILE SIZE ("+ logFile.length() + "]", logHeader);
// //DB로그에 남길 파일 헤더,트레일러 내용 설정
// super.setFileHeaderAndTrailer(logFile);
// }
// }
// }
//
// }
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, " ", this.al_FieldProps[6]);
//응답코드
compileField(7, super.getSendResponseCode(), this.al_FieldProps[7]);
//전문 전송 일시 (MMddhhmmss)
compileField(8, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[8]);
//송신자명 (어음이미지시스템의 책임자 ID)
compileField(9, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[9]);
//송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호
compileField(10, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[10]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH; //실 DATA BYTE수
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
default:
break;
}
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,293 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.encrypt.EncryptManager;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0220 extends DefaultTelegram implements TelegramService
{
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BI0220() {
//업무종료지시
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, " ", this.al_FieldProps[6]);
//응답코드
compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]);
//전문 전송 일시 (MMddhhmmss)
compileField(8, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[8]);
//송신자명 (어음이미지시스템의 책임자 ID)
compileField(9, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[9]);
//송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호
//compileField(10, batchDoc.getEAIBatchMessage().getHeader().getUserPassword(), this.al_FieldProps[10]);
String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE);
if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) {
//전송자명은 앞에서 8자리이며 8자리 미만은 Z로 채움..
String passwd = EncryptManager.getInstance().getEncryptPwd((batchDoc.getBatchMsg().getHeader().getUserID()+"ZZZZZZZ").substring(0,8),
(batchDoc.getBatchMsg().getHeader().getUserPassword() + "ZZZZZZ").substring(0,6),
telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1,3),
TelegramKeys.getYYYYMMddHHmmss().substring(2,8));
compileField(10, passwd, this.al_FieldProps[10]);
logger.debug("{} SEND_BI0220 ] PASSWD : "+passwd, logHeader);
}else{
compileField(10, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[10]);
}
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH; //실 DATA BYTE수
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
default:
break;
}
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,294 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.encrypt.EncryptManager;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0230 extends DefaultTelegram implements TelegramService
{
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BI0230() {
//업무종료보고
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, " ", this.al_FieldProps[6]);
//응답코드
compileField(7, super.getSendResponseCode(), this.al_FieldProps[7]);
//전문 전송 일시 (MMddhhmmss)
compileField(8, TelegramKeys.getMMddHHmmss(), this.al_FieldProps[8]);
//송신자명 (어음이미지시스템의 책임자 ID)
compileField(9, batchDoc.getBatchMsg().getHeader().getUserID(), this.al_FieldProps[9]);
//송신자 암호 (정당한 송신자 확인을 위한 쌍방간 합의된 암호
//compileField(10, batchDoc.getEAIBatchMessage().getHeader().getUserPassword(), this.al_FieldProps[10]);
String cypherYn = telegramInfo.getProperty(TelegramKeys.CMS_CIPHER_USE);
if (( cypherYn != null) &&cypherYn.equalsIgnoreCase("Y") ) {
//전송자명은 앞에서 8자리이며 8자리 미만은 Z로 채움..
String passwd = EncryptManager.getInstance().getEncryptPwd((batchDoc.getBatchMsg().getHeader().getUserID()+"ZZZZZZZ").substring(0,8),
(batchDoc.getBatchMsg().getHeader().getUserPassword() + "ZZZZZZ").substring(0,6),
telegramInfo.getProperty(TelegramKeys.BANK_CODE).substring(1,3),
TelegramKeys.getYYYYMMddHHmmss().substring(2,8));
compileField(10, passwd, this.al_FieldProps[10]);
logger.debug("{} SEND_BI0230 ] PASSWD : "+passwd, logHeader);
}else{
compileField(10, batchDoc.getBatchMsg().getHeader().getUserPassword(), this.al_FieldProps[10]);
}
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH; //실 DATA BYTE수
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
default:
break;
}
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,339 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.running.BatchOpenFileManager;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0400 extends DefaultTelegram implements TelegramService
{
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private Properties telegramInfo;
private BufferedInputStream bis;
/**
* 생성자
*/
public SEND_BI0400() {
//화일정보수신지시
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]);
//응답코드
compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]);
//화일 사이즈
compileField(8, ""+calculateFileSize(), this.al_FieldProps[8]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
private long calculateFileSize () {
createFile();
long length = this.batchDoc.getBatchMsg().getHeader().getFileSize();
if (length < 0) {
return 0;
}
return length;
}
private void createFile ()
{
try {
String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath();
String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName();
if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) {
fileDir = fileDir + File.separator;
}
String fileName = fileDir + fileNm;
File file = new File(fileName);
if (!file.exists()) // 파일이 없으면 리턴 False
{
logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = fileName;
String errCode = "BECEAIFJI022";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
}
bis = new BufferedInputStream (new FileInputStream (file));
if (bis == null){
logger.debug("{} the File["+fileDir+"/"+file.getName()+"] 을 읽기 위한 객체 생성에 실패했습니다.", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = fileName;
String errCode = "BECEAIFJI022";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
}
//BatchOpenFileManager.getInstance().addFbr(batchDoc.getEAIBatchMessage().getHeader().getUUID() , fileName, fbr);
BatchOpenFileManager.getInstance().addBis(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, bis);
this.batchDoc.getBatchMsg().getHeader().setFileSize(file.length());
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI028";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
}
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
default:
break;
}
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,282 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0410 extends DefaultTelegram implements TelegramService
{
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BI0410() {
//화일정보수신보고
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]);
//응답코드
compileField(7, super.getSendResponseCode(), this.al_FieldProps[7]);
//화일 사이즈 - RECV_BI0400에서 계산된 현재 화일 크기를 설정한다..
compileField(8, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[8]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
//수신 파일 Start DB로그
LogUtil.setLogFileStart(batchDoc);
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
default:
break;
}
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,280 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0420 extends DefaultTelegram implements TelegramService
{
private int SEQUENCE_NO;
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BI0420() {
//결번확인지시
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum();
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]);
//응답코드
compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]);
//최종 SEQUENCE-NO
compileField(8, ""+SEQUENCE_NO, this.al_FieldProps[8]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH; //실 DATA BYTE수
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
default:
break;
}
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,416 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0430 extends DefaultTelegram implements TelegramService
{
private int SEQUENCE_NO;
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private int MISSING_COUNT; //결번갯수
private String MISSING_FIELD;
private File f;
private FileOutputStream fout;
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BI0430() {
//결번확인지시
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
SEQUENCE_NO = this.batchDoc.getBatchMsg().getBody().getSeqNum();
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]);
//응답코드
compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]);
//최종 SEQUENCE-NO
compileField(8, ""+SEQUENCE_NO, this.al_FieldProps[8]);
//결번갯수
compileField(9, ""+MISSING_COUNT, this.al_FieldProps[9]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH; //실 DATA BYTE수
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
boolean result = calculateMissingCount();
if (!result) return false;
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
if (MISSING_COUNT==0 && fout != null) {
fout.close();
}
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< (this.al_Field.size()-1); i++) { //마지막은 비정형 필드이므로 제외
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
SEND_LENGTH += MISSING_FIELD.length(); //비정형 필드인 결번확인의 길이 더함.
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0); //트랜잭션코드의 길이를 더함.
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
private boolean calculateMissingCount () {
try {
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum();
JobProcessData job = JobProcessData.getInstance();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
@SuppressWarnings("unchecked")
HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>)hm.get(JobProcessData.PROCDATA_BLOCKDATA);
@SuppressWarnings("unchecked")
HashMap<Integer, String> miss_data = (HashMap<Integer, String>) hm.get(JobProcessData.PROCDATA_MISSDATA); //결번여부 저장..
@SuppressWarnings("unchecked")
HashMap<String, Integer> last_miss_field = (HashMap<String, Integer>)hm.get(JobProcessData.PROCDATA_LAST_MISS);
MISSING_COUNT = this.batchDoc.getBatchMsg().getBody().getMissingNmCount();
if (seq_no==miss_data.size()){
byte[] _missingNm = new byte[seq_no];
if (block_data == null ){//block_data는 결번이 발생할 경우에만 저장하므로, null이면 결번없음.
for (int n = 0; n<seq_no; n++){
_missingNm[n] = '1';
}
} else {
for (int j = 0; j<seq_no; j++) { //받은 seq_no만큼만 데이터 확인
String field = miss_data.get( new Integer(j) );
_missingNm[j] = field.getBytes()[0]; //결번이 발생한 seq만 '0' 설정
}
if (MISSING_COUNT == 0) {
if (!createFile()) {
return false;
}
Integer lastMiss = last_miss_field.get(JobProcessData.PROCDATA_LAST_MISS);
for (int i = lastMiss.intValue(); i<seq_no; i++) { //결번이후 메모리에 저장한 데이터 기록
byte[] data = (byte[]) block_data.get(new Integer(i));
fout.write(data);
}
hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); //데이터 기록후 Vector 초기화
}
}
this.MISSING_FIELD = new String (_missingNm);
this.batchDoc.getBatchMsg().getBody().setMissingNmCount(MISSING_COUNT);
this.batchDoc.getBatchMsg().getBody().setMissingNmField(MISSING_FIELD);
}else {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errMsg = "최종 수신된 SEQUENCE NO와 결번 데이터 크기가 일치하지 않습니다. seq_no/miss_data.size - ["+seq_no+"/"+miss_data.size()+"]";
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return false;
}
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI027";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}finally{
try{
if (fout != null) {
fout.close();
}
}catch(Exception e){
}
}
return true;
}
private boolean createFile () {
try {
String strFullPath = batchDoc.getBatchMsg().getHeader().getFilePath();
if (strFullPath.charAt(strFullPath.length()-1) != File.separatorChar) {
strFullPath = strFullPath + File.separator;
}
strFullPath = strFullPath + batchDoc.getBatchMsg().getHeader().getFileName();
logger.info("{} getCalculatedLength >> File full-path [" + strFullPath + "]", logHeader);
f = new File(strFullPath);
fout = new FileOutputStream(f, true); //bytes will be written to the end of the file rather than the beginning
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI028";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
case 10:
return MISSING_FIELD.length();
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
case 10:
//mod by khs data = MISSING_FIELD.getBytes();
ByteArrayInputStream bin = new ByteArrayInputStream(MISSING_FIELD.getBytes());
bin.read(data, 0, MISSING_FIELD.length());
return MISSING_FIELD.length();
default:
break;
}
// 로깅을 위해
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,278 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0440 extends DefaultTelegram implements TelegramService
{
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BI0440() {
// 화일송신완료지시
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]);
//응답코드
compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]);
//화일 사이즈
compileField(8, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[8]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
default:
break;
}
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,347 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0450 extends DefaultTelegram implements TelegramService
{
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private Properties telegramInfo;
private File rcvRealFile = null;
/**
* 생성자
*/
public SEND_BI0450() {
// 화일송신완료보고
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]);
//응답코드
compileField(7, super.getSendResponseCode(), this.al_FieldProps[7]);
//화일 사이즈
compileField(8, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[8]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지전문의 헤더는 응답코드까지 임.
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
String strFullPathName = batchDoc.getBatchMsg().getHeader().getFilePath();
String fileName = batchDoc.getBatchMsg().getHeader().getFileName();
String dirDelimiter = StringUtil.getDirDelimiter(strFullPathName);
strFullPathName = strFullPathName+dirDelimiter+fileName;
rcvRealFile = new File( strFullPathName ); //응답수신_Real 또는 응답송신_Real 디렉토리
try {
//수신 파일 (Real 디렉토리)
if (rcvRealFile.exists()) {
//DB로그에 남길 파일 사이즈 설정
//batchDoc.getEAIBatchMessage().getHeader().setFileSize(rcvRealFile.length());
//DB로그에 남길 파일 헤더,트레일러 내용 설정
super.setFileHeaderAndTrailer(rcvRealFile);
//수신 파일 End DB로그
LogUtil.setLogFileEnd(batchDoc);
//수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동 (파일명 변경 안함)
logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Arch 디렉토리로 이동.....", logHeader);
File rcvRootFile = new File( StringUtil.realToRootDir(strFullPathName) );
File rcvArchFile = new File( StringUtil.realToArchDir(strFullPathName) );
File rcvErrorFile = new File( StringUtil.realToErrorDir(strFullPathName) );
boolean isSuccessMoveFile = rcvRealFile.renameTo(rcvArchFile);
if (!isSuccessMoveFile) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI030", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()});
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Arch 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Arch Path: {2}]
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR);
return false;
}
if ( !super.getResolveResponseCode().equals(TelegramKeys.BI_RES_CODE_SUCESS) ) {
//수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동 (파일명 변경 안함)
logger.info("{} >>>>> 수신 파일을 수신 Real 디렉토리 -> 수신 Error 디렉토리로 이동.....", logHeader);
isSuccessMoveFile = rcvRealFile.renameTo(rcvErrorFile);
if (!isSuccessMoveFile) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI042", new String[] {rcvRealFile.getAbsolutePath(), rcvArchFile.getAbsolutePath()});
if (!batchDoc.getBatchMsg().getBody().getErrorMsg().equals("")) {
errMsg += "\n] caused by..." + batchDoc.getBatchMsg().getBody().getErrorMsg();
}
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 파일을 수신 Real 디렉토리에서 수신 Error 디렉로 이동시 오류가 발생하였습니다. [Real Path: {1}] [Error Path: {2}]
}
return false;
}
logger.info("{} >>>>> 수신 파일과 동일 파일명의 0 Byte 파일을 Root 디렉토리에 생성......(방카슈랑스 서버에 자동 송신하도록 수신 File Event 발생)", logHeader);
isSuccessMoveFile = rcvRootFile.createNewFile();
if (!isSuccessMoveFile) {
String errMsg = ExceptionUtil.getErrorCode("BECEAIFJI031", new String[] {rcvRootFile.getAbsolutePath()});
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}]
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR);//기타 에러 999
return false;
}
}
} catch (Exception ex) {
String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIFJI031", new String[] { StringUtil.realToRootDir(strFullPathName) });
batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg); //수신 Root 디렉토리에 0 Byte 파일을 생성할 수 없습니다. [Path: {1}]
super.setResolveResponseCode(TelegramKeys.BI_RES_CODE_ETC_ERROR); //기타 에러 999
return false;
}
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
default:
break;
}
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,455 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.running.BatchOpenFileManager;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0700 extends DefaultTelegram implements TelegramService
{
private BufferedInputStream bis;
private int SEQUENCE_NO;
private int REAL_BYTE; // 실 data byte수
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private Properties telegramInfo;
private byte[] fileData;
/**
* 생성자
*/
public SEND_BI0700() {
//data송신
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = setBlockAndSeqNO();
if (!result) {
return false;
}
result = calculateSendLength();
if (!result) return false;
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]);
//응답코드
compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]);
//SEQUENCE-NO
compileField(8, ""+SEQUENCE_NO, this.al_FieldProps[8]);
//실 data byte수
compileField(9, ""+REAL_BYTE, this.al_FieldProps[9]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH; //실 DATA BYTE수
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
case 10:
return REAL_BYTE;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< (this.al_Field.size()-1); i++) { //마지막 필드는 비정형 필드이므로 제외 시킴.
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
SEND_LENGTH = SEND_LENGTH + REAL_BYTE;
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (data.length < REAL_BYTE) {
logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI014";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
break;
case 10:
ByteArrayInputStream bin = new ByteArrayInputStream(fileData);
bin.read(data, 0, REAL_BYTE);
// 20060419 add by khs for 전송상태 확인
long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE ;
batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize);
logger.debug("lnCurSize-->" + lnCurSize);
break;
default:
break;
}
return fldLen;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
private boolean setBlockAndSeqNO ()
{
try {
if (!createFile()) {
logger.error("{} file open failed", logHeader);
return false;
}
int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum();
this.batchDoc.getBatchMsg().getHeader().getRecLen();
this.SEQUENCE_NO = seq_no+1;
this.setConditionTxt("");
// for 결번 테스트 -- start
/*
if (SEQUENCE_NO==4 || SEQUENCE_NO==14 || SEQUENCE_NO==24){
// for 결번 테스트
//seq_no 4의 데이터 값 설정..
int seq_size = this.batchDoc.getEAIBatchMessage().getHeader().getSequenceSize();
StringBuffer seqBuffer = new StringBuffer();
long curLength = batchDoc.getEAIBatchMessage().getBody().getCurFileSize();
long fileLength = batchDoc.getEAIBatchMessage().getHeader().getFileSize();
int readBufferSize = seq_size;
if (seq_size > (fileLength - curLength) ){
readBufferSize = (int)(fileLength - curLength);
}
fileData = new byte[readBufferSize];
REAL_BYTE = bis.read(fileData);
// 파일을 다 읽었으면...
if ( curLength + REAL_BYTE >= fileLength) {
this.setConditionTxt(TelegramKeys.EOF);
bis.close();
BatchOpenFileManager.getInstance().removeBis(batchDoc.getEAIBatchMessage().getHeader().getUUID());
}
// 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다.
JobProcessData job = JobProcessData.getInstance();
String uuid = this.batchDoc.getEAIBatchMessage().getHeader().getUUID();
HashMap hm = job.getBatchStageData(uuid);
HashMap block_data = (HashMap) hm.get(JobProcessData.PROCDATA_BLOCKDATA);
if (block_data == null) {
block_data = new HashMap();
}
block_data.put( new Integer(SEQUENCE_NO-1) , fileData);
hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);
this.batchDoc.getEAIBatchMessage().getBody().setSeqNum(SEQUENCE_NO);
long lnCurSize = batchDoc.getEAIBatchMessage().getBody().getCurFileSize() + REAL_BYTE ;
batchDoc.getEAIBatchMessage().getBody().setCurFileSize(lnCurSize);
this.SEQUENCE_NO = this.batchDoc.getEAIBatchMessage().getBody().getSeqNum()+1;
this.setConditionTxt("");
}*/
// for 결번 테스트 - end
int seq_size = this.batchDoc.getBatchMsg().getHeader().getSequenceSize();
// StringBuffer seqBuffer = new StringBuffer();
long curLength = batchDoc.getBatchMsg().getBody().getCurFileSize();
long fileLength = batchDoc.getBatchMsg().getHeader().getFileSize();
int readBufferSize = seq_size;
if (seq_size > (fileLength - curLength) ){
readBufferSize = (int)(fileLength - curLength);
}
fileData = new byte[readBufferSize];
REAL_BYTE = bis.read(fileData);
// 파일을 다 읽었으면...
if ( curLength + REAL_BYTE >= fileLength) {
this.setConditionTxt(TelegramKeys.EOF);
bis.close();
BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID());
}
// 파일에서 읽은 DATA를 추후 결번 재전송을 위해 메모리에 저장해 둔다.
JobProcessData job = JobProcessData.getInstance();
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
@SuppressWarnings("unchecked")
HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>) hm.get(JobProcessData.PROCDATA_BLOCKDATA);
if (block_data == null) {
block_data = new HashMap<Integer, byte[]>();
}
block_data.put( new Integer(SEQUENCE_NO-1) , fileData);
hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);
this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO);
return true;
} catch (Exception e ) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI029";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
private boolean createFile ()
{
try {
bis = BatchOpenFileManager.getInstance().getBis(batchDoc.getBatchMsg().getHeader().getUUID() );
if (bis == null){
logger.warn("FILE정보가 NULL입니다.");
return false;
}
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI028";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,360 @@
package com.eactive.eai.batch.job.jobItem.billimg;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BI0710 extends DefaultTelegram implements TelegramService
{
private int SEQUENCE_NO;
private int REAL_BYTE; // 실 data byte수
private int SEND_LENGTH; //TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이
private Properties telegramInfo;
private byte[] fileData;
/**
* 생성자
*/
public SEND_BI0710() {
//data송신
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = setBlockAndSeqNO();
if (!result) {
return false;
}
result = calculateSendLength();
if (!result) return false;
// TRANSACTION CODE로 은행에서 필요할 경우 센터에서 SET
//compileField(0, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[0]);
//TCP/IP전문 송신 BYTES수로 "업무구분코드"이후의 송신할 전문 길이
compileField(1, ""+SEND_LENGTH, this.al_FieldProps[1]);
//업무구분코드 - 센터 및 은행에서 업무구분을 위하여 SET
compileField(2, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[2]);
//전문종별코드. 전문의 기능을 나타냄.
compileField(3, this.getFldTelegramType(), this.al_FieldProps[3]);
//거래구분코드 "R"-센터 수신 업무, "S"-센터 송신업무
compileField(4, this.getFldTrClass(), this.al_FieldProps[4]);
//송수신 FLAG "C"-센터에서 전문을 발생할 시, "B"-은행에서 전문을 발생할 시
compileField(5, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[5]);
//화일명
compileField(6, batchDoc.getBatchMsg().getHeader().getFileName(), this.al_FieldProps[6]);
//응답코드
compileField(7, TelegramKeys.RPS_HDB_RET_CODE_SUCCESS, this.al_FieldProps[7]);
//SEQUENCE-NO
compileField(8, ""+SEQUENCE_NO, this.al_FieldProps[8]);
//실 data byte수
compileField(9, ""+REAL_BYTE, this.al_FieldProps[9]);
if (batchDoc.getBatchMsg().getBody().getMissingNmCount() == 0) { //결번갯수가 0이면 결번데이터 전송 완료
this.setConditionTxt(TelegramKeys.LOSSEND);
}
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH; //실 DATA BYTE수
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<8; i++) { //어음이미지 전문의 헤더는 응답코드까지 임.
byte[] barr = (byte[])this.al_Field.get(i);
if ( barr[0] != '\0') {
baout.write((byte[])this.al_Field.get(i));
}
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=8; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
//여기에서 파일을 연다.
//return REAL_BYTE;
int fieldLen = -1;
String propKey = "";
switch (idx) {
case 0:
propKey = TelegramKeys.TRCD_LEN;
break;
case 10:
return REAL_BYTE;
default:
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
fieldLen = Integer.parseInt( telegramInfo.getProperty(propKey) );
return fieldLen;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
private boolean calculateSendLength () {
try {
for (int i=2; i< (this.al_Field.size()-1); i++) { //마지막 필드는 비정형 타입이라 제외
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
SEND_LENGTH += REAL_BYTE;
REAL_SEND_LENGTH = SEND_LENGTH;
for (int i=1; i < 2 ; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
REAL_SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH +=getCalculatedLength(0);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
private boolean setBlockAndSeqNO ()
{
int missing_count = this.batchDoc.getBatchMsg().getBody().getMissingNmCount();
String missing_field = this.batchDoc.getBatchMsg().getBody().getMissingNmField();
int missing_fld_len = missing_field.getBytes().length;
byte[] _missing = missing_field.getBytes();
for (int i=0; i<missing_fld_len; i++) { //missing_filed의 길이는 block_size와 동일
if(_missing[i] == '0') {
this.SEQUENCE_NO = i+1;
_missing[i] = '1';
missing_count -= 1;
this.batchDoc.getBatchMsg().getBody().setMissingNmField(new String(_missing));
this.batchDoc.getBatchMsg().getBody().setMissingNmCount(missing_count);
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
JobProcessData job = JobProcessData.getInstance();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
@SuppressWarnings("unchecked")
HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>)hm.get(JobProcessData.PROCDATA_BLOCKDATA);
if (block_data == null ){
logger.debug("{"+logHeader+"}"+" {"+ExceptionUtil.getErrorCode("SENDED FILE DATA IS NULL")+"}");
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI026-1";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return false;
}
byte[] data = block_data.get( new Integer(i) );
fileData = new byte[data.length];
System.arraycopy( data, 0, fileData, 0, data.length);
this.REAL_BYTE = data.length;
break;
}
}
return true;
}
public int getInformalFieldSendData(int idx, byte[] data) {
int fldLen = getCalculatedLength(idx);
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (data.length < REAL_BYTE) {
logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI014";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
switch (idx) {
case 0:
// TR 코드
System.arraycopy((telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE) + " ").getBytes(), 0, data, 0, fldLen );
break;
case 10:
ByteArrayInputStream bin = new ByteArrayInputStream(fileData);
bin.read(data, 0, REAL_BYTE);
return REAL_BYTE;
default:
break;
}
byte[] fieldData = new byte[fldLen];
System.arraycopy(data, 0, fieldData, 0, fldLen);
this.al_Field.set( idx, fieldData);
return fldLen;
// return REAL_BYTE;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
return super.getFieldValueString(3);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(4);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(7);
}
}
@@ -0,0 +1,67 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager;
import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BOKEX extends DefaultTelegram implements TelegramService {
/**
* 생성자 : 한은외환망 길이 결정용 텔레그램 클래스 이다.
*/
public RECV_BOKEX() {
}
public boolean doExecute() {
return true;
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
// 거래구분코드 필드값 리턴
public String getTrClass()
{
return super.getFieldValueString(5);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
public int getRemainDataLength()
{
try {
int idx;
String strLength;
int llLength;
String strRuleCode = batchDoc.getBatchMsg().getHeader().getRuleCode();
String strPhaseCode = batchDoc.getBatchMsg().getBody().getFlowPhaseCode();
NodeInfoVO vo = NodeInfoManager.getInstance().getNodeInfo(strRuleCode, strPhaseCode);
idx = vo.getLengthField();
if (idx == 0) return -1;
strLength = new String((byte[])this.al_Field.get(idx-1));
llLength = ((byte[])this.al_Field.get(idx-1)).length;
int nDocLen = Integer.parseInt(strLength);
int nReceivedLen = 0;
for (int i=1; i<this.al_FieldLength.length ; i++) {
nReceivedLen = nReceivedLen + Integer.parseInt(this.al_FieldLength[i]);
}
return (nDocLen-llLength-nReceivedLen);
} catch (Exception ex) {
this.batchDoc.getBatchMsg().getBody().setErrorMsg(ex.toString());
return -1;
}
}
}
@@ -0,0 +1,67 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.lang.String;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BOKEX_03000010 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BOKEX_03000010() {
//테스트용
}
/**
* 전문 해체하기
*/
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,122 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.io.File;
import java.lang.String;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BOKEX_03000020 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BOKEX_03000020() {
//파일 시작 요구
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
try{
String bizCode = new String ((byte[]) al_Field.get( 9));
String fileVer = new String ((byte[]) al_Field.get(10));
String compGb = new String ((byte[]) al_Field.get(12));
String strFileSize = new String ((byte[]) al_Field.get(13));
long fileSize = Long.parseLong(strFileSize); //화일 size
String fileExt = "";
if ( compGb.equals("1")){
fileExt = ".Z";
} else if (compGb.equals("2")){
fileExt = ".ZIP";
}
String fileName = bizCode + "_"+ fileVer + "_" + TelegramKeys.getYYYYMMddHHmmss() + fileExt;
batchDoc.getBatchMsg().getHeader().setBizCode(bizCode);
batchDoc.getBatchMsg().getHeader().setFileName(fileName);
String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath();
if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) {
fileDir = fileDir + File.separator;
}
String fileFullName = fileDir + fileName;
File file = new File(fileFullName);
if (file.exists()) {
file.delete();
}
batchDoc.getBatchMsg().getBody().setCurFileSize(0);
batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
batchDoc.getBatchMsg().getBody().setBlockNum(0);
batchDoc.getBatchMsg().getBody().setSeqNum(0);
} catch ( Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,203 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.util.HashMap;
import java.lang.String;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
public class RECV_BOKEX_03000030 extends DefaultTelegram implements TelegramService
{
private int INFORMALFIELD_INDEX = 12;
private ByteArrayOutputStream bout;
/**
* 생성자
*/
public RECV_BOKEX_03000030() {
//DATA송신
bout = new ByteArrayOutputStream();
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
try {
String _seq_no = new String ((byte[]) al_Field.get(9));
int recv_seq_no = Integer.parseInt(_seq_no);
batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no);
return true;
} catch ( Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
JobProcessData job = JobProcessData.getInstance();
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
@SuppressWarnings("unchecked")
HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>) hm.get(JobProcessData.PROCDATA_BLOCKDATA);
if (block_data == null) {
block_data = new HashMap<Integer, byte[]>();
}
String _seq_no = new String ((byte[]) al_Field.get(9));
int recv_seq_no = Integer.parseInt(_seq_no);
batchDoc.getBatchMsg().getBody().setSeqNum(recv_seq_no);
block_data.put( new Integer(recv_seq_no-1) , bout.toByteArray());
hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size()-1; i++) { //결번확인 필드는 비정형 필드로 바디 로그에서 제외
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
/**
* int getCalculatedLength(int idx)
* --------------------------------------------------------------------------------------
* 전달된 인덱스 idx는 비정형 필드여야 한다. 즉 필드의 길이값이 FILE_NO_LENGTH("XX") 이어야 한다.
* 해당 비정형 필드에 대해 실질적인 전문길이를 동적으로 계산해 낸다.
* SEND : 송신 길이 계산
* RECV : 수신 길이 계산
*/
public int getCalculatedLength(int idx) {
if (idx >= this.getFieldCount()) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
try {
String byte_size = new String ((byte[]) al_Field.get(11)); //실 DATA Byte수
logger.info("{} the sum of definite field length [" + byte_size + "]", logHeader);
return Integer.parseInt(byte_size);
} catch(Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
}
public boolean doInformalField(int idx, byte[] data, int length)
{
try {
if (idx == INFORMALFIELD_INDEX) {
bout.write(data, 0, length);
// 20060419 add by khs for 전송상태처리
long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize()+length;
batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize);
} else {
logger.debug("{} doInformalField >> index of informal action error : " + idx, logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return false;
}
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI004";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
return true;
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,81 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.lang.String;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BOKEX_03000040 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BOKEX_03000040() {
//파일 확인 요구
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,81 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.lang.String;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BOKEX_03000050 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BOKEX_03000050() {
//파일 확인 요구
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,87 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BOKEX_03100010 extends DefaultTelegram implements TelegramService {
/**
* 생성자
*/
public RECV_BOKEX_03100010() {
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
String rtn_yn = new String ((byte[]) al_Field.get(10));
if ( rtn_yn.equalsIgnoreCase("N")){
this.setConditionTxt(TelegramKeys.NOFILE);
}
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,84 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BOKEX_03100020 extends DefaultTelegram implements TelegramService {
/**
* 생성자
*/
public RECV_BOKEX_03100020() {
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
//응답수신 파일 Start DB로그
LogUtil.setLogFileStart(batchDoc);
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,109 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.util.HashMap;
import java.lang.String;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BOKEX_03100040 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BOKEX_03100040() {
//파일 확인 응답
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
String rtn_cd = new String ((byte[]) al_Field.get(9));
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
JobProcessData job = JobProcessData.getInstance();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
if (rtn_cd.equals("00")) {
if ( batchDoc.getBatchMsg().getHeader().getFileSize() <= batchDoc.getBatchMsg().getBody().getCurFileSize()){
this.setConditionTxt(TelegramKeys.EOF);
}
hm.put(JobProcessData.PROCDATA_BLOCKDATA, null); // Vector 초기화
} else {
// 이전에 송신한 최초 시퀀스 찾아 내어 시퀀스 번호 다시 세팅
int seq_no = batchDoc.getBatchMsg().getBody().getSeqNum();
for ( int inx=0;inx<seq_no;inx++){
Object obj = hm.get(new Integer(inx));
if ( obj!= null ){
batchDoc.getBatchMsg().getBody().setSeqNum(inx+1);
break;
}
}
}
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,147 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.common.LogUtil;
import com.eactive.eai.batch.common.StringUtil;
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageManager;
import com.eactive.eai.batch.scheduler.SchedulerMessageVO;
import com.eactive.eai.common.exception.ExceptionUtil;
public class RECV_BOKEX_03100050 extends DefaultTelegram implements TelegramService
{
/**
* 생성자
*/
public RECV_BOKEX_03100050() {
//파일 종료 응답
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doValidation()
{
if (!super.doValidation()) return false;
return true;
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
// 수신 파일 End DB로그
LogUtil.setLogFileEnd(batchDoc);
if ( checkMoreFileInDB()){
this.setConditionTxt("");
} else {
this.setConditionTxt(TelegramKeys.NOFILE);
}
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean checkMoreFileInDB(){
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 false;
}
String strUUID = batchDoc.getBatchMsg().getHeader().getUUID();
String strSubUUID = batchDoc.getBatchMsg().getBody().getSubUUID();
//해당 작업을 Job_Queue 테이블에서 Job_Processing 테이블로 이동
SchedulerMessageManager.getInstance().moveJobQueueToHandleWithNewID(info, strUUID, strSubUUID);
//BatchMsgDoc 값 설정
batchDoc.getBatchMsg().getHeader().setScheduleCode(info.getScheduleCode());
batchDoc.getBatchMsg().getHeader().setScheduleSTime(info.getStartTime());
batchDoc.getBatchMsg().getHeader().setScheduleETime(info.getEndTime());
batchDoc.getBatchMsg().getHeader().setFilePath(info.getFilePath());
batchDoc.getBatchMsg().getHeader().setFileName(info.getFileName());
batchDoc.getBatchMsg().getHeader().setRenamedFileName(info.getRenamedFileName());
batchDoc.getBatchMsg().getHeader().setJobCode(info.getJobCode());
batchDoc.getBatchMsg().getHeader().setBizCode(info.getBizCode());
batchDoc.getBatchMsg().getHeader().setFlowCode(info.getFlowRuleCode());
batchDoc.getBatchMsg().getHeader().setRuleCode(info.getFlowRuleCode());
batchDoc.getBatchMsg().getHeader().setBlockSize(info.getBlockSize());
batchDoc.getBatchMsg().getHeader().setSequenceSize(info.getSequenceSize());
batchDoc.getBatchMsg().getHeader().setPacketSize(info.getPacketSize());
batchDoc.getBatchMsg().getHeader().setUserID(info.getRemoteUserID());
batchDoc.getBatchMsg().getHeader().setUserPassword(info.getRemoteUserPW());
String jobCode = batchDoc.getBatchMsg().getHeader().getJobCode();
BatchJobInfoVO bjvo = DirInfoManager.getInstance().getFileInfo( jobCode );
batchDoc.getBatchMsg().getHeader().setRecLen((int)bjvo.getFileRecSize());
String hdrInfoName = info.getHdrInfoName();
batchDoc.getBatchMsg().getHeader().setHdrInfoName(hdrInfoName);
batchDoc.getBatchMsg().getHeader().setTotRecCnt(StringUtil.getTotRecCountFromHeader(hdrInfoName));
batchDoc.getBatchMsg().getHeader().setBaseDate(StringUtil.getBaseDateFromHeader(hdrInfoName));
batchDoc.getBatchMsg().getHeader().setFileSize(batchDoc.getBatchMsg().getHeader().getRecLen() * batchDoc.getBatchMsg().getHeader().getTotRecCnt());
batchDoc.getBatchMsg().getBody().setCurFileSize(0);
batchDoc.getBatchMsg().getBody().setSeqNum(0);
LogUtil.updateLogMaster(batchDoc);
} catch ( Exception e){
logger.warn(e.getMessage(), e);
return false;
}
return true;
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,73 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.io.ByteArrayOutputStream;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
public class RECV_BOKEX_0600 extends DefaultTelegram implements TelegramService {
/**
* 생성자
*/
public RECV_BOKEX_0600() {
//업무개시요구 및 업무개시통보
}
/**
* 전문 해체하기
*/
public boolean doExecute() {
if (!super.doExecute()) return false;
return true;
}
/**
* 전문 Validation
*/
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,184 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BOKEX_03000010 extends DefaultTelegram implements TelegramService {
private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이)
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BOKEX_03000010() {
//파일 송신 요구
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
int i = -1;
//전문송신 전체 Byte 수
compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]);
// Transaction Code
compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]);
//업무구분코드 - FXB
compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]);
// 참가기관코드
compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]);
//전문종별코드.
compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]);
//송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다.
compileField(++i, getFldTrClass(), this.al_FieldProps[i]);
//기관구분
compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]);
//계속여부
compileField(++i, "N", this.al_FieldProps[i]);
//응답코드
compileField(++i, getSendResponseCode(), this.al_FieldProps[i]);
// 여기 까지 공통부
//송신요구일자
compileField(++i, batchDoc.getBatchMsg().getHeader().getBaseDate(), this.al_FieldProps[i]);
//문서명
compileField(++i, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[i]);
//문서 버젼
compileField(++i, "", this.al_FieldProps[i]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH; //실 DATA BYTE수
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=1; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,241 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BOKEX_03000020 extends DefaultTelegram implements TelegramService {
private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이)
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BOKEX_03000020() {
//파일 시작 요구
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
int i = -1;
//전문송신 전체 Byte 수
compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]);
// Transaction Code
compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]);
//업무구분코드 - FXB
compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]);
// 참가기관코드
compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]);
//전문종별코드.
compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]);
//송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다.
compileField(++i, getFldTrClass(), this.al_FieldProps[i]);
//기관구분
compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]);
//계속여부
compileField(++i, "N", this.al_FieldProps[i]);
//응답코드
compileField(++i, getSendResponseCode(), this.al_FieldProps[i]);
// 여기 까지 공통부
//문서명
compileField(++i, batchDoc.getBatchMsg().getHeader().getBizCode(), this.al_FieldProps[i]);
//문서 버젼
compileField(++i, "00", this.al_FieldProps[i]);
//레코드 길이
compileField(++i, "0001", this.al_FieldProps[i]);
//압축사용여부
String renamedFileName = batchDoc.getBatchMsg().getHeader().getRenamedFileName();
String compGb = "0";
if ( ( renamedFileName.indexOf(".ZIP_") > -1 ) || ( renamedFileName.indexOf(".zip_")) > -1 ){
compGb = "2";
}
if ( renamedFileName.indexOf(".Z_") > -1 ){
compGb = "1";
}
compileField(++i, compGb, this.al_FieldProps[i]);
//파일 전체 크기
compileField(++i, ""+ calculateFileSize(), this.al_FieldProps[i]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
private long calculateFileSize () {
// long length = 0L;
String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath();
String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName();
if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) {
fileDir = fileDir + File.separator;
}
String fileName = fileDir + fileNm;
try {
File file = new File(fileName);
if (!file.exists()) // 파일이 없으면 리턴 False
{
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = fileName;
String errCode = "BECEAIFJI022";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
throw new Exception(" the File["+fileName+"] does not exist!!!");
}
// length = file.length();
super.setFileHeaderAndTrailer(file);
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI028";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
}
// if (length < 0) {
// return 0;
// }
// this.batchDoc.getBatchMsg().getHeader().setFileSize(length);
// return length;
return this.batchDoc.getBatchMsg().getHeader().getFileSize();
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength(){
try {
return REAL_SEND_LENGTH; //실 DATA BYTE수
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
public boolean doPreExecute(){
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=1; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,413 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobHandle.JobProcessData;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.running.BatchOpenFileManager;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BOKEX_03000030 extends DefaultTelegram implements TelegramService
{
private BufferedReader fbr ;
private int SEQUENCE_NO;
private int REAL_BYTE; //실 data byte수
private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이)
private Properties telegramInfo;
private byte[] fileData;
/**
* 생성자
*/
public SEND_BOKEX_03000030() {
//파일 데이터 송신
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = setData();
if (!result) {
return false;
}
result = calculateSendLength();
if (!result) return false;
int i = -1;
//전문송신 전체 Byte 수
compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]);
// Transaction Code
compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]);
//업무구분코드 - FXB
compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]);
// 참가기관코드
compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]);
//전문종별코드.
compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]);
//송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다.
compileField(++i, getFldTrClass(), this.al_FieldProps[i]);
//기관구분
compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]);
//계속여부
if ( this.getConditionTxt().equals(TelegramKeys.BLOCKEND) ){
compileField(++i, "N", this.al_FieldProps[i]);
}else {
compileField(++i, "Y", this.al_FieldProps[i]);
}
//응답코드
compileField(++i, getSendResponseCode(), this.al_FieldProps[i]);
// 여기 까지 공통부
//SEQUENCE-NO
compileField(++i, ""+SEQUENCE_NO, this.al_FieldProps[i]);
//기송신 크기
compileField(++i, ""+(batchDoc.getBatchMsg().getBody().getCurFileSize()- REAL_BYTE), this.al_FieldProps[i]);
//실 DATA BYTE 수
compileField(++i, ""+REAL_BYTE, this.al_FieldProps[i]);
//<< XX를 제외한 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
public int getInformalFieldSendData(int idx, byte[] data) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getInformalFieldSendData> " +idx+ " is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (data.length < REAL_BYTE) {
logger.debug("{} getInformalFieldSendData> InformalFieldSendData size is bigger than buffer size", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI014";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
//data = fileData;
ByteArrayInputStream bin = new ByteArrayInputStream(fileData);
bin.read(data, 0, REAL_BYTE);
return REAL_BYTE;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI006";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return -1;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
try {
return REAL_SEND_LENGTH; //실 DATA BYTE수
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI013";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
/**
* 비정형 필드에 대한 송신 길이를 계산해서 리턴해준다.
*
* 필드(idx)가 비정형 필드(XX)인지 점검하고 , 해당 필드에 대한 예상 길이를 계산하여 리턴하도록 한다
*
* 비정형 필드를 가지고 있는 개별 Telegram Class 에서 오버라이드 필요.
*/
public int getCalculatedLength(int idx) {
try {
if (idx >= this.getFieldCount() ) {
logger.debug("{} getCalculatedLength> parameter is bigger than field count", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI011";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return -1;
}
if (this.getFieldLength(idx).equalsIgnoreCase(TelegramService.FIELD_NO_LENGTH)) {
return REAL_BYTE;
} else {
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = ""+idx;
String errCode = "BECEAIFJI012";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.debug("{} getCalculatedLength> parameter is not FIELD_NO_LENGTH", logHeader);
return -1;
}
}catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI005";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return -1;
}
}
private boolean createFile ()
{
fbr = BatchOpenFileManager.getInstance().getFbr(batchDoc.getBatchMsg().getHeader().getUUID() );
try {
String fileDir = batchDoc.getBatchMsg().getHeader().getFilePath();
String fileNm = batchDoc.getBatchMsg().getHeader().getRenamedFileName();
if (fileDir.charAt(fileDir.length()-1) != File.separatorChar) {
fileDir = fileDir + File.separator;
}
String fileName = fileDir + fileNm;
File file = new File(fileName);
if (!file.exists()) // 파일이 없으면 리턴 False
{
logger.debug("{} the File["+fileDir+"/"+file.getName()+"] does not exist!!!", logHeader);
String[] msgArgs = new String[2];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
msgArgs[1] = fileName;
String errCode = "BECEAIFJI022";
String errMsg = ExceptionUtil.getErrorCode (errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
return false;
}
if ( fbr == null) {
fbr = new BufferedReader(new FileReader(file));
BatchOpenFileManager.getInstance().addFbr(batchDoc.getBatchMsg().getHeader().getUUID() , fileName, fbr);
}
logger.info("{} File [" + file.getName() + "] Size =" + file.length(), logHeader);
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI028";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
private boolean setData ()
{
try {
if (!createFile()) {
logger.error("{} file open failed", logHeader);
return false;
}
int sequence_size = this.batchDoc.getBatchMsg().getHeader().getSequenceSize();
int block_size = this.batchDoc.getBatchMsg().getHeader().getBlockSize();
int seq_no = this.batchDoc.getBatchMsg().getBody().getSeqNum();
this.SEQUENCE_NO = seq_no + 1;
if (( this.SEQUENCE_NO % block_size) == 0 ) { //블럭 크기에 도달하면 BLOCKEND 하여 다음 03000040전문으로 넘어가게 함
this.setConditionTxt(TelegramKeys.BLOCKEND);
}
if (batchDoc.getBatchMsg().getBody().getCurFileSize() + sequence_size >= batchDoc.getBatchMsg().getHeader().getFileSize()) {
this.setConditionTxt(TelegramKeys.BLOCKEND);
}
// 저장된 메모리 정보 참조 하기
JobProcessData job = JobProcessData.getInstance();
String uuid = this.batchDoc.getBatchMsg().getHeader().getUUID();
HashMap<String, Object> hm = job.getBatchStageData(uuid);
@SuppressWarnings("unchecked")
HashMap<Integer, byte[]> block_data = (HashMap<Integer, byte[]>) hm.get(JobProcessData.PROCDATA_BLOCKDATA);
if (block_data == null) {
block_data = new HashMap<Integer, byte[]>();
}
fileData = block_data.get(new Integer(SEQUENCE_NO-1));
if ( fileData == null ){
fileData = new byte[sequence_size];
int offset = 0;
byte[] temp_buffer = batchDoc.getBatchMsg().getBody().getSendBuffer();
if ( temp_buffer != null ){
System.arraycopy(temp_buffer, 0, fileData, offset, temp_buffer.length);
offset = temp_buffer.length;
}
batchDoc.getBatchMsg().getBody().setSendBuffer(null);
while ( offset < sequence_size) {
String tempLine = fbr.readLine();
if ( tempLine == null )
break;
temp_buffer = tempLine.getBytes();
System.arraycopy(temp_buffer, 0, fileData, offset, Math.min(temp_buffer.length, sequence_size-offset));
int remains_size = temp_buffer.length + offset - sequence_size;
offset += Math.min(temp_buffer.length, sequence_size-offset);
if ( sequence_size == offset ){
byte [] remains = new byte[remains_size];
System.arraycopy(temp_buffer, temp_buffer.length-remains_size, remains, 0, remains_size);
batchDoc.getBatchMsg().getBody().setSendBuffer(remains);
}
}
REAL_BYTE = offset;
block_data.put( new Integer(SEQUENCE_NO-1) , fileData);
hm.put(JobProcessData.PROCDATA_BLOCKDATA, block_data);
// 전송 상태 처리
long lnCurSize = batchDoc.getBatchMsg().getBody().getCurFileSize() + REAL_BYTE;
batchDoc.getBatchMsg().getBody().setCurFileSize(lnCurSize);
} else {
REAL_BYTE = fileData.length;
}
this.batchDoc.getBatchMsg().getBody().setSeqNum(SEQUENCE_NO);
return true;
} catch (Exception e ) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI029";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
private boolean calculateSendLength () {
try {
for (int i=1; i< this.al_Field.size()-1; i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
SEND_LENGTH += REAL_BYTE;
REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,172 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BOKEX_03000040 extends DefaultTelegram implements TelegramService
{
private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이)
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BOKEX_03000040() {
//파일 확인 요구
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
int i = -1;
//전문송신 전체 Byte 수
compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]);
// Transaction Code
compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]);
//업무구분코드 - FXB
compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]);
// 참가기관코드
compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]);
//전문종별코드.
compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]);
//송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다.
compileField(++i, getFldTrClass(), this.al_FieldProps[i]);
//기관구분
compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]);
//계속여부
compileField(++i, "N", this.al_FieldProps[i]);
//응답코드
compileField(++i, getSendResponseCode(), this.al_FieldProps[i]);
// 여기 까지 공통부
//SEQUENCE-NO
compileField(++i, ""+batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[i]);
//기송신 크기
compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
return REAL_SEND_LENGTH; //실 DATA BYTE수
}
private boolean calculateSendLength () {
try {
for (int i=1; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}
@@ -0,0 +1,184 @@
package com.eactive.eai.batch.job.jobItem.bokex;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import com.eactive.eai.batch.job.jobConstant.TelegramKeys;
import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;
import com.eactive.eai.batch.running.BatchOpenFileManager;
import com.eactive.eai.common.exception.ExceptionUtil;
public class SEND_BOKEX_03000050 extends DefaultTelegram implements TelegramService
{
private int SEND_LENGTH; //길이 필드를 제외한 전문의 총길이
private int REAL_SEND_LENGTH; //실제 송신할 전문의 총길이( SEND_LENGTH + 길이필드 길이)
private Properties telegramInfo;
/**
* 생성자
*/
public SEND_BOKEX_03000050() {
//파일 종료 요구
}
/**
* 전문조립
*/
public boolean doExecute() {
try {
boolean result = calculateSendLength();
if (!result) return false;
int i = -1;
//전문송신 전체 Byte 수
compileField(++i, ""+SEND_LENGTH, this.al_FieldProps[i]);
// Transaction Code
compileField(++i, telegramInfo.getProperty(TelegramKeys.TRANSACTION_CODE), this.al_FieldProps[i]);
//업무구분코드 - FXB
compileField(++i, telegramInfo.getProperty(TelegramKeys.BIZ_GBN), this.al_FieldProps[i]);
// 참가기관코드
compileField(++i, telegramInfo.getProperty(TelegramKeys.BANK_CODE), this.al_FieldProps[i]);
//전문종별코드.
compileField(++i, this.getFldTelegramType()+ this.getFldOpCode() + "0", this.al_FieldProps[i]);
//송수신 FLAG : 전문 발생 기관을 구분하여 아래의 값을 SET한다.
compileField(++i, getFldTrClass(), this.al_FieldProps[i]);
//기관구분
compileField(++i, telegramInfo.getProperty(TelegramKeys.TRA_FLAG_BANK), this.al_FieldProps[i]);
//계속여부
compileField(++i, "N", this.al_FieldProps[i]);
//응답코드
compileField(++i, getSendResponseCode(), this.al_FieldProps[i]);
// 여기 까지 공통부
//SEQUENCE-NO
compileField(++i, ""+batchDoc.getBatchMsg().getBody().getSeqNum(), this.al_FieldProps[i]);
//기송신 크기
compileField(++i, ""+batchDoc.getBatchMsg().getBody().getCurFileSize(), this.al_FieldProps[i]);
//종료 일시
compileField(++i, TelegramKeys.getYYYYMMddHHmmss(), this.al_FieldProps[i]);
//<< 전문 완성
return true;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI001";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
}
public boolean doPostExecute() {
if (!super.doPostExecute()) return false;
try {
//DB로그에 남길 전문 헤더 설정
ByteArrayOutputStream baout = new ByteArrayOutputStream();
for (int i=0; i<9; i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));
//DB로그에 남길 전문 바디 설정
baout = new ByteArrayOutputStream();
for (int i=9; i< al_Field.size(); i++) {
baout.write((byte[])this.al_Field.get(i));
}
batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));
BufferedReader fbr = BatchOpenFileManager.getInstance().getFbr(batchDoc.getBatchMsg().getHeader().getUUID() );
if ( fbr != null ){
fbr.close();
BatchOpenFileManager.getInstance().removeFile(batchDoc.getBatchMsg().getHeader().getUUID());
}
return true;
} catch(Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI002";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
public boolean doPreExecute() {
try {
if (!super.doPreExecute()) return false;
telegramInfo = getTelegramInfo();
return true;
} catch (Exception ex) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI003";
String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( ex.getMessage(), ex);
return false;
}
}
/**
* 실제 송신할 전문의 총길이를 리턴해준다.
*/
public int getSendLength()
{
return REAL_SEND_LENGTH; //실 DATA BYTE수
}
private boolean calculateSendLength () {
try {
for (int i=1; i< this.al_Field.size(); i++) {
byte[] aField = (byte[]) this.al_Field.get(i);
SEND_LENGTH += aField.length;
}
REAL_SEND_LENGTH = SEND_LENGTH + ((byte[]) this.al_Field.get(0)).length;
} catch (Exception e) {
String[] msgArgs = new String[1];
msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
String errCode = "BECEAIFJI025";
String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
logger.error( e.getMessage(), e);
return false;
}
return true;
}
//---------------- 특정 필드값을 구하는 부분
// 전문종별코드 필드값 리턴
public String getTelegramType()
{
String telegramNo = super.getFieldValueString(4);
if ( telegramNo.length() < 8 ) return "";
return telegramNo.substring(0,3) + telegramNo.substring(6,7);
}
//응답코드 필드값 리턴
public String getResCode()
{
return super.getFieldValueString(8);
}
}

Some files were not shown because too many files have changed in this diff Show More