Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bfda9ef610 | |||
| df1b1f2667 | |||
| a891676617 | |||
| cd2ab33a0d | |||
| b39a26350e | |||
| 65d61e646b | |||
| 68bc6fa47a | |||
| 787f9a4f42 | |||
| bca28dbd1b | |||
| bc79b8b166 | |||
| 2d17387def | |||
| 1508d01afb | |||
| 17d533fe06 | |||
| 7e7d107dde | |||
| 557a071b1e | |||
| 18b3e781b1 | |||
| 1efd2deb9d | |||
| f9a520eacc | |||
| dc1ee33517 | |||
| 7fbe64f562 | |||
| 42cbafd67d | |||
| e21f134c11 |
@@ -235,3 +235,7 @@ gradle-app.setting
|
||||
# End of https://www.gitignore.io/api/java,macos,gradle,intellij
|
||||
/EAISIMWeb/
|
||||
/.apt_generated_tests/
|
||||
|
||||
# Claude Code
|
||||
.claude/
|
||||
/작업내역*.md
|
||||
|
||||
+1
-1
Submodule elink-online-common updated: 7aa230f156...d81aeeef67
+1
-1
Submodule elink-online-core updated: 8b24475d2d...b27138d8f7
+1
-1
Submodule elink-online-core-jpa updated: 92aeddecd0...76342bfaef
+1
-1
Submodule elink-online-transformer updated: c8a58fdf5b...17f6df5068
@@ -1,380 +1,380 @@
|
||||
package com.eactive.eai.adapter.controller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
// jwhong
|
||||
import org.json.simple.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.Keys;
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilterFactoryKjb;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.adapter.service.ApiAdapterService;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||
import com.eactive.eai.common.stdmessage.STDMsgInfoAddOnVO;
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.common.util.InboundErrorLogger;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.common.util.UUIDGenerator;
|
||||
import com.eactive.eai.inbound.action.ActionException;
|
||||
import com.eactive.eai.inbound.action.ActionFactory;
|
||||
import com.eactive.eai.inbound.action.RequestAction;
|
||||
import com.eactive.eai.inbound.error.InboundErrorInfoVO;
|
||||
|
||||
@RestController
|
||||
public class ApiAdapterController implements HttpAdapterServiceKey {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
@Autowired
|
||||
ApiAdapterService service;
|
||||
|
||||
/**
|
||||
* KJBANK 요구사항으로 /mapi/oauth2/token 과 같은 형태로 토큰 발급거래를 수행해야해서 예외처리함
|
||||
*
|
||||
* @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
|
||||
* endpoints)
|
||||
*/
|
||||
@RequestMapping(value = { "/api/*", "/mapi/*", "/api/*/{path:^(?!.*oauth).*$}/**",
|
||||
"/mapi/{path:^(?!.*oauth2).*$}/**" })
|
||||
// @RequestMapping(value = {"/api/**"})
|
||||
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
||||
throws Exception {
|
||||
// /ONLWeb/api/v1/public/getUserInfo.svc
|
||||
String apiUri = servletRequest.getRequestURI();
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
apiUri = StringUtils.removeStart(apiUri, servletRequest.getContextPath());
|
||||
apiUri = StringUtils.removeEnd(apiUri, "/");
|
||||
|
||||
HttpDynamicInAdapterUri adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), "");
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
||||
}
|
||||
|
||||
if (adptUri == null) {
|
||||
logError(servletRequest);
|
||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
||||
"can not find Adapter Uri");
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(errorMsg);
|
||||
}
|
||||
|
||||
// Received time , jwhong
|
||||
long receivedTimeMillis = System.currentTimeMillis(); // 밀리세컨 단위로 보내야함
|
||||
String receivedTimeStr = String.valueOf(receivedTimeMillis);
|
||||
|
||||
String adapterGroupName = adptUri.getAdptGrpName();
|
||||
String adapterName = adptUri.getAdptName();
|
||||
AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
AdapterVO adapterVO = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName);
|
||||
if (adapterVO == null) {
|
||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR,
|
||||
"Adapter not found error");
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
|
||||
.body(errorMsg);
|
||||
}
|
||||
|
||||
Properties httpProp = AdapterPropManager.getInstance().getProperties(adapterVO.getPropGroupName());
|
||||
|
||||
String adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||
MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
||||
String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||
|
||||
String responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
|
||||
ResponseEntity responseEntity = null;
|
||||
Properties transactionProp = new Properties();
|
||||
// jwhong, put api received time, eaiSvcCode
|
||||
transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
||||
|
||||
// ** jwhong TSEAIHS04의 api full path와 비교하여 adapter를 가져온다
|
||||
// String bzwkSvcKeyName = ""; // Adapter Group별 Action Class에 따라 구성이 달라짐. 예)
|
||||
// // _AGW_IN_RST_SyS:POST/account/{acc_no}
|
||||
// String adapterGrpName = ""; // Adapter Group명 예) _AGW_IN_RST_SyS : API_PATH(/api/test)
|
||||
String apiSvcCode = ""; // eaiSvcCd 예) LONNCHCON00005S2
|
||||
String apiFullPathKey = ""; // 예) POST|/api/test/account/list, POST|/api/test/account/{acc_no}
|
||||
Map<String, String> pathVariables = null;
|
||||
try {
|
||||
// PathVariable(ex:/api/test/account/{acc_no}) 대응 및 DAO조회 제거.
|
||||
// /api/test/account/1234567 호출시 /api/test/account/{acc_no} API 로 식별.
|
||||
|
||||
// String methodAndUri = getRequestRuledPath(servletRequest, apiUri, adapterVO, transactionProp);
|
||||
String methodAndUri = servletRequest.getMethod() + "|" + apiUri;
|
||||
STDMessageManager manager = STDMessageManager.getInstance();
|
||||
STDMsgInfoAddOnVO stdMsgInfo = manager.getStdMsgInfoAddOn(methodAndUri);
|
||||
// bzwkSvcKeyName = stdMsgInfo.getBzwksvckeyname();
|
||||
apiSvcCode = stdMsgInfo.getEaiSvcCd();
|
||||
transactionProp.put(API_SERVICE_CODE, apiSvcCode);
|
||||
|
||||
// adapterGrpName = stdMsgInfo.gAdapterGroupName();
|
||||
apiFullPathKey = stdMsgInfo.getApiFullPath();
|
||||
if (STDMessageManager.isPathVariable(apiFullPathKey)) {
|
||||
pathVariables = new AntPathMatcher().extractUriTemplateVariables(apiFullPathKey, methodAndUri);
|
||||
}
|
||||
|
||||
// adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), adapterGrpName);
|
||||
} catch (Exception e) {
|
||||
// adptUri = null;
|
||||
}
|
||||
// ***
|
||||
if (pathVariables != null) {
|
||||
transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
||||
}
|
||||
|
||||
try {
|
||||
String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||
transactionProp);
|
||||
// if (RESPONSE_TYPE_ASYNC.equals(responseType)) { // table의 값이 ASYNC 로 들어가 있는데
|
||||
// response_type_async는 ASYN 로 되어 있어 아래처럼 비교함 jwhong 2025
|
||||
if ("ASYNC".equals(responseType)) {
|
||||
// responseEntity = ResponseEntity.ok("dummy"); // comment by jwhong
|
||||
// servletResponse.addHeader("traceId", responseData); // uuid를 response header에
|
||||
servletResponse.addHeader("traceId",
|
||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
int httpStatus = servletResponse.getStatus();
|
||||
if (httpStatus == 200) {
|
||||
// 업체별 aync response message 가 다르다.
|
||||
String asyncMsgStyle = httpProp.getProperty("ASYNC_RTNMSG_TYPE", "");
|
||||
String responseBody = "";
|
||||
boolean encryptAsyncAckApply = StringUtils
|
||||
.equalsIgnoreCase(httpProp.getProperty("ASYNC_ENCRYPT_ACK", "N"), "Y");
|
||||
|
||||
if (asyncMsgStyle == null || asyncMsgStyle.trim().isEmpty()) {
|
||||
responseBody = makeResponseBodyMsg();
|
||||
} else {
|
||||
responseBody = asyncMsgStyle;
|
||||
}
|
||||
if (encryptAsyncAckApply) {
|
||||
responseBody = service.doPostEncryption(responseBody, transactionProp, servletRequest);
|
||||
}
|
||||
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseBody);
|
||||
// jwhong
|
||||
} else {
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
}
|
||||
} else {
|
||||
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
|
||||
// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
|
||||
|
||||
servletResponse.addHeader("traceId",
|
||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
int httpStatus = servletResponse.getStatus();
|
||||
if (httpStatus != 200) {
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
} else {
|
||||
responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
|
||||
String errorMsg = null;
|
||||
|
||||
if( e instanceof HttpStatusException ) {
|
||||
logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||
HttpStatusException e1 = (HttpStatusException) e;
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AP_ERROR, e1.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||
}
|
||||
else if( e instanceof JwtAuthException )
|
||||
{
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType)
|
||||
.body(errorMsg);
|
||||
}
|
||||
String postFilterNames = httpProp.getProperty("POST_FILTERS","");
|
||||
|
||||
if( postFilterNames.contains("HMAC_SHA256") ) {
|
||||
HttpAdapterFilter filter = HttpAdapterFilterFactoryKjb.createFilter("HMAC_SHA256");
|
||||
filter.doPostFilter(adapterGroupName, postFilterNames, errorMsg, transactionProp, servletRequest, servletResponse);
|
||||
}
|
||||
|
||||
|
||||
} finally {
|
||||
/**
|
||||
* 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
||||
* 추후 더 좋은방법이 생길경우 개선 요망
|
||||
*/
|
||||
try {
|
||||
|
||||
servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
||||
|
||||
if (!"ASYNC".equals(responseType)) {
|
||||
String uuid = transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
String url = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
|
||||
String method = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
|
||||
int httpStatusCode = servletResponse.getStatus();
|
||||
|
||||
Map<Object, Object> headerMap = new HashMap<>();
|
||||
// 응답 헤더 로깅
|
||||
for (String headerName : servletResponse.getHeaderNames()) {
|
||||
String headerValue = servletResponse.getHeader(headerName);
|
||||
logger.debug(String.format("httpHeader logging headerKey=%s, headerValue=%s",
|
||||
headerName, headerValue));
|
||||
headerMap.put(headerName, headerValue);
|
||||
}
|
||||
//HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName,adapterName, headerMap, url, method, httpStatusCode);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("http header db logging fail.", e);
|
||||
}
|
||||
}
|
||||
return responseEntity;
|
||||
}
|
||||
|
||||
/**
|
||||
* url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
|
||||
* /api/v1/public/getUserInfo.svc
|
||||
*
|
||||
* @param apiUri
|
||||
* @return
|
||||
*/
|
||||
private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager,
|
||||
String adapterGrpName) throws Exception {
|
||||
if (StringUtils.isBlank(apiUri)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// * manager 출력
|
||||
logger.warn("===== adptUriMap 상세 내용 =====");
|
||||
for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
||||
HttpDynamicInAdapterUri uriObj = entry.getValue();
|
||||
logger.warn("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
||||
+ uriObj.getUri());
|
||||
}
|
||||
logger.warn("================================");
|
||||
|
||||
//
|
||||
for (int i = 0; i < 10; i++) {
|
||||
HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
|
||||
if (adptUri != null) {
|
||||
if (StringUtils.isNotEmpty(adapterGrpName)) {
|
||||
if(adptUri.getAdptGrpName().equals(adapterGrpName)) {
|
||||
return adptUri;
|
||||
}
|
||||
} else {
|
||||
return adptUri;
|
||||
}
|
||||
}
|
||||
|
||||
// /api/v1/public
|
||||
apiUri = StringUtils.substringBeforeLast(apiUri, "/");
|
||||
if (apiUri.length() < 4) { // /api
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void logError(HttpServletRequest request) {
|
||||
InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||
|
||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||
String serverName = eaiServerManager.getLocalServerName();
|
||||
String uuid = null;
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
String instanceid1 = serverName.substring(0, 2);
|
||||
String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||
String instid = instanceid1 + instanceid2;
|
||||
uuid = instid + UUIDGenerator.getUUID();
|
||||
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = request.getRequestURI();
|
||||
|
||||
String errorCode = "RECEAIIRP010";
|
||||
String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
|
||||
|
||||
errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
||||
errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
|
||||
errorInfoVO.setErrCd(errorCode); // 에러코드
|
||||
errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||
errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
||||
errorInfoVO.setErrDstcd(" ");
|
||||
sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
|
||||
.append(request.getRequestURI());
|
||||
errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
||||
errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
||||
|
||||
InboundErrorLogger.error(errorInfoVO);
|
||||
}
|
||||
|
||||
private String makeResponseBodyMsg() {
|
||||
|
||||
Map<String, Object> dataMap = new HashMap<>();
|
||||
dataMap.put("result", 1);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
|
||||
map.put("code", "200");
|
||||
map.put("data", dataMap);
|
||||
map.put("message", "정상 처리 되었습니다.");
|
||||
|
||||
JSONObject json = new JSONObject();
|
||||
json.putAll(map);
|
||||
|
||||
return json.toJSONString();
|
||||
}
|
||||
|
||||
/*
|
||||
* private String makeResponseBodyMsg(String asyncMsgStyle) {
|
||||
*
|
||||
* Map<String, Object> dataMap = new HashMap<>(); dataMap.put("result", 1);
|
||||
* Map<String, Object> map = new HashMap<>();
|
||||
*
|
||||
* switch (asyncMsgStyle) { case "TB_SUC": map.put("rspCode", "TB_SUC_000");
|
||||
* map.put("rspMsg", "정상"); map.put("data", dataMap); break; case "ONLYDATA":
|
||||
* map.put("data", dataMap); map.put("success", "true"); break; default:
|
||||
* map.put("code", "200"); map.put("data", dataMap); map.put("message",
|
||||
* "정상 처리 되었습니다."); break; }
|
||||
*
|
||||
* JSONObject json = new JSONObject(); json.putAll(map);
|
||||
*
|
||||
* return json.toJSONString(); }
|
||||
*/
|
||||
}
|
||||
//package com.eactive.eai.adapter.controller;
|
||||
//
|
||||
//import java.util.ArrayList;
|
||||
//import java.util.Collections;
|
||||
//import java.util.Date;
|
||||
//import java.util.Enumeration;
|
||||
//import java.util.HashMap;
|
||||
//import java.util.List;
|
||||
//import java.util.Map;
|
||||
//import java.util.Properties;
|
||||
//
|
||||
//import javax.servlet.http.HttpServletRequest;
|
||||
//import javax.servlet.http.HttpServletResponse;
|
||||
//
|
||||
//import org.apache.commons.lang3.StringUtils;
|
||||
//// jwhong
|
||||
//import org.json.simple.JSONObject;
|
||||
//import org.springframework.beans.factory.annotation.Autowired;
|
||||
//import org.springframework.http.HttpStatus;
|
||||
//import org.springframework.http.MediaType;
|
||||
//import org.springframework.http.ResponseEntity;
|
||||
//import org.springframework.util.AntPathMatcher;
|
||||
//import org.springframework.web.bind.annotation.RequestMapping;
|
||||
//import org.springframework.web.bind.annotation.RestController;
|
||||
//
|
||||
//import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
//import com.eactive.eai.adapter.AdapterManager;
|
||||
//import com.eactive.eai.adapter.AdapterPropManager;
|
||||
//import com.eactive.eai.adapter.AdapterVO;
|
||||
//import com.eactive.eai.adapter.Keys;
|
||||
//import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
//import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
//import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
//import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
||||
//import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
||||
//import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
//import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilterFactoryKjb;
|
||||
//import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
//import com.eactive.eai.adapter.service.ApiAdapterService;
|
||||
//import com.eactive.eai.common.TransactionContextKeys;
|
||||
//import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
//import com.eactive.eai.common.server.EAIServerManager;
|
||||
//import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||
//import com.eactive.eai.common.stdmessage.STDMsgInfoAddOnVO;
|
||||
//import com.eactive.eai.common.util.DatetimeUtil;
|
||||
//import com.eactive.eai.common.util.InboundErrorLogger;
|
||||
//import com.eactive.eai.common.util.Logger;
|
||||
//import com.eactive.eai.common.util.MessageUtil;
|
||||
//import com.eactive.eai.common.util.UUIDGenerator;
|
||||
//import com.eactive.eai.inbound.action.ActionException;
|
||||
//import com.eactive.eai.inbound.action.ActionFactory;
|
||||
//import com.eactive.eai.inbound.action.RequestAction;
|
||||
//import com.eactive.eai.inbound.error.InboundErrorInfoVO;
|
||||
//
|
||||
//@RestController
|
||||
//public class ApiAdapterController implements HttpAdapterServiceKey {
|
||||
// static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
//
|
||||
// @Autowired
|
||||
// ApiAdapterService service;
|
||||
//
|
||||
// /**
|
||||
// * KJBANK 요구사항으로 /mapi/oauth2/token 과 같은 형태로 토큰 발급거래를 수행해야해서 예외처리함
|
||||
// *
|
||||
// * @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
|
||||
// * endpoints)
|
||||
// */
|
||||
// @RequestMapping(value = { "/api/*", "/mapi/*", "/api/*/{path:^(?!.*oauth).*$}/**",
|
||||
// "/mapi/{path:^(?!.*oauth2).*$}/**" })
|
||||
//// @RequestMapping(value = {"/api/**"})
|
||||
// public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
||||
// throws Exception {
|
||||
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
||||
// String apiUri = servletRequest.getRequestURI();
|
||||
// // /api/v1/public/getUserInfo.svc
|
||||
// apiUri = StringUtils.removeStart(apiUri, servletRequest.getContextPath());
|
||||
// apiUri = StringUtils.removeEnd(apiUri, "/");
|
||||
//
|
||||
// HttpDynamicInAdapterUri adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), "");
|
||||
//
|
||||
// if (logger.isDebug()) {
|
||||
// logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
||||
// }
|
||||
//
|
||||
// if (adptUri == null) {
|
||||
// logError(servletRequest);
|
||||
// String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
||||
// "can not find Adapter Uri");
|
||||
// return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(errorMsg);
|
||||
// }
|
||||
//
|
||||
// // Received time , jwhong
|
||||
// long receivedTimeMillis = System.currentTimeMillis(); // 밀리세컨 단위로 보내야함
|
||||
// String receivedTimeStr = String.valueOf(receivedTimeMillis);
|
||||
//
|
||||
// String adapterGroupName = adptUri.getAdptGrpName();
|
||||
// String adapterName = adptUri.getAdptName();
|
||||
// AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
// AdapterVO adapterVO = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName);
|
||||
// if (adapterVO == null) {
|
||||
// String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR,
|
||||
// "Adapter not found error");
|
||||
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
|
||||
// .body(errorMsg);
|
||||
// }
|
||||
//
|
||||
// Properties httpProp = AdapterPropManager.getInstance().getProperties(adapterVO.getPropGroupName());
|
||||
//
|
||||
// String adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
// String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||
// MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
||||
// String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||
//
|
||||
// String responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
|
||||
// ResponseEntity responseEntity = null;
|
||||
// Properties transactionProp = new Properties();
|
||||
// // jwhong, put api received time, eaiSvcCode
|
||||
// transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
||||
//
|
||||
// // ** jwhong TSEAIHS04의 api full path와 비교하여 adapter를 가져온다
|
||||
//// String bzwkSvcKeyName = ""; // Adapter Group별 Action Class에 따라 구성이 달라짐. 예)
|
||||
//// // _AGW_IN_RST_SyS:POST/account/{acc_no}
|
||||
//// String adapterGrpName = ""; // Adapter Group명 예) _AGW_IN_RST_SyS : API_PATH(/api/test)
|
||||
// String apiSvcCode = ""; // eaiSvcCd 예) LONNCHCON00005S2
|
||||
// String apiFullPathKey = ""; // 예) POST|/api/test/account/list, POST|/api/test/account/{acc_no}
|
||||
// Map<String, String> pathVariables = null;
|
||||
// try {
|
||||
// // PathVariable(ex:/api/test/account/{acc_no}) 대응 및 DAO조회 제거.
|
||||
// // /api/test/account/1234567 호출시 /api/test/account/{acc_no} API 로 식별.
|
||||
//
|
||||
//// String methodAndUri = getRequestRuledPath(servletRequest, apiUri, adapterVO, transactionProp);
|
||||
// String methodAndUri = servletRequest.getMethod() + "|" + apiUri;
|
||||
// STDMessageManager manager = STDMessageManager.getInstance();
|
||||
// STDMsgInfoAddOnVO stdMsgInfo = manager.getStdMsgInfoAddOn(methodAndUri);
|
||||
//// bzwkSvcKeyName = stdMsgInfo.getBzwksvckeyname();
|
||||
// apiSvcCode = stdMsgInfo.getEaiSvcCd();
|
||||
// transactionProp.put(API_SERVICE_CODE, apiSvcCode);
|
||||
//
|
||||
//// adapterGrpName = stdMsgInfo.gAdapterGroupName();
|
||||
// apiFullPathKey = stdMsgInfo.getApiFullPath();
|
||||
// if (STDMessageManager.isPathVariable(apiFullPathKey)) {
|
||||
// pathVariables = new AntPathMatcher().extractUriTemplateVariables(apiFullPathKey, methodAndUri);
|
||||
// }
|
||||
//
|
||||
//// adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), adapterGrpName);
|
||||
// } catch (Exception e) {
|
||||
//// adptUri = null;
|
||||
// }
|
||||
// // ***
|
||||
// if (pathVariables != null) {
|
||||
// transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||
// transactionProp);
|
||||
// // if (RESPONSE_TYPE_ASYNC.equals(responseType)) { // table의 값이 ASYNC 로 들어가 있는데
|
||||
// // response_type_async는 ASYN 로 되어 있어 아래처럼 비교함 jwhong 2025
|
||||
// if ("ASYNC".equals(responseType)) {
|
||||
// // responseEntity = ResponseEntity.ok("dummy"); // comment by jwhong
|
||||
// // servletResponse.addHeader("traceId", responseData); // uuid를 response header에
|
||||
// servletResponse.addHeader("traceId",
|
||||
// transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
// int httpStatus = servletResponse.getStatus();
|
||||
// if (httpStatus == 200) {
|
||||
// // 업체별 aync response message 가 다르다.
|
||||
// String asyncMsgStyle = httpProp.getProperty("ASYNC_RTNMSG_TYPE", "");
|
||||
// String responseBody = "";
|
||||
// boolean encryptAsyncAckApply = StringUtils
|
||||
// .equalsIgnoreCase(httpProp.getProperty("ASYNC_ENCRYPT_ACK", "N"), "Y");
|
||||
//
|
||||
// if (asyncMsgStyle == null || asyncMsgStyle.trim().isEmpty()) {
|
||||
// responseBody = makeResponseBodyMsg();
|
||||
// } else {
|
||||
// responseBody = asyncMsgStyle;
|
||||
// }
|
||||
// if (encryptAsyncAckApply) {
|
||||
// responseBody = service.doPostEncryption(responseBody, transactionProp, servletRequest);
|
||||
// }
|
||||
//
|
||||
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseBody);
|
||||
// // jwhong
|
||||
// } else {
|
||||
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
// }
|
||||
// } else {
|
||||
//// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
//// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
|
||||
//// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
|
||||
//
|
||||
// servletResponse.addHeader("traceId",
|
||||
// transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
// int httpStatus = servletResponse.getStatus();
|
||||
// if (httpStatus != 200) {
|
||||
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
// } else {
|
||||
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// } catch (Exception e) {
|
||||
//
|
||||
//
|
||||
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
//
|
||||
// String errorMsg = null;
|
||||
//
|
||||
// if( e instanceof HttpStatusException ) {
|
||||
// logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||
// HttpStatusException e1 = (HttpStatusException) e;
|
||||
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
// MessageUtil.ERROR_CODE_AP_ERROR, e1.getMessage(), errorResponseFormat);
|
||||
// responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||
// }
|
||||
// else if( e instanceof JwtAuthException )
|
||||
// {
|
||||
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
// MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage(), errorResponseFormat);
|
||||
// responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
// MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
||||
// responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType)
|
||||
// .body(errorMsg);
|
||||
// }
|
||||
// String postFilterNames = httpProp.getProperty("POST_FILTERS","");
|
||||
//
|
||||
// if( postFilterNames.contains("HMAC_SHA256") ) {
|
||||
// HttpAdapterFilter filter = HttpAdapterFilterFactoryKjb.createFilter("HMAC_SHA256");
|
||||
// filter.doPostFilter(adapterGroupName, postFilterNames, errorMsg, transactionProp, servletRequest, servletResponse);
|
||||
// }
|
||||
//
|
||||
//
|
||||
// } finally {
|
||||
// /**
|
||||
// * 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
||||
// * 추후 더 좋은방법이 생길경우 개선 요망
|
||||
// */
|
||||
// try {
|
||||
//
|
||||
// servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
||||
//
|
||||
// if (!"ASYNC".equals(responseType)) {
|
||||
// String uuid = transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
// String url = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
|
||||
// String method = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
|
||||
// int httpStatusCode = servletResponse.getStatus();
|
||||
//
|
||||
// Map<Object, Object> headerMap = new HashMap<>();
|
||||
// // 응답 헤더 로깅
|
||||
// for (String headerName : servletResponse.getHeaderNames()) {
|
||||
// String headerValue = servletResponse.getHeader(headerName);
|
||||
// logger.debug(String.format("httpHeader logging headerKey=%s, headerValue=%s",
|
||||
// headerName, headerValue));
|
||||
// headerMap.put(headerName, headerValue);
|
||||
// }
|
||||
// //HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName,adapterName, headerMap, url, method, httpStatusCode);
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// logger.warn("http header db logging fail.", e);
|
||||
// }
|
||||
// }
|
||||
// return responseEntity;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
|
||||
// * /api/v1/public/getUserInfo.svc
|
||||
// *
|
||||
// * @param apiUri
|
||||
// * @return
|
||||
// */
|
||||
// private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager,
|
||||
// String adapterGrpName) throws Exception {
|
||||
// if (StringUtils.isBlank(apiUri)) {
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// // * manager 출력
|
||||
// logger.warn("===== adptUriMap 상세 내용 =====");
|
||||
// for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
||||
// HttpDynamicInAdapterUri uriObj = entry.getValue();
|
||||
// logger.warn("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
||||
// + uriObj.getUri());
|
||||
// }
|
||||
// logger.warn("================================");
|
||||
//
|
||||
// //
|
||||
// for (int i = 0; i < 10; i++) {
|
||||
// HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
|
||||
// if (adptUri != null) {
|
||||
// if (StringUtils.isNotEmpty(adapterGrpName)) {
|
||||
// if(adptUri.getAdptGrpName().equals(adapterGrpName)) {
|
||||
// return adptUri;
|
||||
// }
|
||||
// } else {
|
||||
// return adptUri;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // /api/v1/public
|
||||
// apiUri = StringUtils.substringBeforeLast(apiUri, "/");
|
||||
// if (apiUri.length() < 4) { // /api
|
||||
// return null;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// private void logError(HttpServletRequest request) {
|
||||
// InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||
//
|
||||
// EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||
// String serverName = eaiServerManager.getLocalServerName();
|
||||
// String uuid = null;
|
||||
// StringBuffer sb = new StringBuffer();
|
||||
//
|
||||
// String instanceid1 = serverName.substring(0, 2);
|
||||
// String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||
// String instid = instanceid1 + instanceid2;
|
||||
// uuid = instid + UUIDGenerator.getUUID();
|
||||
//
|
||||
// String[] msgArgs = new String[1];
|
||||
// msgArgs[0] = request.getRequestURI();
|
||||
//
|
||||
// String errorCode = "RECEAIIRP010";
|
||||
// String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
|
||||
//
|
||||
// errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
||||
// errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
|
||||
// errorInfoVO.setErrCd(errorCode); // 에러코드
|
||||
// errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||
// errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
||||
// errorInfoVO.setErrDstcd(" ");
|
||||
// sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
|
||||
// .append(request.getRequestURI());
|
||||
// errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
||||
// errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
||||
//
|
||||
// InboundErrorLogger.error(errorInfoVO);
|
||||
// }
|
||||
//
|
||||
// private String makeResponseBodyMsg() {
|
||||
//
|
||||
// Map<String, Object> dataMap = new HashMap<>();
|
||||
// dataMap.put("result", 1);
|
||||
// Map<String, Object> map = new HashMap<>();
|
||||
//
|
||||
// map.put("code", "200");
|
||||
// map.put("data", dataMap);
|
||||
// map.put("message", "정상 처리 되었습니다.");
|
||||
//
|
||||
// JSONObject json = new JSONObject();
|
||||
// json.putAll(map);
|
||||
//
|
||||
// return json.toJSONString();
|
||||
// }
|
||||
//
|
||||
// /*
|
||||
// * private String makeResponseBodyMsg(String asyncMsgStyle) {
|
||||
// *
|
||||
// * Map<String, Object> dataMap = new HashMap<>(); dataMap.put("result", 1);
|
||||
// * Map<String, Object> map = new HashMap<>();
|
||||
// *
|
||||
// * switch (asyncMsgStyle) { case "TB_SUC": map.put("rspCode", "TB_SUC_000");
|
||||
// * map.put("rspMsg", "정상"); map.put("data", dataMap); break; case "ONLYDATA":
|
||||
// * map.put("data", dataMap); map.put("success", "true"); break; default:
|
||||
// * map.put("code", "200"); map.put("data", dataMap); map.put("message",
|
||||
// * "정상 처리 되었습니다."); break; }
|
||||
// *
|
||||
// * JSONObject json = new JSONObject(); json.putAll(map);
|
||||
// *
|
||||
// * return json.toJSONString(); }
|
||||
// */
|
||||
//}
|
||||
@@ -0,0 +1,370 @@
|
||||
package com.eactive.eai.adapter.controller;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
// jwhong
|
||||
import org.json.simple.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilterFactoryKjb;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.adapter.service.DJErpApiAdapterService;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||
import com.eactive.eai.common.stdmessage.STDMsgInfoAddOnVO;
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.common.util.InboundErrorLogger;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.common.util.UUIDGenerator;
|
||||
import com.eactive.eai.inbound.error.InboundErrorInfoVO;
|
||||
|
||||
@RestController
|
||||
public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
@Autowired
|
||||
DJErpApiAdapterService service;
|
||||
|
||||
/**
|
||||
* DJErp OAuth 조기 적용을 위한 Controller
|
||||
*
|
||||
* @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
|
||||
* endpoints)
|
||||
*/
|
||||
@RequestMapping(value = { "/dj/{path:^(?!oauth).*$}", "/dj/{path:^(?!oauth).*$}/**" })
|
||||
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
||||
throws Exception {
|
||||
// /ONLWeb/api/v1/public/getUserInfo.svc
|
||||
String apiUri = servletRequest.getRequestURI();
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
apiUri = StringUtils.removeStart(apiUri, servletRequest.getContextPath());
|
||||
apiUri = StringUtils.removeEnd(apiUri, "/");
|
||||
|
||||
HttpDynamicInAdapterUri adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), "");
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
||||
}
|
||||
|
||||
if (adptUri == null) {
|
||||
logError(servletRequest);
|
||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
||||
"can not find Adapter Uri");
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(errorMsg);
|
||||
}
|
||||
|
||||
// Received time , jwhong
|
||||
long receivedTimeMillis = System.currentTimeMillis(); // 밀리세컨 단위로 보내야함
|
||||
String receivedTimeStr = String.valueOf(receivedTimeMillis);
|
||||
|
||||
String adapterGroupName = adptUri.getAdptGrpName();
|
||||
String adapterName = adptUri.getAdptName();
|
||||
AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
AdapterVO adapterVO = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName);
|
||||
if (adapterVO == null) {
|
||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR,
|
||||
"Adapter not found error");
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
|
||||
.body(errorMsg);
|
||||
}
|
||||
|
||||
Properties httpProp = AdapterPropManager.getInstance().getProperties(adapterVO.getPropGroupName());
|
||||
|
||||
String adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||
MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
||||
String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||
|
||||
String responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
|
||||
ResponseEntity responseEntity = null;
|
||||
Properties transactionProp = new Properties();
|
||||
// jwhong, put api received time, eaiSvcCode
|
||||
transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
||||
|
||||
// ** jwhong TSEAIHS04의 api full path와 비교하여 adapter를 가져온다
|
||||
// String bzwkSvcKeyName = ""; // Adapter Group별 Action Class에 따라 구성이 달라짐. 예)
|
||||
// // _AGW_IN_RST_SyS:POST/account/{acc_no}
|
||||
// String adapterGrpName = ""; // Adapter Group명 예) _AGW_IN_RST_SyS : API_PATH(/api/test)
|
||||
String apiSvcCode = ""; // eaiSvcCd 예) LONNCHCON00005S2
|
||||
String apiFullPathKey = ""; // 예) POST|/api/test/account/list, POST|/api/test/account/{acc_no}
|
||||
Map<String, String> pathVariables = null;
|
||||
try {
|
||||
// PathVariable(ex:/api/test/account/{acc_no}) 대응 및 DAO조회 제거.
|
||||
// /api/test/account/1234567 호출시 /api/test/account/{acc_no} API 로 식별.
|
||||
|
||||
// String methodAndUri = getRequestRuledPath(servletRequest, apiUri, adapterVO, transactionProp);
|
||||
String methodAndUri = servletRequest.getMethod() + "|" + apiUri;
|
||||
STDMessageManager manager = STDMessageManager.getInstance();
|
||||
STDMsgInfoAddOnVO stdMsgInfo = manager.getStdMsgInfoAddOn(methodAndUri);
|
||||
// bzwkSvcKeyName = stdMsgInfo.getBzwksvckeyname();
|
||||
apiSvcCode = stdMsgInfo.getEaiSvcCd();
|
||||
transactionProp.put(API_SERVICE_CODE, apiSvcCode);
|
||||
|
||||
// adapterGrpName = stdMsgInfo.gAdapterGroupName();
|
||||
apiFullPathKey = stdMsgInfo.getApiFullPath();
|
||||
if (STDMessageManager.isPathVariable(apiFullPathKey)) {
|
||||
pathVariables = new AntPathMatcher().extractUriTemplateVariables(apiFullPathKey, methodAndUri);
|
||||
}
|
||||
|
||||
// adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), adapterGrpName);
|
||||
} catch (Exception e) {
|
||||
// adptUri = null;
|
||||
}
|
||||
// ***
|
||||
if (pathVariables != null) {
|
||||
transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
||||
}
|
||||
|
||||
try {
|
||||
String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||
transactionProp);
|
||||
// if (RESPONSE_TYPE_ASYNC.equals(responseType)) { // table의 값이 ASYNC 로 들어가 있는데
|
||||
// response_type_async는 ASYN 로 되어 있어 아래처럼 비교함 jwhong 2025
|
||||
if ("ASYNC".equals(responseType)) {
|
||||
// responseEntity = ResponseEntity.ok("dummy"); // comment by jwhong
|
||||
// servletResponse.addHeader("traceId", responseData); // uuid를 response header에
|
||||
servletResponse.addHeader("traceId",
|
||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
int httpStatus = servletResponse.getStatus();
|
||||
if (httpStatus == 200) {
|
||||
// 업체별 aync response message 가 다르다.
|
||||
String asyncMsgStyle = httpProp.getProperty("ASYNC_RTNMSG_TYPE", "");
|
||||
String responseBody = "";
|
||||
boolean encryptAsyncAckApply = StringUtils
|
||||
.equalsIgnoreCase(httpProp.getProperty("ASYNC_ENCRYPT_ACK", "N"), "Y");
|
||||
|
||||
if (asyncMsgStyle == null || asyncMsgStyle.trim().isEmpty()) {
|
||||
responseBody = makeResponseBodyMsg();
|
||||
} else {
|
||||
responseBody = asyncMsgStyle;
|
||||
}
|
||||
if (encryptAsyncAckApply) {
|
||||
responseBody = service.doPostEncryption(responseBody, transactionProp, servletRequest);
|
||||
}
|
||||
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseBody);
|
||||
// jwhong
|
||||
} else {
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
}
|
||||
} else {
|
||||
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
|
||||
// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
|
||||
|
||||
servletResponse.addHeader("traceId",
|
||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
int httpStatus = servletResponse.getStatus();
|
||||
if (httpStatus != 200) {
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
} else {
|
||||
responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
|
||||
String errorMsg = null;
|
||||
|
||||
if( e instanceof HttpStatusException ) {
|
||||
logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||
HttpStatusException e1 = (HttpStatusException) e;
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AP_ERROR, e1.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||
}
|
||||
else if( e instanceof JwtAuthException )
|
||||
{
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType)
|
||||
.body(errorMsg);
|
||||
}
|
||||
String postFilterNames = httpProp.getProperty("POST_FILTERS","");
|
||||
|
||||
if( postFilterNames.contains("HMAC_SHA256") ) {
|
||||
HttpAdapterFilter filter = HttpAdapterFilterFactoryKjb.createFilter("HMAC_SHA256");
|
||||
filter.doPostFilter(adapterGroupName, postFilterNames, errorMsg, transactionProp, servletRequest, servletResponse);
|
||||
}
|
||||
|
||||
|
||||
} finally {
|
||||
/**
|
||||
* 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
||||
* 추후 더 좋은방법이 생길경우 개선 요망
|
||||
*/
|
||||
try {
|
||||
|
||||
servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
||||
|
||||
if (!"ASYNC".equals(responseType)) {
|
||||
String uuid = transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
String url = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
|
||||
String method = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
|
||||
int httpStatusCode = servletResponse.getStatus();
|
||||
|
||||
Map<Object, Object> headerMap = new HashMap<>();
|
||||
// 응답 헤더 로깅
|
||||
for (String headerName : servletResponse.getHeaderNames()) {
|
||||
String headerValue = servletResponse.getHeader(headerName);
|
||||
logger.debug(String.format("httpHeader logging headerKey=%s, headerValue=%s",
|
||||
headerName, headerValue));
|
||||
headerMap.put(headerName, headerValue);
|
||||
}
|
||||
//HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName,adapterName, headerMap, url, method, httpStatusCode);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("http header db logging fail.", e);
|
||||
}
|
||||
}
|
||||
return responseEntity;
|
||||
}
|
||||
|
||||
/**
|
||||
* url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
|
||||
* /api/v1/public/getUserInfo.svc
|
||||
*
|
||||
* @param apiUri
|
||||
* @return
|
||||
*/
|
||||
private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager,
|
||||
String adapterGrpName) throws Exception {
|
||||
if (StringUtils.isBlank(apiUri)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// * manager 출력
|
||||
logger.warn("===== adptUriMap 상세 내용 =====");
|
||||
for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
||||
HttpDynamicInAdapterUri uriObj = entry.getValue();
|
||||
logger.warn("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
||||
+ uriObj.getUri());
|
||||
}
|
||||
logger.warn("================================");
|
||||
|
||||
//
|
||||
for (int i = 0; i < 10; i++) {
|
||||
HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
|
||||
if (adptUri != null) {
|
||||
if (StringUtils.isNotEmpty(adapterGrpName)) {
|
||||
if(adptUri.getAdptGrpName().equals(adapterGrpName)) {
|
||||
return adptUri;
|
||||
}
|
||||
} else {
|
||||
return adptUri;
|
||||
}
|
||||
}
|
||||
|
||||
// /api/v1/public
|
||||
apiUri = StringUtils.substringBeforeLast(apiUri, "/");
|
||||
if (apiUri.length() < 3) { // /api
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void logError(HttpServletRequest request) {
|
||||
InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||
|
||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||
String serverName = eaiServerManager.getLocalServerName();
|
||||
String uuid = null;
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
String instanceid1 = serverName.substring(0, 2);
|
||||
String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||
String instid = instanceid1 + instanceid2;
|
||||
uuid = instid + UUIDGenerator.getUUID();
|
||||
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = request.getRequestURI();
|
||||
|
||||
String errorCode = "RECEAIIRP010";
|
||||
String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
|
||||
|
||||
errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
||||
errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
|
||||
errorInfoVO.setErrCd(errorCode); // 에러코드
|
||||
errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||
errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
||||
errorInfoVO.setErrDstcd(" ");
|
||||
sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
|
||||
.append(request.getRequestURI());
|
||||
errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
||||
errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
||||
|
||||
InboundErrorLogger.error(errorInfoVO);
|
||||
}
|
||||
|
||||
private String makeResponseBodyMsg() {
|
||||
|
||||
Map<String, Object> dataMap = new HashMap<>();
|
||||
dataMap.put("result", 1);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
|
||||
map.put("code", "200");
|
||||
map.put("data", dataMap);
|
||||
map.put("message", "정상 처리 되었습니다.");
|
||||
|
||||
JSONObject json = new JSONObject();
|
||||
json.putAll(map);
|
||||
|
||||
return json.toJSONString();
|
||||
}
|
||||
|
||||
/*
|
||||
* private String makeResponseBodyMsg(String asyncMsgStyle) {
|
||||
*
|
||||
* Map<String, Object> dataMap = new HashMap<>(); dataMap.put("result", 1);
|
||||
* Map<String, Object> map = new HashMap<>();
|
||||
*
|
||||
* switch (asyncMsgStyle) { case "TB_SUC": map.put("rspCode", "TB_SUC_000");
|
||||
* map.put("rspMsg", "정상"); map.put("data", dataMap); break; case "ONLYDATA":
|
||||
* map.put("data", dataMap); map.put("success", "true"); break; default:
|
||||
* map.put("code", "200"); map.put("data", dataMap); map.put("message",
|
||||
* "정상 처리 되었습니다."); break; }
|
||||
*
|
||||
* JSONObject json = new JSONObject(); json.putAll(map);
|
||||
*
|
||||
* return json.toJSONString(); }
|
||||
*/
|
||||
}
|
||||
+7
-1
@@ -18,12 +18,18 @@ import java.util.Properties;
|
||||
public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
|
||||
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
private static boolean httpHeaderLogMode = HttpAdapterExtraLogUtil.isHttpHeaderMode();
|
||||
|
||||
@Override
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
|
||||
|
||||
logger.debug("httpHeader logging Interceptor start");
|
||||
|
||||
if (!httpHeaderLogMode) {
|
||||
logger.info("httpHeader logging off - use.http.header.log");
|
||||
return;
|
||||
}
|
||||
|
||||
Properties transactionProp = (Properties) request.getAttribute(TransactionContextKeys.TRANSACTION_PROP);
|
||||
if(transactionProp == null || "ASYN".equals(transactionProp.getProperty(HttpAdapterServiceKey.INBOUND_SYNC_ASYNC_TYPE))){
|
||||
logger.debug("httpHeader logging Interceptor ASYNC");
|
||||
|
||||
@@ -0,0 +1,982 @@
|
||||
package com.eactive.eai.adapter.service;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.Keys;
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthFilter;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.inbound.action.ActionFactory;
|
||||
import com.eactive.eai.inbound.action.RequestAction;
|
||||
import com.eactive.eai.inbound.processor.Processor;
|
||||
import com.eactive.eai.message.StandardMessageUtil;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.mina.common.ByteBuffer;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.*;
|
||||
|
||||
//for encrypt/decrypt jwhong
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.kjbank.encrypt.exchange.crypto.AES256Cipher;
|
||||
import com.kjbank.encrypt.exchange.crypto.AESCipher;
|
||||
import com.kjbank.encrypt.exchange.crypto.AES256GCMCipher;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
import com.eactive.eai.common.context.ElinkTransactionContext;
|
||||
|
||||
|
||||
@Service
|
||||
public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||
public static final String HTTP_STATUS = "HTTP_STATUS"; // jwhong
|
||||
// HEADER_GROUP JSON에 추가할 항목 정의, 없으면 전체 header 추가
|
||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||
public static final String PROPERTIES_NAME_HTTP_REQUEST_METHOD = "httpRequestMethod";
|
||||
|
||||
private static final String JSON_CONTENT_TYPE = "application/json";
|
||||
private static final String JSON_FIELD_NAME = "json-body";
|
||||
private static final String FILE_GROUP_NAME = "image-file";
|
||||
private static final String UPLOAD_ROOT_PATH = "UPLOAD_ROOT_PATH";
|
||||
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id"; // jwhong
|
||||
private boolean encryptResponseApply; // inbound에 대한 응답 암호화 여부 flag
|
||||
|
||||
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp, AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
|
||||
int traceLevel = 0;
|
||||
|
||||
AdapterPropManager manager = null;
|
||||
String adptGrpName = adapterGroupVO.getName();
|
||||
String adptName = adapterVO.getName();
|
||||
|
||||
String urlDecodeYn = httpProp.getProperty(URL_DECODE_YN, "N");
|
||||
String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||
|
||||
String traceLevelTemp = httpProp.getProperty(TRACE_LEVEL, "0");
|
||||
String relayRequestHeaderKeys = httpProp.getProperty(HEADER_KEYS);
|
||||
String headerGroupName = httpProp.getProperty(HEADER_GROUP);
|
||||
|
||||
boolean isParameterType = false;
|
||||
String message = null;
|
||||
|
||||
String paramValue = null;
|
||||
String adptMsgType = null;
|
||||
|
||||
transactionProp.put(INBOUND_METHOD, request.getMethod());
|
||||
transactionProp.put(INBOUND_URI, request.getRequestURI());
|
||||
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(request.getQueryString()));
|
||||
transactionProp.put(INBOUND_HEADER, getHeaders(request));
|
||||
transactionProp.put(INBOUND_EXTPARAMS, StringUtils.defaultString(request.getQueryString()));
|
||||
if (StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_REST)
|
||||
|| StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_HTTP_CUSTOM)) {
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
String extUrl = StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
|
||||
transactionProp.put(INBOUND_EXTURI, extUrl);
|
||||
} else {
|
||||
transactionProp.put(INBOUND_EXTURI, getExtUri(request));
|
||||
}
|
||||
transactionProp.put(INBOUND_CLIENT_IP, getClientIp(request)); // Client IP 추가
|
||||
transactionProp.put(Processor.REQUEST_ACTION, adapterVO.getAdapterGroupVO().getRefClass());
|
||||
transactionProp.put(API_PATH, httpProp.getProperty(API_PATH, ""));
|
||||
|
||||
//djerp bypass
|
||||
transactionProp.put(INBOUND_REWRITE_PATH,
|
||||
getRewritePath(transactionProp.getProperty(INBOUND_EXTURI), transactionProp.getProperty(API_PATH)));
|
||||
transactionProp.put(INBOUND_REMOTE_ADDR, request.getRemoteAddr());
|
||||
transactionProp.put(INBOUND_SCHEME, request.getScheme());
|
||||
|
||||
transactionProp.put(PRE_FILTERS, httpProp.getProperty(PRE_FILTERS, ""));
|
||||
transactionProp.put(POST_FILTERS, httpProp.getProperty(POST_FILTERS, ""));
|
||||
transactionProp.put(PROPERTIES_NAME_HTTP_REQUEST_METHOD, request.getMethod());
|
||||
transactionProp.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
|
||||
transactionProp.put("BLOCK_IP", httpProp.getProperty("BLOCK_IP", ""));
|
||||
|
||||
//djerp bypass
|
||||
Map<String, String> pathVariables = assignPathVariables(request, adptGrpName, adptName, null, transactionProp);
|
||||
if (pathVariables != null) {
|
||||
transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
||||
}
|
||||
|
||||
transactionProp.put(ENC_PATHS, httpProp.getProperty(ENC_PATHS, ""));
|
||||
|
||||
transactionProp.put(ENCRYPT_ALGORITHM, httpProp.getProperty(ENCRYPT_ALGORITHM, "")); //jwhong
|
||||
if (getHeaders(request).get(HEADER_NAME_CLIENT_ID) != null) { // jwhong
|
||||
transactionProp.put(HEADER_NAME_CLIENT_ID, getHeaders(request).get(HEADER_NAME_CLIENT_ID));
|
||||
}
|
||||
transactionProp.put(ENCRYPT_BASE_TYPE, httpProp.getProperty(ENCRYPT_BASE_TYPE, "")); //jwhong
|
||||
// //transactionProp.put(INBOUND_TOKEN, getHeaders(request).get(INBOUND_TOKEN)); // jwhong
|
||||
// transactionProp.put(INBOUND_TOKEN, getHeaders(request).get(INBOUND_TOKEN) != null ? getHeaders(request).get(INBOUND_TOKEN) : ""); //jwhong , null 이면 default로 "" put
|
||||
String inboundToken = getHeaders(request).getOrDefault(INBOUND_TOKEN, "").toString();
|
||||
if (StringUtils.isNotBlank(inboundToken) && StringUtils.startsWith(inboundToken, "Bearer ")) {
|
||||
inboundToken = inboundToken.substring(7);
|
||||
}
|
||||
transactionProp.put(INBOUND_TOKEN, inboundToken);
|
||||
transactionProp.put(ENCRYPT_AES256_IV, httpProp.getProperty(ENCRYPT_AES256_IV, "")); //jwhong
|
||||
transactionProp.put(ENCRYPT_AES256_KEY, httpProp.getProperty(ENCRYPT_AES256_KEY, "")); //jwhong
|
||||
|
||||
|
||||
// SEED 컬럼암호하 시 Key로 사용함
|
||||
String seedkey = getHeaders(request).getOrDefault("x-obp-partnercode", "").toString();
|
||||
ElinkTransactionContext.setSeedKey(seedkey);
|
||||
|
||||
try {
|
||||
traceLevel = Integer.parseInt(traceLevelTemp);
|
||||
} catch (Exception e) {
|
||||
traceLevel = 0;
|
||||
}
|
||||
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
logger.debug("시작 >> encode = [" + encode + "]");
|
||||
|
||||
switch (HttpMethodType.getValue(request.getMethod())) {
|
||||
case GET:
|
||||
case DELETE:
|
||||
isParameterType = true;
|
||||
break;
|
||||
case POST:
|
||||
case PUT:
|
||||
if (StringUtils.contains(request.getContentType(), "application/x-www-form-urlencoded")) {
|
||||
isParameterType = true;
|
||||
} else if ( StringUtils.isNoneBlank(request.getQueryString()) ) { // jwhong
|
||||
isParameterType = true;
|
||||
} else {
|
||||
isParameterType = false;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (isParameterType) {
|
||||
paramValue = request.getQueryString();
|
||||
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(paramValue)); // Filter에서 QueryString 검증을 위해 저장
|
||||
if (paramValue == null)
|
||||
paramValue = "";
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(paramValue));
|
||||
}
|
||||
|
||||
// json으로 변환
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("{");
|
||||
Map<String, String[]> paramMap = assignParameterMap(request, adptGrpName, adptName, null, transactionProp);
|
||||
int i = 0;
|
||||
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
|
||||
if (i > 0) {
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append("\"").append(entry.getKey()).append("\":");
|
||||
String[] values = entry.getValue();
|
||||
if (values.length > 1) {
|
||||
// ["111", "222"]
|
||||
sb.append("[");
|
||||
for (int j = 0; j < values.length; j++) {
|
||||
if (j > 0) {
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append("\"").append(JSONValue.escape(values[j])).append("\"");
|
||||
}
|
||||
sb.append("]");
|
||||
} else {
|
||||
sb.append("\"").append(JSONValue.escape(values[0])).append("\"");
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
sb.append("}");
|
||||
|
||||
paramValue = sb.toString();
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
||||
+ CommonLib.getDumpMessage(paramValue.getBytes(encode)));
|
||||
}
|
||||
} else {
|
||||
if (request.getContentLength() > 0) {
|
||||
ServletInputStream sis = request.getInputStream();
|
||||
ByteBuffer bb = ByteBuffer.allocate(1024).setAutoExpand(true);
|
||||
int i = 0;
|
||||
byte[] cbuf = new byte[1024];
|
||||
while ((i = sis.read(cbuf, 0, 1024)) != -1) {
|
||||
if (i == 1024) {
|
||||
bb.put(cbuf);
|
||||
} else {
|
||||
byte[] tail = new byte[i];
|
||||
System.arraycopy(cbuf, 0, tail, 0, i);
|
||||
bb.put(tail);
|
||||
}
|
||||
}
|
||||
byte[] data = new byte[bb.position()];
|
||||
bb.position(0);
|
||||
bb.get(data);
|
||||
String bodyEncode = encode;
|
||||
String contentTypeHeader = request.getContentType();
|
||||
if (StringUtils.isNotBlank(contentTypeHeader)) {
|
||||
try {
|
||||
MediaType mediaType = MediaType.parseMediaType(contentTypeHeader);
|
||||
if (mediaType.getCharset() != null) {
|
||||
bodyEncode = mediaType.getCharset().name();
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
paramValue = new String(data, bodyEncode);
|
||||
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(data));
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
||||
+ CommonLib.getDumpMessage(data));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (paramValue == null) { // parameter가 없는 경우때문에 처리
|
||||
paramValue = "";
|
||||
}
|
||||
// 순수한 Body값을 저장을 위해 위치 변경.
|
||||
transactionProp.put(INBOUND_REQUEST_MESSAGE, paramValue);
|
||||
|
||||
// paramValue가 null이 아닌 빈문자열(""," ")인 경우에 대비하여 조건 수정.
|
||||
// if (StringUtils.isNotBlank(paramValue)) { // jwhong decrypt
|
||||
// paramValue = doPreDecryption(paramValue, transactionProp, request);
|
||||
// }
|
||||
|
||||
if ("Y".equals(urlDecodeYn) && isParameterType) {
|
||||
message = URLDecoder.decode(paramValue);
|
||||
} else {
|
||||
message = paramValue;
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
String[] msgArgs = new String[2];
|
||||
msgArgs[0] = adptGrpName;
|
||||
msgArgs[1] = message;
|
||||
String resMsg = ExceptionUtil.make("RICEAIAHA005", msgArgs);
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
|
||||
|
||||
adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
// HttpHeaders responseHeaders = new HttpHeaders();
|
||||
// responseHeaders.setContentType(MediaType.valueOf("application/json;charset=" + encode));
|
||||
|
||||
|
||||
// HEADER_GROUP 셋팅
|
||||
if (MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)
|
||||
&& StringUtils.isNotBlank(relayRequestHeaderKeys)) {
|
||||
JSONObject jsonMessage = (JSONObject) JSONValue.parse(message);
|
||||
JSONObject headerJson = new JSONObject();
|
||||
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
||||
String key = e.nextElement();
|
||||
headerJson.put(key, request.getHeader(key));
|
||||
}
|
||||
} else {
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils
|
||||
.tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
||||
|
||||
for (String key : relayKeyArr) {
|
||||
String headerValue = request.getHeader(key);
|
||||
if (StringUtils.isNotBlank(headerValue)) {
|
||||
headerJson.put(key, headerValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (headerJson.size() > 0) {
|
||||
jsonMessage.put(headerGroupName, headerJson);
|
||||
message = jsonMessage.toJSONString();
|
||||
}
|
||||
}
|
||||
|
||||
if (message == null) {
|
||||
message = "";
|
||||
}
|
||||
|
||||
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
|
||||
// transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
|
||||
// 로컬 서비스 호출 ,encoding 처리 추가
|
||||
String result = (String) service(adptGrpName, adptName, message, transactionProp, request, response);
|
||||
|
||||
applyOutboundResponseHeaders(transactionProp, response);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] result " + encode + " (" + adptGrpName + ") = [" + result + "]");
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
String syncAsyncType = transactionProp.getProperty(INBOUND_SYNC_ASYNC_TYPE);
|
||||
|
||||
if (!"ASYN".equals(syncAsyncType) && MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode rootNode = (ObjectNode) mapper.readTree(result);
|
||||
JsonNode headerGroup = rootNode.get(headerGroupName);
|
||||
if(headerGroup != null) {
|
||||
for(Iterator<String> it = headerGroup.fieldNames(); it.hasNext();) {
|
||||
String name = it.next();
|
||||
String value = headerGroup.get(name).asText();
|
||||
response.addHeader(name, value);
|
||||
}
|
||||
rootNode.remove(headerGroupName);
|
||||
result = mapper.writeValueAsString(rootNode);
|
||||
}
|
||||
}
|
||||
|
||||
// KJBank는 요청에 대한 응답 (Sync응답, Aync 에 대한 Ack응답) 에 대하여 암호화 하지 않는다. 무조건 안한다. 따라서 아래부분은 구현은 했지만 사용하지 않는다.
|
||||
// 위 2가지 경우 암호화 하는걸로 요청 변경되어 아래 암호화 수행하도록 수정함
|
||||
// encryptResponseApply = StringUtils.equalsIgnoreCase(httpProp.getProperty("ENCRYPT_RESPONSE_APPLY", "N"), "Y");
|
||||
// if ( encryptResponseApply) {
|
||||
// result = doPostEncryption(result, transactionProp, request); // jwhong Encrypt
|
||||
// }
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* HttpClientAdapterServiceBypass.assignRelayDataToInbound() 에서
|
||||
* transactionProp에 저장한 OUTBOUND_RESPONSE_HEADERS를 response에 적용한다.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private void applyOutboundResponseHeaders(Properties transactionProp, HttpServletResponse response) {
|
||||
Map<String, Object> outboundPropertyMap = (Map<String, Object>) transactionProp.get(OUTBOUND_PROPERTY_MAP);
|
||||
if (outboundPropertyMap == null) {
|
||||
return;
|
||||
}
|
||||
Properties headerProp = (Properties) outboundPropertyMap.get(OUTBOUND_RESPONSE_HEADERS);
|
||||
if (headerProp == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String[] hopByHopHeaders = { "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization",
|
||||
"TE", "Trailers", "Transfer-Encoding", "Upgrade" };
|
||||
|
||||
for (Map.Entry<Object, Object> entry : headerProp.entrySet()) {
|
||||
String key = (String) entry.getKey();
|
||||
String value = (String) entry.getValue();
|
||||
|
||||
if (StringUtils.equalsAnyIgnoreCase(key, hopByHopHeaders)) {
|
||||
continue;
|
||||
}
|
||||
if (StringUtils.equalsIgnoreCase(key, HttpHeaders.CONTENT_LENGTH)) {
|
||||
continue;
|
||||
}
|
||||
if (StringUtils.equalsIgnoreCase(key, HTTP_STATUS)) {
|
||||
if (StringUtils.isNotBlank(value)) {
|
||||
try {
|
||||
response.setStatus(Integer.parseInt(value));
|
||||
} catch (NumberFormatException ex) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
response.addHeader(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
// jwhong decrypt
|
||||
|
||||
private String doPreDecryption(String eaiBody, Properties transactionProp, HttpServletRequest request) throws Exception {
|
||||
String decryptAlgorithm = transactionProp.getProperty(ENCRYPT_ALGORITHM, "");
|
||||
String xElinkClientId = transactionProp.getProperty(HEADER_NAME_CLIENT_ID, ""); // 이 값이 OAuth의 client id 값이다 . http header 에 포함되어 온다. jwhong
|
||||
String encryptBaseKeyType = transactionProp.getProperty(ENCRYPT_BASE_TYPE);
|
||||
//String inboundToken2 = transactionProp.getProperty(INBOUND_TOKEN, ""); // 이건 token 값이 아니고 authorization 값이다
|
||||
String inboundToken = "";
|
||||
|
||||
String secretAES256Iv = transactionProp.getProperty("ENCRYPT_AES256_IV");
|
||||
String secretAES256Key = transactionProp.getProperty("ENCRYPT_AES256_KEY");
|
||||
|
||||
if ( decryptAlgorithm == "" ) { // 복호화 대상이 아님
|
||||
return eaiBody;
|
||||
}
|
||||
|
||||
inboundToken = JwtTokenExtractor(request);
|
||||
xElinkClientId = JwtClientIdExtractor(inboundToken); // token에서 client id를 추출함
|
||||
|
||||
// 암호화 key를 token 내용으로 할지 client secret 내용으로 할지 결정함. adapter property에 정의함
|
||||
// ENCRYPT_ALGORITHM 을 설정했는데 ENCRYPT_BASE_TYPE을 설정안하면 Decrypt 수행시 Exception 발생함
|
||||
String clientSecret = "";
|
||||
if ("TOKEN".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||
clientSecret = inboundToken;
|
||||
} else if ( "SECRETKEY".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||
ClientDetails clientDetail = manager.getClientDeatilsStore().get(xElinkClientId);
|
||||
|
||||
if ( clientDetail != null ) { // 여기서 not null 이라는 것은 apim oauth server에서 발급된 token 임.
|
||||
// 즉 KJBank 에서 요청이 들어온 것이다.
|
||||
clientSecret = clientDetail.getClientSecret();
|
||||
} // 그럼 업체에서 요청이 들어오면?? 업체도 apim oauth server에서 발급된 token을 사용하는것이다.
|
||||
}
|
||||
|
||||
byte[] decryptedMessage = null;
|
||||
decryptedMessage = doInboundPreDecrypt(eaiBody, decryptAlgorithm,clientSecret,secretAES256Iv, secretAES256Key );
|
||||
|
||||
if (decryptedMessage == null) {
|
||||
throw new Exception("[ApiAdapterService] Decrypt Error : Invalid encrypted message");
|
||||
}
|
||||
|
||||
|
||||
String resultMessage = new String(decryptedMessage, StandardCharsets.UTF_8 );
|
||||
return resultMessage;
|
||||
//return new String(decryptedMessage, StandardCharsets.UTF_8 );
|
||||
}
|
||||
|
||||
|
||||
// jwhong encrypt
|
||||
public String doPostEncryption(String eaiBody, Properties transactionProp, HttpServletRequest request) throws Exception {
|
||||
|
||||
String decryptAlgorithm = transactionProp.getProperty(ENCRYPT_ALGORITHM, "");
|
||||
String xElinkClientId = transactionProp.getProperty(HEADER_NAME_CLIENT_ID, ""); // 이 값이 OAuth의 client id 값이다 . http header 에 포함되어 온다. jwhong
|
||||
String encryptBaseKeyType = transactionProp.getProperty(ENCRYPT_BASE_TYPE);
|
||||
String inboundToken = "";
|
||||
|
||||
String secretAES256Iv = transactionProp.getProperty("ENCRYPT_AES256_IV");
|
||||
String secretAES256Key = transactionProp.getProperty("ENCRYPT_AES256_KEY");
|
||||
|
||||
if ( decryptAlgorithm == "" ) { // 복호화 대상이 아님
|
||||
return eaiBody;
|
||||
}
|
||||
|
||||
inboundToken = JwtTokenExtractor(request);
|
||||
xElinkClientId = JwtClientIdExtractor(inboundToken); // token에서 client id를 추출함
|
||||
|
||||
// 암호화 key를 token 내용으로 할지 client secret 내용으로 할지 결정함. adapter property에 정의함
|
||||
// ENCRYPT_ALGORITHM 을 설정했는데 ENCRYPT_BASE_TYPE을 설정안하면 Decrypt 수행시 Exception 발생함
|
||||
String clientSecret = "";
|
||||
if ("TOKEN".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||
clientSecret = inboundToken;
|
||||
} else if ( "SECRETKEY".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||
ClientDetails clientDetail = manager.getClientDeatilsStore().get(xElinkClientId);
|
||||
|
||||
if ( clientDetail != null ) {
|
||||
clientSecret = clientDetail.getClientSecret();
|
||||
}
|
||||
}
|
||||
|
||||
String encryptedMessage = null;
|
||||
encryptedMessage = doInboundPostEncrypt(eaiBody, decryptAlgorithm,clientSecret,secretAES256Iv, secretAES256Key );
|
||||
|
||||
if (encryptedMessage == null) {
|
||||
throw new Exception("[ApiAdapterService] Encrypt Error : Invalid PlainText message");
|
||||
}
|
||||
|
||||
return encryptedMessage;
|
||||
//String resultMessage = new String(encryptedMessage, StandardCharsets.UTF_8 );
|
||||
//return resultMessage;
|
||||
}
|
||||
|
||||
|
||||
private byte[] convertObjectToBytes(Object obj) throws IOException {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(bos);
|
||||
oos.writeObject(obj);
|
||||
oos.flush();
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
private byte[] convertObjectToBase64Bytes(Object obj) throws IOException {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(bos);
|
||||
oos.writeObject(obj);
|
||||
oos.flush();
|
||||
oos.close();
|
||||
|
||||
// 직렬화된 byte[] → Base64 문자열 → 다시 byte[]로 변환
|
||||
String base64String = Base64.getEncoder().encodeToString(bos.toByteArray());
|
||||
return base64String.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public static Object convertBytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
|
||||
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
|
||||
ObjectInputStream ois = new ObjectInputStream(bis)) {
|
||||
return ois.readObject();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private byte[] doInboundPreDecrypt(String eaiStringBody, String decryptAlgorithm, String clientSecretKey, String secretAES256Iv, String secretAES256Key) throws Exception {
|
||||
|
||||
byte[] decryptedMessage = null;
|
||||
//String eaiStringBody = new String(eaiBody, StandardCharsets.UTF_8);
|
||||
|
||||
eaiStringBody = extractBodyMsg(decryptAlgorithm, eaiStringBody);
|
||||
|
||||
if (eaiStringBody == null) {
|
||||
throw new Exception("[ApiAdapterService] Cannot decrypt Error : input is plain text");
|
||||
}
|
||||
|
||||
//test source
|
||||
logger.debug("Base64 문자열: " + eaiStringBody);
|
||||
logger.debug("Base64 문자열 길이: " + eaiStringBody.length());
|
||||
logger.debug("Base64 문자열 끝: " + eaiStringBody.substring(eaiStringBody.length() - 10));
|
||||
|
||||
// Base64 디코딩 테스트
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(eaiStringBody);
|
||||
logger.debug("디코딩 성공, 길이: " + decoded.length);
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.debug("Base64 디코딩 실패: " + e.getMessage());
|
||||
}
|
||||
// end test source
|
||||
|
||||
switch (decryptAlgorithm) {
|
||||
case "AES128":
|
||||
case "AES128-TOSS":
|
||||
try {
|
||||
String key128 = clientSecretKey.substring(22,38); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||
//String decryptedStrMessage = AESCipher.decrypt(eaiStringBody, key128);
|
||||
String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES128-TOGETHER":
|
||||
try {
|
||||
String key128 = clientSecretKey.substring(44,60); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||
//String decryptedStrMessage = AESCipher.decrypt(eaiStringBody, key128);
|
||||
String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256":
|
||||
try {
|
||||
String key = clientSecretKey.substring(10,42);
|
||||
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, key);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256-KAKAO":
|
||||
try {
|
||||
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256-TOSS":
|
||||
try {
|
||||
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
|
||||
case "AES256GCM":
|
||||
try {
|
||||
byte[] key = AES256GCMCipher.generateKey();
|
||||
AES256GCMCipher cipher = new AES256GCMCipher(key);
|
||||
byte[] aad = "metadata".getBytes();
|
||||
|
||||
String decryptedStrMessage = cipher.decrypt(eaiStringBody , aad);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
try {
|
||||
decryptedMessage = eaiStringBody.getBytes();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] doOutboundPostFilter Array copy error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return decryptedMessage;
|
||||
}
|
||||
|
||||
private String extractBodyMsg(String decryptAlgorithm, String eaiStringBody) {
|
||||
|
||||
String decryptedJsonKey = "";
|
||||
String decryptedBodyMessage = "";
|
||||
|
||||
decryptedJsonKey = getJsonKey(decryptAlgorithm);
|
||||
|
||||
try {
|
||||
JSONParser parser = new JSONParser();
|
||||
JSONObject jsonObject = (JSONObject) parser.parse(eaiStringBody);
|
||||
decryptedBodyMessage = (String) jsonObject.get(decryptedJsonKey);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClient5AdapterServiceRest] extractBodyMsg error : " + e.getMessage());
|
||||
}
|
||||
|
||||
return decryptedBodyMessage;
|
||||
|
||||
}
|
||||
|
||||
private String getJsonKey(String Algorithm) {
|
||||
|
||||
String jsonKey = "";
|
||||
|
||||
switch (Algorithm) {
|
||||
case "AES128":
|
||||
case "AES128-TOSS":
|
||||
jsonKey = "preScreeningRequest";
|
||||
break;
|
||||
case "AES128-TOGETHER":
|
||||
jsonKey = "obpTxData";
|
||||
break;
|
||||
case "AES256":
|
||||
jsonKey = "preScreeningRequest";
|
||||
break;
|
||||
case "AES256-KAKAO":
|
||||
jsonKey = "encrypted_data";
|
||||
break;
|
||||
case "AES256-TOSS":
|
||||
jsonKey = "encryptedData";
|
||||
break;
|
||||
case "AES256-NICEON":
|
||||
jsonKey = "enc_data";
|
||||
break;
|
||||
case "AES256GCM":
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return jsonKey;
|
||||
}
|
||||
|
||||
private String doInboundPostEncrypt(String eaiStringBody, String encryptAlgorithm, String clientSecretKey, String secretAES256Iv, String secretAES256Key) {
|
||||
|
||||
//byte[] encryptedMessage = null;
|
||||
String encryptedStrMessage = null;
|
||||
String encryptedJsonKey = "";
|
||||
|
||||
encryptedJsonKey = getJsonKey(encryptAlgorithm);
|
||||
|
||||
switch (encryptAlgorithm) {
|
||||
case "AES128":
|
||||
case "AES128-TOSS":
|
||||
try {
|
||||
String key128 = clientSecretKey.substring(22,38); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||
encryptedStrMessage = AESCipher.encrypt(eaiStringBody, key128);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES128-TOGETHER":
|
||||
try {
|
||||
String key128 = clientSecretKey.substring(44,60); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||
encryptedStrMessage = AESCipher.encrypt(eaiStringBody, key128);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256":
|
||||
try {
|
||||
String key = clientSecretKey.substring(10,42);
|
||||
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, key);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256-KAKAO":
|
||||
try {
|
||||
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256-TOSS":
|
||||
try {
|
||||
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
|
||||
case "AES256GCM":
|
||||
try {
|
||||
byte[] key = AES256GCMCipher.generateKey();
|
||||
AES256GCMCipher cipher = new AES256GCMCipher(key);
|
||||
byte[] aad = "metadata".getBytes();
|
||||
|
||||
encryptedStrMessage = cipher.encrypt(eaiStringBody , aad);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
try {
|
||||
encryptedStrMessage = eaiStringBody;
|
||||
//encryptedMessage = eaiStringBody.getBytes();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] doOutboundPostFilter Array copy error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put(encryptedJsonKey, encryptedStrMessage);
|
||||
JSONObject json = new JSONObject();
|
||||
json.putAll(map);
|
||||
return json.toJSONString();
|
||||
//return encryptedMessage;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private String JwtTokenExtractor(HttpServletRequest request) {
|
||||
|
||||
String Token = "";
|
||||
try {
|
||||
Token = JwtAuthFilter.extractJWTToken(request);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
logger.debug("Token is: " + Token);
|
||||
return Token;
|
||||
|
||||
}
|
||||
|
||||
private String JwtClientIdExtractor(String inboundToken) {
|
||||
|
||||
String tokenClientId ="";
|
||||
try {
|
||||
SignedJWT signedJWT = SignedJWT.parse(inboundToken);
|
||||
tokenClientId = (String) signedJWT.getJWTClaimsSet().getClaim(PAYLOAD_PARAM_NAME_CLIENT_ID);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
tokenClientId = "";
|
||||
}
|
||||
|
||||
logger.debug("Token Client ID: " + tokenClientId);
|
||||
return tokenClientId;
|
||||
|
||||
}
|
||||
|
||||
// jwhong until here
|
||||
|
||||
|
||||
private Map<String, String[]> assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName,
|
||||
Object requestBytes, Properties prop) {
|
||||
// PathVariable 체크
|
||||
if (StringUtils.equalsAnyIgnoreCase(request.getMethod(), HttpMethod.GET.name(), HttpMethod.DELETE.name())
|
||||
&& StringUtils.isBlank(request.getQueryString())) {
|
||||
try {
|
||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||
RequestAction action = ActionFactory.createAction(actionName);
|
||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||
String[] keys = action.perform(requestBytes);
|
||||
String requestPath = keys[0];
|
||||
|
||||
// PathVariable 지원 추가
|
||||
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
||||
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
||||
Map<String, String> paramMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath,
|
||||
requestPath);
|
||||
if (paramMap != null && paramMap.size() > 0) {
|
||||
Map<String, String[]> returnMap = new HashMap<>();
|
||||
for (String key : paramMap.keySet()) {
|
||||
if (StringUtils.equalsIgnoreCase(key, "method")) {
|
||||
continue;
|
||||
}
|
||||
returnMap.put(key, new String[] { paramMap.get(key) });
|
||||
}
|
||||
|
||||
return returnMap;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
return request.getParameterMap();
|
||||
}
|
||||
|
||||
private String getRewritePath(String extUri, String basePath) {
|
||||
return StringUtils.removeStart(extUri, StringUtils.removeEnd(basePath, "/"));
|
||||
}
|
||||
|
||||
private Map<String, String> assignPathVariables(HttpServletRequest request, String adptGrpName, String adptName,
|
||||
Object requestBytes, Properties prop) {
|
||||
Map<String, String> variablesMap = null;
|
||||
// QueryString 있을때는 체크(X)
|
||||
if (StringUtils.isBlank(request.getQueryString())) {
|
||||
try {
|
||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||
RequestAction action = ActionFactory.createAction(actionName);
|
||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||
String[] keys = action.perform(requestBytes);
|
||||
String requestPath = keys[0];
|
||||
|
||||
// PathVariable 지원 추가
|
||||
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
||||
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
||||
variablesMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath, requestPath);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
return variablesMap;
|
||||
}
|
||||
|
||||
private Properties getHeaders(HttpServletRequest request) {
|
||||
Properties prop = new Properties();
|
||||
|
||||
Enumeration<String> headerNames = request.getHeaderNames();
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String key = headerNames.nextElement();
|
||||
// 동일 이름의 헤더가 여러 개인 경우 콤마로 합침 (RFC 7230)
|
||||
Enumeration<String> values = request.getHeaders(key);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
while (values.hasMoreElements()) {
|
||||
if (sb.length() > 0) sb.append(", ");
|
||||
sb.append(values.nextElement());
|
||||
}
|
||||
prop.setProperty(key, sb.toString());
|
||||
}
|
||||
|
||||
return prop;
|
||||
}
|
||||
|
||||
private String getExtUri(HttpServletRequest request) {
|
||||
String orgUri = request.getRequestURI().replaceAll(request.getContextPath(), "");
|
||||
String uri = getExtUri(orgUri, 3);
|
||||
if (uri != null && uri.trim().length() > 0) {
|
||||
return "/" + uri;
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static String getExtUri(String url, int length) {
|
||||
String[] urls = url.split("/");
|
||||
List<String> newUrls = new ArrayList<>();
|
||||
Collections.addAll(newUrls, urls);
|
||||
return StringUtils.join(newUrls.subList(length, urls.length).toArray(), "/");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Deprecated
|
||||
public void service(String adptGrpName, String adptName, HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP 요청에서 클라이언트 IP를 추출합니다.
|
||||
* X-Forwarded-For 헤더가 있는 경우 이를 우선적으로 사용하고,
|
||||
* 없는 경우 remoteAddr을 사용합니다.
|
||||
*/
|
||||
private String getClientIp(HttpServletRequest request) {
|
||||
String ipAddress = request.getHeader("X-Forwarded-For");
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getRemoteAddr();
|
||||
}
|
||||
return ipAddress;
|
||||
}
|
||||
|
||||
private String assignApiId(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request) {
|
||||
String apiId = null;
|
||||
try {
|
||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||
RequestAction action = ActionFactory.createAction(actionName);
|
||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||
String[] keys = action.perform(message);
|
||||
apiId = keys[0];
|
||||
|
||||
// PathVariable 지원 추가
|
||||
apiId = StandardMessageUtil.getMatchedKey(apiId, actionName);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
// // header 에서 확보
|
||||
// String apiId = request.getHeader(HEADER_NAME_API_CODE);
|
||||
// if (StringUtils.isBlank(apiId)) {
|
||||
// // url에서 확보
|
||||
// // /ONLWeb/api/v1/public/getUserInfo.svc/
|
||||
// apiId = request.getRequestURI();
|
||||
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
||||
// apiId = StringUtils.removeEnd(apiId, "/");
|
||||
// // getUserInfo.svc
|
||||
// apiId = StringUtils.substringAfterLast(apiId, "/");
|
||||
// }
|
||||
|
||||
return apiId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class DJErpOAuth2AccessTokenRequest implements Serializable {
|
||||
|
||||
@JsonProperty("grant_type")
|
||||
private String grantType;
|
||||
@JsonProperty("client_id")
|
||||
private String clientId;
|
||||
@JsonProperty("client_secret")
|
||||
private String clientSecret;
|
||||
private String scope;
|
||||
|
||||
public String getGrantType() {
|
||||
return grantType;
|
||||
}
|
||||
|
||||
public void setGrantType(String grantType) {
|
||||
this.grantType = grantType;
|
||||
}
|
||||
|
||||
public String getClientId() {
|
||||
return clientId;
|
||||
}
|
||||
|
||||
public void setClientId(String clientId) {
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
public String getClientSecret() {
|
||||
return clientSecret;
|
||||
}
|
||||
|
||||
public void setClientSecret(String clientSecret) {
|
||||
this.clientSecret = clientSecret;
|
||||
}
|
||||
|
||||
public String getScope() {
|
||||
return scope;
|
||||
}
|
||||
|
||||
public void setScope(String scope) {
|
||||
this.scope = scope;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DJErpOAuth2AccessTokenRequest [grantType=" + grantType + ", clientId=" + clientId
|
||||
+ ", clientSecret=" + clientSecret + ", scope=" + scope + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
@JsonInclude(Include.NON_NULL)
|
||||
@JsonPropertyOrder({ "access_token", "token_type", "expires_in", "scope", "jti", "client_id" })
|
||||
public class DJErpOAuth2AccessTokenResponse implements Serializable {
|
||||
|
||||
@JsonProperty("access_token")
|
||||
private String accessToken;
|
||||
@JsonProperty("token_type")
|
||||
private String tokenType;
|
||||
@JsonProperty("expires_in")
|
||||
private Long expiresIn;
|
||||
private String scope;
|
||||
private String jti;
|
||||
@JsonProperty("client_id")
|
||||
private String clientId;
|
||||
|
||||
public String getAccessToken() {
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
public void setAccessToken(String accessToken) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
|
||||
public String getTokenType() {
|
||||
return tokenType;
|
||||
}
|
||||
|
||||
public void setTokenType(String tokenType) {
|
||||
this.tokenType = tokenType;
|
||||
}
|
||||
|
||||
public Long getExpiresIn() {
|
||||
return expiresIn;
|
||||
}
|
||||
|
||||
public void setExpiresIn(Long expiresIn) {
|
||||
this.expiresIn = expiresIn;
|
||||
}
|
||||
|
||||
public String getScope() {
|
||||
return scope;
|
||||
}
|
||||
|
||||
public void setScope(String scope) {
|
||||
this.scope = scope;
|
||||
}
|
||||
|
||||
public String getJti() {
|
||||
return jti;
|
||||
}
|
||||
|
||||
public void setJti(String jti) {
|
||||
this.jti = jti;
|
||||
}
|
||||
|
||||
public String getClientId() {
|
||||
return clientId;
|
||||
}
|
||||
|
||||
public void setClientId(String clientId) {
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DJErpOAuth2AccessTokenResponse [accessToken=" + accessToken + ", tokenType=" + tokenType
|
||||
+ ", expiresIn=" + expiresIn + ", scope=" + scope + ", jti=" + jti + ", clientId=" + clientId + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.util.OAuth2Utils;
|
||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Request;
|
||||
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.authserver.config.RequestContextData;
|
||||
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.util.BeanUtils;
|
||||
import com.eactive.eai.authserver.vo.ClientVO;
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.logger.EAIDBLogControl;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.common.util.UUID;
|
||||
import com.eactive.eai.data.entity.onl.authserver.TokenIssuanceLog;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
@Controller
|
||||
public class DJErpOAuth2Controller {
|
||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
private static final String HEADER_TRACEID = "traceId";
|
||||
private static final String SERVICE_CODE_ACCESS_TOKEN = "00";
|
||||
|
||||
@Autowired
|
||||
private TokenIssuanceLogDAO tokenIssuanceLogDAO;
|
||||
|
||||
@RequestMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, method = RequestMethod.POST,
|
||||
consumes = "application/json", produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<?> tokenJson(@RequestBody DJErpOAuth2AccessTokenRequest tokenRequest,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
@RequestMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, method = RequestMethod.POST,
|
||||
consumes = "application/x-www-form-urlencoded", produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<?> tokenForm(@RequestParam Map<String, String> params,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
DJErpOAuth2AccessTokenRequest tokenRequest = new DJErpOAuth2AccessTokenRequest();
|
||||
tokenRequest.setGrantType(params.get("grant_type"));
|
||||
tokenRequest.setClientId(params.get("client_id"));
|
||||
tokenRequest.setClientSecret(params.get("client_secret"));
|
||||
tokenRequest.setScope(params.get("scope"));
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
@GetMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<?> tokenGet(@RequestParam Map<String, String> params,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
DJErpOAuth2AccessTokenRequest tokenRequest = new DJErpOAuth2AccessTokenRequest();
|
||||
tokenRequest.setGrantType(params.get("grant_type"));
|
||||
tokenRequest.setClientId(params.get("client_id"));
|
||||
tokenRequest.setClientSecret(params.get("client_secret"));
|
||||
tokenRequest.setScope(params.get("scope"));
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> issueToken(DJErpOAuth2AccessTokenRequest tokenRequest,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(tokenRequest.toString());
|
||||
}
|
||||
|
||||
RequestContextData data = new RequestContextData();
|
||||
data.setClientId(tokenRequest.getClientId());
|
||||
data.setIpAddress(extractIpAddress(request));
|
||||
data.setGrantType(tokenRequest.getGrantType());
|
||||
data.setScope(tokenRequest.getScope());
|
||||
data.setUsername("none");
|
||||
data.setResource("none");
|
||||
RequestContextData.ThreadLocalRequestContext.set(data);
|
||||
|
||||
String grantType = tokenRequest.getGrantType();
|
||||
String clientId = tokenRequest.getClientId();
|
||||
String clientSecret = tokenRequest.getClientSecret();
|
||||
String scopes = tokenRequest.getScope();
|
||||
|
||||
try {
|
||||
if (!StringUtils.equals(grantType, "client_credentials")) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {grant_type}");
|
||||
}
|
||||
|
||||
String[] scopeArr = org.springframework.util.StringUtils.tokenizeToStringArray(scopes, " ");
|
||||
Set<String> scopeSet = new HashSet<>();
|
||||
for (String scope : scopeArr) {
|
||||
scopeSet.add(scope);
|
||||
}
|
||||
|
||||
ClientDetails clientDetails = OAuth2Manager.getInstance().getClientDeatilsStore().get(clientId);
|
||||
verifyClient(clientDetails, clientId, clientSecret, scopeSet);
|
||||
|
||||
String traceId = UUID.randomUUID().toString().replace("-", "");
|
||||
response.setHeader(HEADER_TRACEID, traceId);
|
||||
|
||||
HashMap<String, String> authorizationParameters = new HashMap<>();
|
||||
authorizationParameters.put(OAuth2Utils.GRANT_TYPE, grantType);
|
||||
authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
|
||||
authorizationParameters.put("client_secret", clientSecret);
|
||||
|
||||
Set<String> responseType = new HashSet<>();
|
||||
responseType.add(grantType);
|
||||
|
||||
OAuth2Request authorizationRequest = new OAuth2Request(authorizationParameters, clientId, null, true,
|
||||
scopeSet, null, "", responseType, null);
|
||||
|
||||
Principal principal = new OAuth2Authentication(authorizationRequest, null);
|
||||
ResponseEntity<OAuth2AccessToken> result = tokenEndpoint().postAccessToken(principal, authorizationParameters);
|
||||
OAuth2AccessToken token = result.getBody();
|
||||
|
||||
DJErpOAuth2AccessTokenResponse responseToken = new DJErpOAuth2AccessTokenResponse();
|
||||
responseToken.setAccessToken(token.getValue());
|
||||
responseToken.setTokenType(token.getTokenType());
|
||||
responseToken.setExpiresIn(Long.valueOf(token.getExpiresIn()));
|
||||
responseToken.setScope(StringUtils.join(token.getScope(), " "));
|
||||
responseToken.setJti((String) token.getAdditionalInformation().get("jti"));
|
||||
responseToken.setClientId((String) token.getAdditionalInformation().get("client_id"));
|
||||
|
||||
//logTokenIssuance(true, false, "Token issued successfully", token.getValue());
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
return ResponseEntity.ok(mapper.writeValueAsString(responseToken));
|
||||
|
||||
} catch (JwtAuthException e) {
|
||||
logger.info("Token request[/dj/oauth2/token] => clientId: {}, grantType: {}, scope: {}",
|
||||
clientId, grantType, scopes);
|
||||
logger.error(e.getMessage());
|
||||
logTokenIssuance(false, false, e.getMessage(), null);
|
||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage());
|
||||
int statusCode = NumberUtils.toInt(StringUtils.left(e.getCode(), 3), HttpStatus.UNAUTHORIZED.value());
|
||||
return ResponseEntity.status(statusCode).body(errorJson);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.info("Token request[/dj/oauth2/token] => clientId: {}, grantType: {}, scope: {}",
|
||||
clientId, grantType, scopes);
|
||||
logger.error(e.getMessage());
|
||||
logTokenIssuance(false, false, e.getMessage(), null);
|
||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, "Unauthorized. [Unknown]");
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorJson);
|
||||
|
||||
} finally {
|
||||
RequestContextData.ThreadLocalRequestContext.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private void verifyClient(ClientDetails clientDetails, String clientId, String clientSecret, Set<String> scopeSet)
|
||||
throws JwtAuthException {
|
||||
|
||||
if (StringUtils.isBlank(clientId)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {client_id}");
|
||||
}
|
||||
if (clientDetails == null) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [client not found]");
|
||||
}
|
||||
if (StringUtils.isBlank(clientSecret)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {client_secret}");
|
||||
}
|
||||
if (!StringUtils.equals(clientDetails.getClientSecret(), clientSecret)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [Bad client credentials(Client Secret is not match)]");
|
||||
}
|
||||
if (scopeSet.isEmpty()) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {scope}");
|
||||
}
|
||||
if (!clientDetails.getScope().containsAll(scopeSet)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [Bad client credentials(Include unacceptable scope)]");
|
||||
}
|
||||
}
|
||||
|
||||
private String extractIpAddress(HttpServletRequest request) {
|
||||
String ip = request.getHeader("X-Forwarded-For");
|
||||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("Proxy-Client-IP");
|
||||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("HTTP_CLIENT_IP");
|
||||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getRemoteAddr();
|
||||
return ip;
|
||||
}
|
||||
|
||||
private TokenEndpoint tokenEndpoint() {
|
||||
return BeanUtils.getBean("tokenEndpoint", TokenEndpoint.class);
|
||||
}
|
||||
|
||||
private void logTokenIssuance(boolean isSuccess, boolean isRestrictionExempt, String resultMessage, String accessToken) {
|
||||
try {
|
||||
if (!EAIDBLogControl.isEnable()) {
|
||||
logger.warn("DB logging is disabled. Skipping token issuance logging.");
|
||||
return;
|
||||
}
|
||||
RequestContextData data = RequestContextData.ThreadLocalRequestContext.get();
|
||||
|
||||
TokenIssuanceLog log = new TokenIssuanceLog();
|
||||
String clientId = data.getClientId();
|
||||
log.setClientId(clientId);
|
||||
|
||||
if (StringUtils.isNotBlank(clientId)) {
|
||||
try {
|
||||
ClientVO clientVO = OAuth2Manager.getInstance().getClientInfo(clientId);
|
||||
log.setAppName(clientVO.getClientName());
|
||||
log.setOrgId(clientVO.getOrgId());
|
||||
log.setOrgName(clientVO.getOrgName());
|
||||
} catch (DAOException e) {
|
||||
logger.warn("cannot find clientVO - " + clientId);
|
||||
}
|
||||
}
|
||||
|
||||
log.setGrantType(data.getGrantType());
|
||||
log.setScope(data.getScope());
|
||||
log.setIpAddress(data.getIpAddress());
|
||||
log.setSuccessYn(isSuccess ? "Y" : "N");
|
||||
log.setIssuanceDateTime(LocalDateTime.now());
|
||||
log.setRestrictionExemptYn(isRestrictionExempt ? "Y" : "N");
|
||||
log.setResultMessage(resultMessage);
|
||||
log.setAccessToken(accessToken);
|
||||
|
||||
tokenIssuanceLogDAO.saveTokenIssuanceLog(log);
|
||||
} catch (Throwable th) {
|
||||
logger.error("Error while logging token issuance: " + th.getMessage(), th);
|
||||
}
|
||||
}
|
||||
}
|
||||
+680
@@ -0,0 +1,680 @@
|
||||
package com.eactive.eai.custom.adapter.http.client.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.BitSet;
|
||||
import java.util.Formatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
||||
import com.eactive.eai.adapter.http.client.impl.HttpClientAdapterServiceRest;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.impl.HttpAdapterServiceBypass;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
|
||||
public class HttpClient5AdapterServiceBypass extends HttpClient5AdapterServiceSupport
|
||||
implements HttpClientAdapterServiceKey {
|
||||
public static final String TYPE_BYPASS_REQUEST = "bypassRequest";
|
||||
public static final String REST_OPTION = "REST_OPTION";
|
||||
|
||||
protected boolean doSendUrlFragment = true;
|
||||
protected boolean doHandleCompression = false;
|
||||
protected boolean doForwardIP = false;
|
||||
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
||||
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
||||
|
||||
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
||||
|
||||
// ex) $.dataHeader.GW_RSLT_CD
|
||||
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
||||
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
||||
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
||||
* - type : simpleRequest, variableUrlRequest
|
||||
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
||||
* - method : get, delete, post, put
|
||||
* - contentType : application/json, application/x-www-form-urlencoded
|
||||
* - adapterTokenUseYn: Y, N(default)
|
||||
* ex)
|
||||
* {"type":"variableUrlRequest","extraPath":"/aaa/{userId}","uriVariables":["userId"]}
|
||||
* @formatter:on
|
||||
*/
|
||||
String restOptionData = tempProp.getProperty(REST_OPTION, "{}");
|
||||
|
||||
JSONObject restOptionObject = parseJson(restOptionData);
|
||||
|
||||
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
||||
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
||||
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
||||
}
|
||||
|
||||
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
||||
String inboundRewritePath = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_REWRITE_PATH, "");
|
||||
String inboundQueryString = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_QUERY_STRING, "");
|
||||
Properties inboundHeaders = (Properties) tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
||||
Map<String, String> inboundPathVariables = (Map<String, String>) tempProp
|
||||
.get(HttpAdapterServiceKey.INBOUND_PATH_VARIABLES);
|
||||
|
||||
String restMethod = (String) restOptionObject.get("method");
|
||||
if (StringUtils.isBlank(restMethod)) {
|
||||
restMethod = inboundMethod;
|
||||
}
|
||||
|
||||
String url = getRewriteUrl(vo, inboundRewritePath, inboundQueryString, restOptionObject, inboundPathVariables);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] url = [" + url + "]");
|
||||
}
|
||||
|
||||
HttpClient mclient = this.client;
|
||||
HttpUriRequestBase method = generateMethod(restMethod, url);
|
||||
|
||||
assignRequestHeaders(method, inboundHeaders, tempProp);
|
||||
|
||||
if (hasBody(data, method)) {
|
||||
byte[] bodyBytes;
|
||||
if (data instanceof byte[]) {
|
||||
bodyBytes = (byte[]) data;
|
||||
} else if (data instanceof String) {
|
||||
bodyBytes = ((String) data).getBytes(vo.getEncode());
|
||||
} else {
|
||||
bodyBytes = new byte[0];
|
||||
}
|
||||
method.setEntity(new ByteArrayEntity(bodyBytes, null));
|
||||
}
|
||||
|
||||
String contentType = (String) restOptionObject.get("contentType");
|
||||
if (StringUtils.isBlank(contentType) && inboundHeaders != null) {
|
||||
contentType = getIgnoreCaseProp(inboundHeaders, HttpHeaders.CONTENT_TYPE);
|
||||
contentType = StringUtils.substringBefore(contentType, ";");
|
||||
}
|
||||
|
||||
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
|
||||
configureHttpClient(requestConfigBuilder, vo, method);
|
||||
|
||||
OAuth2AccessTokenVO accessToken = null;
|
||||
if (useAdapterToken) {
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
||||
|
||||
// 토큰이 없거나 만료 됐으면 재발급
|
||||
if (accessToken == null || accessToken.isExpired()) {
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
||||
oldToken);
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
||||
+ accessToken + "]");
|
||||
}
|
||||
|
||||
setAuthHeaders(method, accessToken);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RequestHeader [Authorization=" + method.getFirstHeader("Authorization") + "]");
|
||||
}
|
||||
}
|
||||
|
||||
// 로깅 인터셉터에 전달할 컨텍스트 정보 설정
|
||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
HttpContext context = new BasicHttpContext();
|
||||
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
||||
Integer logProcessNo = (Integer) tempProp.get(HttpClientAdapterServiceKey.LOG_PROCESS_NO);
|
||||
if (logProcessNo != null && logProcessNo > 0) {
|
||||
context.setAttribute(HttpClientAdapterServiceKey.LOG_PROCESS_NO, logProcessNo);
|
||||
}
|
||||
|
||||
int status = -1;
|
||||
|
||||
try {
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
byte[] responseMessage = null;
|
||||
Header[] responseHeaders = null;
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"SEND [Bypass Request..]" + CommonLib.getDumpMessage(data));
|
||||
}
|
||||
try {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[method getName]" + method.getMethod());
|
||||
logger.debug("[method getRequestHeaders]" + java.util.Arrays.toString(method.getHeaders()));
|
||||
logger.debug("[method getURI]" + method.getPath());
|
||||
}
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = response.getCode();
|
||||
responseHeaders = response.getHeaders();
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
}
|
||||
}
|
||||
} catch (ConnectException e) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
||||
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
||||
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
||||
*
|
||||
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
||||
* __ex) $.dataHeader.resultCode
|
||||
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
||||
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
||||
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
||||
* @formatter:on
|
||||
*/
|
||||
boolean needReissue = false;
|
||||
|
||||
if (status == 200) {
|
||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
} else if (status >= 400 && status < 500) {
|
||||
if (useAdapterToken) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
|
||||
if (!needReissue) {
|
||||
// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
|
||||
if (responseMessage == null || responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
} else if (status != 200) {
|
||||
responseMessage = responseMessage != null ? responseMessage : new byte[0];
|
||||
// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
|
||||
if (responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
if (useAdapterToken) {
|
||||
if (responseMessage == null) {
|
||||
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
||||
}
|
||||
|
||||
// OAuth 토큰 재요청 코드 확인
|
||||
if (needReissue) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] retry access token response code = ["
|
||||
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
}
|
||||
|
||||
// 토큰 재발급
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
OAuth2AccessTokenVO newAccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||
method.setHeader("Authorization", newAccessToken.getAuthorization());
|
||||
setAuthHeaders(method, newAccessToken);
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RETRY TOKEN = [" + newAccessToken + "]");
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse retryResponse = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = retryResponse.getCode();
|
||||
responseHeaders = retryResponse.getHeaders();
|
||||
responseMessage = EntityUtils.toByteArray(retryResponse.getEntity());
|
||||
} catch (IOException e) {
|
||||
throw new Exception("retry excuteMethod Exception = " + e.getMessage());
|
||||
}
|
||||
|
||||
if (status != 200) {
|
||||
responseMessage = responseMessage != null ? responseMessage : new byte[0];
|
||||
if (responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod,
|
||||
responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RETRY responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"RECV [Bypass Request..]" + CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
// 응답 Content-Type charset 기반 인코딩 결정, 없으면 어댑터 encoding 사용
|
||||
String responseEncode = vo.getEncode();
|
||||
if (responseHeaders != null) {
|
||||
for (Header header : responseHeaders) {
|
||||
if (StringUtils.equalsIgnoreCase(header.getName(), HttpHeaders.CONTENT_TYPE)) {
|
||||
try {
|
||||
MediaType mediaType = MediaType.parseMediaType(header.getValue());
|
||||
if (mediaType.getCharset() != null) {
|
||||
responseEncode = mediaType.getCharset().name();
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assignRelayDataToInbound(tempProp, responseHeaders, status);
|
||||
return responseMessage != null ? new String(responseMessage, responseEncode) : "";
|
||||
} catch (SocketTimeoutException ste) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClient5AdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(),
|
||||
ste);
|
||||
}
|
||||
logger.error("HttpClient5AdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(), ste);
|
||||
throw ste;
|
||||
} catch (ConnectException ce) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClient5AdapterServiceBypass] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(),
|
||||
ce);
|
||||
}
|
||||
logger.error("HttpClient5AdapterServiceBypass] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(), ce);
|
||||
throw ce;
|
||||
} catch (Exception e) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
||||
}
|
||||
logger.error(
|
||||
"HttpClient5AdapterServiceBypass] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
||||
e);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status != HttpStatus.SC_OK) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = String.valueOf(status);
|
||||
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasBody(Object data, HttpUriRequestBase method) {
|
||||
if (data == null) {
|
||||
return false;
|
||||
}
|
||||
// GET, DELETE는 표준 HTTP에서 body를 지원하지 않음
|
||||
return method instanceof HttpPost || method instanceof HttpPut;
|
||||
}
|
||||
|
||||
private HttpUriRequestBase generateMethod(String restMethod, String url) {
|
||||
switch (HttpMethodType.getValue(restMethod)) {
|
||||
case GET:
|
||||
return new HttpGet(url);
|
||||
case DELETE:
|
||||
return new HttpDelete(url);
|
||||
case POST:
|
||||
return new HttpPost(url);
|
||||
case PUT:
|
||||
return new HttpPut(url);
|
||||
default:
|
||||
return new HttpPost(url);
|
||||
}
|
||||
}
|
||||
|
||||
private String getRewriteUrl(HttpClientAdapterVO vo, String inboundRewritePath, String queryString,
|
||||
JSONObject restOptionObject, Map<String, String> inboundPathVariables) {
|
||||
String fragment = null;
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
int fragIdx = queryString.indexOf('#');
|
||||
if (fragIdx >= 0) {
|
||||
fragment = queryString.substring(fragIdx + 1);
|
||||
queryString = queryString.substring(0, fragIdx);
|
||||
}
|
||||
}
|
||||
|
||||
String restExtraPath = (String) restOptionObject.get("extraPath");
|
||||
if (StringUtils.isBlank(restExtraPath)) {
|
||||
StringBuilder uri = new StringBuilder(500);
|
||||
String baseUrl = StringUtils.removeEnd(vo.getUrl(), "/");
|
||||
String rewritePath = inboundRewritePath != null && !inboundRewritePath.startsWith("/")
|
||||
? "/" + inboundRewritePath : inboundRewritePath;
|
||||
uri.append(baseUrl).append(StringUtils.defaultString(rewritePath));
|
||||
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
uri.append('?');
|
||||
uri.append(encodeUriQuery(queryString, false));
|
||||
}
|
||||
|
||||
if (doSendUrlFragment && fragment != null) {
|
||||
uri.append('#');
|
||||
uri.append(encodeUriQuery(fragment, false));
|
||||
}
|
||||
|
||||
return uri.toString();
|
||||
} else {
|
||||
String type = (String) restOptionObject.get("type");
|
||||
String url = getUrl(vo.getUrl(), restExtraPath);
|
||||
|
||||
if (StringUtils.equalsIgnoreCase(type, HttpClientAdapterServiceRest.TYPE_VARIABLE_URL_REQUEST)) {
|
||||
inboundPathVariables = mergeInboundPathVariables(inboundPathVariables, queryString);
|
||||
List<String> urlVariableValueList = new ArrayList<>();
|
||||
JSONArray uriVariables = (JSONArray) restOptionObject.get("uriVariables");
|
||||
if (uriVariables != null && !uriVariables.isEmpty() && inboundPathVariables != null
|
||||
&& !inboundPathVariables.isEmpty()) {
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
String uriVariableValue = inboundPathVariables.get(urlVaribleId);
|
||||
urlVariableValueList.add(uriVariableValue);
|
||||
}
|
||||
|
||||
if (!urlVariableValueList.isEmpty()) {
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
||||
Object[] urls = urlVariableValueList.toArray();
|
||||
url = uriComponents.expand(urls).toUriString();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
url += "?" + encodeUriQuery(queryString, false);
|
||||
}
|
||||
|
||||
if (doSendUrlFragment && fragment != null) {
|
||||
url += "#" + encodeUriQuery(fragment, false);
|
||||
}
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> mergeInboundPathVariables(Map<String, String> inboundPathVariables,
|
||||
String queryString) {
|
||||
if (StringUtils.isBlank(queryString)) {
|
||||
return inboundPathVariables;
|
||||
}
|
||||
|
||||
if (inboundPathVariables == null) {
|
||||
inboundPathVariables = new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
String[] pairs = queryString.split("&");
|
||||
for (String pair : pairs) {
|
||||
int idx = pair.indexOf("=");
|
||||
inboundPathVariables.put(pair.substring(0, idx), pair.substring(idx + 1));
|
||||
}
|
||||
|
||||
return inboundPathVariables;
|
||||
}
|
||||
|
||||
private String getUrl(String baseUrl, String extraPath) {
|
||||
if (StringUtils.isBlank(extraPath)) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
||||
return extraPath;
|
||||
}
|
||||
|
||||
String targetUrl = baseUrl;
|
||||
if (!targetUrl.endsWith("/")) {
|
||||
targetUrl += "/";
|
||||
}
|
||||
if (extraPath.startsWith("/")) {
|
||||
targetUrl += extraPath.substring(1);
|
||||
} else {
|
||||
targetUrl += extraPath;
|
||||
}
|
||||
|
||||
return targetUrl;
|
||||
}
|
||||
|
||||
protected CharSequence encodeUriQuery(CharSequence in, boolean encodePercent) {
|
||||
StringBuilder outBuf = null;
|
||||
Formatter formatter = null;
|
||||
for (int i = 0; i < in.length(); i++) {
|
||||
char c = in.charAt(i);
|
||||
boolean escape = true;
|
||||
if (c < 128) {
|
||||
if (asciiQueryChars.get(c) && !(encodePercent && c == '%')) {
|
||||
escape = false;
|
||||
}
|
||||
} else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {
|
||||
escape = false;
|
||||
}
|
||||
if (!escape) {
|
||||
if (outBuf != null)
|
||||
outBuf.append(c);
|
||||
} else {
|
||||
if (outBuf == null) {
|
||||
outBuf = new StringBuilder(in.length() + 5 * 3);
|
||||
outBuf.append(in, 0, i);
|
||||
formatter = new Formatter(outBuf);
|
||||
}
|
||||
formatter.format("%%%02X", (int) c);
|
||||
}
|
||||
}
|
||||
return outBuf != null ? outBuf : in;
|
||||
}
|
||||
|
||||
protected static final BitSet asciiQueryChars;
|
||||
static {
|
||||
char[] c_unreserved = "_-!.~'()*".toCharArray();
|
||||
char[] c_punct = ",;:$&+=".toCharArray();
|
||||
char[] c_reserved = "/@".toCharArray();
|
||||
asciiQueryChars = new BitSet(128);
|
||||
for (char c = 'a'; c <= 'z'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c = 'A'; c <= 'Z'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c = '0'; c <= '9'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_unreserved)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_punct)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_reserved)
|
||||
asciiQueryChars.set(c);
|
||||
asciiQueryChars.set('%');
|
||||
}
|
||||
|
||||
private void assignRelayDataToInbound(Properties prop, Header[] responseHeaders, int status) {
|
||||
Properties headerProp = new Properties();
|
||||
if (responseHeaders != null) {
|
||||
for (Header header : responseHeaders) {
|
||||
String name = header.getName();
|
||||
String value = header.getValue();
|
||||
String existing = headerProp.getProperty(name);
|
||||
if (existing != null) {
|
||||
// 동일 이름의 헤더가 여러 개인 경우 콤마로 합침 (RFC 7230)
|
||||
headerProp.put(name, existing + ", " + value);
|
||||
} else {
|
||||
headerProp.put(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
headerProp.put(HttpAdapterServiceBypass.HTTP_STATUS, String.valueOf(status));
|
||||
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, headerProp);
|
||||
|
||||
prop.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
}
|
||||
|
||||
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||
String encode) {
|
||||
if (responseMessage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
||||
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
||||
if (StringUtils.isBlank(responseCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
||||
return ArrayUtils.contains(arr, responseCode);
|
||||
} catch (Exception e) {
|
||||
logger.error("HttpClient5AdapterServiceBypass] checkTokenRetry error=" + e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void assignRequestHeaders(HttpUriRequestBase method, Properties headerProp, Properties inProp) {
|
||||
if (headerProp == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (Entry<Object, Object> e : headerProp.entrySet()) {
|
||||
String key = (String) e.getKey();
|
||||
String value = (String) e.getValue();
|
||||
|
||||
if (StringUtils.equalsAnyIgnoreCase(key, HttpAdapterServiceBypass.HOP_BY_HOP_HEADERS)
|
||||
|| StringUtils.equalsIgnoreCase(key, HttpHeaders.CONTENT_LENGTH)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (doHandleCompression && StringUtils.equalsIgnoreCase(key, HttpHeaders.ACCEPT_ENCODING)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
method.addHeader(key, value);
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request Header :" + key + "=[" + value + "]");
|
||||
}
|
||||
}
|
||||
|
||||
if (doForwardIP) {
|
||||
String forHeaderName = "X-Forwarded-For";
|
||||
String forHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_REMOTE_ADDR);
|
||||
if (StringUtils.isNotBlank(forHeader)) {
|
||||
String existingForHeader = headerProp.getProperty(forHeaderName);
|
||||
if (existingForHeader != null) {
|
||||
forHeader = existingForHeader + ", " + forHeader;
|
||||
}
|
||||
method.addHeader(forHeaderName, forHeader);
|
||||
}
|
||||
|
||||
String protoHeaderName = "X-Forwarded-Proto";
|
||||
String protoHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_SCHEME);
|
||||
if (StringUtils.isNotBlank(protoHeader)) {
|
||||
method.addHeader(protoHeaderName, protoHeader);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private JSONObject parseJson(String message) throws Exception {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (JSONObject) JSONValue.parse(message);
|
||||
}
|
||||
|
||||
public static final String getIgnoreCaseProp(Properties prop, String key) {
|
||||
if (prop == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (Entry<Object, Object> e : prop.entrySet()) {
|
||||
if (StringUtils.equalsIgnoreCase(key, (String) e.getKey())) {
|
||||
return (String) e.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.eactive.eai.custom.inbound.action;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.Keys;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.impl.HttpAdapterServiceRest;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||
import com.eactive.eai.common.util.MessageKeyExtractor;
|
||||
import com.eactive.eai.inbound.action.ActionException;
|
||||
import com.eactive.eai.inbound.action.RequestActionSupport;
|
||||
|
||||
public class RestAdapterMethodUrlFallbackRequestAction extends RequestActionSupport {
|
||||
|
||||
/**
|
||||
* 1. 기능 : Inbound Adapter를 통해 전달받은 비표준메시지에서 표준메시지를 생성하기 위한 키값을 추출
|
||||
* 2. 처리 개요 :
|
||||
* - TYPE_HTTP_CUSTOM / TYPE_REST: 전체 URI로 키를 먼저 조회하고,
|
||||
* 없으면 뒤 경로를 하나씩 제거하면서 일치하는 키를 탐색한다.
|
||||
* - 그 외: MessageKeyExtractor를 통해 추출
|
||||
*
|
||||
* @param message Object 타입의 요청메시지
|
||||
* @return String 비표준메시지의 메시지키값
|
||||
**/
|
||||
public String[] perform(Object message) throws ActionException {
|
||||
String[] key = null;
|
||||
|
||||
AdapterManager adapterManager = AdapterManager.getInstance();
|
||||
AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(adapterGroupName);
|
||||
String adptGrpName = adptGrpVO.getName();
|
||||
|
||||
if (StringUtils.equals(adptGrpVO.getType(), Keys.TYPE_HTTP_CUSTOM)
|
||||
|| StringUtils.equals(adptGrpVO.getType(), Keys.TYPE_REST)) {
|
||||
try {
|
||||
String requestMethod = prop
|
||||
.getProperty(HttpAdapterServiceRest.PROPERTIES_NAME_HTTP_REQUEST_METHOD);
|
||||
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
String inboundUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
|
||||
String apiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH);
|
||||
|
||||
// /getUserInfo.svc
|
||||
String apiUri = org.apache.commons.lang.StringUtils.removeStart(inboundUri, apiPath);
|
||||
|
||||
Set<String> allKeys = new HashSet<>(Arrays.asList(
|
||||
STDMessageManager.getInstance().getAllSTDMessageKeys()));
|
||||
|
||||
// 전체 URI부터 시작해서 뒤 경로를 하나씩 제거하며 일치하는 키를 탐색
|
||||
String searchUri = apiUri;
|
||||
for (int i = 0; i < 10; i++) {
|
||||
String candidateKey = adptGrpName + ":" + requestMethod + "|"
|
||||
+ StringUtils.removeStart(searchUri, "/");
|
||||
if (allKeys.contains(candidateKey)) {
|
||||
return new String[] { candidateKey };
|
||||
}
|
||||
String shortened = StringUtils.substringBeforeLast(searchUri, "/");
|
||||
if (StringUtils.isBlank(shortened)) {
|
||||
break;
|
||||
}
|
||||
searchUri = shortened;
|
||||
}
|
||||
|
||||
// 일치하는 키가 없으면 원래 키로 fallback
|
||||
String apiKey = adptGrpName + ":" + requestMethod + "|"
|
||||
+ StringUtils.removeStart(apiUri, "/");
|
||||
return new String[] { apiKey };
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new ActionException(ExceptionUtil.getErrorCode(e, "RECEAIIRA001"));
|
||||
}
|
||||
}
|
||||
|
||||
if (message instanceof byte[]) {
|
||||
try {
|
||||
key = MessageKeyExtractor.getMessageKeyValueForRest(this.adapterGroupName, message, prop, "url", true);
|
||||
} catch (Exception e) {
|
||||
throw new ActionException(ExceptionUtil.getErrorCode(e, "RECEAIIRA001"));
|
||||
}
|
||||
if (logger.isDebug())
|
||||
logger.debug(adapterName + "] received data >> [" + new String((byte[]) message) + "]");
|
||||
} else {
|
||||
try {
|
||||
key = MessageKeyExtractor.getMessageKeyValueForRest(this.adapterGroupName, message, prop, "url", true);
|
||||
} catch (Exception e) {
|
||||
throw new ActionException(ExceptionUtil.getErrorCode(e, "RECEAIIRA001"));
|
||||
}
|
||||
if (logger.isDebug())
|
||||
logger.debug(adapterName + "] received data >> [" + message + "]");
|
||||
}
|
||||
|
||||
for (int i = 0; i < key.length; i++) {
|
||||
key[i] = adptGrpName.trim() + key[i];
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* DJBank(제주은행) 차세대 표준전문 GUID 생성기
|
||||
*
|
||||
* GUID 구성 (40자):
|
||||
* 일자(8) + 시간(6) + 밀리초(3) + 시스템코드(3) + 노드번호(2) + 세션ID(12) + Random(6)
|
||||
* = 8 + 6 + 3 + 3 + 2 + 12 + 6 = 40자
|
||||
*/
|
||||
public final class GUIDGeneratorDJB {
|
||||
|
||||
public static final int GUID_LENGTH = 40;
|
||||
|
||||
private static final DateTimeFormatter FMT_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
private static final DateTimeFormatter FMT_TIME = DateTimeFormatter.ofPattern("HHmmss");
|
||||
private static final DateTimeFormatter FMT_MILLIS = DateTimeFormatter.ofPattern("SSS");
|
||||
|
||||
private static final AtomicInteger seq = new AtomicInteger(1);
|
||||
private static final SecureRandom rnd = new SecureRandom();
|
||||
|
||||
private static final String NODE_NO;
|
||||
private static final String SESSION_ID_BASE;
|
||||
|
||||
static {
|
||||
// 노드번호(2): 서버명 마지막 2자리, 없으면 "00"
|
||||
String serverName = System.getProperty("server.key", "");
|
||||
if (serverName.length() >= 2) {
|
||||
NODE_NO = serverName.substring(serverName.length() - 2);
|
||||
} else {
|
||||
NODE_NO = "00";
|
||||
}
|
||||
|
||||
// 세션ID 기반(12): 호스트명 앞 12자 (부족 시 '_'로 우측패딩)
|
||||
String hostname;
|
||||
try {
|
||||
hostname = java.net.InetAddress.getLocalHost().getHostName();
|
||||
} catch (Exception e) {
|
||||
hostname = "____________";
|
||||
}
|
||||
if (hostname.length() >= 12) {
|
||||
SESSION_ID_BASE = hostname.substring(0, 12).toUpperCase();
|
||||
} else {
|
||||
SESSION_ID_BASE = String.format("%-12s", hostname).toUpperCase().replace(' ', '_');
|
||||
}
|
||||
}
|
||||
|
||||
private GUIDGeneratorDJB() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param systemCode 시스템구분코드 3자 (예: "EAI", "OPA")
|
||||
*/
|
||||
public static String getGUID(String systemCode) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
String date = now.format(FMT_DATE); // 8자
|
||||
String time = now.format(FMT_TIME); // 6자
|
||||
String millis = now.format(FMT_MILLIS); // 3자
|
||||
|
||||
// 시스템코드 3자 정규화
|
||||
String sysCode = normalizeCode(systemCode, 3);
|
||||
|
||||
// 노드번호 2자
|
||||
String nodeNo = NODE_NO;
|
||||
|
||||
// 세션ID 12자
|
||||
String sessionId = SESSION_ID_BASE;
|
||||
|
||||
// Random 6자 (숫자)
|
||||
int seqVal = seq.getAndUpdate(v -> v >= 999999 ? 1 : v + 1);
|
||||
String random = String.format("%06d", seqVal);
|
||||
|
||||
String guid = date + time + millis + sysCode + nodeNo + sessionId + random;
|
||||
|
||||
if (guid.length() != GUID_LENGTH) {
|
||||
throw new IllegalStateException("GUID length error: " + guid.length() + " [" + guid + "]");
|
||||
}
|
||||
return guid;
|
||||
}
|
||||
|
||||
private static String normalizeCode(String code, int len) {
|
||||
if (code == null) code = "";
|
||||
code = code.toUpperCase();
|
||||
if (code.length() >= len) return code.substring(0, len);
|
||||
return String.format("%-" + len + "s", code).replace(' ', '_');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.service.DefaultInterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
/**
|
||||
* DJBank(제주은행) 차세대 표준전문 InterfaceMapper
|
||||
*
|
||||
* HEAD 영역이 평면 구조로 변경됨에 따라 필드 접근 경로 및 값 변환 로직을 재정의.
|
||||
*
|
||||
* 주요 변경사항:
|
||||
* - GUID: 40자 (기존 36자)
|
||||
* - GUID 진행번호: HEAD.guid_prgs_no 별도 필드 (기존 GUID 문자열 내 포함)
|
||||
* - 처리결과구분코드: S(성공)/F(오류) (기존 NR/ER)
|
||||
* - 시스템환경구분코드: D/T/P (기존 O/S/D)
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class InterfaceMapperDJB extends DefaultInterfaceMapper {
|
||||
|
||||
private static final String PATH_MCI_NODE = "HEAD.mci_node_dvcd";
|
||||
private static final String PATH_EAI_NODE = "HEAD.eai_node_dvcd";
|
||||
private static final String PATH_MCI_SESN = "HEAD.mci_sesn_id";
|
||||
|
||||
// 처리결과구분코드 DJBank 값
|
||||
private static final String PROCS_RSLT_SUCCESS = "S";
|
||||
private static final String PROCS_RSLT_FAIL = "F";
|
||||
|
||||
@Override
|
||||
public String getEaiSvcCode(StandardMessage standardMessage) {
|
||||
String interfaceId = getInterfaceId(standardMessage);
|
||||
String sendRecvDvcd = getSendRecvDivision(standardMessage); // S | R
|
||||
String inExDivision = getInExDivision(standardMessage); // 1 | 2
|
||||
|
||||
if (interfaceId == null) interfaceId = "";
|
||||
interfaceId = interfaceId.trim();
|
||||
|
||||
return interfaceId + sendRecvDvcd + StringUtils.defaultString(inExDivision);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// GUID (40자 고정)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public void setGuid(StandardMessage standardMessage, String guid) {
|
||||
if (guid == null) throw new RuntimeException("guid is null");
|
||||
if (guid.length() != GUIDGeneratorDJB.GUID_LENGTH) {
|
||||
throw new RuntimeException("GUID length must be " + GUIDGeneratorDJB.GUID_LENGTH + ", actual=" + guid.length());
|
||||
}
|
||||
setItemValue(standardMessage, getPath(GUID), guid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getGuid(StandardMessage standardMessage) {
|
||||
return StringUtils.defaultString(getItemValue(standardMessage, getPath(GUID)));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// GUID 진행번호 — HEAD.guid_prgs_no 별도 필드
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public String getGuidSeq(StandardMessage standardMessage) {
|
||||
String val = getItemValue(standardMessage, getPath(GUID_SEQ));
|
||||
if (StringUtils.isBlank(val)) return "001";
|
||||
try {
|
||||
// NUMBER 타입은 내부적으로 선행 0 제거 → 조회 시 3자리로 복원
|
||||
return String.format("%03d", Integer.parseInt(val.trim()));
|
||||
} catch (NumberFormatException e) {
|
||||
return StringUtils.defaultString(val, "001");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setGuidSeq(StandardMessage standardMessage, String guidSeq) {
|
||||
setItemValue(standardMessage, getPath(GUID_SEQ), guidSeq);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String nextGuidSeq(StandardMessage standardMessage) {
|
||||
String current = getGuidSeq(standardMessage);
|
||||
int seq = 1;
|
||||
try {
|
||||
seq = Integer.parseInt(current.trim()) + 1;
|
||||
} catch (NumberFormatException e) {
|
||||
seq = 2;
|
||||
}
|
||||
String next = String.format("%03d", seq);
|
||||
setGuidSeq(standardMessage, next);
|
||||
return next;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 원거래 GUID — HEAD.ortr_guid (40자 그대로)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public String getOrgGuid(StandardMessage standardMessage) {
|
||||
return StringUtils.defaultString(getItemValue(standardMessage, getPath(GUID_ORG)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOrgGuid(StandardMessage standardMessage, String orgGuid) {
|
||||
setItemValue(standardMessage, getPath(GUID_ORG), orgGuid);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 처리결과구분코드: 엔진 내부(0=정상, 1=오류) ↔ DJBank(S/F)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public String getResponseType(StandardMessage standardMessage) {
|
||||
String val = getItemValue(standardMessage, getPath(RESPONSE_TYPE));
|
||||
if (PROCS_RSLT_SUCCESS.equals(val)) return STDMessageKeys.RESPONSE_TYPE_CODE_N;
|
||||
if (PROCS_RSLT_FAIL.equals(val)) return STDMessageKeys.RESPONSE_TYPE_CODE_E;
|
||||
return val;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setResponseType(StandardMessage standardMessage, String responseType) {
|
||||
String siteVal;
|
||||
if (STDMessageKeys.RESPONSE_TYPE_CODE_N.equals(responseType)) {
|
||||
siteVal = PROCS_RSLT_SUCCESS;
|
||||
} else if (STDMessageKeys.RESPONSE_TYPE_CODE_E.equals(responseType)) {
|
||||
siteVal = PROCS_RSLT_FAIL;
|
||||
} else {
|
||||
siteVal = responseType;
|
||||
}
|
||||
setItemValue(standardMessage, getPath(RESPONSE_TYPE), siteVal);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 원거래복원여부: Y/N 그대로 사용 (엔진 내부 1/0과 변환)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public String getRecoverYn(StandardMessage standardMessage) {
|
||||
String val = getItemValue(standardMessage, getPath(RECOVER_YN));
|
||||
return "Y".equals(val) ? "1" : "0";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRecoverYn(StandardMessage standardMessage, String recoverYn) {
|
||||
setItemValue(standardMessage, getPath(RECOVER_YN), "1".equals(recoverYn) ? "Y" : "N");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 인터페이스ID (trim 처리)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public String getInterfaceId(StandardMessage standardMessage) {
|
||||
String val = getItemValue(standardMessage, getPath(INTERFACE_ID));
|
||||
return val == null ? "" : val.trim();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 세션ID / 인스턴스코드 — MCI 여부에 따라 처리
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public String getSessionId(StandardMessage standardMessage) {
|
||||
EAIServerManager server = EAIServerManager.getInstance();
|
||||
if (server != null && server.isMCI()) {
|
||||
return StringUtils.defaultString(getItemValue(standardMessage, PATH_MCI_SESN));
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSessionId(StandardMessage standardMessage, String sessionId) {
|
||||
EAIServerManager server = EAIServerManager.getInstance();
|
||||
if (server != null && server.isMCI()) {
|
||||
setItemValue(standardMessage, PATH_MCI_SESN, sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getInstCode(StandardMessage standardMessage) {
|
||||
EAIServerManager server = EAIServerManager.getInstance();
|
||||
if (server != null && server.isMCI()) {
|
||||
return StringUtils.defaultString(getItemValue(standardMessage, PATH_MCI_NODE));
|
||||
}
|
||||
return StringUtils.defaultString(getItemValue(standardMessage, PATH_EAI_NODE));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInstCode(StandardMessage standardMessage, String instCode) {
|
||||
EAIServerManager server = EAIServerManager.getInstance();
|
||||
if (server != null && server.isMCI()) {
|
||||
setItemValue(standardMessage, PATH_MCI_NODE, instCode);
|
||||
} else {
|
||||
setItemValue(standardMessage, PATH_EAI_NODE, instCode);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 요청시스템코드 — 채널유형코드(chnl_tycd)에서 추출
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public String getReqSysCode(StandardMessage standardMessage) {
|
||||
String chnlTycd = getItemValue(standardMessage, getPath(CHANNEL_TYPE_CD));
|
||||
if (StringUtils.isNotBlank(chnlTycd)) {
|
||||
return chnlTycd.trim();
|
||||
}
|
||||
// fallback: tx_id(서비스ID) 경로에서 추출
|
||||
String txId = getItemValue(standardMessage, getPath(SERVICE_ID));
|
||||
if (txId != null) {
|
||||
String[] split = txId.split("/");
|
||||
if (split.length > 1) {
|
||||
String route = split[1].toUpperCase();
|
||||
return route.length() > 3 ? route.substring(0, 3) : route;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.inbound.processor.ProcessVO;
|
||||
import com.eactive.eai.message.StandardItem;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.service.DefaultStandardMessageCoordinator;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
/**
|
||||
* DJBank(제주은행) 차세대 표준전문 Coordinator
|
||||
*
|
||||
* 표준전문 구조 변경에 따른 각 처리 단계 후처리 정의:
|
||||
* - HEAD 평면 구조, GUID 40자, guid_prgs_no 별도 필드
|
||||
* - MSG 영역: msg_dvcd(NM/EM) + MAIN_MSG + MSG_LIST
|
||||
* - 처리결과구분코드: S(성공) / F(오류)
|
||||
* - 전문종료부: @JJ
|
||||
*/
|
||||
public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordinator {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
private static final DateTimeFormatter FMT_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
private static final DateTimeFormatter FMT_TIME_MILLIS = DateTimeFormatter.ofPattern("HHmmssSSS");
|
||||
|
||||
// HEAD 필드 경로
|
||||
private static final String HEAD_FRST_MESG_DMAN_DT = "HEAD.frst_mesg_dman_dt";
|
||||
private static final String HEAD_FRST_MESG_DMAN_TIME = "HEAD.frst_mesg_dman_time";
|
||||
private static final String HEAD_FRST_TRNM_IPAD = "HEAD.frst_trnm_ipad";
|
||||
private static final String HEAD_FRST_TRNM_IPV4_ADDR = "HEAD.frst_trnm_ipv4_addr";
|
||||
private static final String HEAD_FRST_TRNM_MAC = "HEAD.frst_trnm_mac";
|
||||
private static final String HEAD_SYS_ENV_DVCD = "HEAD.sys_env_dvcd";
|
||||
private static final String HEAD_TRNM_SYS_DVCD = "HEAD.trnm_sys_dvcd";
|
||||
private static final String HEAD_MESG_RSPN_DT = "HEAD.mesg_rspn_dt";
|
||||
private static final String HEAD_MESG_RSPN_TIME = "HEAD.mesg_rspn_time";
|
||||
|
||||
// EZDATA 영역 경로
|
||||
private static final String EZDATA_ELFN_BNKN_DVCD = "EZDATA.elfn_bnkn_dvcd";
|
||||
private static final String EZDATA_SVR_TX_SEQNO = "EZDATA.svr_tx_seqno";
|
||||
private static final String EZDATA_ELFN_MAC = "EZDATA.elfn_mac";
|
||||
private static final String EZDATA_PC_OFCL_IPAD = "EZDATA.pc_ofcl_ipad";
|
||||
private static final String EZDATA_PC_PRVAT_IPAD = "EZDATA.pc_prvat_ipad";
|
||||
private static final String EZDATA_ELFN_SPR_FILD = "EZDATA.elfn_spr_fild";
|
||||
|
||||
// MSG 영역 경로
|
||||
private static final String MSG_DVCD = "MSG.msg_dvcd";
|
||||
private static final String MSG_SCOP_LEN = "MSG.msg_scop_len";
|
||||
private static final String MSG_MAIN_MSG = "MSG.MAIN_MSG";
|
||||
private static final String MSG_OUTP_ATRB_CD = "MSG.MAIN_MSG.outp_atrb_cd";
|
||||
private static final String MSG_OUTP_MSG_CD = "MSG.MAIN_MSG.outp_msg_cd";
|
||||
private static final String MSG_OUTP_MSG_CTNT = "MSG.MAIN_MSG.outp_msg_ctnt";
|
||||
private static final String MSG_LIST_ROWCNT = "MSG.MAIN_MSG.msg_list_rowcnt";
|
||||
private static final String MSG_LIST = "MSG.MSG_LIST";
|
||||
|
||||
// DATA 영역 경로
|
||||
private static final String DATA_SCOP_LEN = "DATA.data_scop_len";
|
||||
|
||||
@Override
|
||||
public void coordinateAfterParsing(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void coordinateAfterCreateMessageByRule(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
||||
StandardMessageManager manager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = manager.getMapper();
|
||||
|
||||
// GUID 생성 (40자) 및 설정
|
||||
String guid = GUIDGeneratorDJB.getGUID("EAI");
|
||||
mapper.setGuid(standardMessage, guid);
|
||||
|
||||
// GUID 진행번호 초기화 (최초=001)
|
||||
mapper.setGuidSeq(standardMessage, "001");
|
||||
|
||||
// 원거래GUID = GUID 동일값 설정
|
||||
mapper.setOrgGuid(standardMessage, guid);
|
||||
|
||||
// 최초전문요청일자/시각 설정
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
standardMessage.setData(HEAD_FRST_MESG_DMAN_DT, now.format(FMT_DATE));
|
||||
standardMessage.setData(HEAD_FRST_MESG_DMAN_TIME, now.format(FMT_TIME_MILLIS));
|
||||
|
||||
// 전송시스템구분코드 설정
|
||||
standardMessage.setData(HEAD_TRNM_SYS_DVCD, "EAI");
|
||||
|
||||
// 시스템환경구분코드 설정 (D/T/P)
|
||||
EAIServerManager eaiServer = EAIServerManager.getInstance();
|
||||
standardMessage.setData(HEAD_SYS_ENV_DVCD, getSysEnvDvcd(eaiServer));
|
||||
|
||||
// 최초전송 IP / IPv4 / MAC 수집 및 설정
|
||||
String[] netInfo = collectNetworkInfo();
|
||||
String ipv4 = netInfo[0];
|
||||
String mac = netInfo[1];
|
||||
standardMessage.setData(HEAD_FRST_TRNM_IPAD, ipv4);
|
||||
standardMessage.setData(HEAD_FRST_TRNM_IPV4_ADDR, ipv4);
|
||||
standardMessage.setData(HEAD_FRST_TRNM_MAC, mac);
|
||||
|
||||
// ERP 채널 전자금융공통영역(EZDATA) 설정 — CSV refPath/refValue 조건 평가
|
||||
StandardItem ezdataItem = standardMessage.findItem("EZDATA");
|
||||
if (ezdataItem != null && evaluateBlockCondition(standardMessage, ezdataItem)) {
|
||||
setEzdataFields(standardMessage, ezdataItem, ipv4, mac);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void coordinateBeforeStandardMessageSend(StandardMessage standardMessage, String msgType, String charset) {
|
||||
makeupDataScopLen(standardMessage, charset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void coordinateBeforeResponse(StandardMessage standardMessage, ProcessVO processVO, Properties prop, String charset) {
|
||||
StandardMessageManager manager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = manager.getMapper();
|
||||
|
||||
// GUID 진행번호 +1
|
||||
//mapper.nextGuidSeq(standardMessage);
|
||||
|
||||
// 요청응답구분 = 응답(R)
|
||||
mapper.setSendRecvDivision(standardMessage, STDMessageKeys.SEND_RECV_CD_RECV);
|
||||
|
||||
// 응답일자/시각 설정
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
standardMessage.setData(HEAD_MESG_RSPN_DT, now.format(FMT_DATE));
|
||||
standardMessage.setData(HEAD_MESG_RSPN_TIME, now.format(FMT_TIME_MILLIS));
|
||||
|
||||
makeupDataScopLen(standardMessage, charset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean coordinateSetStandardMessageError(StandardMessage standardMessage, InterfaceMapper mapper,
|
||||
String errCode, String errMsg) {
|
||||
|
||||
// 처리결과 = 오류(F)
|
||||
mapper.setResponseType(standardMessage, STDMessageKeys.RESPONSE_TYPE_CODE_E);
|
||||
// 요청응답구분 = 응답(R)
|
||||
mapper.setSendRecvDivision(standardMessage, STDMessageKeys.SEND_RECV_CD_RECV);
|
||||
|
||||
// 에러코드/메시지 변환
|
||||
String siteErrCode = StringUtils.defaultString(MessageUtil.getTobeCode(errCode));
|
||||
String siteErrMsg = StringUtils.defaultString(MessageUtil.getTobeMessage(errCode));
|
||||
|
||||
// MSG 영역 활성화
|
||||
StandardItem msgItem = standardMessage.findItem("MSG");
|
||||
if (msgItem != null) {
|
||||
msgItem.setHidden(false);
|
||||
msgItem.setSize(1);
|
||||
}
|
||||
StandardItem mainMsgItem = standardMessage.findItem(MSG_MAIN_MSG);
|
||||
if (mainMsgItem != null) {
|
||||
mainMsgItem.setHidden(false);
|
||||
mainMsgItem.setSize(1);
|
||||
}
|
||||
|
||||
// msg_dvcd = EM (에러메시지)
|
||||
standardMessage.setData(MSG_DVCD, "EM");
|
||||
|
||||
// 출력속성코드 = 1(팝업)
|
||||
standardMessage.setData(MSG_OUTP_ATRB_CD, "1");
|
||||
|
||||
// 대표 에러코드/메시지
|
||||
standardMessage.setData(MSG_OUTP_MSG_CD, siteErrCode);
|
||||
standardMessage.setData(MSG_OUTP_MSG_CTNT, siteErrMsg);
|
||||
|
||||
// MSG_LIST 1건 구성
|
||||
standardMessage.setData(MSG_LIST_ROWCNT, "1");
|
||||
StandardItem msgList = standardMessage.findItem(MSG_LIST);
|
||||
if (msgList != null) {
|
||||
msgList.setSize(1);
|
||||
LinkedHashMap<String, StandardItem> row = msgList.getArrayChilds(0, true);
|
||||
if (row != null) {
|
||||
if (row.containsKey("outp_msg_cd")) row.get("outp_msg_cd").setValue(siteErrCode);
|
||||
if (row.containsKey("outp_msg_ctnt")) row.get("outp_msg_ctnt").setValue(siteErrMsg);
|
||||
if (row.containsKey("outp_msg_desc")) row.get("outp_msg_desc").setValue(siteErrMsg);
|
||||
if (row.containsKey("err_occu_loct")) row.get("err_occu_loct").setValue(errCode);
|
||||
}
|
||||
}
|
||||
|
||||
// mapper 에러코드 설정
|
||||
mapper.setErrorCode(standardMessage, siteErrCode);
|
||||
mapper.setErrorMsg(standardMessage, siteErrMsg);
|
||||
|
||||
// msg_scop_len 계산
|
||||
makeMsgScopLen(standardMessage);
|
||||
|
||||
// BIZ_DATA는 null 처리 (false 반환)
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void coordinateAfterRecvNonStdSyncResponse(StandardMessage responseMessage) {
|
||||
// 처리결과 = 성공(S)
|
||||
StandardMessageManager manager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = manager.getMapper();
|
||||
mapper.setResponseType(responseMessage, STDMessageKeys.RESPONSE_TYPE_CODE_N);
|
||||
|
||||
// 요청응답구분 = 응답(R) — dman_rspn_dvcd 기본값이 S(요청)이므로 반드시 설정
|
||||
mapper.setSendRecvDivision(responseMessage, STDMessageKeys.SEND_RECV_CD_RECV);
|
||||
|
||||
// MSG 영역 활성화
|
||||
StandardItem msgItem = responseMessage.findItem("MSG");
|
||||
if (msgItem != null) {
|
||||
msgItem.setHidden(false);
|
||||
msgItem.setSize(1);
|
||||
}
|
||||
StandardItem mainMsgItem = responseMessage.findItem(MSG_MAIN_MSG);
|
||||
if (mainMsgItem != null) {
|
||||
mainMsgItem.setHidden(false);
|
||||
mainMsgItem.setSize(1);
|
||||
}
|
||||
|
||||
// msg_dvcd=NM, outp_atrb_cd=0, outp_msg_cd, outp_msg_ctnt, msg_list_rowcnt=0
|
||||
// → 모두 CSV 기본값 사용
|
||||
|
||||
makeMsgScopLen(responseMessage);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// private helpers
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
private String getSysEnvDvcd(EAIServerManager server) {
|
||||
if (server.isPEAIServer()) return "P"; // 운영
|
||||
if (server.isSEAIServer()) return "T"; // 검증/테스트
|
||||
return "D"; // 개발
|
||||
}
|
||||
|
||||
private String[] collectNetworkInfo() {
|
||||
String ipv4 = "";
|
||||
String mac = "";
|
||||
try {
|
||||
InetAddress localAddr = InetAddress.getLocalHost();
|
||||
ipv4 = localAddr.getHostAddress();
|
||||
NetworkInterface ni = NetworkInterface.getByInetAddress(localAddr);
|
||||
if (ni != null) {
|
||||
byte[] macBytes = ni.getHardwareAddress();
|
||||
if (macBytes != null) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < macBytes.length; i++) {
|
||||
if (i > 0) sb.append(":");
|
||||
sb.append(String.format("%02X", macBytes[i]));
|
||||
}
|
||||
mac = sb.toString();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (logger.isWarn()) logger.warn("Failed to collect network info", e);
|
||||
}
|
||||
return new String[]{ipv4, mac};
|
||||
}
|
||||
|
||||
private void setEzdataFields(StandardMessage standardMessage, StandardItem ezdataItem, String ipv4, String mac) {
|
||||
ezdataItem.setHidden(false);
|
||||
ezdataItem.setSize(1);
|
||||
standardMessage.setData(EZDATA_ELFN_BNKN_DVCD, "10");
|
||||
standardMessage.setData(EZDATA_SVR_TX_SEQNO, String.valueOf(System.currentTimeMillis() / 1000L));
|
||||
standardMessage.setData(EZDATA_ELFN_MAC, mac);
|
||||
standardMessage.setData(EZDATA_PC_OFCL_IPAD, ipv4);
|
||||
standardMessage.setData(EZDATA_PC_PRVAT_IPAD, ipv4);
|
||||
standardMessage.setData(EZDATA_ELFN_SPR_FILD, ezdataItem.getRefValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* StandardItem의 refPath/refValue를 현재 메시지 필드값과 비교해 조건 충족 여부를 반환한다.
|
||||
* refValue 앞에 '!'를 붙이면 NOT 조건, '|'로 구분하면 OR 조건이다.
|
||||
* refPath 또는 refValue가 없으면 조건 없음(true)으로 처리한다.
|
||||
*/
|
||||
private boolean evaluateBlockCondition(StandardMessage standardMessage, StandardItem item) {
|
||||
String refPath = item.getRefPath();
|
||||
String refValue = item.getRefValue();
|
||||
if (StringUtils.isBlank(refPath) || StringUtils.isBlank(refValue)) {
|
||||
return true;
|
||||
}
|
||||
String actualValue = StringUtils.trimToEmpty(standardMessage.findItemValue(refPath));
|
||||
boolean negate = refValue.startsWith("!");
|
||||
String compareValue = negate ? refValue.substring(1) : refValue;
|
||||
boolean matched = matchesAny(compareValue, actualValue);
|
||||
return negate ? !matched : matched;
|
||||
}
|
||||
|
||||
private boolean matchesAny(String refValue, String actualValue) {
|
||||
for (String v : refValue.split("\\|")) {
|
||||
if (v.equals(actualValue)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void makeupDataScopLen(StandardMessage standardMessage, String charset) {
|
||||
try {
|
||||
int dataLen = standardMessage.getBizDataBytes(charset).length;
|
||||
String lenStr = StringUtils.leftPad(String.valueOf(dataLen), 8, '0');
|
||||
standardMessage.setData(DATA_SCOP_LEN, lenStr);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to calculate data_scop_len", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void makeMsgScopLen(StandardMessage standardMessage) {
|
||||
try {
|
||||
StandardItem mainMsg = standardMessage.findItem(MSG_MAIN_MSG);
|
||||
if (mainMsg == null) return;
|
||||
int len = standardMessage.getBytesDataLengthForPath(MSG_MAIN_MSG);
|
||||
standardMessage.setData(MSG_SCOP_LEN, StringUtils.leftPad(String.valueOf(len), 8, '0'));
|
||||
} catch (Exception e) {
|
||||
if (logger.isWarn()) logger.warn("Failed to calculate msg_scop_len", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -1,9 +1,9 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAix2aE0JUkUDGfGAWH23S
|
||||
uVqh+yRzxVTZ8yy8gtz1MOUSLOFOtme6AgVyfVmOs7p/HyNl6oe9Iw3FM/70Mpn0
|
||||
0HLsPr38VL1e5Ez1gkONCmqx5YIVbVYgBmdfYtOhKyjRZl7nsprngq6pHeETNqHa
|
||||
ama1WpZjrUQtdPya6bSrXbx0mnK3JhuFpuJqUL7oEqFOMuz3OxCN053iJnDyNNmT
|
||||
SlI0XB78old2VbTY0l67FW4Kmp8YVMFm7mrxlnhUh2bhh49r1C9tsOTTXppNdyOk
|
||||
0DjZ9jjwLFGUYNsFa4HeRHMg1YioyT2luw2gDoe06D6+CAYc893tgNa32+K+KURd
|
||||
dQIDAQAB
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqteC0VxYMc9Q4kYZpklI
|
||||
8Zt/iqul2ccsvRV82U0m10RDmzR2zHHaw2sP/qtbx8l/gIpwP8pwGwVJ6tvYkH3i
|
||||
6f17P4vkPhdV2OdqweDixOibkuytfbiNPpK5wVxs535Ps+9yVsPoTUyCcMEtLcBD
|
||||
f5N+DmGpIm+OzJPzf95kpCHw7aVrStFu3KEgIJ8ppSZ6FCkj5Th4KnqtHl5kiYjv
|
||||
Pda5tSqqpQd7fgRVvDsYdLP8HJYLsL2cMjAmrkdUtE/Gkkp3T93JUQf82tYc8df5
|
||||
KO/nD3r1MAhiKHpfdaDD8vaXSL2fJmKVQcENA+2PXg5/0/axMcGn0CQbjsATxvWa
|
||||
mQIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
#-----------------------------------------------------------------------------
|
||||
# comment start with #
|
||||
# level; // 0 : root ~ n
|
||||
# type; // 0: Message, 1: Field, 2:Group 3, Grid, 4 : Field Array, 9 : BIZ DATA
|
||||
# size // 0 : variable, > 0 fixed
|
||||
# fieldType; // 0: ELEMENT, 1: ATTRIBUTE,
|
||||
# length;
|
||||
# dataType; // 1: String, 2: Number, 11: ZZ String, 12: LL_NUMBER(LL prefix auto)
|
||||
#-----------------------------------------------------------------------------
|
||||
# name ,level ,type ,size ,fieldType ,length ,dataType ,refPath, refValue, value
|
||||
#-----------------------------------------------------------------------------
|
||||
# ============================================================
|
||||
# HEAD - 헤더영역 (시스템헤더부 + 공통부)
|
||||
# ============================================================
|
||||
HEAD,1,3,1,1,0,1,,,
|
||||
stnd_mesg_len,2,2,1,1,8,12,,,
|
||||
nxgn_stnd_idfr,2,2,1,1,4,1,,,JERA
|
||||
guid,2,2,1,1,40,1,,,
|
||||
guid_prgs_no,2,2,1,1,3,2,,,001
|
||||
stnd_mesg_ver,2,2,1,1,3,1,,,R10
|
||||
ortr_guid,2,2,1,1,40,1,,,
|
||||
sect_ecrpt_yn,2,2,1,1,1,1,,,N
|
||||
frst_trnm_ipad,2,2,1,1,40,1,,,
|
||||
frst_trnm_ipv4_addr,2,2,1,1,15,1,,,
|
||||
frst_trnm_mac,2,2,1,1,17,1,,,
|
||||
frst_mesg_dman_dt,2,2,1,1,8,1,,,
|
||||
frst_mesg_dman_time,2,2,1,1,9,1,,,
|
||||
frst_trnm_sys_dvcd,2,2,1,1,3,1,,,OPA
|
||||
trnm_sys_dvcd,2,2,1,1,3,1,,,EAI
|
||||
mesg_rspn_dt,2,2,1,1,8,1,,,
|
||||
mesg_rspn_time,2,2,1,1,9,1,,,
|
||||
dman_rspn_dvcd,2,2,1,1,1,1,,,S
|
||||
otsd_tmot_occu_rspn_yn,2,2,1,1,1,1,,,
|
||||
sys_env_dvcd,2,2,1,1,1,1,,,D
|
||||
tx_tycd,2,2,1,1,1,1,,,O
|
||||
synz_dvcd,2,2,1,1,1,1,,,S
|
||||
tx_id,2,2,1,1,12,1,,,
|
||||
procs_rslt_dvcd,2,2,1,1,1,1,,,S
|
||||
procs_rslt_romsg_tx_id,2,2,1,1,12,1,,,
|
||||
chnl_tycd,2,2,1,1,3,1,,,EAI
|
||||
chnl_dtls_clcd,2,2,1,1,3,1,,,
|
||||
xtis_cd,2,2,1,1,3,1,,,
|
||||
osdch_dvcd,2,2,1,1,3,1,,,
|
||||
lnkd_seqno,2,2,1,1,3,2,,,
|
||||
if_id,2,2,1,1,30,1,,,
|
||||
hmab_dvcd,2,2,1,1,1,1,,,
|
||||
mci_sesn_id,2,2,1,1,8,1,,,
|
||||
mci_node_dvcd,2,2,1,1,2,1,,,
|
||||
eai_node_dvcd,2,2,1,1,2,1,,,
|
||||
fep_node_dvcd,2,2,1,1,2,1,,,
|
||||
fep_sesn_id,2,2,1,1,8,1,,,
|
||||
ortr_restr_yn,2,2,1,1,1,1,,,
|
||||
input_mesg_tycd,2,2,1,1,1,1,,,
|
||||
outp_mesg_tycd,2,2,1,1,1,1,,,
|
||||
mesg_cnty_seqno,2,2,1,1,3,2,,,
|
||||
msg_trnm_tycd,2,2,1,1,1,1,,,
|
||||
msg_trnm_brcd,2,2,1,1,3,1,,,
|
||||
msg_trnm_tlrno,2,2,1,1,6,1,,,
|
||||
tx_cmgr_cd,2,2,1,1,4,1,,,S004
|
||||
mgmt_brcd,2,2,1,1,3,1,,,260
|
||||
tx_brcd,2,2,1,1,3,1,,,260
|
||||
insl_brcd,2,2,1,1,3,1,,,260
|
||||
blng_brcd,2,2,1,1,3,1,,,260
|
||||
corp_tlwn_virt_brcd,2,2,1,1,3,1,,,
|
||||
tlrno,2,2,1,1,6,1,,,
|
||||
telr_jcls_cd,2,2,1,1,2,1,,,
|
||||
clsn_bfaf_dvcd,2,2,1,1,1,1,,,
|
||||
tlwn_dvcd,2,2,1,1,1,1,,,
|
||||
scfc_tmnl_dvcd,2,2,1,1,2,1,,,
|
||||
telr_cnfr_trgt_yn,2,2,1,1,1,1,,,
|
||||
telr_cnfr_yn,2,2,1,1,1,1,,,
|
||||
prcg_aprv_typ_dvcd,2,2,1,1,1,1,,,
|
||||
sq1_aprv_media_dvcd,2,2,1,1,1,1,,,
|
||||
sq1_aprv_prcg_empno,2,2,1,1,6,1,,,
|
||||
sq1_aprv_prcg_athn_no,2,2,1,1,32,1,,,
|
||||
sq2_aprv_media_dvcd,2,2,1,1,1,1,,,
|
||||
sq2_aprv_prcg_empno,2,2,1,1,6,1,,,
|
||||
sq2_aprv_prcg_athn_no,2,2,1,1,32,1,,,
|
||||
main_scn_id,2,2,1,1,12,1,,,
|
||||
tx_scn_id,2,2,1,1,12,1,,,
|
||||
pb_seqno,2,2,1,1,5,2,,,
|
||||
pb_ms_read_yn,2,2,1,1,1,1,,,
|
||||
pb_print_conn_yn,2,2,1,1,1,1,,,
|
||||
dgtl_tlwn_dvcd,2,2,1,1,1,1,,,
|
||||
idc_scan_rnno,2,2,1,1,32,1,,,
|
||||
idc_scan_no,2,2,1,1,25,1,,,
|
||||
ctsed_dt,2,2,1,1,8,1,,,
|
||||
reckn_dt,2,2,1,1,8,1,,,
|
||||
slip_no,2,2,1,1,5,2,,,
|
||||
gnrz_tmot_tktm,2,2,1,1,3,2,,,35
|
||||
tx_tmot_tktm,2,2,1,1,3,2,,,30
|
||||
idvd_info_iqry_prps_dvcd,2,2,1,1,3,1,,,
|
||||
idvd_info_iqry_rsn,2,2,1,1,100,1,,,
|
||||
rprs_msg_cd,2,2,1,1,12,1,,,
|
||||
# ============================================================
|
||||
# EZDATA - 전자금융공통영역 (corp_tlwn_virt_brcd=ERP 조건부)
|
||||
# ============================================================
|
||||
EZDATA,1,3,0,1,0,1,HEAD.corp_tlwn_virt_brcd,ERP,
|
||||
login_mhod_dvcd,2,2,1,1,1,1,,,
|
||||
elfn_bnkn_dvcd,2,2,1,1,2,1,,,01
|
||||
usr_no,2,2,1,1,16,1,,,
|
||||
rgsr_id,2,2,1,1,16,1,,,
|
||||
svr_tx_seqno,2,2,1,1,10,2,,,
|
||||
tx_seqno,2,2,1,1,10,2,,,
|
||||
priqr_tx_seqno,2,2,1,1,10,2,,,
|
||||
secu_media_dvcd,2,2,1,1,2,1,,,00
|
||||
secu_media_sta_dvcd,2,2,1,1,2,1,,,00
|
||||
brll_srcd_yn,2,2,1,1,1,1,,,N
|
||||
sq1_srcd_indc_no,2,2,1,1,2,2,,,
|
||||
sq1_srcd_pswd,2,2,1,1,32,1,,,
|
||||
sq2_srcd_indc_no,2,2,1,1,2,2,,,
|
||||
sq2_srcd_pswd,2,2,1,1,32,1,,,
|
||||
otp_athn_val,2,2,1,1,6,1,,,
|
||||
secu_media_seqno_dman_val,2,2,1,1,4,1,,,
|
||||
secu_media_seqno_athn_val,2,2,1,1,4,1,,,
|
||||
next_data_exis_yn,2,2,1,1,1,1,,,
|
||||
page_no,2,2,1,1,5,2,,,
|
||||
page_size,2,2,1,1,5,2,,,
|
||||
ttcnt,2,2,1,1,5,2,,,
|
||||
iqry_ccnt,2,2,1,1,5,2,,,
|
||||
next_data_info,2,2,1,1,100,1,,,
|
||||
cstno,2,2,1,1,10,2,,,
|
||||
otp_expr_gdnc_yn,2,2,1,1,1,1,,,N
|
||||
dup_tx_yn,2,2,1,1,1,1,,,N
|
||||
cpu_id_no,2,2,1,1,64,1,,,
|
||||
elfn_mac,2,2,1,1,17,1,,,
|
||||
hdd_srial_no,2,2,1,1,64,1,,,
|
||||
main_board_srial_no,2,2,1,1,64,1,,,
|
||||
pc_ofcl_ipad,2,2,1,1,40,1,,,
|
||||
pc_prvat_ipad,2,2,1,1,40,1,,,
|
||||
smph_old_unq_no,2,2,1,1,32,1,,,
|
||||
smph_nw_unq_no,2,2,1,1,32,1,,,
|
||||
smph_mac,2,2,1,1,12,1,,,
|
||||
smph_modl_no,2,2,1,1,20,1,,,
|
||||
ostp_cd,2,2,1,1,1,1,,,
|
||||
mcco_dvcd,2,2,1,1,1,1,,,
|
||||
elfn_use_tlno,2,2,1,1,12,1,,,
|
||||
addt_athn_yn,2,2,1,1,1,1,,,
|
||||
addt_athn_meth_dvcd,2,2,1,1,1,1,,,
|
||||
abr_ip_yn,2,2,1,1,1,1,,,N
|
||||
login_dt,2,2,1,1,8,1,,,
|
||||
login_time,2,2,1,1,6,1,,,
|
||||
cst_nm,2,2,1,1,100,1,,,
|
||||
aprv_aprvl_rol_dvcd,2,2,1,1,1,1,,,
|
||||
elfn_spr_fild,2,2,1,1,698,1,,,
|
||||
# ============================================================
|
||||
# MSG - 메시지영역 (dman_rspn_dvcd != S 조건부, 응답 시)
|
||||
# ============================================================
|
||||
MSG,1,3,0,1,0,1,HEAD.dman_rspn_dvcd,!S,
|
||||
msg_dvcd,2,2,0,1,2,1,,,NM
|
||||
msg_scop_len,2,2,0,1,8,2,,,
|
||||
MAIN_MSG,2,3,0,1,0,1,,,
|
||||
outp_atrb_cd,3,2,1,1,1,1,,,0
|
||||
outp_msg_cd,3,2,1,1,12,1,,,NCMM00001
|
||||
outp_msg_ctnt,3,2,1,1,200,1,,,정상처리되었습니다.
|
||||
outp_msg_desc,3,2,1,1,300,1,,,
|
||||
mngm_msg_cd,3,2,1,1,12,1,,,
|
||||
msg_list_rowcnt,3,2,0,1,5,2,,,0
|
||||
MSG_LIST,2,4,0,1,0,1,MSG.MAIN_MSG.msg_list_rowcnt,,
|
||||
outp_msg_cd,3,2,0,1,12,1,,,
|
||||
outp_msg_ctnt,3,2,0,1,200,1,,,
|
||||
outp_msg_desc,3,2,0,1,300,1,,,
|
||||
mngm_msg_cd,3,2,0,1,12,1,,,
|
||||
err_occu_item_nm,3,2,0,1,50,1,,,
|
||||
err_occu_loct,3,2,0,1,300,1,,,
|
||||
err_chgr_nm,3,2,0,1,10,1,,,
|
||||
err_chrg_cnpl_no,3,2,0,1,20,1,,,
|
||||
# ============================================================
|
||||
# DATA - 데이터부
|
||||
# ============================================================
|
||||
DATA,1,3,1,1,0,1,,,
|
||||
data_dvcd,2,2,1,1,2,1,,,IO
|
||||
data_scop_len,2,2,1,1,8,2,,,
|
||||
BIZ_DATA,2,9,1,1,0,1,,,
|
||||
|
@@ -1,18 +1,12 @@
|
||||
# layout : StandardMessage layout definition
|
||||
#layout.file.type=CSV
|
||||
layout.file.type=DB
|
||||
#layout.file.path=standard-layout-kjb.csv
|
||||
#layout.file.path=standard-layout-elk.csv
|
||||
#layout.filter.FLAT=com.eactive.eai.custom.message.FlatMessageFilterSBI
|
||||
layout.filter.FLAT=com.eactive.eai.message.filter.FlatMessageFilter
|
||||
# mapper : StandardMessage's fields getter/setter interface
|
||||
#mapper.class=com.eactive.eai.custom.message.InterfaceMapperSBI
|
||||
mapper.class=com.eactive.eai.custom.message.InterfaceMapperKJB
|
||||
#mapper.definition=standard-message-mapping-config-sbi.properties
|
||||
#mapper.definition=standard-message-mapping-config-elk.properties
|
||||
mapper.definition=standard-message-mapping-config-kjb.properties
|
||||
mapper.class=com.eactive.eai.custom.message.InterfaceMapperDJB
|
||||
mapper.definition=standard-message-mapping-config-djb.properties
|
||||
# StandardMessage Coordinator implementation
|
||||
message.coordinator.class=com.eactive.eai.custom.message.StandardMessageCoordinatorKJB
|
||||
message.coordinator.class=com.eactive.eai.custom.message.StandardMessageCoordinatorDJB
|
||||
# RequestProcessor implementation
|
||||
#requestProcessor.class=com.eactive.eai.inbound.processor.RequestProcessor
|
||||
# reader : parsing input data to StandardMessage
|
||||
@@ -25,7 +19,3 @@ reader.ASC=com.eactive.eai.message.parser.FlatReader
|
||||
reader.FLAT=com.eactive.eai.message.parser.FlatReader
|
||||
encode.flat=euc-kr
|
||||
encode.xml=utf-8
|
||||
#version.layout.name=VERSION_SAMPLE
|
||||
#version.layout.filter.FLAT=com.eactive.eai.message.filter.FlatMessageFilter
|
||||
#version.mapper=com.eactive.eai.message.mapper.DefaultMessageMapper
|
||||
#version.mapper.definition=version-message-mapping-config.properties
|
||||
@@ -0,0 +1,26 @@
|
||||
GUID=HEAD.guid
|
||||
GUID_SEQ=HEAD.guid_prgs_no
|
||||
GUID_ORG=HEAD.ortr_guid
|
||||
SERVICE_ID=HEAD.tx_id
|
||||
INTERFACE_ID=HEAD.if_id
|
||||
SEND_RECV_DIVISION=HEAD.dman_rspn_dvcd
|
||||
IN_EX_DIVISION=HEAD.hmab_dvcd
|
||||
OPERATION_ENV=HEAD.sys_env_dvcd
|
||||
FIRST_REQ_IP=HEAD.frst_trnm_ipad
|
||||
RECOVER_YN=HEAD.ortr_restr_yn
|
||||
SESSION_ID=HEAD.mci_sesn_id
|
||||
SYNC_ASYNC_TYPE=HEAD.synz_dvcd
|
||||
CHANNEL_TYPE_CD=HEAD.chnl_tycd
|
||||
CHANNEL_DETAIL_CD=HEAD.chnl_dtls_clcd
|
||||
SEND_TIME=HEAD.frst_mesg_dman_time
|
||||
RECV_TIME=HEAD.mesg_rspn_time
|
||||
SYSTEM_TYPE=HEAD.trnm_sys_dvcd
|
||||
TIMEOUT=HEAD.gnrz_tmot_tktm
|
||||
INST_CODE=HEAD.xtis_cd
|
||||
USER_ID=HEAD.tlrno
|
||||
REQ_SYS_CODE=
|
||||
ERROR_CODE=MSG.MAIN_MSG.outp_msg_cd
|
||||
ERROR_MSG=MSG.MAIN_MSG.outp_msg_ctnt
|
||||
RESPONSE_TYPE=HEAD.procs_rslt_dvcd
|
||||
RETURN_VALUE=
|
||||
RETURN_SERVICE_ID=
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class GUIDGeneratorDJBTest {
|
||||
|
||||
@Test
|
||||
void guid_길이는_40자여야_한다() {
|
||||
String guid = GUIDGeneratorDJB.getGUID("EAI");
|
||||
assertEquals(40, guid.length(), "GUID 길이는 40자: " + guid);
|
||||
}
|
||||
|
||||
@Test
|
||||
void guid_시스템코드_3자로_정규화된다() {
|
||||
// 짧은 코드
|
||||
String guid1 = GUIDGeneratorDJB.getGUID("EA");
|
||||
assertEquals(40, guid1.length());
|
||||
|
||||
// 긴 코드 (잘림)
|
||||
String guid2 = GUIDGeneratorDJB.getGUID("EAIFEP");
|
||||
assertEquals(40, guid2.length());
|
||||
|
||||
// null
|
||||
String guid3 = GUIDGeneratorDJB.getGUID(null);
|
||||
assertEquals(40, guid3.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void guid_구성_형식_검증() {
|
||||
String guid = GUIDGeneratorDJB.getGUID("EAI");
|
||||
// 일자(8) + 시간(6) + 밀리초(3) + 시스템코드(3) + 노드번호(2) + 세션ID(12) + Random(6)
|
||||
String date = guid.substring(0, 8);
|
||||
String time = guid.substring(8, 14);
|
||||
String millis = guid.substring(14, 17);
|
||||
String sysCode = guid.substring(17, 20);
|
||||
String nodeNo = guid.substring(20, 22);
|
||||
String sessId = guid.substring(22, 34);
|
||||
String random = guid.substring(34, 40);
|
||||
|
||||
// 일자: 숫자 8자리
|
||||
assertDoesNotThrow(() -> Long.parseLong(date), "일자 부분이 숫자가 아님: " + date);
|
||||
assertTrue(date.matches("\\d{8}"), "일자 형식 오류: " + date);
|
||||
|
||||
// 시간: 숫자 6자리
|
||||
assertTrue(time.matches("\\d{6}"), "시간 형식 오류: " + time);
|
||||
|
||||
// 밀리초: 숫자 3자리
|
||||
assertTrue(millis.matches("\\d{3}"), "밀리초 형식 오류: " + millis);
|
||||
|
||||
// 시스템코드: 3자리 영문/숫자
|
||||
assertEquals(3, sysCode.length(), "시스템코드 길이 오류: " + sysCode);
|
||||
|
||||
// 노드번호: 2자리
|
||||
assertEquals(2, nodeNo.length(), "노드번호 길이 오류: " + nodeNo);
|
||||
|
||||
// 세션ID: 12자리
|
||||
assertEquals(12, sessId.length(), "세션ID 길이 오류: " + sessId);
|
||||
|
||||
// Random: 숫자 6자리
|
||||
assertTrue(random.matches("\\d{6}"), "Random 형식 오류: " + random);
|
||||
}
|
||||
|
||||
@Test
|
||||
void guid_연속_생성시_유니크해야_한다() {
|
||||
Set<String> guids = new HashSet<>();
|
||||
int count = 1000;
|
||||
for (int i = 0; i < count; i++) {
|
||||
guids.add(GUIDGeneratorDJB.getGUID("EAI"));
|
||||
}
|
||||
assertEquals(count, guids.size(), "GUID 중복 발생");
|
||||
}
|
||||
|
||||
@Test
|
||||
void guid_상수_길이값_확인() {
|
||||
assertEquals(40, GUIDGeneratorDJB.GUID_LENGTH);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.StandardMessageUtil;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
class InterfaceMapperDJBTest {
|
||||
|
||||
private InterfaceMapperDJB mapper;
|
||||
private StandardMessage message;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
// CSV에서 표준전문 레이아웃 로드
|
||||
message = StandardMessageUtil.generateMessageFromCsvFile(
|
||||
"src/main/resources/standard-layout-djb.csv");
|
||||
assertNotNull(message, "standard-layout-djb.csv 로드 실패");
|
||||
message.setReadPosition(0);
|
||||
|
||||
// 매핑 설정 로드
|
||||
Properties props = new Properties();
|
||||
try (java.io.InputStream in = getClass().getClassLoader()
|
||||
.getResourceAsStream("standard-message-mapping-config-djb.properties")) {
|
||||
assertNotNull(in, "standard-message-mapping-config-djb.properties 로드 실패");
|
||||
props.load(in);
|
||||
}
|
||||
|
||||
HashMap<String, String> pathMap = new HashMap<>();
|
||||
for (String key : props.stringPropertyNames()) {
|
||||
pathMap.put(key.trim(), props.getProperty(key).trim());
|
||||
}
|
||||
|
||||
mapper = new InterfaceMapperDJB();
|
||||
mapper.initPathMap(pathMap);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// GUID
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void setGuid_40자_정상_설정() {
|
||||
String guid = GUIDGeneratorDJB.getGUID("EAI");
|
||||
mapper.setGuid(message, guid);
|
||||
assertEquals(guid, mapper.getGuid(message));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setGuid_40자_아닌경우_예외발생() {
|
||||
assertThrows(RuntimeException.class, () -> mapper.setGuid(message, "SHORT"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setGuid_null이면_예외발생() {
|
||||
assertThrows(RuntimeException.class, () -> mapper.setGuid(message, null));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// GUID 진행번호 (guid_prgs_no - 별도 필드)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void guidSeq_초기값_및_nextGuidSeq_증가() {
|
||||
// 초기값 설정
|
||||
mapper.setGuidSeq(message, "001");
|
||||
assertEquals("001", mapper.getGuidSeq(message));
|
||||
|
||||
// +1 증가
|
||||
String next = mapper.nextGuidSeq(message);
|
||||
assertEquals("002", next);
|
||||
assertEquals("002", mapper.getGuidSeq(message));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nextGuidSeq_3자리_zero_padding() {
|
||||
mapper.setGuidSeq(message, "009");
|
||||
assertEquals("010", mapper.nextGuidSeq(message));
|
||||
|
||||
mapper.setGuidSeq(message, "099");
|
||||
assertEquals("100", mapper.nextGuidSeq(message));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 원거래 GUID (ortr_guid)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void orgGuid_설정_조회() {
|
||||
String guid = GUIDGeneratorDJB.getGUID("EAI");
|
||||
mapper.setOrgGuid(message, guid);
|
||||
assertEquals(guid, mapper.getOrgGuid(message));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 처리결과구분코드 (S/F ↔ 엔진 내부 NR/ER)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void setResponseType_정상_NR_to_S() {
|
||||
mapper.setResponseType(message, STDMessageKeys.RESPONSE_TYPE_CODE_N); // "NR"
|
||||
assertEquals("S", message.findItemValue("HEAD.procs_rslt_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setResponseType_오류_ER_to_F() {
|
||||
mapper.setResponseType(message, STDMessageKeys.RESPONSE_TYPE_CODE_E); // "ER"
|
||||
assertEquals("F", message.findItemValue("HEAD.procs_rslt_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getResponseType_S_to_NR() {
|
||||
message.setData("HEAD.procs_rslt_dvcd", "S");
|
||||
assertEquals(STDMessageKeys.RESPONSE_TYPE_CODE_N, mapper.getResponseType(message));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getResponseType_F_to_ER() {
|
||||
message.setData("HEAD.procs_rslt_dvcd", "F");
|
||||
assertEquals(STDMessageKeys.RESPONSE_TYPE_CODE_E, mapper.getResponseType(message));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 원거래복원여부 (Y/N ↔ 엔진 내부 1/0)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void recoverYn_Y면_1반환() {
|
||||
message.setData("HEAD.ortr_restr_yn", "Y");
|
||||
assertEquals("1", mapper.getRecoverYn(message));
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoverYn_N면_0반환() {
|
||||
message.setData("HEAD.ortr_restr_yn", "N");
|
||||
assertEquals("0", mapper.getRecoverYn(message));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setRecoverYn_1이면_Y설정() {
|
||||
mapper.setRecoverYn(message, "1");
|
||||
assertEquals("Y", message.findItemValue("HEAD.ortr_restr_yn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setRecoverYn_0이면_N설정() {
|
||||
mapper.setRecoverYn(message, "0");
|
||||
assertEquals("N", message.findItemValue("HEAD.ortr_restr_yn"));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 인터페이스ID (trim)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void getInterfaceId_공백_trim() {
|
||||
message.setData("HEAD.if_id", " IF001 ");
|
||||
assertEquals("IF001", mapper.getInterfaceId(message));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInterfaceId_null이면_빈문자열() {
|
||||
// 초기 공백상태
|
||||
String ifId = mapper.getInterfaceId(message);
|
||||
assertNotNull(ifId);
|
||||
assertEquals("", ifId.trim());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// EAI 서비스코드 조합
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void getEaiSvcCode_인터페이스ID_요청응답_내외구분_조합() {
|
||||
message.setData("HEAD.if_id", "IF_TEST_001");
|
||||
message.setData("HEAD.dman_rspn_dvcd", "S");
|
||||
message.setData("HEAD.hmab_dvcd", "1");
|
||||
|
||||
String svcCode = mapper.getEaiSvcCode(message);
|
||||
assertTrue(svcCode.startsWith("IF_TEST_001"), "EAI 서비스코드: " + svcCode);
|
||||
assertTrue(svcCode.contains("S"), "요청응답구분 포함: " + svcCode);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 필드 경로 기본 동작 확인 (매핑 설정 유효성)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void sendRecvDivision_설정_조회() {
|
||||
mapper.setSendRecvDivision(message, "R");
|
||||
assertEquals("R", mapper.getSendRecvDivision(message));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inExDivision_설정_조회() {
|
||||
mapper.setInExDivision(message, "1");
|
||||
assertEquals("1", mapper.getInExDivision(message));
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorCode_설정_조회() {
|
||||
mapper.setErrorCode(message, "ERR001");
|
||||
assertEquals("ERR001", mapper.getErrorCode(message));
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorMsg_설정_조회() {
|
||||
mapper.setErrorMsg(message, "오류가 발생했습니다.");
|
||||
assertEquals("오류가 발생했습니다.", mapper.getErrorMsg(message));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.eactive.eai.message.StandardItem;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.StandardMessageUtil;
|
||||
|
||||
/**
|
||||
* standard-layout-djb.csv 로드 및 전문 구조 검증
|
||||
*/
|
||||
class StandardLayoutDJBTest {
|
||||
|
||||
private StandardMessage message;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
message = StandardMessageUtil.generateMessageFromCsvFile(
|
||||
"src/main/resources/standard-layout-djb.csv");
|
||||
assertNotNull(message, "standard-layout-djb.csv 로드 실패");
|
||||
message.setReadPosition(0);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 최상위 블록 존재 여부
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void HEAD_블록_존재() {
|
||||
assertNotNull(message.findItem("HEAD"), "HEAD 블록 없음");
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_블록_존재() {
|
||||
assertNotNull(message.findItem("EZDATA"), "EZDATA 블록 없음");
|
||||
}
|
||||
|
||||
@Test
|
||||
void MSG_블록_존재() {
|
||||
assertNotNull(message.findItem("MSG"), "MSG 블록 없음");
|
||||
}
|
||||
|
||||
@Test
|
||||
void DATA_블록_존재() {
|
||||
assertNotNull(message.findItem("DATA"), "DATA 블록 없음");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// HEAD 핵심 필드 검증
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void HEAD_guid_필드_존재_및_길이40() {
|
||||
StandardItem guidItem = message.findItem("HEAD.guid");
|
||||
assertNotNull(guidItem, "HEAD.guid 필드 없음");
|
||||
assertEquals(40, guidItem.getLength(), "HEAD.guid 길이는 40자여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void HEAD_guid_prgs_no_필드_존재() {
|
||||
StandardItem item = message.findItem("HEAD.guid_prgs_no");
|
||||
assertNotNull(item, "HEAD.guid_prgs_no 필드 없음");
|
||||
assertEquals(3, item.getLength());
|
||||
}
|
||||
|
||||
@Test
|
||||
void HEAD_nxgn_stnd_idfr_기본값_JERA() {
|
||||
StandardItem item = message.findItem("HEAD.nxgn_stnd_idfr");
|
||||
assertNotNull(item, "HEAD.nxgn_stnd_idfr 필드 없음");
|
||||
assertEquals(4, item.getLength());
|
||||
assertEquals("JERA", item.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void HEAD_ortr_guid_필드_존재_및_길이40() {
|
||||
StandardItem item = message.findItem("HEAD.ortr_guid");
|
||||
assertNotNull(item, "HEAD.ortr_guid 필드 없음");
|
||||
assertEquals(40, item.getLength());
|
||||
}
|
||||
|
||||
@Test
|
||||
void HEAD_if_id_필드_길이30() {
|
||||
StandardItem item = message.findItem("HEAD.if_id");
|
||||
assertNotNull(item, "HEAD.if_id 필드 없음");
|
||||
assertEquals(30, item.getLength(), "HEAD.if_id 길이는 30자여야 함 (기존 20자에서 변경)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void HEAD_dman_rspn_dvcd_기본값_S() {
|
||||
StandardItem item = message.findItem("HEAD.dman_rspn_dvcd");
|
||||
assertNotNull(item, "HEAD.dman_rspn_dvcd 필드 없음");
|
||||
assertEquals("S", item.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void HEAD_procs_rslt_dvcd_기본값_S() {
|
||||
StandardItem item = message.findItem("HEAD.procs_rslt_dvcd");
|
||||
assertNotNull(item, "HEAD.procs_rslt_dvcd 필드 없음");
|
||||
assertEquals("S", item.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void HEAD_trnm_sys_dvcd_기본값_EAI() {
|
||||
StandardItem item = message.findItem("HEAD.trnm_sys_dvcd");
|
||||
assertNotNull(item, "HEAD.trnm_sys_dvcd 필드 없음");
|
||||
assertEquals("EAI", item.getValue());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MSG 영역 구조 검증
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void MSG_MAIN_MSG_블록_존재() {
|
||||
assertNotNull(message.findItem("MSG.MAIN_MSG"), "MSG.MAIN_MSG 블록 없음");
|
||||
}
|
||||
|
||||
@Test
|
||||
void MSG_outp_msg_cd_길이12() {
|
||||
StandardItem item = message.findItem("MSG.MAIN_MSG.outp_msg_cd");
|
||||
assertNotNull(item, "MSG.MAIN_MSG.outp_msg_cd 필드 없음");
|
||||
assertEquals(12, item.getLength());
|
||||
}
|
||||
|
||||
@Test
|
||||
void MSG_MSG_LIST_Grid_존재() {
|
||||
assertNotNull(message.findItem("MSG.MSG_LIST"), "MSG.MSG_LIST Grid 없음");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// DATA 영역 구조 검증
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void DATA_BIZ_DATA_존재() {
|
||||
assertNotNull(message.findItem("DATA.BIZ_DATA"), "DATA.BIZ_DATA 없음");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// setData / findItemValue 기본 동작
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void HEAD_필드_setData_findItemValue() {
|
||||
String guid40 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; // 40자
|
||||
message.setData("HEAD.guid", guid40);
|
||||
assertEquals(guid40, message.findItemValue("HEAD.guid"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void MSG_필드_setData_findItemValue() {
|
||||
message.setData("MSG.MAIN_MSG.outp_msg_ctnt", "테스트오류메시지");
|
||||
assertEquals("테스트오류메시지", message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import com.eactive.eai.common.monitor.EAIServiceMonitor;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
/**
|
||||
* StandardMessageCoordinatorDJB 단위테스트
|
||||
*
|
||||
* DB/Spring 없는 환경에서 EAIServerManager·PropManager를 Mockito로 stub 처리.
|
||||
* ApplicationContextProvider.context에 mock ApplicationContext를 리플렉션으로 주입.
|
||||
*/
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class StandardMessageCoordinatorDJBTest {
|
||||
|
||||
private static final DateTimeFormatter FMT_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
private StandardMessageManager manager;
|
||||
private StandardMessageCoordinatorDJB coordinator;
|
||||
private InterfaceMapper mapper;
|
||||
private StandardMessage message;
|
||||
|
||||
@BeforeAll
|
||||
void setUpAll() throws Exception {
|
||||
// ① PropManager mock — STDMessageErrorKeys 정적 초기화가 getProperty(group,key,def)를 호출함.
|
||||
// def(3번째 인자)를 그대로 반환하여 기본 에러코드 상수값이 설정되도록 함.
|
||||
PropManager mockPropManager = Mockito.mock(PropManager.class);
|
||||
Mockito.when(mockPropManager.getProperty(anyString(), anyString(), anyString()))
|
||||
.thenAnswer(new Answer<String>() {
|
||||
public String answer(InvocationOnMock inv) {
|
||||
return (String) inv.getArguments()[2];
|
||||
}
|
||||
});
|
||||
|
||||
// ② EAIServerManager mock — DB 미연결 환경 대응.
|
||||
// isPEAIServer/isSEAIServer → false → getSysEnvDvcd()가 "D"(개발)를 반환.
|
||||
EAIServerManager mockServer = Mockito.mock(EAIServerManager.class);
|
||||
Mockito.when(mockServer.isPEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isSEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isMCI()).thenReturn(false);
|
||||
|
||||
// ③ EAIServiceMonitor mock — MessageUtil.getTobeCode()가 사용.
|
||||
// isTimeOutCodes/isBizErrorCodes → false → SYSTEM_ERROR_CODE 분기로 처리.
|
||||
EAIServiceMonitor mockMonitor = Mockito.mock(EAIServiceMonitor.class);
|
||||
Mockito.when(mockMonitor.isTimeOutCodes(anyString())).thenReturn(false);
|
||||
Mockito.when(mockMonitor.isBizErrorCodes(anyString())).thenReturn(false);
|
||||
|
||||
// ④ ApplicationContext mock → 세 빈을 반환하도록 설정
|
||||
ApplicationContext mockCtx = Mockito.mock(ApplicationContext.class);
|
||||
Mockito.when(mockCtx.getBean(EAIServerManager.class)).thenReturn(mockServer);
|
||||
Mockito.when(mockCtx.getBean(PropManager.class)).thenReturn(mockPropManager);
|
||||
Mockito.when(mockCtx.getBean(EAIServiceMonitor.class)).thenReturn(mockMonitor);
|
||||
|
||||
// ⑤ ApplicationContextProvider.context(static 필드)에 mock 주입
|
||||
Field ctxField = ApplicationContextProvider.class.getDeclaredField("context");
|
||||
ctxField.setAccessible(true);
|
||||
ctxField.set(null, mockCtx);
|
||||
|
||||
// ⑥ StandardMessageManager 초기화 (DJB 테스트용 설정)
|
||||
System.setProperty(StandardMessageManager.STANDARD_MESSAGE_CONFIG,
|
||||
"src/test/resources/standard-message-config-test.properties");
|
||||
manager = StandardMessageManager.getInstance();
|
||||
manager.init();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
message = manager.getStandardMessage();
|
||||
mapper = manager.getMapper();
|
||||
coordinator = new StandardMessageCoordinatorDJB();
|
||||
message.setReadPosition(0);
|
||||
assertNotNull(mapper, "mapper가 null — StandardMessageManager.init() 실패 의심");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// coordinateAfterCreateMessageByRule
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void GUID_40자_생성_설정() {
|
||||
coordinator.coordinateAfterCreateMessageByRule(message, null, null);
|
||||
|
||||
String guid = mapper.getGuid(message);
|
||||
assertNotNull(guid, "GUID가 null");
|
||||
assertEquals(GUIDGeneratorDJB.GUID_LENGTH, guid.length(),
|
||||
"GUID 길이가 40자가 아님: " + guid.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void guid_prgs_no_001_초기화() {
|
||||
coordinator.coordinateAfterCreateMessageByRule(message, null, null);
|
||||
|
||||
assertEquals("001", mapper.getGuidSeq(message), "guid_prgs_no 초기값은 001이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ortr_guid_GUID_동일값_설정() {
|
||||
coordinator.coordinateAfterCreateMessageByRule(message, null, null);
|
||||
|
||||
String guid = mapper.getGuid(message);
|
||||
String orgGuid = mapper.getOrgGuid(message);
|
||||
assertEquals(guid, orgGuid, "원거래GUID는 GUID와 동일해야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void frst_mesg_dman_dt_오늘날짜_설정() {
|
||||
coordinator.coordinateAfterCreateMessageByRule(message, null, null);
|
||||
|
||||
String expected = LocalDate.now().format(FMT_DATE);
|
||||
assertEquals(expected, message.findItemValue("HEAD.frst_mesg_dman_dt"),
|
||||
"frst_mesg_dman_dt가 오늘 날짜가 아님");
|
||||
}
|
||||
|
||||
@Test
|
||||
void frst_mesg_dman_time_설정_9자리() {
|
||||
coordinator.coordinateAfterCreateMessageByRule(message, null, null);
|
||||
|
||||
String time = message.findItemValue("HEAD.frst_mesg_dman_time");
|
||||
assertNotNull(time, "frst_mesg_dman_time이 null");
|
||||
assertEquals(9, time.length(), "frst_mesg_dman_time은 HHmmssSSS(9자)여야 함: " + time);
|
||||
assertTrue(time.matches("\\d{9}"), "frst_mesg_dman_time 형식 오류: " + time);
|
||||
}
|
||||
|
||||
@Test
|
||||
void trnm_sys_dvcd_EAI_설정() {
|
||||
coordinator.coordinateAfterCreateMessageByRule(message, null, null);
|
||||
|
||||
assertEquals("EAI", message.findItemValue("HEAD.trnm_sys_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sys_env_dvcd_D_설정_mock_isPEAIServer_false() {
|
||||
// mock: isPEAIServer=false, isSEAIServer=false → "D"(개발) 반환
|
||||
coordinator.coordinateAfterCreateMessageByRule(message, null, null);
|
||||
|
||||
assertEquals("D", message.findItemValue("HEAD.sys_env_dvcd"),
|
||||
"mock 환경에서 sys_env_dvcd는 D여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void frst_trnm_ipad_설정() {
|
||||
coordinator.coordinateAfterCreateMessageByRule(message, null, null);
|
||||
|
||||
String ip = message.findItemValue("HEAD.frst_trnm_ipad");
|
||||
assertNotNull(ip, "frst_trnm_ipad가 null");
|
||||
assertFalse(ip.trim().isEmpty(), "frst_trnm_ipad가 공백");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// coordinateBeforeStandardMessageSend
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void data_scop_len_정수값으로_설정() {
|
||||
coordinator.coordinateBeforeStandardMessageSend(message, "FLAT", "euc-kr");
|
||||
|
||||
String len = message.findItemValue("DATA.data_scop_len");
|
||||
assertNotNull(len, "DATA.data_scop_len이 null");
|
||||
// NUMBER 타입은 선행 0을 모두 제거: "00000000"(0 바이트) → "" 반환됨
|
||||
// 빈 문자열은 0 바이트를 의미하므로 0 이상 조건 통과
|
||||
int dataLen = (len.trim().isEmpty()) ? 0 : Integer.parseInt(len.trim());
|
||||
assertTrue(dataLen >= 0, "data_scop_len은 0 이상이어야 함: '" + len + "'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void data_scop_len_BIZ_DATA_비어있을때_0() {
|
||||
// BIZ_DATA에 데이터 미설정 → 0 바이트 → "00000000" → NUMBER 타입이 "" 반환
|
||||
coordinator.coordinateBeforeStandardMessageSend(message, "JSON", "utf-8");
|
||||
|
||||
String len = message.findItemValue("DATA.data_scop_len");
|
||||
assertNotNull(len, "DATA.data_scop_len이 null");
|
||||
int dataLen = (len.trim().isEmpty()) ? 0 : Integer.parseInt(len.trim());
|
||||
assertEquals(0, dataLen, "BIZ_DATA 미설정 시 data_scop_len은 0이어야 함");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// coordinateBeforeResponse
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void mesg_rspn_dt_오늘날짜_설정() {
|
||||
coordinator.coordinateBeforeResponse(message, null, null, "euc-kr");
|
||||
|
||||
String expected = LocalDate.now().format(FMT_DATE);
|
||||
assertEquals(expected, message.findItemValue("HEAD.mesg_rspn_dt"),
|
||||
"mesg_rspn_dt가 오늘 날짜가 아님");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mesg_rspn_time_9자리_설정() {
|
||||
coordinator.coordinateBeforeResponse(message, null, null, "euc-kr");
|
||||
|
||||
String time = message.findItemValue("HEAD.mesg_rspn_time");
|
||||
assertNotNull(time, "mesg_rspn_time이 null");
|
||||
assertEquals(9, time.length(), "mesg_rspn_time은 HHmmssSSS(9자)여야 함: " + time);
|
||||
assertTrue(time.matches("\\d{9}"), "mesg_rspn_time 형식 오류: " + time);
|
||||
}
|
||||
|
||||
@Test
|
||||
void coordinateBeforeResponse_data_scop_len_설정() {
|
||||
coordinator.coordinateBeforeResponse(message, null, null, "euc-kr");
|
||||
|
||||
String len = message.findItemValue("DATA.data_scop_len");
|
||||
assertNotNull(len);
|
||||
int dataLen = (len.trim().isEmpty()) ? 0 : Integer.parseInt(len.trim());
|
||||
assertTrue(dataLen >= 0);
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// coordinateSetStandardMessageError
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 에러시_procs_rslt_dvcd_F_설정() {
|
||||
coordinator.coordinateSetStandardMessageError(message, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
assertEquals("F", message.findItemValue("HEAD.procs_rslt_dvcd"),
|
||||
"오류 시 procs_rslt_dvcd는 F여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 에러시_dman_rspn_dvcd_R_설정() {
|
||||
coordinator.coordinateSetStandardMessageError(message, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
assertEquals(STDMessageKeys.SEND_RECV_CD_RECV,
|
||||
message.findItemValue("HEAD.dman_rspn_dvcd"),
|
||||
"오류 시 dman_rspn_dvcd는 R이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 에러시_MSG_msg_dvcd_EM_설정() {
|
||||
coordinator.coordinateSetStandardMessageError(message, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
assertEquals("EM", message.findItemValue("MSG.msg_dvcd"),
|
||||
"오류 시 msg_dvcd는 EM이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 에러시_outp_atrb_cd_1_설정() {
|
||||
coordinator.coordinateSetStandardMessageError(message, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
assertEquals("1", message.findItemValue("MSG.MAIN_MSG.outp_atrb_cd"),
|
||||
"오류 시 outp_atrb_cd는 1(팝업)이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 에러시_outp_msg_cd_설정됨() {
|
||||
coordinator.coordinateSetStandardMessageError(message, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
// mock PropManager가 defaultValue("900400")를 반환 → SYSTEM_ERROR_CODE_VALUE="900400"
|
||||
String errCode = message.findItemValue("MSG.MAIN_MSG.outp_msg_cd");
|
||||
assertNotNull(errCode, "outp_msg_cd가 null");
|
||||
assertFalse(errCode.trim().isEmpty(), "outp_msg_cd가 공백");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 에러시_outp_msg_ctnt_설정됨() {
|
||||
coordinator.coordinateSetStandardMessageError(message, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
String errMsg = message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt");
|
||||
assertNotNull(errMsg, "outp_msg_ctnt가 null");
|
||||
assertFalse(errMsg.trim().isEmpty(), "outp_msg_ctnt가 공백");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 에러시_반환값_false() {
|
||||
boolean result = coordinator.coordinateSetStandardMessageError(message, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
assertFalse(result, "coordinateSetStandardMessageError는 false를 반환해야 함 (BIZ_DATA null 처리)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 에러시_msg_scop_len_정수값으로_설정() {
|
||||
coordinator.coordinateSetStandardMessageError(message, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
// NUMBER 타입이므로 선행 0 제거됨 — 숫자 파싱 가능 여부와 0 이상인지 검증
|
||||
String scopLen = message.findItemValue("MSG.msg_scop_len");
|
||||
assertNotNull(scopLen, "msg_scop_len이 null");
|
||||
assertTrue(Integer.parseInt(scopLen.trim()) >= 0, "msg_scop_len은 0 이상이어야 함: " + scopLen);
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// coordinateAfterRecvNonStdSyncResponse
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 정상수신시_procs_rslt_dvcd_S_설정() {
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
|
||||
|
||||
assertEquals("S", message.findItemValue("HEAD.procs_rslt_dvcd"),
|
||||
"정상 수신 시 procs_rslt_dvcd는 S여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 정상수신시_msg_dvcd_NM_설정() {
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
|
||||
|
||||
assertEquals("NM", message.findItemValue("MSG.msg_dvcd"),
|
||||
"정상 수신 시 msg_dvcd는 NM이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 정상수신시_outp_msg_cd_설정됨() {
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
|
||||
|
||||
String msgCd = message.findItemValue("MSG.MAIN_MSG.outp_msg_cd");
|
||||
assertFalse(msgCd == null || msgCd.trim().isEmpty(), "outp_msg_cd가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 정상수신시_outp_msg_ctnt_설정됨() {
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
|
||||
|
||||
String ctnt = message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt");
|
||||
assertFalse(ctnt == null || ctnt.trim().isEmpty(), "outp_msg_ctnt가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 정상수신시_msg_list_rowcnt_0() {
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
|
||||
|
||||
String rowcnt = message.findItemValue("MSG.MAIN_MSG.msg_list_rowcnt");
|
||||
String normalized = (rowcnt == null || rowcnt.trim().isEmpty()) ? "0" : rowcnt.trim();
|
||||
assertEquals(0, Integer.parseInt(normalized), "정상 응답 msg_list는 0건이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 정상수신시_msg_scop_len_정수값으로_설정() {
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
|
||||
|
||||
// NUMBER 타입이므로 선행 0 제거됨 — 숫자 파싱 가능 여부와 0 이상인지 검증
|
||||
String scopLen = message.findItemValue("MSG.msg_scop_len");
|
||||
assertNotNull(scopLen, "msg_scop_len이 null");
|
||||
assertTrue(Integer.parseInt(scopLen.trim()) >= 0, "msg_scop_len은 0 이상이어야 함: " + scopLen);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import com.eactive.eai.common.monitor.EAIServiceMonitor;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.message.StandardItem;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.parser.JsonReader;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
|
||||
/**
|
||||
* DJBank 표준전문 EZDATA(전자금융공통영역) JSON 처리 흐름 통합 테스트
|
||||
*
|
||||
* 검증 시나리오:
|
||||
* 1. EZDATA 포함 요청 JSON 파싱 — corp_tlwn_virt_brcd=ERP 조건 활성
|
||||
* 2. EZDATA 핵심 필드 값 검증
|
||||
* 3. EZDATA 조건 미충족(비ERP) 시 JSON 직렬화 제외 검증
|
||||
* 4. EZDATA 포함 JSON 왕복(parse → serialize) 일관성
|
||||
* 5. coordinateAfterCreateMessageByRule 후 EZDATA 보존
|
||||
* 6. coordinateBeforeResponse 후 EZDATA 포함 직렬화
|
||||
* 7. 오류 응답 생성 시 EZDATA 보존
|
||||
*/
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class StandardMessageEzdataJsonFlowTest {
|
||||
|
||||
private static final String TEST_GUID =
|
||||
"20260420" + "120000" + "000" + "EAI" + "01" + "123456789012" + "000001";
|
||||
|
||||
private static final String TEST_IF_ID = "IF_DJBTEST_EZ001";
|
||||
private static final String TEST_TX_ID = "TXTEST000002";
|
||||
|
||||
/**
|
||||
* ERP 채널 요청 JSON — corp_tlwn_virt_brcd=ERP → EZDATA 블록 활성화
|
||||
*/
|
||||
private static final String ERP_REQ_JSON =
|
||||
"{"
|
||||
+ "\"HEAD\":{"
|
||||
+ "\"nxgn_stnd_idfr\":\"JERA\","
|
||||
+ "\"guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"guid_prgs_no\":\"1\","
|
||||
+ "\"stnd_mesg_ver\":\"R10\","
|
||||
+ "\"ortr_guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"dman_rspn_dvcd\":\"S\","
|
||||
+ "\"if_id\":\"" + TEST_IF_ID + "\","
|
||||
+ "\"procs_rslt_dvcd\":\"S\","
|
||||
+ "\"tx_id\":\"" + TEST_TX_ID + "\","
|
||||
+ "\"chnl_tycd\":\"EAI\","
|
||||
+ "\"hmab_dvcd\":\"1\","
|
||||
+ "\"corp_tlwn_virt_brcd\":\"ERP\","
|
||||
+ "\"trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"frst_trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"sys_env_dvcd\":\"D\","
|
||||
+ "\"frst_mesg_dman_dt\":\"20260420\","
|
||||
+ "\"frst_mesg_dman_time\":\"120000000\""
|
||||
+ "},"
|
||||
+ "\"EZDATA\":{"
|
||||
+ "\"login_mhod_dvcd\":\"1\","
|
||||
+ "\"elfn_bnkn_dvcd\":\"01\","
|
||||
+ "\"usr_no\":\"USR0000000000001\","
|
||||
+ "\"rgsr_id\":\"REG_ID_000000001\","
|
||||
+ "\"secu_media_dvcd\":\"00\","
|
||||
+ "\"secu_media_sta_dvcd\":\"00\","
|
||||
+ "\"brll_srcd_yn\":\"N\","
|
||||
+ "\"next_data_exis_yn\":\"N\","
|
||||
+ "\"page_no\":\"00001\","
|
||||
+ "\"page_size\":\"00020\","
|
||||
+ "\"dup_tx_yn\":\"N\""
|
||||
+ "},"
|
||||
+ "\"DATA\":{"
|
||||
+ "\"data_dvcd\":\"IO\","
|
||||
+ "\"data_scop_len\":\"37\","
|
||||
+ "\"BIZ_DATA\":{\"acct_no\":\"987654321\",\"amt\":\"500000\"}"
|
||||
+ "}"
|
||||
+ "}";
|
||||
|
||||
/**
|
||||
* 비ERP 요청 JSON — corp_tlwn_virt_brcd 미설정 → EZDATA 블록 비활성
|
||||
*/
|
||||
private static final String NON_ERP_REQ_JSON =
|
||||
"{"
|
||||
+ "\"HEAD\":{"
|
||||
+ "\"nxgn_stnd_idfr\":\"JERA\","
|
||||
+ "\"guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"guid_prgs_no\":\"1\","
|
||||
+ "\"stnd_mesg_ver\":\"R10\","
|
||||
+ "\"ortr_guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"dman_rspn_dvcd\":\"S\","
|
||||
+ "\"if_id\":\"" + TEST_IF_ID + "\","
|
||||
+ "\"procs_rslt_dvcd\":\"S\","
|
||||
+ "\"tx_id\":\"" + TEST_TX_ID + "\","
|
||||
+ "\"chnl_tycd\":\"EAI\","
|
||||
+ "\"hmab_dvcd\":\"1\","
|
||||
+ "\"trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"frst_trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"sys_env_dvcd\":\"D\","
|
||||
+ "\"frst_mesg_dman_dt\":\"20260420\","
|
||||
+ "\"frst_mesg_dman_time\":\"120000000\""
|
||||
+ "},"
|
||||
+ "\"DATA\":{"
|
||||
+ "\"data_dvcd\":\"IO\","
|
||||
+ "\"data_scop_len\":\"20\","
|
||||
+ "\"BIZ_DATA\":{\"acct_no\":\"111222333\"}"
|
||||
+ "}"
|
||||
+ "}";
|
||||
|
||||
private StandardMessageManager manager;
|
||||
private InterfaceMapper mapper;
|
||||
private JsonReader jsonReader;
|
||||
private StandardMessageCoordinatorDJB coordinator;
|
||||
private ObjectMapper jacksonMapper;
|
||||
|
||||
@BeforeAll
|
||||
void setUpAll() throws Exception {
|
||||
PropManager mockPropManager = Mockito.mock(PropManager.class);
|
||||
Mockito.when(mockPropManager.getProperty(anyString(), anyString(), anyString()))
|
||||
.thenAnswer(new Answer<String>() {
|
||||
public String answer(InvocationOnMock inv) { return (String) inv.getArguments()[2]; }
|
||||
});
|
||||
|
||||
EAIServerManager mockServer = Mockito.mock(EAIServerManager.class);
|
||||
Mockito.when(mockServer.isPEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isSEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isMCI()).thenReturn(false);
|
||||
Mockito.when(mockServer.getLocalServerName()).thenReturn("TEST_SERVER");
|
||||
Mockito.when(mockServer.getGroupInstId()).thenReturn("TEST_INST");
|
||||
|
||||
EAIServiceMonitor mockMonitor = Mockito.mock(EAIServiceMonitor.class);
|
||||
Mockito.when(mockMonitor.isTimeOutCodes(anyString())).thenReturn(false);
|
||||
Mockito.when(mockMonitor.isBizErrorCodes(anyString())).thenReturn(false);
|
||||
|
||||
ApplicationContext mockCtx = Mockito.mock(ApplicationContext.class);
|
||||
Mockito.when(mockCtx.getBean(EAIServerManager.class)).thenReturn(mockServer);
|
||||
Mockito.when(mockCtx.getBean(PropManager.class)).thenReturn(mockPropManager);
|
||||
Mockito.when(mockCtx.getBean(EAIServiceMonitor.class)).thenReturn(mockMonitor);
|
||||
|
||||
Field ctxField = ApplicationContextProvider.class.getDeclaredField("context");
|
||||
ctxField.setAccessible(true);
|
||||
ctxField.set(null, mockCtx);
|
||||
|
||||
System.setProperty(StandardMessageManager.STANDARD_MESSAGE_CONFIG,
|
||||
"src/test/resources/standard-message-config-test.properties");
|
||||
manager = StandardMessageManager.getInstance();
|
||||
manager.init();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mapper = manager.getMapper();
|
||||
jsonReader = (JsonReader) manager.getReader("JSON");
|
||||
coordinator = new StandardMessageCoordinatorDJB();
|
||||
jacksonMapper = new ObjectMapper();
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 1. EZDATA 포함 요청 JSON 파싱
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void ERP요청_파싱_EZDATA_블록_활성() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
assertNotNull(msg.findItem("EZDATA"), "EZDATA 블록이 null");
|
||||
assertFalse(msg.findItem("EZDATA").isHidden(), "EZDATA 블록이 hidden 상태");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_파싱_HEAD_corp_tlwn_virt_brcd_ERP() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
assertEquals("ERP", msg.findItemValue("HEAD.corp_tlwn_virt_brcd"),
|
||||
"corp_tlwn_virt_brcd가 ERP가 아님");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 2. EZDATA 핵심 필드 값 검증
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void EZDATA_login_mhod_dvcd_파싱() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
assertEquals("1", msg.findItemValue("EZDATA.login_mhod_dvcd"),
|
||||
"EZDATA.login_mhod_dvcd 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_elfn_bnkn_dvcd_파싱() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
assertEquals("01", msg.findItemValue("EZDATA.elfn_bnkn_dvcd"),
|
||||
"EZDATA.elfn_bnkn_dvcd 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_usr_no_파싱() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
assertEquals("USR0000000000001", msg.findItemValue("EZDATA.usr_no").trim(),
|
||||
"EZDATA.usr_no 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_rgsr_id_파싱() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
assertEquals("REG_ID_000000001", msg.findItemValue("EZDATA.rgsr_id").trim(),
|
||||
"EZDATA.rgsr_id 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_secu_media_dvcd_파싱() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
assertEquals("00", msg.findItemValue("EZDATA.secu_media_dvcd"),
|
||||
"EZDATA.secu_media_dvcd 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_dup_tx_yn_파싱() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
assertEquals("N", msg.findItemValue("EZDATA.dup_tx_yn"),
|
||||
"EZDATA.dup_tx_yn 불일치");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 3. EZDATA 조건 미충족(비ERP) — EZDATA 블록 직렬화 제외 검증
|
||||
// size=0 + refPath/refValue 조건 미충족 → isHidden=true → JSON 제외
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 비ERP요청_파싱_EZDATA_size_0() throws Exception {
|
||||
StandardMessage msg = parseNonErpReq();
|
||||
|
||||
StandardItem ezdataItem = msg.findItem("EZDATA");
|
||||
assertTrue(ezdataItem == null || ezdataItem.getSize() == 0,
|
||||
"비ERP 요청에서 EZDATA 블록 size는 0이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비ERP요청_파싱_JSON_직렬화_EZDATA_제외() throws Exception {
|
||||
StandardMessage msg = parseNonErpReq();
|
||||
|
||||
String json = msg.toJson(false, false);
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertFalse(root.has("EZDATA"), "비ERP 요청 직렬화 JSON에 EZDATA 블록이 없어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비ERP요청_파싱_BIZ_DATA_정상파싱() throws Exception {
|
||||
StandardMessage msg = parseNonErpReq();
|
||||
|
||||
String bizData = msg.findItemValue("DATA.BIZ_DATA");
|
||||
assertNotNull(bizData, "비ERP 요청의 BIZ_DATA가 null");
|
||||
JsonNode node = jacksonMapper.readTree(bizData);
|
||||
assertEquals("111222333", node.path("acct_no").asText());
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 4. EZDATA 포함 JSON 왕복(parse → serialize) 일관성
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void JSON_왕복_EZDATA_포함_직렬화() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertTrue(root.has("EZDATA"), "JSON 왕복 후 EZDATA 블록 소실");
|
||||
}
|
||||
|
||||
@Test
|
||||
void JSON_왕복_EZDATA_usr_no_보존() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertEquals("USR0000000000001",
|
||||
root.path("EZDATA").path("usr_no").asText().trim(),
|
||||
"JSON 왕복 후 EZDATA.usr_no 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void JSON_왕복_HEAD_guid_보존() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertEquals(TEST_GUID, root.path("HEAD").path("guid").asText(),
|
||||
"JSON 왕복 후 guid 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void JSON_왕복_BIZ_DATA_보존() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
JsonNode bizData = root.path("DATA").get("BIZ_DATA");
|
||||
assertNotNull(bizData, "JSON 왕복 후 BIZ_DATA 소실");
|
||||
assertEquals("987654321", bizData.path("acct_no").asText(),
|
||||
"JSON 왕복 후 BIZ_DATA.acct_no 불일치");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 5. coordinateAfterCreateMessageByRule 후 EZDATA 보존
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 표준수신_coordinateAfterCreateMessageByRule_EZDATA_보존() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertTrue(root.has("EZDATA"), "coordinateAfterCreateMessageByRule 후 EZDATA 소실");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 표준수신_coordinateAfterCreateMessageByRule_EZDATA_usr_no_보존() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
|
||||
assertEquals("USR0000000000001", msg.findItemValue("EZDATA.usr_no").trim(),
|
||||
"coordinateAfterCreateMessageByRule 후 EZDATA.usr_no 변경됨");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 6. coordinateBeforeResponse 후 EZDATA 포함 직렬화
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 표준응답생성_coordinateBeforeResponse_EZDATA_포함() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertTrue(root.has("EZDATA"), "coordinateBeforeResponse 후 EZDATA 소실");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 표준응답생성_coordinateBeforeResponse_HEAD_mesg_rspn_dt_설정() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
|
||||
String dt = msg.findItemValue("HEAD.mesg_rspn_dt");
|
||||
assertNotNull(dt, "mesg_rspn_dt가 null");
|
||||
assertTrue(dt.matches("\\d{8}"), "mesg_rspn_dt 형식 오류: " + dt);
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 7. 오류 응답 생성 시 EZDATA 보존
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 오류응답_EZDATA_포함_JSON_직렬화() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertTrue(root.has("EZDATA"), "오류응답 JSON에 EZDATA 블록 소실");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 오류응답_EZDATA_procs_rslt_dvcd_F() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
assertEquals("F", msg.findItemValue("HEAD.procs_rslt_dvcd"),
|
||||
"오류 응답의 procs_rslt_dvcd는 F여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 오류응답_EZDATA_MSG_블록_포함() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertTrue(root.has("MSG"), "오류응답 JSON에 MSG 블록 없음");
|
||||
assertEquals("EM", root.path("MSG").path("msg_dvcd").asText(),
|
||||
"오류응답 msg_dvcd가 EM이 아님");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// helper
|
||||
// ================================================================
|
||||
|
||||
private StandardMessage parseErpReq() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
jsonReader.parse(msg, ERP_REQ_JSON);
|
||||
return msg;
|
||||
}
|
||||
|
||||
private StandardMessage parseNonErpReq() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
jsonReader.parse(msg, NON_ERP_REQ_JSON);
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import com.eactive.eai.common.monitor.EAIServiceMonitor;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.message.StandardItem;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.parser.JsonReader;
|
||||
import com.eactive.eai.message.parser.StandardReader;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
|
||||
/**
|
||||
* DJBank 표준전문 FLAT 직렬화/파싱 흐름 통합 테스트
|
||||
*
|
||||
* 검증 시나리오:
|
||||
* 1. FlatReader 등록 확인
|
||||
* 2. 비ERP 요청 FLAT 왕복 — HEAD 보존, EZDATA/MSG 바이트 미포함
|
||||
* 3. ERP 요청 FLAT 왕복 — EZDATA 포함 보존
|
||||
* 4. 오류 응답 FLAT 왕복 — MSG EM 포함 보존
|
||||
* 5. 정상 응답 FLAT 왕복 — MSG NM 포함 보존
|
||||
* 6. 거래로그 시나리오 — FLAT 바이트 길이 검증 (조건부 블록 포함 여부)
|
||||
*
|
||||
* 핵심 버그 (EZDATA FLAT 오류):
|
||||
* JSON 파싱 시 JSON에 없는 조건부 블록(EZDATA, MSG)은 isHidden=false 로 남는다.
|
||||
* toByteArray() GROUP 케이스에서 size=0 이면서 refPath/refValue 가 있는 경우
|
||||
* isHidden 체크만으로는 불충분 → FLAT에 비활성 블록 바이트가 잘못 포함된다.
|
||||
*
|
||||
* 수정: toByteArray() / getBytesDataLength() GROUP 케이스를
|
||||
* toJson() 과 동일하게 size==0 이면 무조건 skip 으로 변경
|
||||
* (StandardItem.java 두 곳)
|
||||
*/
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class StandardMessageFlatFlowTest {
|
||||
|
||||
private static final String TEST_GUID =
|
||||
"20260420" + "120000" + "000" + "EAI" + "01" + "123456789012" + "000001";
|
||||
// 8+6+3+3+2+12+6 = 40자
|
||||
|
||||
private static final String TEST_IF_ID = "IF_DJBTEST_FLAT01";
|
||||
private static final String TEST_TX_ID = "TXTEST000003";
|
||||
private static final String FLAT_CHARSET = "euc-kr";
|
||||
|
||||
/** 비ERP 요청 JSON — dman_rspn_dvcd=S, corp_tlwn_virt_brcd 미설정 */
|
||||
private static final String NON_ERP_REQ_JSON =
|
||||
"{"
|
||||
+ "\"HEAD\":{"
|
||||
+ "\"nxgn_stnd_idfr\":\"JERA\","
|
||||
+ "\"guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"guid_prgs_no\":\"1\","
|
||||
+ "\"stnd_mesg_ver\":\"R10\","
|
||||
+ "\"ortr_guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"dman_rspn_dvcd\":\"S\","
|
||||
+ "\"if_id\":\"" + TEST_IF_ID + "\","
|
||||
+ "\"procs_rslt_dvcd\":\"S\","
|
||||
+ "\"tx_id\":\"" + TEST_TX_ID + "\","
|
||||
+ "\"chnl_tycd\":\"EAI\","
|
||||
+ "\"hmab_dvcd\":\"1\","
|
||||
+ "\"trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"frst_trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"sys_env_dvcd\":\"D\","
|
||||
+ "\"frst_mesg_dman_dt\":\"20260420\","
|
||||
+ "\"frst_mesg_dman_time\":\"120000000\""
|
||||
+ "},"
|
||||
+ "\"DATA\":{"
|
||||
+ "\"data_dvcd\":\"IO\","
|
||||
+ "\"data_scop_len\":\"00000037\","
|
||||
+ "\"BIZ_DATA\":{\"acct_no\":\"123456789\",\"amt\":\"100000\"}"
|
||||
+ "}"
|
||||
+ "}";
|
||||
|
||||
/** ERP 요청 JSON — corp_tlwn_virt_brcd=ERP, EZDATA 포함 */
|
||||
private static final String ERP_REQ_JSON =
|
||||
"{"
|
||||
+ "\"HEAD\":{"
|
||||
+ "\"nxgn_stnd_idfr\":\"JERA\","
|
||||
+ "\"guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"guid_prgs_no\":\"1\","
|
||||
+ "\"stnd_mesg_ver\":\"R10\","
|
||||
+ "\"ortr_guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"dman_rspn_dvcd\":\"S\","
|
||||
+ "\"if_id\":\"" + TEST_IF_ID + "\","
|
||||
+ "\"procs_rslt_dvcd\":\"S\","
|
||||
+ "\"tx_id\":\"" + TEST_TX_ID + "\","
|
||||
+ "\"chnl_tycd\":\"EAI\","
|
||||
+ "\"hmab_dvcd\":\"1\","
|
||||
+ "\"corp_tlwn_virt_brcd\":\"ERP\","
|
||||
+ "\"trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"frst_trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"sys_env_dvcd\":\"D\","
|
||||
+ "\"frst_mesg_dman_dt\":\"20260420\","
|
||||
+ "\"frst_mesg_dman_time\":\"120000000\""
|
||||
+ "},"
|
||||
+ "\"EZDATA\":{"
|
||||
+ "\"login_mhod_dvcd\":\"1\","
|
||||
+ "\"elfn_bnkn_dvcd\":\"01\","
|
||||
+ "\"usr_no\":\"USR0000000000001\","
|
||||
+ "\"rgsr_id\":\"REG_ID_000000001\","
|
||||
+ "\"secu_media_dvcd\":\"00\","
|
||||
+ "\"secu_media_sta_dvcd\":\"00\","
|
||||
+ "\"brll_srcd_yn\":\"N\","
|
||||
+ "\"next_data_exis_yn\":\"N\","
|
||||
+ "\"page_no\":\"00001\","
|
||||
+ "\"page_size\":\"00020\","
|
||||
+ "\"dup_tx_yn\":\"N\""
|
||||
+ "},"
|
||||
+ "\"DATA\":{"
|
||||
+ "\"data_dvcd\":\"IO\","
|
||||
+ "\"data_scop_len\":\"00000037\","
|
||||
+ "\"BIZ_DATA\":{\"acct_no\":\"987654321\",\"amt\":\"500000\"}"
|
||||
+ "}"
|
||||
+ "}";
|
||||
|
||||
private StandardMessageManager manager;
|
||||
private InterfaceMapper mapper;
|
||||
private StandardReader flatReader;
|
||||
private JsonReader jsonReader;
|
||||
private StandardMessageCoordinatorDJB coordinator;
|
||||
|
||||
@BeforeAll
|
||||
void setUpAll() throws Exception {
|
||||
PropManager mockPropManager = Mockito.mock(PropManager.class);
|
||||
Mockito.when(mockPropManager.getProperty(anyString(), anyString(), anyString()))
|
||||
.thenAnswer(new Answer<String>() {
|
||||
public String answer(InvocationOnMock inv) { return (String) inv.getArguments()[2]; }
|
||||
});
|
||||
|
||||
EAIServerManager mockServer = Mockito.mock(EAIServerManager.class);
|
||||
Mockito.when(mockServer.isPEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isSEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isMCI()).thenReturn(false);
|
||||
Mockito.when(mockServer.getLocalServerName()).thenReturn("TEST_SERVER");
|
||||
Mockito.when(mockServer.getGroupInstId()).thenReturn("TEST_INST");
|
||||
|
||||
EAIServiceMonitor mockMonitor = Mockito.mock(EAIServiceMonitor.class);
|
||||
Mockito.when(mockMonitor.isTimeOutCodes(anyString())).thenReturn(false);
|
||||
Mockito.when(mockMonitor.isBizErrorCodes(anyString())).thenReturn(false);
|
||||
|
||||
ApplicationContext mockCtx = Mockito.mock(ApplicationContext.class);
|
||||
Mockito.when(mockCtx.getBean(EAIServerManager.class)).thenReturn(mockServer);
|
||||
Mockito.when(mockCtx.getBean(PropManager.class)).thenReturn(mockPropManager);
|
||||
Mockito.when(mockCtx.getBean(EAIServiceMonitor.class)).thenReturn(mockMonitor);
|
||||
|
||||
Field ctxField = ApplicationContextProvider.class.getDeclaredField("context");
|
||||
ctxField.setAccessible(true);
|
||||
ctxField.set(null, mockCtx);
|
||||
|
||||
System.setProperty(StandardMessageManager.STANDARD_MESSAGE_CONFIG,
|
||||
"src/test/resources/standard-message-config-test.properties");
|
||||
manager = StandardMessageManager.getInstance();
|
||||
manager.init();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mapper = manager.getMapper();
|
||||
flatReader = manager.getReader("FLAT");
|
||||
jsonReader = (JsonReader) manager.getReader("JSON");
|
||||
coordinator = new StandardMessageCoordinatorDJB();
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 1. FlatReader 등록 확인
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void FlatReader_등록_확인() {
|
||||
assertNotNull(flatReader, "FlatReader가 등록되지 않음 (reader.FLAT 설정 확인)");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 2. 비ERP 요청 FLAT 왕복 — HEAD 보존, EZDATA/MSG 비포함
|
||||
//
|
||||
// [버그] 수정 전: EZDATA(1500B) + MSG(10B) 가 FLAT에 잘못 포함
|
||||
// → FlatReader 파싱 시 overflow 예외 발생
|
||||
// [수정] StandardItem.toByteArray() GROUP 케이스: size==0 이면 무조건 skip
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 비ERP요청_FLAT_파싱_예외없음() throws Exception {
|
||||
StandardMessage src = parseJson(NON_ERP_REQ_JSON);
|
||||
String flatStr = src.toFixedString(false, FLAT_CHARSET);
|
||||
|
||||
StandardMessage dst = manager.getStandardMessage();
|
||||
assertDoesNotThrow(() -> flatReader.parse(dst, flatStr),
|
||||
"비ERP FLAT 파싱 중 예외 발생 — EZDATA 바이트 오버플로우 버그 확인 필요\n"
|
||||
+ "원인: StandardItem.toByteArray() GROUP size==0 skip 조건 미적용");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비ERP요청_FLAT_왕복_HEAD_guid_보존() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(NON_ERP_REQ_JSON));
|
||||
|
||||
assertEquals(TEST_GUID, dst.findItemValue("HEAD.guid").trim(),
|
||||
"FLAT 왕복 후 HEAD.guid 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비ERP요청_FLAT_왕복_HEAD_if_id_보존() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(NON_ERP_REQ_JSON));
|
||||
|
||||
assertEquals(TEST_IF_ID, dst.findItemValue("HEAD.if_id").trim(),
|
||||
"FLAT 왕복 후 HEAD.if_id 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비ERP요청_FLAT_왕복_HEAD_dman_rspn_dvcd_S() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(NON_ERP_REQ_JSON));
|
||||
|
||||
assertEquals("S", dst.findItemValue("HEAD.dman_rspn_dvcd").trim(),
|
||||
"FLAT 왕복 후 HEAD.dman_rspn_dvcd 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비ERP요청_FLAT_왕복_HEAD_stnd_mesg_ver_R10() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(NON_ERP_REQ_JSON));
|
||||
|
||||
assertEquals("R10", dst.findItemValue("HEAD.stnd_mesg_ver").trim(),
|
||||
"FLAT 왕복 후 HEAD.stnd_mesg_ver 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비ERP요청_FLAT_왕복_DATA_data_dvcd_IO() throws Exception {
|
||||
// [버그] 수정 전: MSG 바이트가 잘못 포함 → DATA.data_dvcd 자리에 MSG 바이트 읽힘 ("NM")
|
||||
StandardMessage dst = flatRoundTrip(parseJson(NON_ERP_REQ_JSON));
|
||||
|
||||
assertEquals("IO", dst.findItemValue("DATA.data_dvcd").trim(),
|
||||
"FLAT 왕복 후 DATA.data_dvcd 불일치 — MSG 바이트 오염 가능성");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비ERP요청_FLAT_왕복_EZDATA_비활성() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(NON_ERP_REQ_JSON));
|
||||
|
||||
StandardItem ezdataItem = dst.findItem("EZDATA");
|
||||
assertTrue(ezdataItem == null || ezdataItem.isHidden() || ezdataItem.getSize() == 0,
|
||||
"비ERP FLAT 왕복 후 EZDATA 블록이 활성 상태이면 안 됨");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 3. ERP 요청 FLAT 왕복 — EZDATA 포함
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_파싱_예외없음() throws Exception {
|
||||
StandardMessage src = parseJson(ERP_REQ_JSON);
|
||||
String flatStr = src.toFixedString(false, FLAT_CHARSET);
|
||||
|
||||
StandardMessage dst = manager.getStandardMessage();
|
||||
assertDoesNotThrow(() -> flatReader.parse(dst, flatStr),
|
||||
"ERP FLAT 파싱 중 예외 발생");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_HEAD_guid_보존() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
assertEquals(TEST_GUID, dst.findItemValue("HEAD.guid").trim(),
|
||||
"ERP FLAT 왕복 후 HEAD.guid 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_HEAD_corp_tlwn_virt_brcd_ERP() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
assertEquals("ERP", dst.findItemValue("HEAD.corp_tlwn_virt_brcd").trim(),
|
||||
"ERP FLAT 왕복 후 HEAD.corp_tlwn_virt_brcd 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_EZDATA_활성() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
StandardItem ezdataItem = dst.findItem("EZDATA");
|
||||
assertNotNull(ezdataItem, "ERP FLAT 왕복 후 EZDATA 블록 없음");
|
||||
assertFalse(ezdataItem.isHidden(), "ERP FLAT 왕복 후 EZDATA 블록이 hidden 상태");
|
||||
assertTrue(ezdataItem.getSize() > 0, "ERP FLAT 왕복 후 EZDATA 블록 size가 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_EZDATA_login_mhod_dvcd_보존() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
assertEquals("1", dst.findItemValue("EZDATA.login_mhod_dvcd").trim(),
|
||||
"ERP FLAT 왕복 후 EZDATA.login_mhod_dvcd 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_EZDATA_elfn_bnkn_dvcd_보존() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
assertEquals("01", dst.findItemValue("EZDATA.elfn_bnkn_dvcd").trim(),
|
||||
"ERP FLAT 왕복 후 EZDATA.elfn_bnkn_dvcd 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_EZDATA_usr_no_보존() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
assertEquals("USR0000000000001", dst.findItemValue("EZDATA.usr_no").trim(),
|
||||
"ERP FLAT 왕복 후 EZDATA.usr_no 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_EZDATA_rgsr_id_보존() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
assertEquals("REG_ID_000000001", dst.findItemValue("EZDATA.rgsr_id").trim(),
|
||||
"ERP FLAT 왕복 후 EZDATA.rgsr_id 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_EZDATA_secu_media_dvcd_보존() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
assertEquals("00", dst.findItemValue("EZDATA.secu_media_dvcd").trim(),
|
||||
"ERP FLAT 왕복 후 EZDATA.secu_media_dvcd 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_EZDATA_dup_tx_yn_보존() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
assertEquals("N", dst.findItemValue("EZDATA.dup_tx_yn").trim(),
|
||||
"ERP FLAT 왕복 후 EZDATA.dup_tx_yn 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_EZDATA_NUMBER_page_no_보존() throws Exception {
|
||||
// page_no 는 NUMBER 타입: "00001" → toTypeValue() 선행 0 제거 → "1"
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
String pageNo = dst.findItemValue("EZDATA.page_no").trim();
|
||||
assertFalse(pageNo.isEmpty(), "ERP FLAT 왕복 후 EZDATA.page_no가 비어 있음");
|
||||
assertEquals(1, Integer.parseInt(pageNo),
|
||||
"ERP FLAT 왕복 후 EZDATA.page_no 값 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_EZDATA_NUMBER_page_size_보존() throws Exception {
|
||||
// page_size 는 NUMBER 타입: "00020" → "20"
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
String pageSize = dst.findItemValue("EZDATA.page_size").trim();
|
||||
assertFalse(pageSize.isEmpty(), "ERP FLAT 왕복 후 EZDATA.page_size가 비어 있음");
|
||||
assertEquals(20, Integer.parseInt(pageSize),
|
||||
"ERP FLAT 왕복 후 EZDATA.page_size 값 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ERP요청_FLAT_왕복_DATA_data_dvcd_IO() throws Exception {
|
||||
// [버그] 수정 전: MSG 바이트가 잘못 포함 → DATA.data_dvcd 자리에 MSG 바이트 읽힘
|
||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_JSON));
|
||||
|
||||
assertEquals("IO", dst.findItemValue("DATA.data_dvcd").trim(),
|
||||
"ERP FLAT 왕복 후 DATA.data_dvcd 불일치 — MSG 바이트 오염 가능성");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 4. 오류 응답 FLAT 왕복 — MSG EM 포함
|
||||
// coordinateSetStandardMessageError() → MSG.size=1, MAIN_MSG.size=1
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 오류응답_FLAT_파싱_예외없음() throws Exception {
|
||||
StandardMessage src = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(src, mapper, "RECEAICMM999", "테스트 오류");
|
||||
String flatStr = src.toFixedString(false, FLAT_CHARSET);
|
||||
|
||||
StandardMessage dst = manager.getStandardMessage();
|
||||
assertDoesNotThrow(() -> flatReader.parse(dst, flatStr),
|
||||
"오류응답 FLAT 파싱 중 예외 발생");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 오류응답_FLAT_왕복_HEAD_procs_rslt_dvcd_F() throws Exception {
|
||||
StandardMessage src = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(src, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
assertEquals("F", flatRoundTrip(src).findItemValue("HEAD.procs_rslt_dvcd").trim(),
|
||||
"오류응답 FLAT 왕복 후 HEAD.procs_rslt_dvcd가 F가 아님");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 오류응답_FLAT_왕복_MSG_msg_dvcd_EM() throws Exception {
|
||||
StandardMessage src = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(src, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
assertEquals("EM", flatRoundTrip(src).findItemValue("MSG.msg_dvcd").trim(),
|
||||
"오류응답 FLAT 왕복 후 MSG.msg_dvcd가 EM이 아님");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 오류응답_FLAT_왕복_MSG_outp_atrb_cd_1_팝업() throws Exception {
|
||||
StandardMessage src = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(src, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
assertEquals("1", flatRoundTrip(src).findItemValue("MSG.MAIN_MSG.outp_atrb_cd").trim(),
|
||||
"오류응답 FLAT 왕복 후 MSG.MAIN_MSG.outp_atrb_cd가 1(팝업)이 아님");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 오류응답_FLAT_왕복_MSG_MAIN_MSG_활성() throws Exception {
|
||||
StandardMessage src = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(src, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
StandardItem mainMsgItem = flatRoundTrip(src).findItem("MSG.MAIN_MSG");
|
||||
assertNotNull(mainMsgItem, "오류응답 FLAT 왕복 후 MSG.MAIN_MSG 블록 없음");
|
||||
assertTrue(mainMsgItem.getSize() > 0,
|
||||
"오류응답 FLAT 왕복 후 MSG.MAIN_MSG size가 0");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 5. 정상 응답 FLAT 왕복 — MSG NM 포함
|
||||
// coordinateAfterRecvNonStdSyncResponse() → MSG.size=1, MAIN_MSG.size=1
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 정상응답_FLAT_파싱_예외없음() throws Exception {
|
||||
StandardMessage src = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(src);
|
||||
String flatStr = src.toFixedString(false, FLAT_CHARSET);
|
||||
|
||||
StandardMessage dst = manager.getStandardMessage();
|
||||
assertDoesNotThrow(() -> flatReader.parse(dst, flatStr),
|
||||
"정상응답 FLAT 파싱 중 예외 발생");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 정상응답_FLAT_왕복_MSG_msg_dvcd_NM() throws Exception {
|
||||
StandardMessage src = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(src);
|
||||
|
||||
assertEquals("NM", flatRoundTrip(src).findItemValue("MSG.msg_dvcd").trim(),
|
||||
"정상응답 FLAT 왕복 후 MSG.msg_dvcd가 NM이 아님");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 정상응답_FLAT_왕복_MSG_활성() throws Exception {
|
||||
StandardMessage src = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(src);
|
||||
StandardMessage dst = flatRoundTrip(src);
|
||||
|
||||
StandardItem msgItem = dst.findItem("MSG");
|
||||
assertNotNull(msgItem, "정상응답 FLAT 왕복 후 MSG 블록 없음");
|
||||
assertFalse(msgItem.isHidden(), "정상응답 FLAT 왕복 후 MSG 블록이 hidden 상태");
|
||||
assertTrue(msgItem.getSize() > 0, "정상응답 FLAT 왕복 후 MSG 블록 size가 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 정상응답_FLAT_왕복_MSG_MAIN_MSG_활성() throws Exception {
|
||||
StandardMessage src = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(src);
|
||||
|
||||
StandardItem mainMsgItem = flatRoundTrip(src).findItem("MSG.MAIN_MSG");
|
||||
assertNotNull(mainMsgItem, "정상응답 FLAT 왕복 후 MSG.MAIN_MSG 블록 없음");
|
||||
assertTrue(mainMsgItem.getSize() > 0,
|
||||
"정상응답 FLAT 왕복 후 MSG.MAIN_MSG size가 0");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 6. 거래로그 시나리오 — FLAT 바이트 길이로 조건부 블록 포함 여부 검증
|
||||
//
|
||||
// [버그] 수정 전: 비ERP 에도 EZDATA(1500B) 포함 → ERP 와 길이 동일
|
||||
// [수정] 비ERP FLAT < ERP FLAT (EZDATA 1500바이트 차이)
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 거래로그_비ERP_FLAT_길이가_ERP_FLAT_보다_짧음() throws Exception {
|
||||
byte[] nonErpBytes = parseJson(NON_ERP_REQ_JSON)
|
||||
.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
|
||||
byte[] erpBytes = parseJson(ERP_REQ_JSON)
|
||||
.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
|
||||
|
||||
// EZDATA = 1500바이트 — ERP FLAT 이 비ERP FLAT 보다 길어야 함
|
||||
// 버그 발생 시: 둘 다 EZDATA 포함 → 길이 동일 → 검증 실패
|
||||
assertTrue(erpBytes.length > nonErpBytes.length,
|
||||
String.format("ERP FLAT 길이(%d) > 비ERP FLAT 길이(%d) 이어야 함 (EZDATA 1500B 차이)",
|
||||
erpBytes.length, nonErpBytes.length));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 거래로그_요청_FLAT_길이가_응답_FLAT_보다_짧음() throws Exception {
|
||||
// 요청(dman_rspn_dvcd=S): MSG 비활성 / 응답: MSG 활성 → 응답이 더 긺
|
||||
StandardMessage rspMsg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(rspMsg);
|
||||
|
||||
byte[] reqBytes = parseJson(NON_ERP_REQ_JSON)
|
||||
.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
|
||||
byte[] rspBytes = rspMsg.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
|
||||
|
||||
// 버그 발생 시: 요청도 MSG 바이트 포함 → 길이 역전 가능
|
||||
assertTrue(rspBytes.length > reqBytes.length,
|
||||
String.format("응답 FLAT 길이(%d) > 요청 FLAT 길이(%d) 이어야 함 (MSG 블록 포함 여부)",
|
||||
rspBytes.length, reqBytes.length));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비ERP요청_FLAT_왕복_HEAD_chnl_tycd_EAI값확인() throws Exception {
|
||||
StandardMessage dst = flatRoundTrip(parseJson(NON_ERP_REQ_JSON));
|
||||
|
||||
assertEquals("EAI", dst.findItemValue("HEAD.chnl_tycd").trim(),
|
||||
"FLAT 왕복 후 HEAD.chnl_tycd EAI 확인");
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ================================================================
|
||||
// helpers
|
||||
// ================================================================
|
||||
|
||||
private StandardMessage parseJson(String json) throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
jsonReader.parse(msg, json);
|
||||
return msg;
|
||||
}
|
||||
|
||||
/**
|
||||
* FLAT 왕복: src → toFixedString(false, euc-kr) → FlatReader.parse() → dst
|
||||
* STDMessageDAO.addRestoreSTDMessage / getRestoreSTDMessage 와 동일한 흐름
|
||||
*/
|
||||
private StandardMessage flatRoundTrip(StandardMessage src) throws Exception {
|
||||
String flatStr = src.toFixedString(false, FLAT_CHARSET);
|
||||
StandardMessage dst = manager.getStandardMessage();
|
||||
flatReader.parse(dst, flatStr);
|
||||
return dst;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import com.eactive.eai.common.monitor.EAIServiceMonitor;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.parser.JsonReader;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
|
||||
/**
|
||||
* DJBank 표준전문 JSON 처리 흐름 통합 테스트
|
||||
*
|
||||
* 검증 시나리오:
|
||||
* 1. JSON → StandardMessage 파싱 (표준 요청 수신)
|
||||
* 2. JSON → StandardMessage 파싱 (표준 응답 수신 — MSG 포함)
|
||||
* 3. 표준 메시지 요청 수신 처리 (coordinateAfterCreateMessageByRule)
|
||||
* 4. 표준 응답 생성 (coordinateBeforeResponse → JSON 직렬화)
|
||||
* 5. 비표준 수신 → 정상 응답 표준 생성 (coordinateAfterRecvNonStdSyncResponse → JSON)
|
||||
* 6. 오류 응답 표준 생성 (coordinateSetStandardMessageError → JSON)
|
||||
* 7. JSON 왕복(parse → serialize) 일관성
|
||||
*/
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class StandardMessageJsonFlowTest {
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 테스트용 상수 (GUID 40자 고정)
|
||||
// ----------------------------------------------------------------
|
||||
private static final String TEST_GUID =
|
||||
"20260420" + "120000" + "000" + "EAI" + "01" + "123456789012" + "000001";
|
||||
// 8+6+3+3+2+12+6 = 40자
|
||||
|
||||
private static final String TEST_IF_ID = "IF_DJBTEST_001";
|
||||
private static final String TEST_TX_ID = "TXTEST000001";
|
||||
|
||||
private static final DateTimeFormatter FMT_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
/**
|
||||
* 표준 요청 JSON (dman_rspn_dvcd=S → MSG 블록 미포함)
|
||||
* BIZ_DATA는 JSON 오브젝트 — 파싱 후 JSON 문자열로 저장됨
|
||||
*/
|
||||
private static final String REQ_JSON =
|
||||
"{"
|
||||
+ "\"HEAD\":{"
|
||||
+ "\"nxgn_stnd_idfr\":\"JERA\","
|
||||
+ "\"guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"guid_prgs_no\":\"1\","
|
||||
+ "\"stnd_mesg_ver\":\"R10\","
|
||||
+ "\"ortr_guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"dman_rspn_dvcd\":\"S\","
|
||||
+ "\"if_id\":\"" + TEST_IF_ID + "\","
|
||||
+ "\"procs_rslt_dvcd\":\"S\","
|
||||
+ "\"tx_id\":\"" + TEST_TX_ID + "\","
|
||||
+ "\"chnl_tycd\":\"EAI\","
|
||||
+ "\"hmab_dvcd\":\"1\","
|
||||
+ "\"trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"frst_trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"sys_env_dvcd\":\"D\","
|
||||
+ "\"frst_mesg_dman_dt\":\"20260420\","
|
||||
+ "\"frst_mesg_dman_time\":\"120000000\""
|
||||
+ "},"
|
||||
+ "\"DATA\":{"
|
||||
+ "\"data_dvcd\":\"IO\","
|
||||
+ "\"data_scop_len\":\"37\","
|
||||
+ "\"BIZ_DATA\":{\"acct_no\":\"123456789\",\"amt\":\"100000\"}"
|
||||
+ "}"
|
||||
+ "}";
|
||||
|
||||
/**
|
||||
* 표준 응답 JSON (dman_rspn_dvcd=R → MSG 블록 포함, 정상)
|
||||
*/
|
||||
private static final String RSP_JSON_OK =
|
||||
"{"
|
||||
+ "\"HEAD\":{"
|
||||
+ "\"nxgn_stnd_idfr\":\"JERA\","
|
||||
+ "\"guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"guid_prgs_no\":\"2\","
|
||||
+ "\"stnd_mesg_ver\":\"R10\","
|
||||
+ "\"ortr_guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"dman_rspn_dvcd\":\"R\","
|
||||
+ "\"if_id\":\"" + TEST_IF_ID + "\","
|
||||
+ "\"procs_rslt_dvcd\":\"S\","
|
||||
+ "\"tx_id\":\"" + TEST_TX_ID + "\","
|
||||
+ "\"chnl_tycd\":\"EAI\","
|
||||
+ "\"hmab_dvcd\":\"1\","
|
||||
+ "\"trnm_sys_dvcd\":\"EAI\","
|
||||
+ "\"sys_env_dvcd\":\"D\","
|
||||
+ "\"frst_mesg_dman_dt\":\"20260420\","
|
||||
+ "\"frst_mesg_dman_time\":\"120000000\","
|
||||
+ "\"mesg_rspn_dt\":\"20260420\","
|
||||
+ "\"mesg_rspn_time\":\"120100000\""
|
||||
+ "},"
|
||||
+ "\"MSG\":{"
|
||||
+ "\"msg_dvcd\":\"NM\","
|
||||
+ "\"msg_scop_len\":\"0\","
|
||||
+ "\"MAIN_MSG\":{"
|
||||
+ "\"outp_atrb_cd\":\"0\","
|
||||
+ "\"outp_msg_cd\":\"000000000000\","
|
||||
+ "\"outp_msg_ctnt\":\"정상처리\","
|
||||
+ "\"msg_list_rowcnt\":\"1\""
|
||||
+ "}"
|
||||
+ "},"
|
||||
+ "\"DATA\":{"
|
||||
+ "\"data_dvcd\":\"IO\","
|
||||
+ "\"data_scop_len\":\"37\","
|
||||
+ "\"BIZ_DATA\":{\"acct_no\":\"123456789\",\"bal\":\"900000\"}"
|
||||
+ "}"
|
||||
+ "}";
|
||||
|
||||
private StandardMessageManager manager;
|
||||
private InterfaceMapper mapper;
|
||||
private JsonReader jsonReader;
|
||||
private StandardMessageCoordinatorDJB coordinator;
|
||||
private ObjectMapper jacksonMapper;
|
||||
|
||||
@BeforeAll
|
||||
void setUpAll() throws Exception {
|
||||
PropManager mockPropManager = Mockito.mock(PropManager.class);
|
||||
Mockito.when(mockPropManager.getProperty(anyString(), anyString(), anyString()))
|
||||
.thenAnswer(new Answer<String>() {
|
||||
public String answer(InvocationOnMock inv) { return (String) inv.getArguments()[2]; }
|
||||
});
|
||||
|
||||
EAIServerManager mockServer = Mockito.mock(EAIServerManager.class);
|
||||
Mockito.when(mockServer.isPEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isSEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isMCI()).thenReturn(false);
|
||||
Mockito.when(mockServer.getLocalServerName()).thenReturn("TEST_SERVER");
|
||||
Mockito.when(mockServer.getGroupInstId()).thenReturn("TEST_INST");
|
||||
|
||||
EAIServiceMonitor mockMonitor = Mockito.mock(EAIServiceMonitor.class);
|
||||
Mockito.when(mockMonitor.isTimeOutCodes(anyString())).thenReturn(false);
|
||||
Mockito.when(mockMonitor.isBizErrorCodes(anyString())).thenReturn(false);
|
||||
|
||||
ApplicationContext mockCtx = Mockito.mock(ApplicationContext.class);
|
||||
Mockito.when(mockCtx.getBean(EAIServerManager.class)).thenReturn(mockServer);
|
||||
Mockito.when(mockCtx.getBean(PropManager.class)).thenReturn(mockPropManager);
|
||||
Mockito.when(mockCtx.getBean(EAIServiceMonitor.class)).thenReturn(mockMonitor);
|
||||
|
||||
Field ctxField = ApplicationContextProvider.class.getDeclaredField("context");
|
||||
ctxField.setAccessible(true);
|
||||
ctxField.set(null, mockCtx);
|
||||
|
||||
System.setProperty(StandardMessageManager.STANDARD_MESSAGE_CONFIG,
|
||||
"src/test/resources/standard-message-config-test.properties");
|
||||
manager = StandardMessageManager.getInstance();
|
||||
manager.init();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mapper = manager.getMapper();
|
||||
jsonReader = (JsonReader) manager.getReader("JSON");
|
||||
coordinator = new StandardMessageCoordinatorDJB();
|
||||
jacksonMapper = new ObjectMapper();
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 1. 표준 요청 JSON 파싱
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 요청JSON_파싱_HEAD_guid_40자_정확() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
|
||||
String guid = mapper.getGuid(msg);
|
||||
assertEquals(TEST_GUID, guid, "파싱된 guid가 입력 JSON과 다름");
|
||||
assertEquals(GUIDGeneratorDJB.GUID_LENGTH, guid.length(), "GUID 길이가 40자가 아님");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 요청JSON_파싱_HEAD_if_id_매핑() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
|
||||
assertEquals(TEST_IF_ID, msg.findItemValue("HEAD.if_id").trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 요청JSON_파싱_HEAD_dman_rspn_dvcd_S() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
|
||||
assertEquals("S", msg.findItemValue("HEAD.dman_rspn_dvcd"),
|
||||
"요청 방향은 dman_rspn_dvcd = S 여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 요청JSON_파싱_DATA_BIZ_DATA_JSON_오브젝트_저장() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
|
||||
String bizData = msg.findItemValue("DATA.BIZ_DATA");
|
||||
assertNotNull(bizData, "BIZ_DATA가 null");
|
||||
assertFalse(bizData.trim().isEmpty(), "BIZ_DATA가 공백");
|
||||
// JSON 오브젝트로 파싱 가능한지 검증
|
||||
JsonNode node = jacksonMapper.readTree(bizData);
|
||||
assertEquals("123456789", node.path("acct_no").asText(), "BIZ_DATA.acct_no 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 요청JSON_파싱_MSG_블록_사이즈_0_숨김() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
|
||||
// dman_rspn_dvcd=S → MSG 블록은 조건 미충족 → size=0(숨김)
|
||||
// JSON 직렬화 결과에 MSG 키가 없어야 함
|
||||
String json = msg.toJson();
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertFalse(root.has("MSG"), "요청 전문 JSON에 MSG 블록이 포함되면 안 됨");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 2. 표준 응답 JSON 파싱 (MSG 포함)
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 응답JSON_파싱_MSG_msg_dvcd_NM() throws Exception {
|
||||
StandardMessage msg = parseRsp();
|
||||
|
||||
assertEquals("NM", msg.findItemValue("MSG.msg_dvcd"),
|
||||
"정상 응답의 msg_dvcd는 NM이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 응답JSON_파싱_MSG_MAIN_MSG_outp_msg_ctnt_정상처리() throws Exception {
|
||||
StandardMessage msg = parseRsp();
|
||||
|
||||
assertEquals("정상처리", msg.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt"),
|
||||
"정상 응답의 outp_msg_ctnt는 '정상처리'여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 응답JSON_파싱_HEAD_procs_rslt_dvcd_S() throws Exception {
|
||||
StandardMessage msg = parseRsp();
|
||||
|
||||
assertEquals("S", msg.findItemValue("HEAD.procs_rslt_dvcd"),
|
||||
"정상 응답의 procs_rslt_dvcd는 S여야 함");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 3. 표준 메시지 수신 처리 — coordinateAfterCreateMessageByRule
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 표준수신_coordinateAfterCreateMessageByRule_새GUID_40자_재설정() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
|
||||
String newGuid = mapper.getGuid(msg);
|
||||
assertNotNull(newGuid, "coordinateAfterCreateMessageByRule 후 GUID null");
|
||||
assertEquals(GUIDGeneratorDJB.GUID_LENGTH, newGuid.length(), "재설정된 GUID가 40자가 아님");
|
||||
// Coordinator는 새 GUID를 생성하므로 원본과 달라야 함
|
||||
assertNotEquals(TEST_GUID, newGuid, "Coordinator가 기존 GUID를 그대로 사용함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 표준수신_coordinateAfterCreateMessageByRule_frst_mesg_dman_dt_오늘날짜() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
|
||||
String today = LocalDate.now().format(FMT_DATE);
|
||||
assertEquals(today, msg.findItemValue("HEAD.frst_mesg_dman_dt"),
|
||||
"frst_mesg_dman_dt는 오늘 날짜여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 표준수신_coordinateAfterCreateMessageByRule_trnm_sys_dvcd_EAI() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
|
||||
assertEquals("EAI", msg.findItemValue("HEAD.trnm_sys_dvcd"),
|
||||
"coordinateAfterCreateMessageByRule 후 trnm_sys_dvcd는 EAI여야 함");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 4. 표준 응답 생성 — coordinateBeforeResponse + JSON 직렬화
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 표준응답생성_coordinateBeforeResponse_mesg_rspn_dt_오늘날짜() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
|
||||
String today = LocalDate.now().format(FMT_DATE);
|
||||
assertEquals(today, msg.findItemValue("HEAD.mesg_rspn_dt"),
|
||||
"mesg_rspn_dt는 오늘 날짜여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 표준응답생성_coordinateBeforeResponse_mesg_rspn_time_9자리() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
|
||||
String time = msg.findItemValue("HEAD.mesg_rspn_time");
|
||||
assertNotNull(time, "mesg_rspn_time이 null");
|
||||
assertEquals(9, time.length(), "mesg_rspn_time은 HHmmssSSS(9자)여야 함: " + time);
|
||||
assertTrue(time.matches("\\d{9}"), "mesg_rspn_time 형식 오류");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 표준응답생성_JSON_직렬화_HEAD_포함() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
assertNotNull(json, "직렬화 JSON이 null");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertTrue(root.has("HEAD"), "직렬화 JSON에 HEAD 블록 없음");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 표준응답생성_JSON_직렬화_guid_값_보존() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
// Coordinator 호출 없이 파싱된 상태 그대로 직렬화
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertEquals(TEST_GUID, root.path("HEAD").path("guid").asText(),
|
||||
"직렬화 JSON의 guid가 원본과 다름");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 표준응답생성_JSON_직렬화_BIZ_DATA_보존() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
// BIZ_DATA는 JSON 문자열 또는 JSON 오브젝트로 들어갈 수 있음
|
||||
assertNotNull(root.path("DATA").get("BIZ_DATA"),
|
||||
"직렬화 JSON에 DATA.BIZ_DATA 없음");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 5. 비표준 수신 → 표준 정상 응답 생성
|
||||
// (외부 시스템에서 온 비표준 응답을 표준 성공 응답으로 변환)
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 비표준수신_coordinateAfterRecvNonStdSyncResponse_procs_rslt_dvcd_S() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
|
||||
assertEquals("S", msg.findItemValue("HEAD.procs_rslt_dvcd"),
|
||||
"비표준 정상수신 후 procs_rslt_dvcd는 S여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비표준수신_coordinateAfterRecvNonStdSyncResponse_MSG_msg_dvcd_NM() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
|
||||
assertEquals("NM", msg.findItemValue("MSG.msg_dvcd"),
|
||||
"비표준 정상수신 후 msg_dvcd는 NM이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비표준수신_정상응답_JSON_직렬화_NM_포함() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertTrue(root.has("MSG"), "정상응답 JSON에 MSG 블록 없음");
|
||||
assertEquals("NM", root.path("MSG").path("msg_dvcd").asText(),
|
||||
"정상응답 JSON의 msg_dvcd가 NM이 아님");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 비표준수신_정상응답_JSON_직렬화_outp_msg_ctnt_설정됨() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
String ctnt = root.path("MSG").path("MAIN_MSG").path("outp_msg_ctnt").asText();
|
||||
assertFalse(ctnt.isEmpty(), "정상응답 JSON의 outp_msg_ctnt가 설정되어야 함");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 6. 오류 응답 표준 생성 — coordinateSetStandardMessageError + JSON 직렬화
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void 오류응답_coordinateSetStandardMessageError_procs_rslt_dvcd_F() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
assertEquals("F", msg.findItemValue("HEAD.procs_rslt_dvcd"),
|
||||
"오류 응답의 procs_rslt_dvcd는 F여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 오류응답_JSON_직렬화_MSG_블록_포함() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertTrue(root.has("MSG"), "오류응답 JSON에 MSG 블록이 없음");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 오류응답_JSON_직렬화_msg_dvcd_EM() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertEquals("EM", root.path("MSG").path("msg_dvcd").asText(),
|
||||
"오류응답 JSON의 msg_dvcd가 EM이 아님");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 오류응답_JSON_직렬화_outp_atrb_cd_1_팝업() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertEquals("1",
|
||||
root.path("MSG").path("MAIN_MSG").path("outp_atrb_cd").asText(),
|
||||
"오류응답 JSON의 outp_atrb_cd가 1(팝업)이 아님");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 오류응답_JSON_직렬화_procs_rslt_dvcd_F_HEAD에_포함() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "테스트 오류");
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertEquals("F", root.path("HEAD").path("procs_rslt_dvcd").asText(),
|
||||
"오류응답 JSON의 HEAD.procs_rslt_dvcd가 F가 아님");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 7. JSON 왕복 일관성 (parse → serialize)
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void JSON_왕복_파싱후_직렬화_guid_일치() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
|
||||
assertEquals(TEST_GUID, root.path("HEAD").path("guid").asText(),
|
||||
"JSON 왕복 후 guid 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void JSON_왕복_파싱후_직렬화_if_id_일치() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
|
||||
assertEquals(TEST_IF_ID, root.path("HEAD").path("if_id").asText().trim(),
|
||||
"JSON 왕복 후 if_id 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void JSON_왕복_응답JSON_파싱후_직렬화_MSG_보존() throws Exception {
|
||||
StandardMessage msg = parseRsp();
|
||||
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
|
||||
assertTrue(root.has("MSG"), "응답 JSON 왕복 후 MSG 블록 소실");
|
||||
assertEquals("NM", root.path("MSG").path("msg_dvcd").asText(),
|
||||
"응답 JSON 왕복 후 msg_dvcd 불일치");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// helper
|
||||
// ================================================================
|
||||
|
||||
private StandardMessage parseReq() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
jsonReader.parse(msg, REQ_JSON);
|
||||
return msg;
|
||||
}
|
||||
|
||||
private StandardMessage parseRsp() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
jsonReader.parse(msg, RSP_JSON_OK);
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import com.eactive.eai.common.monitor.EAIServiceMonitor;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.parser.JsonReader;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
|
||||
/**
|
||||
* DJBank 표준전문 처리 스펙 전체 검증 테스트
|
||||
*
|
||||
* 요청 메시지 필수 처리 항목
|
||||
* - HEAD 레이아웃 기본값 (nxgn_stnd_idfr, stnd_mesg_ver, frst_trnm_sys_dvcd, trnm_sys_dvcd, ...)
|
||||
* - coordinateAfterCreateMessageByRule: GUID, 날짜, IP, MAC, ERP 분기
|
||||
* - ERP 채널: HEAD 지점코드 필드 + EZDATA 전자금융공통영역
|
||||
* - BIZ_DATA 임의 데이터
|
||||
*
|
||||
* 응답 메시지 필수 처리 항목
|
||||
* - coordinateBeforeResponse: guid_prgs_no+1, dman_rspn_dvcd=R, 응답일시
|
||||
* - 정상 MSG: NM, msg_list_rowcnt=0
|
||||
* - 오류 MSG: EM, msg_list_rowcnt=1, MSG_LIST outp_msg_desc/err_occu_loct
|
||||
* - BIZ_DATA 임의 데이터
|
||||
*/
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class StandardMessageSpecTest {
|
||||
|
||||
private static final String TEST_GUID =
|
||||
"20260420" + "120000" + "000" + "EAI" + "01" + "123456789012" + "000001";
|
||||
private static final String TEST_IF_ID = "IF_DJBTEST_SPEC";
|
||||
private static final String TEST_TX_ID = "TXSPEC000001";
|
||||
private static final DateTimeFormatter FMT_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
/** 일반(비ERP) 요청 JSON */
|
||||
private static final String REQ_JSON =
|
||||
"{"
|
||||
+ "\"HEAD\":{"
|
||||
+ "\"nxgn_stnd_idfr\":\"JERA\","
|
||||
+ "\"guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"guid_prgs_no\":\"1\","
|
||||
+ "\"stnd_mesg_ver\":\"R10\","
|
||||
+ "\"ortr_guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"dman_rspn_dvcd\":\"S\","
|
||||
+ "\"if_id\":\"" + TEST_IF_ID + "\","
|
||||
+ "\"procs_rslt_dvcd\":\"S\","
|
||||
+ "\"tx_id\":\"" + TEST_TX_ID + "\","
|
||||
+ "\"chnl_tycd\":\"EAI\","
|
||||
+ "\"hmab_dvcd\":\"1\","
|
||||
+ "\"trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"frst_trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"sys_env_dvcd\":\"D\","
|
||||
+ "\"frst_mesg_dman_dt\":\"20260420\","
|
||||
+ "\"frst_mesg_dman_time\":\"120000000\""
|
||||
+ "},"
|
||||
+ "\"DATA\":{"
|
||||
+ "\"data_dvcd\":\"IO\","
|
||||
+ "\"data_scop_len\":\"00000037\","
|
||||
+ "\"BIZ_DATA\":{\"acct_no\":\"987654321\",\"amt\":\"500000\"}"
|
||||
+ "}"
|
||||
+ "}";
|
||||
|
||||
/** ERP 채널 요청 JSON — corp_tlwn_virt_brcd=ERP */
|
||||
private static final String ERP_REQ_JSON =
|
||||
"{"
|
||||
+ "\"HEAD\":{"
|
||||
+ "\"nxgn_stnd_idfr\":\"JERA\","
|
||||
+ "\"guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"guid_prgs_no\":\"1\","
|
||||
+ "\"stnd_mesg_ver\":\"R10\","
|
||||
+ "\"ortr_guid\":\"" + TEST_GUID + "\","
|
||||
+ "\"dman_rspn_dvcd\":\"S\","
|
||||
+ "\"if_id\":\"" + TEST_IF_ID + "\","
|
||||
+ "\"procs_rslt_dvcd\":\"S\","
|
||||
+ "\"tx_id\":\"" + TEST_TX_ID + "\","
|
||||
+ "\"chnl_tycd\":\"EAI\","
|
||||
+ "\"hmab_dvcd\":\"1\","
|
||||
+ "\"corp_tlwn_virt_brcd\":\"ERP\","
|
||||
+ "\"trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"frst_trnm_sys_dvcd\":\"OPA\","
|
||||
+ "\"sys_env_dvcd\":\"D\","
|
||||
+ "\"frst_mesg_dman_dt\":\"20260420\","
|
||||
+ "\"frst_mesg_dman_time\":\"120000000\""
|
||||
+ "},"
|
||||
+ "\"EZDATA\":{"
|
||||
+ "\"elfn_bnkn_dvcd\":\"01\","
|
||||
+ "\"usr_no\":\"USR0000000000001\""
|
||||
+ "},"
|
||||
+ "\"DATA\":{"
|
||||
+ "\"data_dvcd\":\"IO\","
|
||||
+ "\"data_scop_len\":\"00000037\","
|
||||
+ "\"BIZ_DATA\":{\"acct_no\":\"111222333\",\"bal\":\"1000000\"}"
|
||||
+ "}"
|
||||
+ "}";
|
||||
|
||||
private StandardMessageManager manager;
|
||||
private InterfaceMapper mapper;
|
||||
private JsonReader jsonReader;
|
||||
private StandardMessageCoordinatorDJB coordinator;
|
||||
private ObjectMapper jacksonMapper;
|
||||
|
||||
@BeforeAll
|
||||
void setUpAll() throws Exception {
|
||||
PropManager mockPropManager = Mockito.mock(PropManager.class);
|
||||
Mockito.when(mockPropManager.getProperty(anyString(), anyString(), anyString()))
|
||||
.thenAnswer(new Answer<String>() {
|
||||
public String answer(InvocationOnMock inv) { return (String) inv.getArguments()[2]; }
|
||||
});
|
||||
|
||||
EAIServerManager mockServer = Mockito.mock(EAIServerManager.class);
|
||||
Mockito.when(mockServer.isPEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isSEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isMCI()).thenReturn(false);
|
||||
Mockito.when(mockServer.getLocalServerName()).thenReturn("TEST_SERVER");
|
||||
Mockito.when(mockServer.getGroupInstId()).thenReturn("TEST_INST");
|
||||
|
||||
EAIServiceMonitor mockMonitor = Mockito.mock(EAIServiceMonitor.class);
|
||||
Mockito.when(mockMonitor.isTimeOutCodes(anyString())).thenReturn(false);
|
||||
Mockito.when(mockMonitor.isBizErrorCodes(anyString())).thenReturn(false);
|
||||
|
||||
ApplicationContext mockCtx = Mockito.mock(ApplicationContext.class);
|
||||
Mockito.when(mockCtx.getBean(EAIServerManager.class)).thenReturn(mockServer);
|
||||
Mockito.when(mockCtx.getBean(PropManager.class)).thenReturn(mockPropManager);
|
||||
Mockito.when(mockCtx.getBean(EAIServiceMonitor.class)).thenReturn(mockMonitor);
|
||||
|
||||
Field ctxField = ApplicationContextProvider.class.getDeclaredField("context");
|
||||
ctxField.setAccessible(true);
|
||||
ctxField.set(null, mockCtx);
|
||||
|
||||
System.setProperty(StandardMessageManager.STANDARD_MESSAGE_CONFIG,
|
||||
"src/test/resources/standard-message-config-test.properties");
|
||||
manager = StandardMessageManager.getInstance();
|
||||
manager.init();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mapper = manager.getMapper();
|
||||
jsonReader = (JsonReader) manager.getReader("JSON");
|
||||
coordinator = new StandardMessageCoordinatorDJB();
|
||||
jacksonMapper = new ObjectMapper();
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 1. 요청 HEAD — 레이아웃 기본값 검증
|
||||
// ================================================================
|
||||
|
||||
@Nested
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class 요청HEAD_레이아웃_기본값 {
|
||||
|
||||
@Test
|
||||
void nxgn_stnd_idfr_기본값_JERA() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertEquals("JERA", msg.findItemValue("HEAD.nxgn_stnd_idfr"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stnd_mesg_ver_기본값_R10() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertEquals("R10", msg.findItemValue("HEAD.stnd_mesg_ver"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void frst_trnm_sys_dvcd_기본값_OPA() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertEquals("OPA", msg.findItemValue("HEAD.frst_trnm_sys_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void trnm_sys_dvcd_기본값_EAI() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertEquals("EAI", msg.findItemValue("HEAD.trnm_sys_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dman_rspn_dvcd_기본값_S() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertEquals("S", msg.findItemValue("HEAD.dman_rspn_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sys_env_dvcd_기본값_D() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertEquals("D", msg.findItemValue("HEAD.sys_env_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tx_tycd_기본값_O() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertEquals("O", msg.findItemValue("HEAD.tx_tycd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void synz_dvcd_기본값_S() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertEquals("S", msg.findItemValue("HEAD.synz_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chnl_tycd_기본값_EAI() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertEquals("EAI", msg.findItemValue("HEAD.chnl_tycd"));
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 2. 요청 처리 — coordinateAfterCreateMessageByRule
|
||||
// ================================================================
|
||||
|
||||
@Nested
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class 요청처리_coordinateAfterCreateMessageByRule {
|
||||
|
||||
@Test
|
||||
void GUID_40자_생성() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
String guid = mapper.getGuid(msg);
|
||||
assertNotNull(guid);
|
||||
assertEquals(GUIDGeneratorDJB.GUID_LENGTH, guid.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void GUID_기존값_갱신() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertNotEquals(TEST_GUID, mapper.getGuid(msg), "새 GUID가 생성되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void guid_prgs_no_초기값_001() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertEquals("001", mapper.getGuidSeq(msg));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ortr_guid_equals_guid() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertEquals(mapper.getGuid(msg), mapper.getOrgGuid(msg), "ortr_guid는 guid와 동일해야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void frst_mesg_dman_dt_오늘날짜() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertEquals(LocalDate.now().format(FMT_DATE), msg.findItemValue("HEAD.frst_mesg_dman_dt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void frst_mesg_dman_time_9자리_숫자() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
String time = msg.findItemValue("HEAD.frst_mesg_dman_time");
|
||||
assertNotNull(time);
|
||||
assertEquals(9, time.length(), "HHmmssSSS 9자리여야 함");
|
||||
assertTrue(time.matches("\\d{9}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void trnm_sys_dvcd_EAI_설정() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertEquals("EAI", msg.findItemValue("HEAD.trnm_sys_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sys_env_dvcd_D_개발환경() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
String env = msg.findItemValue("HEAD.sys_env_dvcd");
|
||||
assertTrue("D".equals(env) || "T".equals(env) || "P".equals(env),
|
||||
"sys_env_dvcd는 D/T/P 중 하나여야 함: " + env);
|
||||
}
|
||||
|
||||
@Test
|
||||
void frst_trnm_ipad_설정됨() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
String ip = msg.findItemValue("HEAD.frst_trnm_ipad");
|
||||
assertFalse(ip == null || ip.trim().isEmpty(), "frst_trnm_ipad가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void frst_trnm_ipv4_addr_설정됨() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
String ip = msg.findItemValue("HEAD.frst_trnm_ipv4_addr");
|
||||
assertFalse(ip == null || ip.trim().isEmpty(), "frst_trnm_ipv4_addr가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void frst_trnm_mac_설정됨() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
// MAC 주소는 가상환경에서 null일 수 있으므로 존재만 확인
|
||||
assertNotNull(msg.findItem("HEAD.frst_trnm_mac"), "frst_trnm_mac 필드가 없음");
|
||||
}
|
||||
|
||||
@Test
|
||||
void BIZ_DATA_임의값_처리_후_유지() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
String bizData = msg.findItemValue("DATA.BIZ_DATA");
|
||||
assertNotNull(bizData);
|
||||
assertFalse(bizData.trim().isEmpty(), "BIZ_DATA가 유지되어야 함");
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 3. ERP 채널 — HEAD 지점코드 + EZDATA 전자금융공통영역
|
||||
// ================================================================
|
||||
|
||||
@Nested
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class ERP채널_처리 {
|
||||
|
||||
@Test
|
||||
void HEAD_tx_cmgr_cd_S004() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertEquals("S004", msg.findItemValue("HEAD.tx_cmgr_cd").trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void HEAD_mgmt_brcd_260() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertEquals("260", msg.findItemValue("HEAD.mgmt_brcd").trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void HEAD_tx_brcd_260() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertEquals("260", msg.findItemValue("HEAD.tx_brcd").trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void HEAD_insl_brcd_260() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertEquals("260", msg.findItemValue("HEAD.insl_brcd").trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void HEAD_blng_brcd_260() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertEquals("260", msg.findItemValue("HEAD.blng_brcd").trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_elfn_bnkn_dvcd_10() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertEquals("10", msg.findItemValue("EZDATA.elfn_bnkn_dvcd").trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_svr_tx_seqno_10자리_숫자() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
String seqno = msg.findItemValue("EZDATA.svr_tx_seqno");
|
||||
assertNotNull(seqno);
|
||||
String trimmed = seqno.trim();
|
||||
assertTrue(trimmed.matches("\\d{1,10}"), "svr_tx_seqno는 unix timestamp 숫자여야 함: " + trimmed);
|
||||
assertTrue(Long.parseLong(trimmed) > 0, "svr_tx_seqno는 양수여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_elfn_mac_설정됨() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertNotNull(msg.findItem("EZDATA.elfn_mac"), "EZDATA.elfn_mac 필드가 없음");
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_pc_ofcl_ipad_설정됨() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
String ip = msg.findItemValue("EZDATA.pc_ofcl_ipad");
|
||||
assertFalse(ip == null || ip.trim().isEmpty(), "EZDATA.pc_ofcl_ipad가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_pc_prvat_ipad_설정됨() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
String ip = msg.findItemValue("EZDATA.pc_prvat_ipad");
|
||||
assertFalse(ip == null || ip.trim().isEmpty(), "EZDATA.pc_prvat_ipad가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void EZDATA_elfn_spr_fild_ERP() throws Exception {
|
||||
StandardMessage msg = parseErpReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
assertEquals("ERP", msg.findItemValue("EZDATA.elfn_spr_fild").trim());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 4. 응답 처리 — coordinateBeforeResponse
|
||||
// ================================================================
|
||||
|
||||
@Nested
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class 응답처리_coordinateBeforeResponse {
|
||||
|
||||
@Test
|
||||
void guid_prgs_no_1_증가() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
// 파싱 후 guid_prgs_no = 1
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
String seq = mapper.getGuidSeq(msg);
|
||||
assertEquals("002", seq, "응답 시 guid_prgs_no는 002여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void dman_rspn_dvcd_R_응답설정() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertEquals("R", root.path("HEAD").path("dman_rspn_dvcd").asText(),
|
||||
"응답 시 dman_rspn_dvcd는 R이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mesg_rspn_dt_오늘날짜() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
assertEquals(LocalDate.now().format(FMT_DATE), msg.findItemValue("HEAD.mesg_rspn_dt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mesg_rspn_time_9자리_숫자() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
String time = msg.findItemValue("HEAD.mesg_rspn_time");
|
||||
assertNotNull(time);
|
||||
assertEquals(9, time.length());
|
||||
assertTrue(time.matches("\\d{9}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 요청_HEAD_guid_응답에서_유지() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateAfterCreateMessageByRule(msg, null, null);
|
||||
String guidAfterReq = mapper.getGuid(msg);
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
assertEquals(guidAfterReq, mapper.getGuid(msg), "응답 시 guid가 변경되면 안 됨");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 요청_HEAD_if_id_응답에서_유지() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
assertEquals(TEST_IF_ID, msg.findItemValue("HEAD.if_id").trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 요청_HEAD_tx_id_응답에서_유지() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
assertEquals(TEST_TX_ID, msg.findItemValue("HEAD.tx_id").trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
void BIZ_DATA_임의값_응답에서_유지() throws Exception {
|
||||
StandardMessage msg = parseReq();
|
||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertNotNull(root.path("DATA").get("BIZ_DATA"), "응답에서 BIZ_DATA가 유지되어야 함");
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 5. 정상 응답 MSG — coordinateAfterRecvNonStdSyncResponse
|
||||
// ================================================================
|
||||
|
||||
@Nested
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class 정상응답_MSG {
|
||||
|
||||
@Test
|
||||
void procs_rslt_dvcd_S() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
assertEquals("S", msg.findItemValue("HEAD.procs_rslt_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void msg_dvcd_NM() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
assertEquals("NM", msg.findItemValue("MSG.msg_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void msg_list_rowcnt_0() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
String rowcnt = msg.findItemValue("MSG.MAIN_MSG.msg_list_rowcnt");
|
||||
// NUMBER 타입: "00000" → trim 후 "" 또는 "0" 모두 0을 의미함
|
||||
String normalized = (rowcnt == null || rowcnt.trim().isEmpty()) ? "0" : rowcnt.trim();
|
||||
assertEquals(0, Integer.parseInt(normalized), "정상 응답 msg_list_rowcnt는 0이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void outp_atrb_cd_0() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
assertEquals("0", msg.findItemValue("MSG.MAIN_MSG.outp_atrb_cd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void outp_msg_cd_정상코드() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
String msgCd = msg.findItemValue("MSG.MAIN_MSG.outp_msg_cd");
|
||||
assertFalse(msgCd == null || msgCd.trim().isEmpty(), "outp_msg_cd가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void outp_msg_ctnt_정상처리() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
String ctnt = msg.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt");
|
||||
assertFalse(ctnt == null || ctnt.trim().isEmpty(), "outp_msg_ctnt가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void JSON_직렬화_MSG_NM_포함() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertTrue(root.has("MSG"), "정상응답 JSON에 MSG 블록 없음");
|
||||
assertEquals("NM", root.path("MSG").path("msg_dvcd").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void BIZ_DATA_임의값_설정_가능() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
msg.setData("DATA.BIZ_DATA", "{\"result\":\"OK\"}");
|
||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||
String bizData = msg.findItemValue("DATA.BIZ_DATA");
|
||||
assertFalse(bizData == null || bizData.trim().isEmpty(), "BIZ_DATA가 설정된 상태로 유지되어야 함");
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// 6. 오류 응답 MSG — coordinateSetStandardMessageError
|
||||
// ================================================================
|
||||
|
||||
@Nested
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class 오류응답_MSG {
|
||||
|
||||
@Test
|
||||
void procs_rslt_dvcd_F() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
assertEquals("F", msg.findItemValue("HEAD.procs_rslt_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dman_rspn_dvcd_R() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
assertEquals("R", msg.findItemValue("HEAD.dman_rspn_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void msg_dvcd_EM() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
assertEquals("EM", msg.findItemValue("MSG.msg_dvcd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void outp_atrb_cd_1_팝업() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
assertEquals("1", msg.findItemValue("MSG.MAIN_MSG.outp_atrb_cd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void msg_list_rowcnt_1() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
String rowcnt = msg.findItemValue("MSG.MAIN_MSG.msg_list_rowcnt");
|
||||
String normalized = (rowcnt == null || rowcnt.trim().isEmpty()) ? "0" : rowcnt.trim();
|
||||
assertEquals(1, Integer.parseInt(normalized), "오류응답 msg_list_rowcnt는 1이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void outp_msg_cd_에러코드_설정됨() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
String msgCd = msg.findItemValue("MSG.MAIN_MSG.outp_msg_cd");
|
||||
assertFalse(msgCd == null || msgCd.trim().isEmpty(), "outp_msg_cd가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void outp_msg_ctnt_에러메시지_설정됨() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
String ctnt = msg.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt");
|
||||
assertFalse(ctnt == null || ctnt.trim().isEmpty(), "outp_msg_ctnt가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void MSG_LIST_outp_msg_cd_설정됨() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
JsonNode msgList = root.path("MSG").path("MSG_LIST");
|
||||
assertFalse(msgList.isMissingNode() || msgList.isEmpty(),
|
||||
"MSG_LIST에 1건이 있어야 함");
|
||||
String cd = msgList.get(0).path("outp_msg_cd").asText();
|
||||
assertFalse(cd.isEmpty(), "MSG_LIST[0].outp_msg_cd가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void MSG_LIST_outp_msg_ctnt_설정됨() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
String ctnt = root.path("MSG").path("MSG_LIST").get(0).path("outp_msg_ctnt").asText();
|
||||
assertFalse(ctnt.isEmpty(), "MSG_LIST[0].outp_msg_ctnt가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void MSG_LIST_outp_msg_desc_설정됨() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류설명");
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
String desc = root.path("MSG").path("MSG_LIST").get(0).path("outp_msg_desc").asText();
|
||||
assertFalse(desc.isEmpty(), "MSG_LIST[0].outp_msg_desc가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void MSG_LIST_err_occu_loct_설정됨() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
String loct = root.path("MSG").path("MSG_LIST").get(0).path("err_occu_loct").asText();
|
||||
assertFalse(loct.isEmpty(), "MSG_LIST[0].err_occu_loct가 설정되어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void JSON_직렬화_MSG_EM_포함() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||
JsonNode root = jacksonMapper.readTree(json);
|
||||
assertTrue(root.has("MSG"), "오류응답 JSON에 MSG 블록 없음");
|
||||
assertEquals("EM", root.path("MSG").path("msg_dvcd").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void BIZ_DATA_임의값_설정_가능() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
msg.setData("DATA.BIZ_DATA", "{\"error_info\":\"test\"}");
|
||||
coordinator.coordinateSetStandardMessageError(msg, mapper, "RECEAICMM999", "오류발생");
|
||||
String bizData = msg.findItemValue("DATA.BIZ_DATA");
|
||||
assertFalse(bizData == null || bizData.trim().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// helper
|
||||
// ================================================================
|
||||
|
||||
private StandardMessage parseReq() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
jsonReader.parse(msg, REQ_JSON);
|
||||
return msg;
|
||||
}
|
||||
|
||||
private StandardMessage parseErpReq() throws Exception {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
jsonReader.parse(msg, ERP_REQ_JSON);
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package com.eactive.eai.inbound.processor;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import com.eactive.eai.adapter.Keys;
|
||||
import com.eactive.eai.common.monitor.EAIServiceMonitor;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.restrict.RestrictInfoVO;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
/**
|
||||
* RequestProcessor 단위테스트 — StandardMessageManager/Coordinator 연동 검증
|
||||
*
|
||||
* 전략:
|
||||
* - DB/Spring 없는 환경에서 Mockito + 리플렉션으로 ApplicationContextProvider 주입
|
||||
* - RequestProcessor 클래스 로드 전(static 블록 실행 전)에 mock ApplicationContext를 주입
|
||||
* - private 메서드(getInboundErrorResponseForStandard, getInboundErrorResponse)는
|
||||
* 리플렉션으로 직접 호출하여 Coordinator 연동 결과를 검증
|
||||
*/
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class RequestProcessorStdMsgTest {
|
||||
|
||||
private StandardMessageManager stdMsgManager;
|
||||
|
||||
@BeforeAll
|
||||
void setUpAll() throws Exception {
|
||||
// ① PropManager mock — STDMessageErrorKeys 정적 초기화용 (def 반환)
|
||||
PropManager mockPropManager = Mockito.mock(PropManager.class);
|
||||
Mockito.when(mockPropManager.getProperty(anyString(), anyString(), anyString()))
|
||||
.thenAnswer(new Answer<String>() {
|
||||
public String answer(InvocationOnMock inv) {
|
||||
return (String) inv.getArguments()[2];
|
||||
}
|
||||
});
|
||||
|
||||
// ② EAIServerManager mock — static 블록의 getLocalServerName/getGroupInstId 대응
|
||||
EAIServerManager mockServer = Mockito.mock(EAIServerManager.class);
|
||||
Mockito.when(mockServer.isPEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isSEAIServer()).thenReturn(false);
|
||||
Mockito.when(mockServer.isMCI()).thenReturn(false);
|
||||
Mockito.when(mockServer.getLocalServerName()).thenReturn("TEST_SERVER");
|
||||
Mockito.when(mockServer.getGroupInstId()).thenReturn("TEST_INST");
|
||||
|
||||
// ③ EAIServiceMonitor mock — MessageUtil.getTobeCode() 사용
|
||||
EAIServiceMonitor mockMonitor = Mockito.mock(EAIServiceMonitor.class);
|
||||
Mockito.when(mockMonitor.isTimeOutCodes(anyString())).thenReturn(false);
|
||||
Mockito.when(mockMonitor.isBizErrorCodes(anyString())).thenReturn(false);
|
||||
|
||||
// ④ ApplicationContext mock
|
||||
ApplicationContext mockCtx = Mockito.mock(ApplicationContext.class);
|
||||
Mockito.when(mockCtx.getBean(EAIServerManager.class)).thenReturn(mockServer);
|
||||
Mockito.when(mockCtx.getBean(PropManager.class)).thenReturn(mockPropManager);
|
||||
Mockito.when(mockCtx.getBean(EAIServiceMonitor.class)).thenReturn(mockMonitor);
|
||||
|
||||
// ⑤ ApplicationContextProvider.context(static 필드)에 mock 주입
|
||||
Field ctxField = ApplicationContextProvider.class.getDeclaredField("context");
|
||||
ctxField.setAccessible(true);
|
||||
ctxField.set(null, mockCtx);
|
||||
|
||||
// ⑥ StandardMessageManager 초기화
|
||||
System.setProperty(StandardMessageManager.STANDARD_MESSAGE_CONFIG,
|
||||
"src/test/resources/standard-message-config-test.properties");
|
||||
stdMsgManager = StandardMessageManager.getInstance();
|
||||
stdMsgManager.init();
|
||||
|
||||
// ⑦ RequestProcessor 클래스 강제 로드 — mock 주입 완료 후 static 블록 안전 실행
|
||||
Class.forName("com.eactive.eai.inbound.processor.RequestProcessor");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// getInboundErrorResponseForStandard (private) — Coordinator 연동 검증
|
||||
//
|
||||
// 이 메서드 내부 흐름:
|
||||
// mapper.nextGuidSeq(msg)
|
||||
// mapper.setSendRecvDivision(msg, R)
|
||||
// standardManager.getMessageCoordinator().coordinateSetStandardMessageError(...)
|
||||
// standardMessage.getDataString(messageType, charset)
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void getInboundErrorResponseForStandard_procs_rslt_dvcd_F_설정() throws Exception {
|
||||
StandardMessage msg = stdMsgManager.getStandardMessage();
|
||||
InterfaceMapper mapper = stdMsgManager.getMapper();
|
||||
|
||||
callGetInboundErrorResponseForStandard(msg, mapper, "RECEAICMM999", "테스트 오류", "euc-kr", "FLAT");
|
||||
|
||||
assertEquals("F", msg.findItemValue("HEAD.procs_rslt_dvcd"),
|
||||
"오류 응답 생성 시 procs_rslt_dvcd는 F여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInboundErrorResponseForStandard_dman_rspn_dvcd_R_설정() throws Exception {
|
||||
StandardMessage msg = stdMsgManager.getStandardMessage();
|
||||
InterfaceMapper mapper = stdMsgManager.getMapper();
|
||||
|
||||
callGetInboundErrorResponseForStandard(msg, mapper, "RECEAICMM999", "테스트 오류", "euc-kr", "FLAT");
|
||||
|
||||
assertEquals(STDMessageKeys.SEND_RECV_CD_RECV, msg.findItemValue("HEAD.dman_rspn_dvcd"),
|
||||
"오류 응답 생성 시 dman_rspn_dvcd는 R이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInboundErrorResponseForStandard_MSG_msg_dvcd_EM_설정() throws Exception {
|
||||
StandardMessage msg = stdMsgManager.getStandardMessage();
|
||||
InterfaceMapper mapper = stdMsgManager.getMapper();
|
||||
|
||||
callGetInboundErrorResponseForStandard(msg, mapper, "RECEAICMM999", "테스트 오류", "euc-kr", "FLAT");
|
||||
|
||||
assertEquals("EM", msg.findItemValue("MSG.msg_dvcd"),
|
||||
"오류 응답 생성 시 msg_dvcd는 EM이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInboundErrorResponseForStandard_outp_atrb_cd_1_설정() throws Exception {
|
||||
StandardMessage msg = stdMsgManager.getStandardMessage();
|
||||
InterfaceMapper mapper = stdMsgManager.getMapper();
|
||||
|
||||
callGetInboundErrorResponseForStandard(msg, mapper, "RECEAICMM999", "테스트 오류", "euc-kr", "FLAT");
|
||||
|
||||
assertEquals("1", msg.findItemValue("MSG.MAIN_MSG.outp_atrb_cd"),
|
||||
"오류 시 outp_atrb_cd는 1(팝업)이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInboundErrorResponseForStandard_outp_msg_cd_설정됨() throws Exception {
|
||||
StandardMessage msg = stdMsgManager.getStandardMessage();
|
||||
InterfaceMapper mapper = stdMsgManager.getMapper();
|
||||
|
||||
callGetInboundErrorResponseForStandard(msg, mapper, "RECEAICMM999", "테스트 오류", "euc-kr", "FLAT");
|
||||
|
||||
String errCode = msg.findItemValue("MSG.MAIN_MSG.outp_msg_cd");
|
||||
assertNotNull(errCode, "outp_msg_cd가 null");
|
||||
assertFalse(errCode.trim().isEmpty(), "outp_msg_cd가 공백");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInboundErrorResponseForStandard_예외없이_완료() {
|
||||
assertDoesNotThrow(() -> {
|
||||
StandardMessage msg = stdMsgManager.getStandardMessage();
|
||||
InterfaceMapper mapper = stdMsgManager.getMapper();
|
||||
callGetInboundErrorResponseForStandard(msg, mapper, "RECEAICMM999", "테스트 오류", "euc-kr", "FLAT");
|
||||
}, "getInboundErrorResponseForStandard 실행 중 예외 발생");
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// getInboundErrorResponse (private) — IF_STANDARD 분기 검증
|
||||
//
|
||||
// IF_STANDARD 분기 흐름:
|
||||
// coordinateBeforeInboundErrorResponse(standardMessage) ← StandardMessageCoordinatorDJB 호출
|
||||
// getInboundErrorResponseForStandard(...) ← 위 검증된 메서드
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void getInboundErrorResponse_IF_STANDARD_procs_rslt_dvcd_F_설정() throws Exception {
|
||||
StandardMessage msg = stdMsgManager.getStandardMessage();
|
||||
InterfaceMapper mapper = stdMsgManager.getMapper();
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(Processor.STD_MESSAGE, Keys.IF_STANDARD);
|
||||
prop.setProperty(Processor.MESSAGE_TYPE, "FLAT");
|
||||
|
||||
callGetInboundErrorResponse(prop, msg, mapper, "RECEAICMM999", "테스트 오류", "euc-kr");
|
||||
|
||||
assertEquals("F", msg.findItemValue("HEAD.procs_rslt_dvcd"),
|
||||
"IF_STANDARD 오류응답 후 procs_rslt_dvcd는 F여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInboundErrorResponse_IF_STANDARD_msg_dvcd_EM_설정() throws Exception {
|
||||
StandardMessage msg = stdMsgManager.getStandardMessage();
|
||||
InterfaceMapper mapper = stdMsgManager.getMapper();
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(Processor.STD_MESSAGE, Keys.IF_STANDARD);
|
||||
prop.setProperty(Processor.MESSAGE_TYPE, "FLAT");
|
||||
|
||||
callGetInboundErrorResponse(prop, msg, mapper, "RECEAICMM999", "테스트 오류", "euc-kr");
|
||||
|
||||
assertEquals("EM", msg.findItemValue("MSG.msg_dvcd"),
|
||||
"IF_STANDARD 오류응답 후 msg_dvcd는 EM이어야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInboundErrorResponse_standardMessage_null_비표준_예외없음() {
|
||||
Properties prop = new Properties();
|
||||
prop.setProperty(Processor.STD_MESSAGE, "X"); // 비표준 → ExceptionHandler.handle(errMsg)
|
||||
prop.setProperty(Processor.MESSAGE_TYPE, "FLAT");
|
||||
|
||||
assertDoesNotThrow(() ->
|
||||
callGetInboundErrorResponse(prop, null, null, "RECEAICMM999", "테스트 오류", "euc-kr"),
|
||||
"standardMessage null 비표준 케이스에서 예외 발생"
|
||||
);
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// checkRestrictTime (public)
|
||||
// ================================================================
|
||||
|
||||
@Test
|
||||
void checkRestrictTime_start_end_미설정_항상_true() throws Exception {
|
||||
RequestProcessor rp = new RequestProcessor();
|
||||
RestrictInfoVO rVo = new RestrictInfoVO();
|
||||
// params 길이 < 6 → start/end 모두 null → true 반환
|
||||
rVo.setEAICtrlDsticCtnt("a|b|c|d|e");
|
||||
|
||||
assertTrue(rp.checkRestrictTime(rVo), "start/end 미설정 시 true 기대");
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkRestrictTime_start_0000_end_0000_항상_true() throws Exception {
|
||||
RequestProcessor rp = new RequestProcessor();
|
||||
RestrictInfoVO rVo = new RestrictInfoVO();
|
||||
// end="0000" 이면 코드상 종료시간 체크 블록 건너뜀 → start 0000 이후면 true
|
||||
rVo.setEAICtrlDsticCtnt("a|b|c|d|e|0000|0000");
|
||||
|
||||
assertTrue(rp.checkRestrictTime(rVo), "start=0000/end=0000 설정 시 true 기대");
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkRestrictTime_end_0001_현재시간_이후_false() throws Exception {
|
||||
RequestProcessor rp = new RequestProcessor();
|
||||
RestrictInfoVO rVo = new RestrictInfoVO();
|
||||
// 종료시간이 00:01이면 00:01 이후(= 거의 항상)는 false 반환
|
||||
// 단, 자정(00:00) 실행 시에는 통과 — 허용 오차
|
||||
rVo.setEAICtrlDsticCtnt("a|b|c|d|e|0000|0001");
|
||||
|
||||
java.util.Calendar cal = java.util.Calendar.getInstance();
|
||||
int hour = cal.get(java.util.Calendar.HOUR_OF_DAY);
|
||||
int minute = cal.get(java.util.Calendar.MINUTE);
|
||||
|
||||
boolean result = rp.checkRestrictTime(rVo);
|
||||
// 00:01 이후(99% 이상의 시간)에는 false여야 함
|
||||
if (hour > 0 || minute >= 1) {
|
||||
assertFalse(result, "종료시간(00:01) 이후에는 false여야 함");
|
||||
}
|
||||
// 정확히 00:00에 실행되면 검증 생략 (허용)
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// helper
|
||||
// ================================================================
|
||||
|
||||
private Object callGetInboundErrorResponseForStandard(
|
||||
StandardMessage msg, InterfaceMapper mapper,
|
||||
String errCode, String errMsg, String charset, String messageType) throws Exception {
|
||||
Method method = RequestProcessor.class.getDeclaredMethod(
|
||||
"getInboundErrorResponseForStandard",
|
||||
StandardMessage.class, InterfaceMapper.class,
|
||||
String.class, String.class, String.class, String.class);
|
||||
method.setAccessible(true);
|
||||
try {
|
||||
return method.invoke(new RequestProcessor(), msg, mapper, errCode, errMsg, charset, messageType);
|
||||
} catch (InvocationTargetException e) {
|
||||
throw (Exception) e.getCause();
|
||||
}
|
||||
}
|
||||
|
||||
private Object callGetInboundErrorResponse(
|
||||
Properties prop, StandardMessage msg, InterfaceMapper mapper,
|
||||
String errCode, String errMsg, String charset) throws Exception {
|
||||
Method method = RequestProcessor.class.getDeclaredMethod(
|
||||
"getInboundErrorResponse",
|
||||
Properties.class, StandardMessage.class, InterfaceMapper.class,
|
||||
String.class, String.class, String.class);
|
||||
method.setAccessible(true);
|
||||
try {
|
||||
return method.invoke(new RequestProcessor(), prop, msg, mapper, errCode, errMsg, charset);
|
||||
} catch (InvocationTargetException e) {
|
||||
throw (Exception) e.getCause();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.eactive.eai.message.manager;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
|
||||
import com.eactive.eai.custom.message.GUIDGeneratorDJB;
|
||||
import com.eactive.eai.custom.message.InterfaceMapperDJB;
|
||||
import com.eactive.eai.custom.message.StandardMessageCoordinatorDJB;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.parser.StandardReader;
|
||||
|
||||
/**
|
||||
* StandardMessageManager.init() 단위테스트
|
||||
*
|
||||
* Singleton 특성상 getInstance()로 접근, init()을 직접 호출하여 검증.
|
||||
* System.property를 미설정 → 클래스패스의 standard-message-config.properties 로드.
|
||||
*/
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class StandardMessageManagerInitTest {
|
||||
|
||||
private StandardMessageManager manager;
|
||||
|
||||
@BeforeAll
|
||||
void setUp() throws Exception {
|
||||
// 테스트용 config: layout.file.path에 src/main/resources 상대경로 사용
|
||||
// (StandardMessageUtil.generateMessageFromCsvFile은 파일시스템 상대경로로 읽음)
|
||||
System.setProperty(StandardMessageManager.STANDARD_MESSAGE_CONFIG,
|
||||
"src/test/resources/standard-message-config-test.properties");
|
||||
manager = StandardMessageManager.getInstance();
|
||||
manager.init();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 1. 표준전문 레이아웃 (StandardMessage)
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void standardMessage_정상_로드() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertNotNull(msg, "StandardMessage가 null — CSV 로드 실패");
|
||||
}
|
||||
|
||||
@Test
|
||||
void standardMessage_HEAD_블록_존재() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertNotNull(msg.findItem("HEAD"), "HEAD 블록 없음");
|
||||
}
|
||||
|
||||
@Test
|
||||
void standardMessage_HEAD_guid_40자() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertEquals(GUIDGeneratorDJB.GUID_LENGTH, msg.findItem("HEAD.guid").getLength(),
|
||||
"HEAD.guid 길이는 40자여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void standardMessage_HEAD_if_id_30자() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertEquals(30, msg.findItem("HEAD.if_id").getLength(),
|
||||
"HEAD.if_id 길이는 30자여야 함");
|
||||
}
|
||||
|
||||
@Test
|
||||
void standardMessage_DATA_BIZ_DATA_존재() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertNotNull(msg.findItem("DATA.BIZ_DATA"), "DATA.BIZ_DATA 없음");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 2. InterfaceMapper
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void mapper_InterfaceMapperDJB_인스턴스() {
|
||||
assertNotNull(manager.getMapper(), "mapper가 null");
|
||||
assertInstanceOf(InterfaceMapperDJB.class, manager.getMapper(),
|
||||
"mapper가 InterfaceMapperDJB가 아님: " + manager.getMapper().getClass().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapper_GUID_경로_매핑_정상() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
InterfaceMapperDJB mapper = (InterfaceMapperDJB) manager.getMapper();
|
||||
String guid = GUIDGeneratorDJB.getGUID("EAI");
|
||||
mapper.setGuid(msg, guid);
|
||||
assertEquals(guid, mapper.getGuid(msg), "GUID 설정/조회 불일치");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapper_ResponseType_S_F_변환() {
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
InterfaceMapperDJB mapper = (InterfaceMapperDJB) manager.getMapper();
|
||||
// NR → S
|
||||
mapper.setResponseType(msg, com.ext.eai.common.stdmessage.STDMessageKeys.RESPONSE_TYPE_CODE_N);
|
||||
assertEquals("S", msg.findItemValue("HEAD.procs_rslt_dvcd"));
|
||||
// ER → F
|
||||
mapper.setResponseType(msg, com.ext.eai.common.stdmessage.STDMessageKeys.RESPONSE_TYPE_CODE_E);
|
||||
assertEquals("F", msg.findItemValue("HEAD.procs_rslt_dvcd"));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 3. StandardMessageCoordinator
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void coordinator_StandardMessageCoordinatorDJB_인스턴스() {
|
||||
assertNotNull(manager.getMessageCoordinator(), "messageCoordinator가 null");
|
||||
assertInstanceOf(StandardMessageCoordinatorDJB.class, manager.getMessageCoordinator(),
|
||||
"coordinator가 StandardMessageCoordinatorDJB가 아님: "
|
||||
+ manager.getMessageCoordinator().getClass().getName());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 4. Reader 등록
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void reader_JSON_등록() {
|
||||
StandardReader reader = manager.getReader("JSON");
|
||||
assertNotNull(reader, "JSON reader 미등록");
|
||||
assertEquals("com.eactive.eai.message.parser.JsonReader",
|
||||
reader.getClass().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reader_XML_등록() {
|
||||
StandardReader reader = manager.getReader("XML");
|
||||
assertNotNull(reader, "XML reader 미등록");
|
||||
assertEquals("com.eactive.eai.message.parser.XmlReader",
|
||||
reader.getClass().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reader_ASC_등록() {
|
||||
StandardReader reader = manager.getReader("ASC");
|
||||
assertNotNull(reader, "ASC(Flat) reader 미등록");
|
||||
assertEquals("com.eactive.eai.message.parser.FlatReader",
|
||||
reader.getClass().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reader_FLAT_등록() {
|
||||
StandardReader reader = manager.getReader("FLAT");
|
||||
assertNotNull(reader, "FLAT reader 미등록");
|
||||
assertEquals("com.eactive.eai.message.parser.FlatReader",
|
||||
reader.getClass().getName());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 5. getStandardMessage() 독립 복사본 반환
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void getStandardMessage_호출마다_독립_복사본() {
|
||||
StandardMessage msg1 = manager.getStandardMessage();
|
||||
StandardMessage msg2 = manager.getStandardMessage();
|
||||
assertNotSame(msg1, msg2, "getStandardMessage()는 매번 새 인스턴스를 반환해야 함");
|
||||
|
||||
// 한 쪽 수정이 다른 쪽에 영향 없어야 함
|
||||
msg1.setData("HEAD.guid", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
assertNotEquals(
|
||||
msg1.findItemValue("HEAD.guid"),
|
||||
msg2.findItemValue("HEAD.guid"),
|
||||
"복사본이 원본에 영향을 줌 — clone 미작동");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// 6. reload() — init() 재실행 후 상태 일관성
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void reload_후_mapper_정상() throws Exception {
|
||||
manager.reload();
|
||||
assertNotNull(manager.getMapper(), "reload 후 mapper null");
|
||||
assertInstanceOf(InterfaceMapperDJB.class, manager.getMapper());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reload_후_standardMessage_정상() throws Exception {
|
||||
manager.reload();
|
||||
StandardMessage msg = manager.getStandardMessage();
|
||||
assertNotNull(msg);
|
||||
assertNotNull(msg.findItem("HEAD"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
layout.file.type=CSV
|
||||
layout.file.path=src/main/resources/standard-layout-djb.csv
|
||||
layout.filter.FLAT=com.eactive.eai.message.filter.FlatMessageFilter
|
||||
mapper.class=com.eactive.eai.custom.message.InterfaceMapperDJB
|
||||
mapper.definition=standard-message-mapping-config-djb.properties
|
||||
message.coordinator.class=com.eactive.eai.custom.message.StandardMessageCoordinatorDJB
|
||||
reader.JSON=com.eactive.eai.message.parser.JsonReader
|
||||
reader.JSN=com.eactive.eai.message.parser.JsonReader
|
||||
reader.XML=com.eactive.eai.message.parser.XmlReader
|
||||
reader.ASC=com.eactive.eai.message.parser.FlatReader
|
||||
reader.FLAT=com.eactive.eai.message.parser.FlatReader
|
||||
encode.flat=euc-kr
|
||||
encode.xml=utf-8
|
||||
Reference in New Issue
Block a user