diff --git a/.gitignore b/.gitignore index da26d0a..64949eb 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,9 @@ build *.log *.tmp bin -tmp \ No newline at end of file +tmp +libs/ +.metadata/ +.idea/ +weblogic_mock/ +.gitignore \ No newline at end of file diff --git a/README.md b/README.md index 56512a5..3232dbc 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,6 @@ ANT_HOME=/c/eactive/apps/apache-ant-1.10.15 export PATH=${PATH}:${JAVA_HOME}/bin:${ANT_HOME}/bin -cd /c/eactive/workspaces/kjb-bap/BAPRMSClient -ant -s build-server.xml archive - cd /c/eactive/workspaces/kjb-bap/BAPWeb ant -s build.xml war ``` diff --git a/WebContent/WEB-INF/jms/applicationContext-jms.xml b/WebContent/WEB-INF/jms/applicationContext-jms.xml index 9e4f4c1..e672459 100644 --- a/WebContent/WEB-INF/jms/applicationContext-jms.xml +++ b/WebContent/WEB-INF/jms/applicationContext-jms.xml @@ -17,16 +17,16 @@ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd - "> + "> - - - + + + - - - + + + diff --git a/WebContent/WEB-INF/jms/applicationContext-jms.xml.P b/WebContent/WEB-INF/jms/applicationContext-jms.xml.P index 40580b8..e699da6 100644 --- a/WebContent/WEB-INF/jms/applicationContext-jms.xml.P +++ b/WebContent/WEB-INF/jms/applicationContext-jms.xml.P @@ -19,14 +19,14 @@ applicationContext-jms.xml http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "> - - - + + + - - - + + + diff --git a/WebContent/WEB-INF/jms/applicationContext-jms.xml.Q b/WebContent/WEB-INF/jms/applicationContext-jms.xml.Q index 2385e05..e699da6 100644 --- a/WebContent/WEB-INF/jms/applicationContext-jms.xml.Q +++ b/WebContent/WEB-INF/jms/applicationContext-jms.xml.Q @@ -19,14 +19,14 @@ applicationContext-jms.xml http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "> - - - + + + - - - + + + diff --git a/WebContent/WEB-INF/lib/jackson-annotations-2.21.jar b/WebContent/WEB-INF/lib/jackson-annotations-2.21.jar new file mode 100644 index 0000000..8bcca18 Binary files /dev/null and b/WebContent/WEB-INF/lib/jackson-annotations-2.21.jar differ diff --git a/WebContent/WEB-INF/lib/jackson-core-2.21.3.jar b/WebContent/WEB-INF/lib/jackson-core-2.21.3.jar new file mode 100644 index 0000000..8d4c009 Binary files /dev/null and b/WebContent/WEB-INF/lib/jackson-core-2.21.3.jar differ diff --git a/WebContent/WEB-INF/lib/jackson-databind-2.21.3.jar b/WebContent/WEB-INF/lib/jackson-databind-2.21.3.jar new file mode 100644 index 0000000..5af13ea Binary files /dev/null and b/WebContent/WEB-INF/lib/jackson-databind-2.21.3.jar differ diff --git a/WebContent/WEB-INF/web.xml b/WebContent/WEB-INF/web.xml index 0e52e23..e344d87 100644 --- a/WebContent/WEB-INF/web.xml +++ b/WebContent/WEB-INF/web.xml @@ -37,24 +37,14 @@ - FepSendFile - com.eactive.eai.agent.web.FepSendFile - - - - FepReqRecvFile - com.eactive.eai.agent.web.FepReqRecvFile + FileFetchRequest + com.eactive.eai.agent.web.FileFetchRequestHandler CheckFileSysHealth com.eactive.eai.agent.web.CheckFileSysHealth - - - FepFileSend - com.eactive.eai.agent.web.FepFileSend - FepFileReceive @@ -71,21 +61,13 @@ /DBRefreshAgent - FepSendFile - /FepSendFile - - - FepReqRecvFile - /FepReqRecvFile + FileFetchRequest + /FileFetchRequest CheckFileSysHealth /CheckFileSysHealth - - FepFileSend - /FepFileSend - FepFileReceive /FepFileReceive diff --git a/WebContent/WEB-INF/weblogic.xml b/WebContent/WEB-INF/weblogic.xml deleted file mode 100644 index 42b9941..0000000 --- a/WebContent/WEB-INF/weblogic.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - BAPWeb - - - true - - \ No newline at end of file diff --git a/build.xml b/build.xml index 1997555..664ad89 100644 --- a/build.xml +++ b/build.xml @@ -1,58 +1,21 @@ - - - - - + + + + - - + + + - - - - - - - - - @@ -68,21 +31,15 @@ - - - - - - - - - - - + + + + + - + @@ -91,9 +48,6 @@ - - - diff --git a/src/com/eactive/eai/adapter/ftp/FTPDJ.java b/src/com/eactive/eai/adapter/ftp/FTPDJ.java new file mode 100644 index 0000000..3351b35 --- /dev/null +++ b/src/com/eactive/eai/adapter/ftp/FTPDJ.java @@ -0,0 +1,409 @@ +package com.eactive.eai.adapter.ftp; + +import com.eactive.eai.adapter.socket.config.ConfigurationContext; +import com.eactive.eai.adapter.socket.service.SocketService; +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.common.StringUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.doc.Body; +import com.eactive.eai.batch.doc.Header; +import com.eactive.eai.batch.ftp.FTPFileObject; +import com.eactive.eai.batch.ftp.FTPUtil; +import com.eactive.eai.batch.running.BatchRunningJobManager; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.property.PropManager; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.Arrays; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + + +/** + * DJBank 공융 sftp 전송을 위함 SFTP proxy사용 + * + * 파일명 : FTPDJ + * + */ + +public class FTPDJ extends Transfer implements SocketService { + + private static final String PROP_GROUP_NAME_PREFIX = "TelegramInfo"; + + private static final String REMOTE_PATH = "remote.path";// 원격지 경로 #YYYYMMDD# + private static final String FILENAME_PATTERN = "filename.pattern";// 기준일자 [YYYYMMDD] 당일이전일 [YYYYMMDD-1][YYYYMMDD-2][YYYYMMDD+1] + private static final String EXT_NAME = "ext.name"; + private static final String FTP_TRANSFER_TYPE = "ftp.transfer.type";// ftp ASCII 인 경우만 default BINARY + private static final String BASE_DATE_OVER_YN = "basedate.over.yn"; // 기준일 이후 파일전송여부 + private static final String PROXY_SERVER = "proxy.server"; // 프록시 서버 + private static final String PROTOCOL = "protocol"; // 프록시 서버 + private static final String CHECK_FILE_EXT = "check.file.ext"; + + /** ftp 0 , 인증 방법 1 = id, 2 = key 방식 */ + private static final String AUTH_TYPE = "sftp.auth.type"; + private static final String TRANS_LIB = "sftp.trans.lib"; + + enum Protocol { + FTP("0", false), SFTP_PASSWD("1"), SFTP_KEY("2"); + + private final String val; + private final boolean isSFtp; + + Protocol(String val) { this(val, true); } + Protocol(String val, boolean isSFtp) { + this.val = val; + this.isSFtp = isSFtp; + } + + private static final Map MAP = Arrays.stream(values()) + .collect(Collectors.toMap(p -> p.name().toLowerCase(), p -> p)); + + public static Protocol get(String protocol) { + if (protocol == null || protocol.trim().isEmpty()) + return SFTP_PASSWD; + return MAP.getOrDefault(protocol.trim().toLowerCase(), SFTP_PASSWD); + } + } + + private static class FtpEnv { + private static final Pattern pattern = Pattern.compile("#YYYYMMDD([+-]\\d+)?#"); + String propName; + + String ipaddress; + int port; + String userid; + String passwd; + Protocol protocol; + String remotePath; + String remoteFile; + String proxyServer; + int connTimeout; + int setTimeout; + int bandWidth; + + String ftpTransferType; + String checkFileExt; + + private FtpEnv init(BatchDoc batchDoc) { + Header batchHeader = batchDoc.getBatchMsg().getHeader(); + + propName = PROP_GROUP_NAME_PREFIX + "{" + + batchHeader.getProcessCode() + + "_" + + batchHeader.getInstitutionCode() + "}"; + PropManager pmanager = PropManager.getInstance(); + + ipaddress = batchHeader.getRemoteIP(); + port = Integer.parseInt(batchHeader.getPort()); + userid = batchHeader.getUserID(); + passwd = batchHeader.getUserPassword(); + + remotePath = pmanager.getProperties(propName).getProperty(REMOTE_PATH, ""); + Path requestFile = Paths.get(batchHeader.getFileName()); + String requestPath = Optional.ofNullable(requestFile.getParent()) + .map(Path::toString) + .orElse(""); + remoteFile = requestFile.getFileName().toString(); + remotePath = Paths.get(remotePath).resolve(requestPath).normalize().toString(); + //batchHeader.setFileName(remoteFile); + + proxyServer = pmanager.getProperties(propName).getProperty(PROXY_SERVER, ""); + protocol = Protocol.get(pmanager.getProperties(propName).getProperty(PROTOCOL, "")); + + String connTimeoutStr = pmanager.getProperties(propName).getProperty(CONNECTION_TIMEOUT, "30"); + connTimeout = Integer.parseInt(connTimeoutStr); + String setTimeoutStr = pmanager.getProperties(propName).getProperty(READ_TIMEOUT, "30"); + setTimeout = Integer.parseInt(setTimeoutStr); + String bandWidthLimit = pmanager.getProperties(propName).getProperty(BADNWIDTH, "0"); + bandWidthLimit = bandWidthLimit.replace("K", "000").replace("M", "000000").replace(",", ""); + bandWidth = Integer.parseInt(bandWidthLimit); + + ftpTransferType = pmanager.getProperties(propName).getProperty(FTP_TRANSFER_TYPE, "BINARY"); + checkFileExt = BatchDirUtil.getResponseRootExt(); + + try { + Matcher matcher = pattern.matcher(remotePath); + if (matcher.find()) { + String offset = matcher.group(1); + int days = (offset != null) ? Integer.parseInt(offset) : 0; + String baseDate = DatetimeUtil.addDays(DatetimeUtil.getCurrentDate(), days); + batchHeader.setBaseDate(baseDate); + remotePath = matcher.replaceAll(baseDate); + } + if (!remotePath.endsWith("/")) + remotePath += "/"; + } catch ( Exception e) { + ((Logger) batchDoc.getLogger(Logger.LOGGER_ADAPTER)).error("", e); + } + + return this; + } + } + + Header batchHeader; + Body batchBody; + + @Override + public void sendFile(BatchDoc batchDoc) throws Exception { + throw new UnsupportedOperationException("send is not implemented yet"); + } + + public void recvFile(BatchDoc batchDoc) throws Exception { + + if ( logger.isInfoEnabled() ) logger.info("[FTPDJ] ■ 대외기관 → FEP 파일 수신 시작...... "); + batchHeader = batchDoc.getBatchMsg().getHeader(); + batchBody = batchDoc.getBatchMsg().getBody(); + + firstActivity = System.currentTimeMillis(); + BatchRunningJobManager.getInstance().addRunningJobInfo(batchHeader.getUUID(), this, batchDoc); + + FtpEnv ftpEnv = new FtpEnv().init(batchDoc); + + if(logger.isDebugEnabled()) logger.debug("[FTPDJ] userid:" + ftpEnv.userid + ", localPath=" + batchHeader.getFilePath()); + + try { + batchBody.setPhaseStartTime(CalendarUtil.getCurrentTimeNoDash()); + LogUtil.setLogFileStart(batchDoc); + + //changeRecvPath(batchHeader); + FTPFileObject[] list = FTPUtil.listFilesJSCH( + ftpEnv.ipaddress, ftpEnv.port, ftpEnv.userid, ftpEnv.passwd, + ftpEnv.remotePath, + ftpEnv.protocol.isSFtp, + batchDoc.getLogger(), + ftpEnv.protocol.val, + ftpEnv.proxyServer + ); + + if ( list == null ) { // 파일 경로가 없는경우 20231025 + if(logger.isDebugEnabled()) logger.debug("[FTPDJ] Not found remote path :: "+ftpEnv.remotePath); + throw new RuntimeException("[FTPDJ] Not found remote path :: "+ftpEnv.remotePath); + } + + FTPFileObject found = Arrays.stream(list) + .filter(FTPFileObject::isFile) + .filter(f -> ftpEnv.remoteFile.equals(f.getName())) + .findFirst() + .orElse(null); + + if ( found == null ) { + if(logger.isDebugEnabled()) logger.debug("[FTPDJ] Not found remote file :: "+ftpEnv.remotePath + "/" + ftpEnv.remoteFile); + throw new RuntimeException("[FTPDJ] Not found remote file :: "+ftpEnv.remotePath + "/" + ftpEnv.remoteFile); + } + + fileDownProcess(batchDoc, ftpEnv, found); + //fileDownEndProcess(batchDoc, ftpEnv.remoteFile, ""); + + } catch (Exception ex) { + String[] msgArgs = new String[1]; + msgArgs[0] = batchHeader.getProcessCode(); + String errCode = "BECEAIFJI002"; + String errMsg = ExceptionUtil.getErrorCode(ex, errCode, msgArgs); + batchBody.setErrorMsg(errMsg); + //batchBody.setPhaseEndTime(DatetimeUtil.getCurrentTimeMillis()); + LogUtil.setErrorLog(batchDoc, ex.getMessage()); + logger.error(errMsg, ex); + throw ex; + } finally { + batchBody.setPhaseEndTime(DatetimeUtil.getCurrentTimeMillis()); + LogUtil.setLogFileEnd(batchDoc); + this.disconnect(); + } + + if(logger.isInfoEnabled()) logger.info("[FTPDJ] ■ VAN사 → FEP 파일 수신 완료."); + } + + private void changeRecvPath(Header h) { + String removed = h.getFilePath().replace("/" + h.getProcessCode() + "/" + h.getInstitutionCode(), ""); + String newPath = removed + "/" + h.getBizCode() + "/"; + h.setFilePath(newPath); + if(logger.isInfoEnabled()) logger.debug("[FTPDJ] processCode=" + batchHeader.getProcessCode() + ", institutionCode=" + batchHeader.getInstitutionCode() + ", bizCode=" + batchHeader.getBizCode() + ", newPath=" + newPath); + } + + private void fileDownProcess(BatchDoc batchDoc, FtpEnv env, FTPFileObject remoteFileInfo) throws Exception { + if(logger.isDebugEnabled()) logger.debug("@@@@@@@@@ batchHeader.getJobCode()[" + batchHeader.getJobCode() + "]"); + +// batchBody.setPhaseStartTime(DatetimeUtil.getCurrentTimeMillis()); +// LogUtil.setLogFileStart(batchDoc); + + String receivedFile = batchHeader.getFilePath() + File.separator + env.remoteFile; + Path received = Paths.get(receivedFile); + Path savePath = Paths.get(StringUtil.realToArchDir(receivedFile)); + Path intfcCheckFile = Paths.get(savePath.toAbsolutePath() + env.checkFileExt); + Path emptyCheckFile = Paths.get(StringUtil.realToRootDir(receivedFile)); + + Files.createDirectories(received.getParent()); + Files.createDirectories(savePath.getParent()); + Files.createDirectories(emptyCheckFile.getParent()); + + if ( Files.exists(intfcCheckFile) ) Files.delete( intfcCheckFile ); + if ( Files.exists(emptyCheckFile) ) Files.delete( emptyCheckFile ); + + if(logger.isDebugEnabled()) logger.debug("received=" + received + "savePath=" + savePath); + + try { + + if(logger.isDebugEnabled()) logger.debug("@@@@@@@@" + this.getClass().getName() + " :: filename=[" + env.remoteFile + "], path=[" + batchHeader.getFilePath() + "]"); + + FTPUtil.retrieve(batchDoc, + env.ipaddress, env.port, env.userid, env.passwd, + env.remotePath , + env.remoteFile, + batchHeader.getFilePath(), + env.connTimeout, + env.setTimeout, + env.bandWidth, + batchDoc.getLogger(Logger.LOGGER_ADAPTER), + env.protocol.val, + env.ftpTransferType, env.proxyServer); + + batchHeader.setTotRecCnt(1); + batchHeader.setFileSize(remoteFileInfo.getSize()); + + Files.move(received, savePath, StandardCopyOption.REPLACE_EXISTING); + String checkFileContent = String.format("%-138s@@" , batchHeader.getBizCode()); // Bat에서 읽기 위한 Format + Files.writeString(intfcCheckFile, checkFileContent); + Files.createFile(emptyCheckFile); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + try { + if ( Files.exists(received) ) { + Path errorPath = Paths.get(StringUtil.realToErrorDir(receivedFile)); + Files.createDirectories(errorPath.getParent()); + Files.move(received, errorPath); + } + } catch ( Exception ignore) { } + throw new Exception("파일수신에 실패하였습니다. -" + e.getMessage()); + } finally { + setLastActivity(); + //fos.close(); + } + } + + // 정상처리 20241025 + private void fileDownEndProcess(BatchDoc batchDoc, String fileName, String errMsg) throws Exception { + FileOutputStream fos = null; + + batchHeader.setFileName(fileName); + //batchHeader.setFileSize(0); + //batchHeader.setTotRecCnt(1); + if(logger.isInfoEnabled()) logger.debug("@@@@@@@@@fileDownEndProcess batchHeader.getFileName()["+ fileName + "]"); + + batchBody.setPhaseStartTime(DatetimeUtil.getCurrentTimeMillis()); + + LogUtil.setLogFileStart(batchDoc); + + batchHeader.setTotRecCnt(1); + //batchHeader.getJobCode(); + batchBody.setErrorMsg(errMsg); + + // File 종료시간 설정 + batchBody.setPhaseEndTime(DatetimeUtil.getCurrentTimeMillis()); + LogUtil.setLogFileEnd(batchDoc); + } + + @Override + public void shutdown() { + // TODO Auto-generated method stub + + } + + @Override + public Socket getCurrentSocket() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean connect() { + // TODO Auto-generated method stub + return false; + } + + @Override + public ConfigurationContext getContext() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setControl(Object control) { + // TODO Auto-generated method stub + + } + + @Override + public void notifyMessage() { + // TODO Auto-generated method stub + + } + + @Override + public boolean idle(long timeout) { + // TODO Auto-generated method stub + return false; + } + + @Override + public int getCurrentState() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean isConnected() throws IOException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isActive() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void checkActivity() { + // TODO Auto-generated method stub + + } + + @Override + public String getRemoteIPAddress() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setLastActivity() { + // TODO Auto-generated method stub + lastActivity = System.currentTimeMillis(); + } + + @Override + public long getFirstActivity() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public long getLastActivity() { + // TODO Auto-generated method stub + return 0; + } +} diff --git a/src/com/eactive/eai/adapter/socket/service/SocketServer.java b/src/com/eactive/eai/adapter/socket/service/SocketServer.java index 0541c7a..4f73238 100644 --- a/src/com/eactive/eai/adapter/socket/service/SocketServer.java +++ b/src/com/eactive/eai/adapter/socket/service/SocketServer.java @@ -143,10 +143,10 @@ public class SocketServer extends Thread implements SocketService { String ip = channel.socket().getInetAddress().getHostAddress(); Integer connCount = ipTable.get( ip ); if ( connCount == null ) { - ipTable.put( ip, new Integer( 1 ) ); + ipTable.put( ip, 1); } else if ( connCount.intValue() < context.getConnLimitPerIp() ) { int newCount = connCount.intValue() + 1; - ipTable.put( ip, new Integer( newCount )); + ipTable.put( ip, newCount); } else { logger.error( CommonLib.getMessage("BECEAIMSA023", new String[]{ context.getAdapterName(), Integer.toString( context.getConnLimitPerIp() ),this.getSocketInfo( channel ) } ) ); try { @@ -371,7 +371,7 @@ public class SocketServer extends Thread implements SocketService { int newCount = connCount.intValue() - 1; if ( newCount < 0 ) newCount = 0; - ipTable.put( ip, new Integer( newCount ) ); + ipTable.put( ip, newCount); } } } diff --git a/src/com/eactive/eai/agent/web/FileFetchRequestHandler.java b/src/com/eactive/eai/agent/web/FileFetchRequestHandler.java new file mode 100644 index 0000000..09f5575 --- /dev/null +++ b/src/com/eactive/eai/agent/web/FileFetchRequestHandler.java @@ -0,0 +1,312 @@ +package com.eactive.eai.agent.web; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.eactive.eai.batch.common.BatchDirUtil; +import com.eactive.eai.batch.common.CalendarUtil; +import com.eactive.eai.batch.common.CommonKeys; +import com.eactive.eai.batch.common.LogUtil; +import com.eactive.eai.batch.doc.BatchDoc; +import com.eactive.eai.batch.message.EAIBatchMsgManager; +import com.eactive.eai.batch.osd.OutsideManager; +import com.eactive.eai.batch.osd.OutsideVO; +import com.eactive.eai.batch.scheduler.JobStatusVO; +import com.eactive.eai.batch.scheduler.SchedulerMessageManager; +import com.eactive.eai.batch.scheduler.SchedulerMessageVO; +import com.eactive.eai.common.exception.ExceptionUtil; +import com.eactive.eai.common.util.DatetimeUtil; +import com.eactive.eai.common.util.Logger; +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.exc.MismatchedInputException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +public class FileFetchRequestHandler extends HttpServlet { + + private static final long serialVersionUID = 1L; + Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT); + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + enum STATUS { + QUEUED("Q"), ERROR("E"), RUNNING("S"), FINISHED("T"), UNKNOWN("U");; + String code; + + STATUS(String code) { this.code = code; } + } + + /** + * 1. 기능 : Eai Bat Call + * 2. 처리 개요 : 요청 메세지를 받아서 처리 후 메세지 리턴. + * 3. 주의사항 + * + * @param request HttpServletRequest + * @param response HttpServletResponse + **/ + public void service(HttpServletRequest request, HttpServletResponse response) { + JsonRequest reqJson = null; + try { + logger.info("Servlet starting ......."); + + reqJson = getRequestBody(request, response); + reqJson.validate(); + JsonRequest.Action action = reqJson.action; + + JsonResponse jsonResponse; + switch ( action ) { + case DOWNLOAD -> jsonResponse = getFileEventInfo(reqJson); + case STATUS -> jsonResponse = getTransferStatus(reqJson); + case UPLOAD -> throw new UnsupportedOperationException("Not supported yet: " + action); + default -> throw new IllegalArgumentException("Unsupported command: " + action); + } + + sendResponse(response, jsonResponse); + + } catch (Exception ex) { + logger.error(ex.getMessage(), ex); + sendResponse(response, JsonResponse.getFailureMessage((reqJson == null ? "" : reqJson.jobId), ex)); + } + } + + private JsonRequest getRequestBody(HttpServletRequest request, HttpServletResponse response) { + String encoding = request.getCharacterEncoding(); + if (encoding == null) + encoding = StandardCharsets.UTF_8.name(); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), encoding))) { + return objectMapper.readValue(reader, JsonRequest.class); + } catch (MismatchedInputException e) { // Body 내용이 완전히 비어있는 경우 + logger.error(e.getMessage()); + throw new IllegalArgumentException("Empty Body", e); + } catch (JsonParseException | JsonMappingException e) { // JSON 문법이 틀렸거나, 클래스 구조와 맞지 않는 경우 + throw new IllegalArgumentException("Wrong Json format", e); + } catch (UnsupportedEncodingException e) { // 지원하지 않는 인코딩(charset)을 요청한 경우 + throw new IllegalArgumentException("Unsupported Encoding: " + encoding, e); + } catch (IOException e) { // 기타 순수 IO 에러 (스트림 끊김 등) + throw new RuntimeException("IO Error occurred while reading request body", e); + } + } + + private void sendResponse(HttpServletResponse response, JsonResponse jsonResponse) { + try { + response.setContentType("application/json; charset=UTF-8"); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + response.getWriter().print(jsonResponse.toJsonString()); + } catch (Exception ignore) {} + } + + private JsonResponse getFileEventInfo(JsonRequest reqJson) throws Exception + { + String bizCode = reqJson.remoteCode; + String fileName = reqJson.remoteFile; + + // 수신한 파일 정보 + logger.info("[FetchRequestHandler] ========================================================================="); + logger.info("[FetchRequestHandler] ▶▶▶▶▶▶▶▶▶▶ Local 수신요청 FILE EVENT 발생 !! ◀◀◀◀◀◀◀◀◀◀"); + logger.info("[FetchRequestHandler] ※ remoteCode : [" + bizCode +"]"); + logger.info("[FetchRequestHandler] ※ remoteFile : [" + fileName +"]"); + SchedulerMessageVO codeInfo = SchedulerMessageManager.getInstance().getInfoByteBjobTransDstName(bizCode); + String processCode = codeInfo.getProcessCode(); + String institutionCode = codeInfo.getInstitutionCode(); + logger.info("[FetchRequestHandler] ※ processCode : [" + codeInfo.getProcessCode()+"]"); + logger.info("[FetchRequestHandler] ※ institutionCode : [" + codeInfo.getInstitutionCode() +"]"); + logger.info("[FetchRequestHandler] ========================================================================="); + + + //거래구분 코드 설정 + int bizCodeStartIndex = 0; + int bizCodeEndIndex = 0; + OutsideVO organInfo = OutsideManager.getInstance().getOutsideInfo(processCode, institutionCode); + if ( organInfo == null ){ + throw new RuntimeException("미등록 업무구분/기관코드:" + processCode + "/" + institutionCode); + } + String institutionName = organInfo.getOsdName(); + String processName = organInfo.getBatchName(); + bizCodeStartIndex = organInfo.getBizCdStartIdx(); + bizCodeEndIndex = organInfo.getBizCdEndIdx(); + logger.info("processName = " + processName); + + + if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= fileName.length()) bizCodeStartIndex = 0; + if (bizCodeEndIndex <= 0 || bizCodeEndIndex > fileName.length()) bizCodeEndIndex = fileName.length(); + + logger.info("[FetchRequestHandler] -------------------------------------------------------------------------"); + logger.info("[FetchRequestHandler] ■ File Event 파싱 정보"); + logger.info("[FetchRequestHandler] - 업무구분명 : [" + processName +"] (업무구분코드: "+ processCode +")"); + logger.info("[FetchRequestHandler] - 대외기관명 : [" + institutionName +"] (대외기관코드: "+ institutionCode +")"); + logger.info("[FetchRequestHandler] - 수신파일명 : [" + fileName +"]"); + logger.info("[FetchRequestHandler] - 거래구분코드: [" + bizCode +"]"); + logger.info("[FetchRequestHandler] -------------------------------------------------------------------------"); + + + /* + * FileEvent가 SchedulerProcess로 전달할 기본 EAIBatchMsg를 생성한다. + * FileEventListener가 입력가능한 값들은 EAIBatchMsg의 항목 중 다음과 같다. + * - UUID + * - Layer 구분 코드 (한시적) + * - ProcessCode: 수신한 서브디렉토리와 동일 + * - FileName : 송수신 원 파일명 + * - FilePath : 파일이 실재 존재하는 디렉토리 + * - RenamedFileName : 저장후 이름이 변경된 파일명 + */ + // BatchMsgDoc 생성 + BatchDoc batchMsgDoc = EAIBatchMsgManager.createBatchMsgWithUUID(false); //UUID 생성, false:초기화안함 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_FILE_EVENT, CommonKeys.SUB_LAYER_FILE_EVENT); // layer, flowPahse, 시작시간 설정 + batchMsgDoc.getBatchMsg().getHeader().setProcessCode(processCode); // 업무코드 + batchMsgDoc.getBatchMsg().getHeader().setProcessName(processName); // 업무명 + batchMsgDoc.getBatchMsg().getHeader().setProcessType(CommonKeys.PROCESS_REQUEST_RECEIVE); // 업무유형 (요구송신 설정) + batchMsgDoc.getBatchMsg().getHeader().setInstitutionCode(institutionCode); // 대외기관코드 + batchMsgDoc.getBatchMsg().getHeader().setInstitutionName(institutionName); // 대외기관명 + batchMsgDoc.getBatchMsg().getHeader().setFileName(fileName); // 원 파일명 + batchMsgDoc.getBatchMsg().getHeader().setBizCode(bizCode); // 거래구분코드 + SchedulerMessageVO info = SchedulerMessageManager.getInstance().getRecvScheduleInfo(bizCode, processCode, institutionCode); + if ( info == null ){ + String errMsg = ExceptionUtil.getErrorCode("BECEAISSC016", new String[] {processCode, institutionCode, bizCode}); + throw new Exception(errMsg); // 해당 정보에 대한 스케쥴 정보가 존재하지 않습니다. (업무코드: {1}, 대외기관코드: {2}, 거래구분코드: {3}) + } + + info.setFileName(fileName); + //1. 요구수신 스케쥴러 단계 DB로그를 위한 BatchMsg 객체 생성 + EAIBatchMsgManager.updateBatchMsgWithStageTime(batchMsgDoc, CommonKeys.LAYER_SCHEDULER, CommonKeys.SUB_LAYER_SCHEDULER_QUEUE); // layer, flowPahse, 시작시간 설정 + + //2. 요구수신 디렉토리 설정 (수신_Real/업무구분/대외기관/..) + //요구수신 기준 디렉토리 --> 배치업무유형코드(ProcessCode) 와 대외기관코드 (InstitutionCode) 로 계산. + String strPathName = BatchDirUtil.getResponseRealDir(); + if ( strPathName.charAt(strPathName.length()-1) != '/' ) { + strPathName = strPathName + '/'; + } + + strPathName = strPathName + processCode + "/" + institutionCode; + info.setFilePath(strPathName); + + //3. UUID 설정 및 스케쥴 송수신 시각 설정 + info.setUUID (batchMsgDoc.getBatchMsg().getHeader().getUUID()); + info.setSubUUID (batchMsgDoc.getBatchMsg().getBody().getSubUUID()); + info.setStartTime(DatetimeUtil.getCurrentDate() + "000000000"); + info.setEndTime (DatetimeUtil.getCurrentDate() + "235900000"); + + //4. Job_Queue 테이블에 등록 + logger.info("[요구수신 스케쥴러] ========================================================================="); + logger.info("[요구수신 스케쥴러] ■ 요구수신 스케쥴 정보를 Job_Queue 테이블에 추가......"); + int resultCnt = SchedulerMessageManager.getInstance().insertJobToQueue(info); + logger.info("[요구수신 스케쥴러] ==> 배치 Job_Queue 테이블 INSERT 건수: "+ resultCnt); + logger.info("[요구수신 스케쥴러] ========================================================================="); + + // 단계 종료시간을 추가한다. + batchMsgDoc.getBatchMsg().getBody().setPhaseEndTime(CalendarUtil.getCurrentTimeNoDash()); + + // 요구송신에 대한 최초 DB로그. StartLog 호출. + LogUtil.setStartLog (batchMsgDoc); + logger.info("[FetchRequestHandler] ※ Event 파일명 : [" + fileName +"]"); + + return new JsonResponse( + JsonResponse.RESULT_SUCCESS, + STATUS.QUEUED, + batchMsgDoc.getBatchMsg().getHeader().getUUID() + ).setQueuedTime(); + } + + private JsonResponse getTransferStatus(JsonRequest reqJson) throws Exception { + String jobId = reqJson.jobId; + SchedulerMessageManager manager = SchedulerMessageManager.getInstance(); + JobStatusVO vo = manager.getOenJobByKey(jobId, jobId); + + if ( vo == null ) + throw new RuntimeException("jobId('" + jobId + "')를 찾을수 없습니다."); + + JsonResponse ret = new JsonResponse( + JsonResponse.RESULT_SUCCESS, + STATUS.QUEUED, + jobId + ); + + ret.status = Arrays.stream(STATUS.values()) + .filter(status -> status.code.equals(vo.getTranPrcssDstcd())) + .findFirst() + .orElse(STATUS.UNKNOWN); + ret.message = vo.getEAIObstclOccurCausCtnt(); + ret.queuedAt = vo.getBjobDmndMsgCretnHMS(); + ret.startedAt = vo.getTranStartHMS(); + ret.finishedAt = vo.getTranEndHMS(); + return ret; + } + + @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) + @JsonIgnoreProperties(ignoreUnknown = true) + private static class JsonRequest { + enum Action { + DOWNLOAD, UPLOAD, STATUS; + + @JsonCreator + public static Action from(String value) { + return Action.valueOf(value.toUpperCase()); + } + } + private Action action; + private String jobId; + private String remoteCode; + private String remoteFile; + + private void validate() { + switch (this.action) { + case DOWNLOAD, UPLOAD -> { + if (remoteCode == null || remoteCode.trim().isEmpty()) throw new RuntimeException("remoteCode is Empty."); + if (remoteFile == null || remoteFile.trim().isEmpty()) throw new RuntimeException("remoteFilePath is Empty."); + } + case STATUS -> { + if (jobId == null || jobId.trim().isEmpty()) throw new RuntimeException("jobId is Empty."); + } + } + } + } + + @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) + private static class JsonResponse { + private static final String RESULT_SUCCESS = "success"; + private static final String RESULT_FAILURE = "failure"; + + final String result; + STATUS status; + final String jobId; + String message; + String queuedAt; + String startedAt; + String finishedAt; + + // 생성자를 통해서만 객체를 생성하도록 제한 + private JsonResponse(String result, STATUS status, String jobId) { + this.result = result; + this.status = status; + this.jobId = jobId; + } + + private JsonResponse setQueuedTime() { this.queuedAt = DatetimeUtil.getCurrentDateTime(); return this; } + private JsonResponse setMessage(String message) { this.message = message; return this; } + + private String toJsonString() { + try { + return objectMapper.writeValueAsString(this); + } catch (JsonProcessingException e) { + throw new RuntimeException("JsonResponse JSON 생성 중 오류 발생", e); + } + } + + // --- 유틸리티 메서드 --- + public static JsonResponse getFailureMessage(String jobId, Exception e) { + return new JsonResponse(RESULT_FAILURE, STATUS.ERROR, jobId).setMessage(e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/com/eactive/eai/batch/common/BatchDirUtil.java b/src/com/eactive/eai/batch/common/BatchDirUtil.java index eb109a1..2b65343 100644 --- a/src/com/eactive/eai/batch/common/BatchDirUtil.java +++ b/src/com/eactive/eai/batch/common/BatchDirUtil.java @@ -170,6 +170,11 @@ public class BatchDirUtil // public static final String RESPONSE_RCV_CHK_DIR = "rcv.chk.directory"; public static final String RESPONSE_RCV_ROOT_EXT = "rcv.root.ext"; + public static final String RETENTION_DAY_ROOT = "retension.day.root"; + public static final String RETENTION_DAY_REAL = "retension.day.real"; + public static final String RETENTION_DAY_ARCH = "retension.day.arch"; + public static final String RETENTION_DAY_ERROR = "retension.day.error"; + // 응답송신용 디렉토리 프라퍼티 키 정보 20060425 add by khs // public static final String RESPONSE_SND_DIR_INFO = "ResponseSndDirInfo"; // public static final String RESPONSE_SND_REAL_DIR = "snd.real.directory"; diff --git a/src/com/eactive/eai/batch/common/StringUtil.java b/src/com/eactive/eai/batch/common/StringUtil.java index f03e165..ded3367 100644 --- a/src/com/eactive/eai/batch/common/StringUtil.java +++ b/src/com/eactive/eai/batch/common/StringUtil.java @@ -113,7 +113,7 @@ public class StringUtil public static String itos(int i) { - return (new Integer(i)).toString(); + return Integer.toString(i); } public static String replaceStr(String s, String s1, String s2) throws NullPointerException diff --git a/src/com/eactive/eai/batch/encrypt/EncryptManager.java b/src/com/eactive/eai/batch/encrypt/EncryptManager.java index 987ba4d..e6f19a4 100644 --- a/src/com/eactive/eai/batch/encrypt/EncryptManager.java +++ b/src/com/eactive/eai/batch/encrypt/EncryptManager.java @@ -63,8 +63,8 @@ public class EncryptManager implements Lifecycle { for(int i=65; i<91; i++) { - String key = new Character((char)i).toString(); - String value = new Integer(100 - i).toString(); + String key = Character.toString((char) i); + String value = Integer.toString(100 - i); codeTable.put(key, value); codeTable.put(value, key); @@ -72,8 +72,8 @@ public class EncryptManager implements Lifecycle for(int i=0; i<10; i++) { - String key = new Integer(i).toString(); - String value = new Integer(9-i).toString(); + String key = Integer.toString(i); + String value = Integer.toString(9 - i); codeTable.put(key, value); } //logger.debug("** if Hashtable : A = : " + codeTable.get("A")); @@ -169,9 +169,9 @@ public class EncryptManager implements Lifecycle /* 암호화 문장 생성 */ 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()); + int m_Msg = Integer.parseInt((String) codeTable.get(transferPwd.substring(i, i + 1))); + int m_Key = Integer.parseInt((String) codeTable.get(encryptSeed.substring(i, i + 1))); + encryptMsg += (String)codeTable.get(Integer.toString((m_Msg + m_Key) % 36)); } return encryptMsg; @@ -231,9 +231,9 @@ public class EncryptManager implements Lifecycle /* 암호화 문장 생성 */ 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()); + int m_Msg = Integer.parseInt((String) codeTable.get(transferPwd.substring(i, i + 1))); + int m_Key = Integer.parseInt((String) codeTable.get(encryptSeed.substring(i, i + 1))); + encryptMsg += (String)codeTable.get(Integer.toString((m_Msg + m_Key) % 36)); } return encryptMsg; @@ -258,9 +258,9 @@ public class EncryptManager implements Lifecycle 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()); + int m_Msg = Integer.parseInt((String) codeTable.get(encryptMsg.substring(i, i + 1))) + 36; + int m_Key = Integer.parseInt((String) codeTable.get(seed.substring(i, i + 1))); + normalMsg += (String)codeTable.get(Integer.toString((m_Msg - m_Key) % 36)); } return normalMsg; @@ -347,9 +347,9 @@ public class EncryptManager implements Lifecycle /* 암호화 문장 생성 */ for(int i=0; i>> 수행 SQL 문 : \n"+ SELECT_SEND_SCHEDULE_BY_BIZCODE); + + index = 1; + this.preparedStatement.setString(index++, bjobTranDstcdName ); logger.debug("SchedulerMessageDAO.getInfoByteBjobTransDstName() >>> 바인드("+(index-1)+") : ["+ bjobTranDstcdName +"]"); + + rs = executeQuery(); + + SchedulerMessageVO info = null; + if (rs.next()) { + info = new SchedulerMessageVO(); + info.setProcessCode (StringUtil.nvlTrim(rs.getString("BjobBzwkDstcd" ))); // 업무구분 코드 + info.setInstitutionCode(StringUtil.nvlTrim(rs.getString("OsidInstiDstcd" ))); // 대외기관 코드 + info.setBizCode (StringUtil.nvlTrim(rs.getString("BjobTranDstcdName"))); // 거래구분코드 + } + + return info; + + } catch (DAOException ex) { + throw ex; + } catch(Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAISSC001", new String[] {"unknown", "unknown", bjobTranDstcdName}); + throw new DAOException(errMsg); //해당 스케쥴 정보를 찾을 수 없습니다. (업무구분: %1, 대외기관: %2, 거래구분: %3) + } finally { + disconnect(); + } + } + + public JobStatusVO getOenJobByKey(String bjobDmndMsgID, String bjobDmndSubMsgID) throws DAOException { + + ResultSet rs = null; + int index = 0; + + try { + this.connect(SELECT_ONE_JOB_BY_KEY); + //logger.debug("SchedulerMessageDAO.getScheduleInfo() >>> 수행 SQL 문 : \n"+ SELECT_SEND_SCHEDULE_BY_BIZCODE); + + index = 1; + this.preparedStatement.setString(index++, bjobDmndMsgID ); logger.debug("SchedulerMessageDAO.getOenJobByKey() >>> 바인드("+(index-1)+") : ["+ bjobDmndMsgID +"]"); + this.preparedStatement.setString(index++, bjobDmndMsgID ); logger.debug("SchedulerMessageDAO.getOenJobByKey() >>> 바인드("+(index-1)+") : ["+ bjobDmndSubMsgID+"]"); + + rs = executeQuery(); + + JobStatusVO jobStatus = null; + if (rs.next()) { + jobStatus = new JobStatusVO(); + jobStatus.setBjobMsgScheID (StringUtil.nvlTrim(rs.getString("BjobDmndMsgID" ))); // BATCH작업요청메시지ID + jobStatus.setBjobDmndSubMsgID (StringUtil.nvlTrim(rs.getString("BjobDmndSubMsgID" ))); // BATCH작업요청부메시지ID + jobStatus.setBjobDmndMsgCretnHMS (StringUtil.nvlTrim(rs.getString("BjobDmndMsgCretnHMS" ))); // BATCH작업요청메시지생성시각 + jobStatus.setTranStartHMS (StringUtil.nvlTrim(rs.getString("TranStartHMS" ))); // 송수신시작시각 + jobStatus.setTranEndHMS (StringUtil.nvlTrim(rs.getString("TranEndHMS" ))); // 송수신종료시각 + jobStatus.setTranPrcssDstcd (StringUtil.nvlTrim(rs.getString("TranPrcssDstcd" ))); // 거래처리구분코드 ('Q', 'S', 'E', 'T') + jobStatus.setEAIObstclOccurCausCtnt(StringUtil.nvlTrim(rs.getString("EAIObstclOccurCausCtnt"))); // EAI장애발생원인내용 + //jobStatus.setSndrcvFileName (StringUtil.nvlTrim(rs.getString("SndrcvFileName" ))); // 송수신파일명(,로 구분) + } + + return jobStatus; + + } catch (DAOException ex) { + throw ex; + } catch(Exception e) { + String errMsg = ExceptionUtil.getErrorCode(e, "BECEAISSO001", new String[] {bjobDmndMsgID, bjobDmndSubMsgID}); + throw new DAOException(errMsg); //해당 스케쥴 정보를 찾을 수 없습니다. (업무구분: %1, 대외기관: %2, 거래구분: %3) + } finally { + disconnect(); + } + } } diff --git a/src/com/eactive/eai/batch/scheduler/SchedulerMessageManager.java b/src/com/eactive/eai/batch/scheduler/SchedulerMessageManager.java index 898f46b..b855747 100644 --- a/src/com/eactive/eai/batch/scheduler/SchedulerMessageManager.java +++ b/src/com/eactive/eai/batch/scheduler/SchedulerMessageManager.java @@ -749,5 +749,15 @@ public class SchedulerMessageManager return dao.deleteJobFromProcessing(uuid); } - + public SchedulerMessageVO getInfoByteBjobTransDstName(String bjobTranDstcdName) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.getInfoByteBjobTransDstName(bjobTranDstcdName); + } + + public JobStatusVO getOenJobByKey(String bjobDmndMsgID, String bjobDmndSubMsgID) throws Exception + { + SchedulerMessageDAO dao = (SchedulerMessageDAO)DAOFactory.newInstance().create(SchedulerMessageDAO.class); + return dao.getOenJobByKey(bjobDmndMsgID, bjobDmndSubMsgID); + } } diff --git a/src/com/eactive/eai/batch/scheduler/SchedulerMessageQuery.java b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQuery.java index 2b1f409..10fb167 100644 --- a/src/com/eactive/eai/batch/scheduler/SchedulerMessageQuery.java +++ b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQuery.java @@ -625,4 +625,28 @@ public interface SchedulerMessageQuery + " MsgPrcssStusCd \n" + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04"; + public static String SELECT_INFO_BY_JOB_TRANS_DST_NAME = + "SELECT A.BjobMsgScheID , \n" + + " A.OsidInstiDstcd, \n" + + " B.BjobBzwkDstcd, \n" + + " B.BjobTranDstcdName \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBS01 A,\n" + + " " + Keys.TABLE_OWNER + "TSEAIBJ01 B \n" + + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd\n" + + "AND A.BjobPtrnDstcd = 'RR' \n" + + "AND LTRIM(RTRIM(B.BjobTranDstcdName)) = ? \n" + + "AND B.ThisMsgUseYn = '1'\n"; + + public static final String SELECT_ONE_JOB_BY_KEY = + "SELECT AA.BjobDmndMsgID ,\n" + + " AA.BjobDmndSubMsgID ,\n" + + " AA.BjobDmndMsgCretnHMS ,\n" + + " AA.TranStartHMS ,\n" + + " AA.TranEndHMS ,\n" + + " AA.TranPrcssDstcd ,\n" + + " AA.EAIObstclOccurCausCtnt \n" + + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 AA \n" + + "WHERE AA.BjobDmndMsgID = ? \n" + + "AND AA.BjobDmndSubMsgID = ? \n"; + } \ No newline at end of file diff --git a/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForMariadb.java b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForMariadb.java index 3e95fa3..ff19b24 100644 --- a/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForMariadb.java +++ b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForMariadb.java @@ -621,5 +621,4 @@ public interface SchedulerMessageQueryForMariadb + " MsgQueEtractDmndHMS,\n" + " MsgPrcssStusCd \n" + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04"; - } \ No newline at end of file diff --git a/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForOracle.java b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForOracle.java index f674f3b..3ef1a74 100644 --- a/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForOracle.java +++ b/src/com/eactive/eai/batch/scheduler/SchedulerMessageQueryForOracle.java @@ -34,9 +34,9 @@ public interface SchedulerMessageQueryForOracle + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, \n" + " B.MsgPrcssPrity ,\n" + " CASE WHEN ( TO_CHAR(SYSDATE,'HH24MI') >= A.SndrcvStartHMS AND \n" - + " TO_CHAR(SYSDATE,'HH24MI') < NVL(RTRIM(A.SndrcvEndHMS), '9999') ) THEN 1 \n" //--스케쥴시작시간 <= 현재시간 < 스케쥴종료시간 - + " WHEN ( TO_CHAR(SYSDATE,'HH24MI') < A.SndrcvStartHMS ) THEN 2 \n" //--현재시간 < 스케쥴시작시간 (미래스케쥴) - + " ELSE 3 \n" //--현재시간 > 스케쥴시작시간 (지나간스케쥴) + + " TO_CHAR(SYSDATE,'HH24MI') < NVL(RTRIM(A.SndrcvEndHMS), '9999') ) THEN 1 \n" //--스케쥴시작시간 <= 현재시간 < 스케쥴종료시간 + + " WHEN ( TO_CHAR(SYSDATE,'HH24MI') < A.SndrcvStartHMS ) THEN 2 \n" //--현재시간 < 스케쥴시작시간 (미래스케쥴) + + " ELSE 3 \n" //--현재시간 > 스케쥴시작시간 (지나간스케쥴) + " END FetchPriority ,\n" + " A.HoldyPrcssDstcd ,\n" + " A.StartDlayNoday ,\n" @@ -47,7 +47,7 @@ public interface SchedulerMessageQueryForOracle + "AND B.BjobBzwkDstcd = ? \n" + "AND LTRIM(RTRIM(A.OsidInstiDstcd)) = ? \n" + "AND B.BjobTranDstcdName = ? \n" - + "AND A.BjobPtrnDstcd = 'RS'\n" + + "AND A.BjobPtrnDstcd = 'RS'\n" + "AND A.ThisMsgUseYn = '1' \n" + "AND B.ThisMsgUseYn = '1' \n" + "ORDER BY B.MsgPrcssPrity, FetchPriority, A.SndrcvStartHMS, A.SndrcvEndHMS, B.BjobTranDstcdName"; @@ -65,9 +65,9 @@ public interface SchedulerMessageQueryForOracle + " LTRIM(RTRIM(A.OsidInstiDstcd)) AS OsidInstiDstcd, \n" + " B.MsgPrcssPrity , \n" + " CASE WHEN ( TO_CHAR(SYSDATE,'HH24MI') >= A.SndrcvStartHMS AND \n" - + " TO_CHAR(SYSDATE,'HH24MI') < NVL(RTRIM(A.SndrcvEndHMS), '9999') ) THEN 1 \n" //--스케쥴시작시간 <= 현재시간 < 스케쥴종료시간 - + " WHEN ( TO_CHAR(SYSDATE,'HH24MI') < A.SndrcvStartHMS ) THEN 2 \n" //--현재시간 < 스케쥴시작시간 (미래스케쥴) - + " ELSE 3 \n" //--현재시간 > 스케쥴시작시간 (지나간스케쥴) + + " TO_CHAR(SYSDATE,'HH24MI') < NVL(RTRIM(A.SndrcvEndHMS), '9999') ) THEN 1 \n" //--스케쥴시작시간 <= 현재시간 < 스케쥴종료시간 + + " WHEN ( TO_CHAR(SYSDATE,'HH24MI') < A.SndrcvStartHMS ) THEN 2 \n" //--현재시간 < 스케쥴시작시간 (미래스케쥴) + + " ELSE 3 \n" //--현재시간 > 스케쥴시작시간 (지나간스케쥴) + " END FetchPriority , \n" + " A.HoldyPrcssDstcd , \n" + " A.StartDlayNoday , \n" @@ -140,7 +140,7 @@ public interface SchedulerMessageQueryForOracle + "AND A.BjobBzwkDstcd = E.BjobBzwkDstcd \n" + "AND A.MsgPrcssPrity > 0 \n" //--suspend 스케쥴 제외 + "AND A.SndrcvStartHMS <= TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" - + "AND NVL(RTRIM(A.SndrcvEndHMS), '99991231') > TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" //--종료시간이 없으면 종료시간 체크 안함 + + "AND NVL(RTRIM(A.SndrcvEndHMS), '99991231') > TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" //--종료시간이 없으면 종료시간 체크 안함 + "ORDER BY A.BjobBzwkDstcd, A.MsgPrcssPrity, C.BjobTranDstcdName, A.SndrcvFileName, A.BjobDmndMsgCretnHMS, A.SndrcvStartHMS"; //3. Timer Event 발생시 작업대기목록 테이블에서 수행할(현재시간에 걸리는) 전체 작업목록을 조회 @@ -187,17 +187,17 @@ public interface SchedulerMessageQueryForOracle + "AND A.BjobBzwkDstcd = E.BjobBzwkDstcd \n" // + "AND A.MsgPrcssPrity > '0' \n" //--suspend 스케쥴 제외 + "AND A.SndrcvStartHMS <= TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" - + "AND NVL(RTRIM(A.SndrcvEndHMS), '99991231') > TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" //--종료시간이 없으면 종료시간 체크 안함 + + "AND NVL(RTRIM(A.SndrcvEndHMS), '99991231') > TO_CHAR(SYSTIMESTAMP,'YYYYMMDDHH24MISSFF3') \n" //--종료시간이 없으면 종료시간 체크 안함 + "ORDER BY A.BjobBzwkDstcd, A.MsgPrcssPrity, C.BjobTranDstcdName, A.SndrcvFileName, A.BjobDmndMsgCretnHMS, A.SndrcvStartHMS"; - + //4. 위 3번 쿼리에 의해 조회된 작업목록을 수행하기 전에 해당 작업의 연결정보가 현재 사용중인지 //체크하기 위해 작업진행목록 테이블에서 전체 연결정보를 조회 public static final String SELECT_EXECUTING_SYSTEMCONNID_FROM_PROCESSING = "SELECT SysLnkgDstcd \n" + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04 \n" + "WHERE MsgPrcssStusCd IN ('S','I','C')"; - + // 4-1. 위 3번 쿼리에 의해 조회된 작업목록을 수행하기 전에 해당 작업의 앞선 우선순위 작업이 수행중인지 확인하기 위한 쿼리 //2009.8.14 by kscheon public static final String SELECT_EXECUTING_JOB_FROM_PROCESSING = @@ -297,19 +297,19 @@ public interface SchedulerMessageQueryForOracle + " A.RqstRecvReTralIntvalTtm, \n" + " NVL(C.RecvFileEndCnt , 0) RecvFileEndCnt , \n" + " NVL(C.RecvFileFailCnt, 0) RecvFileFailCnt, \n" - + " NVL(C.RecentExecTime , '') RecentExecTime \n" + + " NVL(C.RecentExecTime , '') RecentExecTime \n" + "FROM " + Keys.TABLE_OWNER + "TSEAIBJ01 B, \n" - + " " + Keys.TABLE_OWNER + "TSEAIBS01 A \n" + + " " + Keys.TABLE_OWNER + "TSEAIBS01 A \n" + " LEFT OUTER JOIN ( SELECT BjobMsgScheID, \n" + " SUM(CASE TranPrcssDstcd WHEN 'T' THEN 1 " + " ELSE 0 END) AS RecvFileEndCnt ,\n" // --파일전송 완료 건수 + " SUM(CASE TranPrcssDstcd WHEN 'T'THEN 0 " - + " ELSE 1 END) AS RecvFileFailCnt,\n" // --파일전송 미완료 건수 - + " MAX(BjobDmndMsgCretnHMS) RecentExecTime \n" // --최근 수행 시간 + + " ELSE 1 END) AS RecvFileFailCnt,\n" // --파일전송 미완료 건수 + + " MAX(BjobDmndMsgCretnHMS) RecentExecTime \n" // --최근 수행 시간 + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" - + " WHERE BjobPtrnDstcd = 'RR' \n" // --요구수신만 + + " WHERE BjobPtrnDstcd = 'RR' \n" // --요구수신만 + " AND BjobDmndMsgCretnHMS LIKE TO_CHAR(SYSDATE,'YYYYMMDD')||'%' \n" - + " GROUP BY BjobMsgScheID ) C " + + " GROUP BY BjobMsgScheID ) C " + "on A.BjobMsgScheID = C.BjobMsgScheID \n" + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + "AND A.BjobPtrnDstcd = 'RR' --요구수신만 \n" @@ -318,15 +318,15 @@ public interface SchedulerMessageQueryForOracle + "AND A.SndrcvStartHMS <= TO_CHAR(SYSDATE,'HH24MI') \n" + "AND NVL(RTRIM(A.SndrcvEndHMS), '9999') > TO_CHAR(SYSDATE,'HH24MI') \n" + "AND NOT EXISTS ( SELECT X.BjobMsgScheID \n" - + " FROM " + Keys.TABLE_OWNER + "TSEAIBS03 X \n" //--대기목록 테이블에 존재하지 않고 + + " FROM " + Keys.TABLE_OWNER + "TSEAIBS03 X \n" //--대기목록 테이블에 존재하지 않고 + " WHERE X.BjobMsgScheID = A.BjobMsgScheID \n" - + " AND X.SndrcvEndHMS >= TO_CHAR(SYSDATE,'YYYYMMDD') ) \n" //--미래의 스케쥴이 + + " AND X.SndrcvEndHMS >= TO_CHAR(SYSDATE,'YYYYMMDD') ) \n" //--미래의 스케쥴이 + "AND NOT EXISTS ( SELECT Y.BjobMsgScheID \n" + " FROM " + Keys.TABLE_OWNER + "TSEAIBS04 Y \n" //--진행목록 테이블에 존재하지 않고 + " WHERE Y.BjobMsgScheID = A.BjobMsgScheID ) \n" + "ORDER BY A.SndrcvStartHMS, B.BjobTranDstcdName, A.SndrcvEndHMS"; - + //10. 스케줄 아이디에 해당되는 스케줄 정보 조회(요구수신) public static String SELECT_SEND_SCHEDULE_BY_SCHEDULEID = "SELECT A.BjobMsgScheID , \n" @@ -370,10 +370,10 @@ public interface SchedulerMessageQueryForOracle + " AND B.BjobBzwkDstcd = D.BjobBzwkDstcd \n" + " AND LTRIM(RTRIM(A.OsidInstiDstcd)) = LTRIM(RTRIM(D.OsidInstiDstcd )) \n" + " AND LTRIM(RTRIM(A.BjobMsgScheID)) = ? \n"; - - - - + + + + // 13. 스케줄 아이디에 해당되는 스케줄 정보 조회(요구송신) public static String SELECT_REQ_SEND_SCHEDULE_BY_SCHEDULEID = "SELECT A.BjobMsgScheID , \n" @@ -393,15 +393,15 @@ public interface SchedulerMessageQueryForOracle + " " + Keys.TABLE_OWNER + "TSEAIBS01 A \n" + " LEFT OUTER JOIN ( SELECT BjobMsgScheID, \n" + " SUM(CASE TranPrcssDstcd WHEN 'T'THEN 0 " - + " ELSE 1 END) AS RecvFileFailCnt\n" //--파일전송 미완료 건수 + + " ELSE 1 END) AS RecvFileFailCnt\n" //--파일전송 미완료 건수 + " FROM " + Keys.TABLE_OWNER + "TSEAIBJ03 \n" + " WHERE BjobPtrnDstcd = 'RS' \n" //--요구송신만 + " AND BjobDmndMsgCretnHMS LIKE TO_CHAR(SYSDATE,'YYYYMMDD')||'%' \n" - + " GROUP BY BjobMsgScheID ) C \n" + + " GROUP BY BjobMsgScheID ) C \n" + " on A.BjobMsgScheID = C.BjobMsgScheID \n" + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + "AND RTRIM(A.BjobMsgScheID) = ? \n" - + "AND A.BjobPtrnDstcd = 'RS'\n" //--요구송신만 + + "AND A.BjobPtrnDstcd = 'RS'\n" //--요구송신만 + "AND A.ThisMsgUseYn = '1' \n" + "AND B.ThisMsgUseYn = '1' \n"; @@ -417,7 +417,7 @@ public interface SchedulerMessageQueryForOracle /** * BATCH작업 메시지일정 ID를 조회하는 쿼리 */ - public static final String GET_BJOBMSGSCHEID = + public static final String GET_BJOBMSGSCHEID = " SELECT BjobBzwkDstcd|| ? ||BjobTranDstcdName|| " + " ( " + " SELECT " @@ -438,7 +438,7 @@ public interface SchedulerMessageQueryForOracle /** * BATCH작업 일정 정보를 등록하는 쿼리 */ - public static final String ADD_JOB_SCH_INFO = + public static final String ADD_JOB_SCH_INFO = "INSERT INTO "+Keys.TABLE_OWNER +"TSEAIBS01 ( " + " BjobMsgScheID " + " ,BjobMsgDstcd " @@ -490,7 +490,7 @@ public interface SchedulerMessageQueryForOracle /** * BATCH작업 일정 정보를 등록하는 쿼리 */ - public static final String SELECT_LOG_MASTER_BY_KEYS = + public static final String SELECT_LOG_MASTER_BY_KEYS = " SELECT A.BjobDmndMsgID , \n" + " A.BjobDmndSubMsgID , \n" + " A.TelgmReTralCnt , \n" @@ -530,7 +530,7 @@ public interface SchedulerMessageQueryForOracle " AND BjobDmndSubMsgID = ? \n" + " AND SndrcvFileName = ? \n"; -// public static final String SELECT_STAGE_LOGS_BY_KEYS = +// public static final String SELECT_STAGE_LOGS_BY_KEYS = // "SELECT B.BjobDmndMsgID , \n" // + " B.BjobDmndSubMsgID , \n" // + " B.BjobStgeID , \n" @@ -570,8 +570,8 @@ public interface SchedulerMessageQueryForOracle // + " WHERE B.BjobDmndMsgID LIKE ? ||'%' \n" // + " AND B.BjobDmndSubMsgID LIKE ? ||'%' \n" // + " ORDER BY B.BjobDmndMsgID, B.BjobDmndSubMsgID, B.ThisStgeStartHMS, B.BjobMsgDstcd"; - - public static final String SELECT_SCHEDULE_BASIS = + + public static final String SELECT_SCHEDULE_BASIS = "SELECT A.BjobMsgScheID , \n" + " B.BjobBzwkDstcd , \n" + " C.BjobBzwkName , \n" @@ -585,10 +585,10 @@ public interface SchedulerMessageQueryForOracle + " B.ThisMsgChrgIDs , \n" + " A.SndrcvStartHMS , \n" + " A.SndrcvEndHMS \n" - + "FROM "+Keys.TABLE_OWNER +"TSEAIBS05 A, \n" - + " "+Keys.TABLE_OWNER +"TSEAIBJ01 B, \n" - + " "+Keys.TABLE_OWNER +"TSEAIBJ02 C, \n" - + " "+Keys.TABLE_OWNER +"TSEAIBJ06 D \n" + + "FROM "+Keys.TABLE_OWNER +"TSEAIBS05 A, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ01 B, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ02 C, \n" + + " "+Keys.TABLE_OWNER +"TSEAIBJ06 D \n" + "WHERE A.BjobMsgDstcd = B.BjobMsgDstcd \n" + "AND B.BjobBzwkDstcd = C.BjobBzwkDstcd \n" + "AND B.BjobBzwkDstcd = D.BjobBzwkDstcd \n" @@ -621,5 +621,4 @@ public interface SchedulerMessageQueryForOracle + " MsgQueEtractDmndHMS,\n" + " MsgPrcssStusCd \n" + "FROM " + Keys.TABLE_OWNER + "TSEAIBS04"; - } \ No newline at end of file diff --git a/src/com/eactive/eai/batch/telegram/TelegramDAO.java b/src/com/eactive/eai/batch/telegram/TelegramDAO.java index ee0abac..0c25a9a 100644 --- a/src/com/eactive/eai/batch/telegram/TelegramDAO.java +++ b/src/com/eactive/eai/batch/telegram/TelegramDAO.java @@ -115,7 +115,7 @@ public class TelegramDAO extends BaseDAO implements TelegramQuery rs = this.executeQuery(); - TelegramVO telegramVO = new TelegramVO(keys[i], new Integer(fieldsCount[i]).intValue()); + TelegramVO telegramVO = new TelegramVO(keys[i], Integer.parseInt(fieldsCount[i])); while(rs.next()) { // telegramitem 순서값은 런타임시에는 사용하지 않는다. 대신 TelegramVO에서 item이 추가될때 순서를 부여한다. diff --git a/src/com/eactive/eai/batch/telegram/TelegramManager.java b/src/com/eactive/eai/batch/telegram/TelegramManager.java index 1b3ad2e..1b342fb 100644 --- a/src/com/eactive/eai/batch/telegram/TelegramManager.java +++ b/src/com/eactive/eai/batch/telegram/TelegramManager.java @@ -287,7 +287,7 @@ public class TelegramManager implements Lifecycle } else { - int delim = new Integer(length_token).intValue(); + int delim = Integer.parseInt(length_token); result[i]=telegram.substring(beginIndex, beginIndex+=delim); logger.debug("> 수신 전문필드 파싱... Index: ["+ i +"], Type: ["+ type_token +"], Length: ["+ length_token +"], Name: ["+ telegramVO.getTelegramItem(i+1).getFieldName() +"], Value: ["+ result[i] +"]"); } @@ -333,7 +333,7 @@ public class TelegramManager implements Lifecycle } else { - int delim = new Integer(length_token).intValue(); + int delim = Integer.parseInt(length_token); result[i]=telegram.substring(beginIndex, beginIndex+=delim); logger.debug("> 수신 전문필드 파싱... Index: ["+ i +"], Length: ["+ length_token +"], Name: ["+ telegramVO.getTelegramItem(i+1).getFieldName() +"], Value: ["+ result[i] +"]"); } @@ -464,7 +464,7 @@ public class TelegramManager implements Lifecycle while(i < lengths.length) { if (!lengths[i].trim().toUpperCase().equals("XX")) - totalLength += new Integer(lengths[i]).intValue(); + totalLength += Integer.parseInt(lengths[i]); i++; } return totalLength; @@ -542,7 +542,7 @@ public class TelegramManager implements Lifecycle else { // 정의된 필드의 길이 - int fieldLen = new Integer(fieldLength).intValue(); + int fieldLen = Integer.parseInt(fieldLength); // 정의된 필드의 길이보다 큰 경우 예외 처리 if (fieldContent.length() > fieldLen) diff --git a/src/com/eactive/eai/batch/telegram/TelegramVO.java b/src/com/eactive/eai/batch/telegram/TelegramVO.java index c4c0456..b578d0b 100644 --- a/src/com/eactive/eai/batch/telegram/TelegramVO.java +++ b/src/com/eactive/eai/batch/telegram/TelegramVO.java @@ -146,7 +146,7 @@ public class TelegramVO implements Serializable String lengthsarray[] = new String[itemVOs.size()]; for(int i=0; i folders = makeFolderInfos(); + for ( FolderInfo folder : folders) + deleteExpiredFiles(folder); + logger.info("=== Finished " + this.getClass().getSimpleName() + " ==="); + } + + private void deleteExpiredFiles(FolderInfo folderInfo) { + Path directory = Paths.get(folderInfo.path).toAbsolutePath().normalize(); + + if (!Files.isDirectory(directory)) { logger.error("Can't find directory: '"+directory+"'"); return; } + if (folderInfo.retentionDay < 1) { + logger.error("Invalid retention day: path='"+directory+"', retentionDay=" + folderInfo.retentionDay); + return; + } + + Instant cutoffTime = Instant.now().minus(folderInfo.retentionDay, ChronoUnit.DAYS); + + try (Stream stream = Files.walk(directory)) { + stream.sorted(Comparator.comparingInt(Path::getNameCount).reversed()) + .filter(path -> !path.equals(directory)) + .forEach(path -> { + try { + if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) { + Files.delete(path); + logger.info("Deleted empty directory: '"+path+"'"); + } else if (!Files.getLastModifiedTime(path).toInstant().isAfter(cutoffTime)) { + Files.delete(path); + logger.info("Deleted expired file: '"+path+"'"); + } + } catch (NoSuchFileException ignored) { // 다른 작업에서 이미 삭제한 경우이므로 무시 + } catch (DirectoryNotEmptyException ignored) { // 보존 대상 파일이 남아 있는 디렉터리는 유지 + } catch (IOException e) { + logger.error("Failed to delete: '"+path+"'", e); + } + }); + } catch (IOException | UncheckedIOException e) { + logger.error("Failed to clean directory: '"+directory+"'", e); + } + } + + private List makeFolderInfos() { + List ret = new ArrayList<>(); + for ( PropertyKeys key : keys ) { + String dirString = PropManager.getInstance().getProperty(PROPERTY_GROUP, key.dirKey); + String retention = PropManager.getInstance().getProperty(PROPERTY_GROUP, key.retentionKey); + + if ( isInvalidProperty(key.dirKey, dirString) ) continue; + if ( isInvalidProperty(key.retentionKey, retention) ) continue; + + if (!Files.exists( Paths.get(dirString)) ) { + logger.error("Can't find dir '"+dirString+"' for '"+key.dirKey+"'"); + continue; + } + + try { + int retentionDays = Integer.parseInt(retention); + ret.add(new FolderInfo(dirString, retentionDays)); + } catch (NumberFormatException e) { + logger.error("Invalid retention days '"+retention+"' for '"+key.retentionKey+"'"); + } + } + + return ret; + } + + private boolean isInvalidProperty(String key, String value) { + if (value == null || value.isEmpty()) { + logger.warn("Can't find property :: Group="+PROPERTY_GROUP+", Key=" + key); + return true; + } + + return false; + } + +} diff --git a/src/com/eactive/eai/common/util/JndiObjectFactoryBeanForElink.java b/src/com/eactive/eai/common/util/JndiObjectFactoryBeanForElink.java deleted file mode 100644 index 78286f6..0000000 --- a/src/com/eactive/eai/common/util/JndiObjectFactoryBeanForElink.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.eactive.eai.common.util; - -import org.springframework.jndi.JndiObjectFactoryBean; - -import com.eactive.eai.rms.client.util.ContainerUtil; - -public class JndiObjectFactoryBeanForElink extends JndiObjectFactoryBean { - public void setJndiName(String jndiName) { - super.setJndiName(jndiName); - - if (ContainerUtil.get() == ContainerUtil.TOMCAT) { - super.setResourceRef(true); - } else if (ContainerUtil.get() == ContainerUtil.WEBLOGIC) { - super.setResourceRef(false); - } else if (ContainerUtil.get() == ContainerUtil.JBOSS) { - super.setResourceRef(false); - } else if (ContainerUtil.get() == ContainerUtil.WEBSPHERE) { - super.setResourceRef(false); - } else { - super.setResourceRef(false); - } - } - public String getJndiName() { - return super.getJndiName(); - } - -} diff --git a/src/com/eactive/eai/common/util/Logger.java b/src/com/eactive/eai/common/util/Logger.java index 8326b1c..ab245d3 100644 --- a/src/com/eactive/eai/common/util/Logger.java +++ b/src/com/eactive/eai/common/util/Logger.java @@ -178,7 +178,6 @@ public class Logger implements LogKeys, Serializable { HashMap> fa = new HashMap>(); for(int i=0;i appender = addFileAppender(appenderNameList[i]); if ( appender == null ) { continue; @@ -201,16 +200,12 @@ public class Logger implements LogKeys, Serializable { if (StringUtils.isNotBlank(encoding)) { fple.setCharset(Charset.forName(encoding)); } - fple.start(); - appender.setEncoder( fple ); appender.start(); - fa.put( appenderNameList[i], appender ); } - //======================================================== //3. 프라퍼티에 설정된 모든 파일 Logger 생성 //======================================================== @@ -320,7 +315,7 @@ public class Logger implements LogKeys, Serializable { } logger = (ch.qos.logback.classic.Logger)fileLogger.getLoggerImpl();//(ch.qos.logback.classic.Logger) LoggerFactory.getLogger(loggerName); try { - logger.setAdditive(new Boolean(aditivity).booleanValue()); + logger.setAdditive(Boolean.parseBoolean(aditivity)); } catch(Exception e) { logger.setAdditive(false); } @@ -402,7 +397,7 @@ public class Logger implements LogKeys, Serializable { appender.setRollingPolicy( rollingPolicy ); try { String append = props.getProperty(APPENDER_FILE_APPEND); - appender.setAppend(new Boolean(append).booleanValue()); + appender.setAppend(Boolean.parseBoolean(append)); } catch(Exception e) { appender.setAppend(true); } @@ -893,7 +888,7 @@ public class Logger implements LogKeys, Serializable { rollingPolicy.setMaxHistory(Integer.parseInt(maxBackupIndex)); rollingPolicy.start(); try { - appender.setAppend(new Boolean(fileAppend).booleanValue()); + appender.setAppend(Boolean.parseBoolean(fileAppend)); } catch(Exception e) { appender.setAppend(true); } @@ -902,7 +897,7 @@ public class Logger implements LogKeys, Serializable { appender.setRollingPolicy( rollingPolicy ); try { - appender.setAppend(new Boolean(fileAppend).booleanValue()); + appender.setAppend(Boolean.parseBoolean(fileAppend)); } catch(Exception e) { appender.setAppend(true); } diff --git a/src/com/eactive/eai/common/util/convert/CodeConversion.java b/src/com/eactive/eai/common/util/convert/CodeConversion.java index b7a4891..82dea60 100644 --- a/src/com/eactive/eai/common/util/convert/CodeConversion.java +++ b/src/com/eactive/eai/common/util/convert/CodeConversion.java @@ -111,7 +111,7 @@ public class CodeConversion throw new Exception("Maximun COMP Length Over["+src+"]"); } - int iKey = new Integer(src).intValue(); + int iKey = Integer.parseInt(src); // System.out.println("HEX[0x"+ Integer.toHexString(iKey)+"]"); @@ -120,8 +120,8 @@ public class CodeConversion int upper = iKey >> 8 & 0xff; comp = new byte[2]; - comp[0] = new Integer(upper).byteValue(); - comp[1] = new Integer(lower).byteValue(); + comp[0] = (byte) upper; + comp[1] = (byte) lower; } else { int byte1 = iKey >> 24 & 0xffff; @@ -129,10 +129,10 @@ public class CodeConversion int byte3 = iKey >> 8 & 0xffff; int byte4 = iKey & 0xffff; comp = new byte[4]; - comp[0] = new Integer(byte1).byteValue(); - comp[1] = new Integer(byte2).byteValue(); - comp[2] = new Integer(byte3).byteValue(); - comp[3] = new Integer(byte4).byteValue(); + comp[0] = (byte) byte1; + comp[1] = (byte) byte2; + comp[2] = (byte) byte3; + comp[3] = (byte) byte4; } } catch(Exception e) { diff --git a/src/com/eactive/eai/common/web/AppInitializer.java b/src/com/eactive/eai/common/web/AppInitializer.java index 3be0059..4abc20d 100644 --- a/src/com/eactive/eai/common/web/AppInitializer.java +++ b/src/com/eactive/eai/common/web/AppInitializer.java @@ -10,6 +10,7 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import javax.sql.DataSource; import com.eactive.eai.adapter.socket.config.SocketAdapterManager; +import com.eactive.eai.batch.code.CodeMessageManager; import com.eactive.eai.batch.scheduler.SchedulerMessageManager; import com.eactive.eai.common.exception.ExceptionUtil; import com.eactive.eai.common.lifecycle.Lifecycle; @@ -124,6 +125,15 @@ public class AppInitializer implements InitializingBean, DisposableBean { } + logger.debug("CodeMessageManager 메모리 로딩 시작 ------------------------------------------"); + try { + CodeMessageManager.getInstance().start(); + } catch(LifecycleException e) { + logger.error( e.getMessage(), e); + throw new RuntimeException(ExceptionUtil.getErrorCode(e,"BFCEAICWB001")); + } + logger.debug("CodeMessageManager 메모리 로딩 종료 ------------------------------------------"); + logger.debug("Property 메모리 로딩 시작 ------------------------------------------"); try { PropManager.getInstance().start(); @@ -132,7 +142,7 @@ public class AppInitializer implements InitializingBean, DisposableBean { throw new RuntimeException(ExceptionUtil.getErrorCode(e,"BFCEAICWB001")); } logger.debug("Property 메모리 로딩 종료 ------------------------------------------"); - + logger.debug("Logger 메모리 로딩 시작 ------------------------------------------"); try { Logger.doConfigure(); @@ -147,22 +157,22 @@ public class AppInitializer implements InitializingBean, DisposableBean { logger.error(e.getMessage(), e); } - try { - Class clazz = Class - .forName("com.eactive.eai.rms.client.context.MonitoringContextFactory"); - Object factory = clazz.newInstance(); - Method method = clazz.getMethod("create"); - method.invoke(factory); - System.out.println("RMSCLIENT AGENT STARTED ~~ !!!!"); - logger.warn("EMSCLIENT AGENT STARTED ~~ !!!!"); - } catch (InvocationTargetException e) { - System.out.println("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.getTargetException().toString()); - logger.error("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.getTargetException().toString(),e.getTargetException()); - e.getTargetException().printStackTrace(); - } catch (Throwable e) { - System.out.println("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.toString()); - logger.error("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.toString(),e); - } +// try { +// Class clazz = Class +// .forName("com.eactive.eai.rms.client.context.MonitoringContextFactory"); +// Object factory = clazz.newInstance(); +// Method method = clazz.getMethod("create"); +// method.invoke(factory); +// System.out.println("RMSCLIENT AGENT STARTED ~~ !!!!"); +// logger.warn("EMSCLIENT AGENT STARTED ~~ !!!!"); +// } catch (InvocationTargetException e) { +// System.out.println("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.getTargetException().toString()); +// logger.error("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.getTargetException().toString(),e.getTargetException()); +// e.getTargetException().printStackTrace(); +// } catch (Throwable e) { +// System.out.println("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.toString()); +// logger.error("RMSCLIENT AGENT CANNOT START ~~ !!!! - "+e.toString(),e); +// } logger.debug("LifeCycle 관련 클래스 메모리 로딩 시작 ------------------------------------------"); LifecycleManager manager = LifecycleManager.getInstance(); diff --git a/src/com/eactive/eai/inbound/ReqRecvEventListener.java b/src/com/eactive/eai/inbound/ReqRecvEventListener.java index fd4d7c8..9237376 100644 --- a/src/com/eactive/eai/inbound/ReqRecvEventListener.java +++ b/src/com/eactive/eai/inbound/ReqRecvEventListener.java @@ -183,10 +183,8 @@ public class ReqRecvEventListener extends Process{ LogUtil.setStartLog (batchMsgDoc); logger.info("[Req Recv File Event] ※ Event 파일명 : [" + fileName +"]"); } - - private void catchException(Exception ex) - { + private void catchException(Exception ex) { try { // 파일로그 처리 String errMsg = ExceptionUtil.getErrorCode(ex, "BECEAIIFE007"); @@ -201,6 +199,7 @@ public class ReqRecvEventListener extends Process{ logger.error("[Req Recv File Event] ★★★★★ 수신 요청 File Event Listner 예외 처리 중 에러 !! ★★★★★", e); } } + @Override public BatchDoc clientRequestwithReturn( BatchDoc batchDoc) throws Exception {