Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 158987b367 | |||
| 8ace28675b | |||
| 1ab36c077b | |||
| 547232bb26 | |||
| ebd89afa0d | |||
| 407eccc827 | |||
| cebdfd6a19 | |||
| 1fd8712de0 | |||
| be204abb5e | |||
| c2ad6d2423 | |||
| b6954139fe | |||
| d46fa8bd1a | |||
| 31171d0187 | |||
| 45ad9d8b6f | |||
| dd02c5902e | |||
| c225104711 | |||
| efcc7fe208 | |||
| 8bcbee7e52 | |||
| 04aa0df977 | |||
| 2eeee58d35 | |||
| 5f24bacd48 | |||
| 21c3bcbc6a | |||
| aff3ed6658 | |||
| 8947fc248f | |||
| 58f659a179 | |||
| 745df6d073 | |||
| 4a41398f03 | |||
| 4d479e4fd6 | |||
| 780b9bd934 | |||
| 42f52a4974 | |||
| 1a79c39e76 | |||
| bfda9ef610 | |||
| df1b1f2667 | |||
| a891676617 | |||
| cd2ab33a0d | |||
| b39a26350e | |||
| 68bc6fa47a | |||
| 787f9a4f42 | |||
| bca28dbd1b | |||
| bc79b8b166 | |||
| 2d17387def | |||
| 1508d01afb | |||
| 17d533fe06 | |||
| 557a071b1e | |||
| 18b3e781b1 |
@@ -25,6 +25,9 @@
|
||||
base-package="com.eactive.eai.adapter" />
|
||||
<context:component-scan
|
||||
base-package="com.eactive.eai.manage" />
|
||||
<context:component-scan
|
||||
base-package="com.eactive.eai.custom.inflow" />
|
||||
|
||||
<context:annotation-config />
|
||||
<mvc:annotation-driven />
|
||||
<mvc:default-servlet-handler />
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
<url-pattern>/agent/*</url-pattern>
|
||||
<url-pattern>/common/*</url-pattern>
|
||||
<url-pattern>/management/*</url-pattern>
|
||||
<url-pattern>/manage/*</url-pattern>
|
||||
<url-pattern>/mgr/*</url-pattern>
|
||||
</filter-mapping>
|
||||
|
||||
|
||||
+1
-1
Submodule elink-online-common updated: 791e362a74...e208a2d64b
+1
-1
Submodule elink-online-core-jpa updated: 76342bfaef...9620845daf
+1
-1
Submodule elink-online-transformer updated: c8a58fdf5b...82c7c2bc8c
@@ -7,6 +7,7 @@ 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.CryptoFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthFilter;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
@@ -142,7 +143,8 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
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
|
||||
|
||||
|
||||
transactionProp.put(CryptoFilter.PROP_MODULE_NAME, httpProp.getProperty(CryptoFilter.PROP_MODULE_NAME, ""));
|
||||
|
||||
// SEED 컬럼암호하 시 Key로 사용함
|
||||
String seedkey = getHeaders(request).getOrDefault("x-obp-partnercode", "").toString();
|
||||
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.CryptoFilter;
|
||||
import com.eactive.eai.util.JsonPathUtil;
|
||||
|
||||
/**
|
||||
* DJB ERP 연동용 암복호화 필터.
|
||||
*
|
||||
* DYNAMIC 키 컨텍스트 추출 규칙:
|
||||
* HTTP 헤더 {@code httpHeaderGroup}의 값은 JSON 객체이며,
|
||||
* 그 중 {@code x-emp-nm} 필드 값을 {@code groupSeq}로
|
||||
* runtimeContext에 담아 키 도출 전략에 전달한다.
|
||||
*
|
||||
* 어댑터 프로퍼티 (부모 클래스 공통 설정 외 추가 키):
|
||||
* crypto.context.key runtimeContext에 넣을 키 이름 (기본: groupSeq)
|
||||
* crypto.context.header 컨텍스트 JSON이 담긴 HTTP 헤더명 (기본: httpHeaderGroup)
|
||||
* crypto.context.header.field 헤더 JSON에서 추출할 필드명 (기본: x-emp-nm)
|
||||
*
|
||||
* 어댑터 프로퍼티 설정 예:
|
||||
* crypto.module.name = AES_GCM_NoPadding_DYNAMIC_sample
|
||||
* crypto.scope = FIELD
|
||||
* crypto.dec.enabled = Y
|
||||
* crypto.enc.enabled = N
|
||||
* crypto.dec.from.path = /encryptedData
|
||||
* crypto.dec.to.path = /
|
||||
* crypto.context.key = groupSeq
|
||||
* crypto.context.header = httpHeaderGroup
|
||||
* crypto.context.header.field = x-emp-nm
|
||||
*
|
||||
* 필터 타입 등록 (FQCN):
|
||||
* com.eactive.eai.custom.adapter.http.dynamic.filter.DJBErpCryptoFilter
|
||||
*/
|
||||
public class DJBErpCryptoFilter extends CryptoFilter {
|
||||
|
||||
public static final String PROP_CONTEXT_KEY = "crypto.context.key";
|
||||
public static final String PROP_CONTEXT_HEADER = "crypto.context.header";
|
||||
public static final String PROP_CONTEXT_HEADER_FIELD = "crypto.context.header.field";
|
||||
|
||||
private static final String DEFAULT_CONTEXT_KEY = "groupSeq";
|
||||
private static final String DEFAULT_CONTEXT_HEADER = "httpHeaderGroup";
|
||||
private static final String DEFAULT_CONTEXT_HEADER_FIELD = "x-emp-nm";
|
||||
|
||||
/**
|
||||
* httpHeaderGroup 헤더(JSON)에서 x-emp-nm 값을 추출하여 groupSeq로 매핑한다.
|
||||
* 헤더가 없거나 필드를 찾을 수 없으면 빈 Map을 반환한다.
|
||||
*/
|
||||
@Override
|
||||
protected Map<String, String> buildRuntimeContext(Properties prop, HttpServletRequest request) {
|
||||
Map<String, String> ctx = new HashMap<>();
|
||||
|
||||
String contextKey = prop.getProperty(PROP_CONTEXT_KEY, DEFAULT_CONTEXT_KEY);
|
||||
String contextHeaderName = prop.getProperty(PROP_CONTEXT_HEADER, DEFAULT_CONTEXT_HEADER);
|
||||
String contextHeaderField = prop.getProperty(PROP_CONTEXT_HEADER_FIELD, DEFAULT_CONTEXT_HEADER_FIELD);
|
||||
|
||||
String headerJson = request.getHeader(contextHeaderName);
|
||||
if (StringUtils.isBlank(headerJson)) {
|
||||
logger.warn("DJBErpCryptoFilter] 컨텍스트 헤더 없음: " + contextHeaderName);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
String value = JsonPathUtil.getValueAtPath(headerJson, "/" + contextHeaderField);
|
||||
if (value == null) {
|
||||
logger.warn("DJBErpCryptoFilter] 헤더 JSON에서 필드 추출 실패: header="
|
||||
+ contextHeaderName + ", field=" + contextHeaderField);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
// x-emp-nm 값은 "groupSeq|empNo" 형태 — '|' 앞부분만 groupSeq로 사용
|
||||
String groupSeq = value.contains("|") ? value.substring(0, value.indexOf('|')) : value;
|
||||
ctx.put(contextKey, groupSeq);
|
||||
|
||||
return ctx;
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.BaseCryptoFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
|
||||
/**
|
||||
* CryptoFilter 프로퍼티를 멤버변수로 관리하는 HttpAdapterFilter 구현체.
|
||||
*
|
||||
* 멤버변수에 세팅된 값을 Properties로 변환하여 {@link BaseCryptoFilter}에 위임한다.
|
||||
* 값이 blank인 멤버변수는 Properties에 포함하지 않으며, CryptoFilter의 기본값이 적용된다.
|
||||
*/
|
||||
public class EncFieldCryptoFilter implements HttpAdapterFilter {
|
||||
|
||||
private final BaseCryptoFilter filter = new BaseCryptoFilter();
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return filter.doPreFilter(adptGrpName, adptName, message, setProp(prop), request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return filter.doPostFilter(adptGrpName, adptName, resultMessage, setProp(prop), request, response);
|
||||
}
|
||||
|
||||
private Properties setProp(Properties p) {
|
||||
p.setProperty(BaseCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
|
||||
p.setProperty(BaseCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
|
||||
return p;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.eactive.eai.custom.inbound.processor;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.common.inflow.Bucket;
|
||||
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||
import com.eactive.eai.common.inflow.dual.ClientDualBucket;
|
||||
import com.eactive.eai.common.inflow.dual.DualBucket;
|
||||
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
|
||||
import com.eactive.eai.inbound.processor.RequestProcessor;
|
||||
|
||||
/**
|
||||
* 어댑터/인터페이스/클라이언트 유량제어 차단 시 어느 버킷(PER_SECOND/THRESHOLD)에서
|
||||
* 차단됐는지 에러 메시지에 포함하는 RequestProcessor 확장.
|
||||
*
|
||||
* <p>ClientDualInflowControlManager와 함께 사용:
|
||||
* <pre>
|
||||
* inflow.control.bucket.className=com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager
|
||||
* </pre>
|
||||
*
|
||||
* <p>Spring Bean 등록 후 기존 RequestProcessor 대신 이 클래스를 어댑터에 설정한다.
|
||||
*/
|
||||
public class DJBRequestProcessor extends RequestProcessor {
|
||||
|
||||
@Override
|
||||
protected String checkClientInflow(Bucket bucket, String clientId) {
|
||||
if (StringUtils.isBlank(clientId)) return null;
|
||||
if (bucket instanceof ClientDualBucket) {
|
||||
return ((ClientDualBucket) bucket).isClientPassDetail(clientId);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected InflowTargetVO resolveClientInflowThreshold(Bucket bucket, String clientId) {
|
||||
if (bucket instanceof ClientDualBucket) {
|
||||
return ((ClientDualBucket) bucket).getClientInflowThreshold(clientId);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String checkAdapterInflow(Bucket bucket, String adapterGroupName) {
|
||||
if (bucket instanceof DualBucket) {
|
||||
return ((DualBucket) bucket).isAdapterPassDetail(adapterGroupName);
|
||||
}
|
||||
return super.checkAdapterInflow(bucket, adapterGroupName);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String checkInterfaceInflow(Bucket bucket, String eaiSvcCd) {
|
||||
if (bucket instanceof DualBucket) {
|
||||
return ((DualBucket) bucket).isInterfacePassDetail(eaiSvcCd);
|
||||
}
|
||||
return super.checkInterfaceInflow(bucket, eaiSvcCd);
|
||||
}
|
||||
|
||||
/**
|
||||
* 차단 원인에 따라 에러 메시지에 한도 정보를 포함.
|
||||
* <ul>
|
||||
* <li>PER_SECOND: "API 호출 한도 초과 [name: Nreq/sec]"</li>
|
||||
* <li>THRESHOLD: "API 호출 한도 초과 [name: Nreq/UNIT]"</li>
|
||||
* <li>그 외: "API 호출 한도 초과 [name]" (기존 동작)</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Override
|
||||
protected String buildInflowTargetErrorMsg(InflowTargetVO inflowTargetVO, String blockedType) {
|
||||
if (DualCustomBucket.RESULT_BLOCKED_PER_SECOND.equals(blockedType)) {
|
||||
return String.format("API 호출 한도 초과 [%s: %dreq/sec]",
|
||||
inflowTargetVO.getName(),
|
||||
inflowTargetVO.getThresholdPerSecond());
|
||||
}
|
||||
if (DualCustomBucket.RESULT_BLOCKED_THRESHOLD.equals(blockedType)) {
|
||||
return String.format("API 호출 한도 초과 [%s: %dreq/%s]",
|
||||
inflowTargetVO.getName(),
|
||||
inflowTargetVO.getThreshold(),
|
||||
inflowTargetVO.getThresholdTimeUnit());
|
||||
}
|
||||
return super.buildInflowTargetErrorMsg(inflowTargetVO, blockedType);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.eactive.eai.custom.inflow;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.eactive.eai.manage.inflow.TargetBucketStatusDTO;
|
||||
|
||||
/**
|
||||
* 클라이언트 버킷 상태 모니터링 API.
|
||||
*
|
||||
* ClientDualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
|
||||
*
|
||||
* GET /manage/inflow/client/bucket-status → 전체 클라이언트 버킷 상태
|
||||
* GET /manage/inflow/client/{clientId}/bucket-status → 특정 클라이언트 버킷 상태
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/manage/inflow")
|
||||
public class ClientInflowTargetBucketController {
|
||||
|
||||
@Autowired
|
||||
private ClientInflowTargetBucketService bucketService;
|
||||
|
||||
@GetMapping("/client/bucket-status")
|
||||
public ResponseEntity<?> getAllClientBucketStatus() {
|
||||
List<TargetBucketStatusDTO> list = bucketService.getAllClientBucketStatus();
|
||||
return ok(list);
|
||||
}
|
||||
|
||||
@GetMapping("/client/{clientId}/bucket-status")
|
||||
public ResponseEntity<?> getClientBucketStatus(@PathVariable String clientId) {
|
||||
TargetBucketStatusDTO dto = bucketService.getClientBucketStatus(clientId);
|
||||
return single(dto, "클라이언트를 찾을 수 없습니다: " + clientId);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> ok(List<TargetBucketStatusDTO> list) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("data", list);
|
||||
result.put("count", list.size());
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> single(TargetBucketStatusDTO dto, String notFoundMsg) {
|
||||
if (dto == null) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", notFoundMsg);
|
||||
return ResponseEntity.ok(error);
|
||||
}
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("data", dto);
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.eactive.eai.custom.inflow;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
|
||||
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
|
||||
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
|
||||
import com.eactive.eai.manage.inflow.GroupBucketStatusDTO;
|
||||
import com.eactive.eai.manage.inflow.TargetBucketStatusDTO;
|
||||
|
||||
/**
|
||||
* 클라이언트 버킷 상태 조회 서비스.
|
||||
*
|
||||
* ClientDualInflowControlManager 가 활성화된 경우에만 동작한다.
|
||||
*/
|
||||
@Service
|
||||
public class ClientInflowTargetBucketService {
|
||||
|
||||
public TargetBucketStatusDTO getClientBucketStatus(String clientId) {
|
||||
ClientDualInflowControlManager manager = getClientDualManager();
|
||||
if (manager == null) return null;
|
||||
DualCustomBucket bucket = manager.getClientBucket(clientId);
|
||||
if (bucket == null) return null;
|
||||
return toDto(clientId, "CLIENT", bucket);
|
||||
}
|
||||
|
||||
public List<TargetBucketStatusDTO> getAllClientBucketStatus() {
|
||||
ClientDualInflowControlManager manager = getClientDualManager();
|
||||
if (manager == null) return new ArrayList<>();
|
||||
return toDtoList("CLIENT", manager.getClientBucketMap());
|
||||
}
|
||||
|
||||
protected ClientDualInflowControlManager getClientDualManager() {
|
||||
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
|
||||
return (base instanceof ClientDualInflowControlManager) ? (ClientDualInflowControlManager) base : null;
|
||||
}
|
||||
|
||||
private TargetBucketStatusDTO toDto(String targetId, String targetType, DualCustomBucket bucket) {
|
||||
InflowTargetVO vo = bucket.getInflowTargetVo();
|
||||
List<GroupBucketStatusDTO.BucketInfo> buckets = new ArrayList<>();
|
||||
|
||||
if (vo.getThresholdPerSecond() > 0) {
|
||||
long capacity = vo.getThresholdPerSecond();
|
||||
long available = bucket.getPerSecondAvailableTokens();
|
||||
if (available < 0) available = capacity;
|
||||
buckets.add(new GroupBucketStatusDTO.BucketInfo(
|
||||
"perSecond", capacity, Math.min(available, capacity), "SEC"));
|
||||
}
|
||||
|
||||
if (vo.getThreshold() > 0) {
|
||||
long capacity = vo.getThreshold();
|
||||
long available = bucket.getThresholdAvailableTokens();
|
||||
if (available < 0) available = capacity;
|
||||
buckets.add(new GroupBucketStatusDTO.BucketInfo(
|
||||
"threshold", capacity, Math.min(available, capacity), vo.getThresholdTimeUnit()));
|
||||
}
|
||||
|
||||
TargetBucketStatusDTO dto = new TargetBucketStatusDTO();
|
||||
dto.setTargetId(targetId);
|
||||
dto.setTargetType(targetType);
|
||||
dto.setActivate(vo.isActivate());
|
||||
dto.setBuckets(buckets);
|
||||
return dto;
|
||||
}
|
||||
|
||||
private List<TargetBucketStatusDTO> toDtoList(String targetType, Map<String, DualCustomBucket> bucketMap) {
|
||||
List<TargetBucketStatusDTO> result = new ArrayList<>();
|
||||
for (Map.Entry<String, DualCustomBucket> entry : bucketMap.entrySet()) {
|
||||
result.add(toDto(entry.getKey(), targetType, entry.getValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.eactive.eai.custom.inflow;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.eactive.eai.manage.inflow.TargetMetricDTO;
|
||||
|
||||
/**
|
||||
* 클라이언트 유량제어 메트릭 API.
|
||||
*
|
||||
* ClientDualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
|
||||
*
|
||||
* GET /manage/inflow/client/metric → 전체 클라이언트 메트릭
|
||||
* GET /manage/inflow/client/{clientId}/metric → 특정 클라이언트 메트릭
|
||||
* POST /manage/inflow/client/metric/reset → 전체 클라이언트 메트릭 초기화
|
||||
* POST /manage/inflow/client/{clientId}/metric/reset → 특정 클라이언트 메트릭 초기화
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/manage/inflow")
|
||||
public class ClientInflowTargetMetricController {
|
||||
|
||||
@Autowired
|
||||
private ClientInflowTargetMetricService metricService;
|
||||
|
||||
@GetMapping("/client/metric")
|
||||
public ResponseEntity<?> getAllClientMetrics() {
|
||||
List<TargetMetricDTO> list = metricService.getAllClientMetrics();
|
||||
return okList(list);
|
||||
}
|
||||
|
||||
@GetMapping("/client/{clientId}/metric")
|
||||
public ResponseEntity<?> getClientMetric(@PathVariable String clientId) {
|
||||
TargetMetricDTO dto = metricService.getClientMetric(clientId);
|
||||
return okSingle(dto, "클라이언트를 찾을 수 없습니다: " + clientId);
|
||||
}
|
||||
|
||||
@PostMapping("/client/metric/reset")
|
||||
public ResponseEntity<?> resetAllClientMetrics() {
|
||||
metricService.resetAllClientMetrics();
|
||||
return okReset("전체 클라이언트 메트릭 초기화 완료");
|
||||
}
|
||||
|
||||
@PostMapping("/client/{clientId}/metric/reset")
|
||||
public ResponseEntity<?> resetClientMetric(@PathVariable String clientId) {
|
||||
boolean ok = metricService.resetClientMetric(clientId);
|
||||
return okResetSingle(ok, clientId, "클라이언트");
|
||||
}
|
||||
|
||||
private ResponseEntity<?> okList(List<TargetMetricDTO> list) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("data", list);
|
||||
result.put("count", list.size());
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> okSingle(TargetMetricDTO dto, String notFoundMsg) {
|
||||
if (dto == null) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", notFoundMsg);
|
||||
return ResponseEntity.ok(error);
|
||||
}
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("data", dto);
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> okReset(String message) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("message", message);
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> okResetSingle(boolean ok, String targetId, String targetLabel) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", ok);
|
||||
result.put("message", ok
|
||||
? "초기화 완료: " + targetId
|
||||
: targetLabel + "를 찾을 수 없습니다: " + targetId);
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.eactive.eai.custom.inflow;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
|
||||
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
|
||||
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||
import com.eactive.eai.manage.inflow.TargetMetricDTO;
|
||||
|
||||
@Service
|
||||
public class ClientInflowTargetMetricService {
|
||||
|
||||
public TargetMetricDTO getClientMetric(String clientId) {
|
||||
ClientDualInflowControlManager manager = getClientDualManager();
|
||||
if (manager == null) return null;
|
||||
InflowTargetVO vo = manager.getClientInflowThreshold(clientId);
|
||||
if (vo == null) return null;
|
||||
return buildDTO(clientId, "CLIENT", vo, manager.getClientMetrics(clientId));
|
||||
}
|
||||
|
||||
public List<TargetMetricDTO> getAllClientMetrics() {
|
||||
ClientDualInflowControlManager manager = getClientDualManager();
|
||||
if (manager == null) return new ArrayList<>();
|
||||
List<TargetMetricDTO> result = new ArrayList<>();
|
||||
for (String id : manager.getClientBucketMap().keySet()) {
|
||||
TargetMetricDTO dto = getClientMetric(id);
|
||||
if (dto != null) result.add(dto);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean resetClientMetric(String clientId) {
|
||||
ClientDualInflowControlManager manager = getClientDualManager();
|
||||
if (manager == null) return false;
|
||||
if (manager.getClientInflowThreshold(clientId) == null) return false;
|
||||
manager.resetClientMetrics(clientId);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void resetAllClientMetrics() {
|
||||
ClientDualInflowControlManager manager = getClientDualManager();
|
||||
if (manager != null) manager.resetAllClientMetrics();
|
||||
}
|
||||
|
||||
protected ClientDualInflowControlManager getClientDualManager() {
|
||||
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
|
||||
return (base instanceof ClientDualInflowControlManager) ? (ClientDualInflowControlManager) base : null;
|
||||
}
|
||||
|
||||
private TargetMetricDTO buildDTO(String targetId, String targetType,
|
||||
InflowTargetVO vo,
|
||||
DualInflowControlManager.TargetMetrics m) {
|
||||
TargetMetricDTO dto = new TargetMetricDTO();
|
||||
dto.setTargetId(targetId);
|
||||
dto.setTargetType(targetType);
|
||||
dto.setActivate(vo.isActivate());
|
||||
|
||||
if (m != null) {
|
||||
long allowed = m.allowed.get();
|
||||
long rejPs = m.rejectedPerSecond.get();
|
||||
long rejTh = m.rejectedThreshold.get();
|
||||
long total = allowed + rejPs + rejTh;
|
||||
dto.setAllowed(allowed);
|
||||
dto.setRejectedPerSecond(rejPs);
|
||||
dto.setRejectedThreshold(rejTh);
|
||||
dto.setTotalRequests(total);
|
||||
dto.setRejectRatio(total > 0
|
||||
? Math.round((double)(rejPs + rejTh) / total * 10000) / 100.0
|
||||
: 0.0);
|
||||
dto.setLastResetTime(m.lastResetTime);
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
public class GroupMetricDTO {
|
||||
private String groupId;
|
||||
private String groupName;
|
||||
private boolean activate;
|
||||
private long allowed;
|
||||
private long rejectedPerSecond;
|
||||
private long rejectedThreshold;
|
||||
private long totalRequests;
|
||||
private double rejectRatio;
|
||||
private long lastResetTime;
|
||||
|
||||
public String getGroupId() { return groupId; }
|
||||
public void setGroupId(String groupId) { this.groupId = groupId; }
|
||||
|
||||
public String getGroupName() { return groupName; }
|
||||
public void setGroupName(String groupName) { this.groupName = groupName; }
|
||||
|
||||
public boolean isActivate() { return activate; }
|
||||
public void setActivate(boolean activate) { this.activate = activate; }
|
||||
|
||||
public long getAllowed() { return allowed; }
|
||||
public void setAllowed(long allowed) { this.allowed = allowed; }
|
||||
|
||||
public long getRejectedPerSecond() { return rejectedPerSecond; }
|
||||
public void setRejectedPerSecond(long rejectedPerSecond) { this.rejectedPerSecond = rejectedPerSecond; }
|
||||
|
||||
public long getRejectedThreshold() { return rejectedThreshold; }
|
||||
public void setRejectedThreshold(long rejectedThreshold) { this.rejectedThreshold = rejectedThreshold; }
|
||||
|
||||
public long getTotalRequests() { return totalRequests; }
|
||||
public void setTotalRequests(long totalRequests) { this.totalRequests = totalRequests; }
|
||||
|
||||
public double getRejectRatio() { return rejectRatio; }
|
||||
public void setRejectRatio(double rejectRatio) { this.rejectRatio = rejectRatio; }
|
||||
|
||||
public long getLastResetTime() { return lastResetTime; }
|
||||
public void setLastResetTime(long lastResetTime) { this.lastResetTime = lastResetTime; }
|
||||
}
|
||||
@@ -1,21 +1,20 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
|
||||
import com.eactive.eai.common.inflow.CustomGroupBucket;
|
||||
import com.eactive.eai.common.inflow.InflowControlManager;
|
||||
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||
import com.eactive.eai.common.inflow.InflowGroupVO;
|
||||
|
||||
@Service
|
||||
public class InflowGroupBucketService {
|
||||
|
||||
public GroupBucketStatusDTO getGroupBucketStatus(String groupId) {
|
||||
InflowControlManager manager = InflowControlManager.getInstance();
|
||||
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
|
||||
|
||||
InflowGroupVO groupVo = manager.getGroupInflowThreshold(groupId);
|
||||
if (groupVo == null) {
|
||||
@@ -72,25 +71,12 @@ public class InflowGroupBucketService {
|
||||
return dto;
|
||||
}
|
||||
|
||||
/**
|
||||
* 그룹 버킷 조회 (리플렉션 사용)
|
||||
*/
|
||||
public CustomGroupBucket getCustomGroupBucket(String groupId) {
|
||||
try {
|
||||
InflowControlManager manager = InflowControlManager.getInstance();
|
||||
Field field = InflowControlManager.class.getDeclaredField("groupBucketList");
|
||||
field.setAccessible(true);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, CustomGroupBucket> groupBucketList =
|
||||
(Map<String, CustomGroupBucket>) field.get(manager);
|
||||
return groupBucketList.get(groupId);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
return InflowControlUtil.getInflowControlManager().getGroupBucket(groupId);
|
||||
}
|
||||
|
||||
public List<GroupBucketStatusDTO> getAllGroupBucketStatus() {
|
||||
InflowControlManager manager = InflowControlManager.getInstance();
|
||||
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
|
||||
String[] groupIds = manager.getGroupAllKeys();
|
||||
|
||||
List<GroupBucketStatusDTO> result = new ArrayList<>();
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/manage/inflow/group")
|
||||
public class InflowGroupMetricController {
|
||||
|
||||
@Autowired
|
||||
private InflowGroupMetricService metricService;
|
||||
|
||||
/**
|
||||
* 특정 그룹의 메트릭 조회
|
||||
* GET /manage/inflow/group/{groupId}/metric
|
||||
*/
|
||||
@GetMapping("/{groupId}/metric")
|
||||
public ResponseEntity<?> getGroupMetric(@PathVariable String groupId) {
|
||||
GroupMetricDTO metric = metricService.getGroupMetric(groupId);
|
||||
|
||||
if (metric == null) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", "그룹을 찾을 수 없습니다: " + groupId);
|
||||
return ResponseEntity.ok(error);
|
||||
}
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("data", metric);
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 모든 그룹의 메트릭 조회
|
||||
* GET /manage/inflow/group/metric
|
||||
*/
|
||||
@GetMapping("/metric")
|
||||
public ResponseEntity<?> getAllGroupMetrics() {
|
||||
List<GroupMetricDTO> list = metricService.getAllGroupMetrics();
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("data", list);
|
||||
result.put("count", list.size());
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 그룹의 메트릭 초기화
|
||||
* POST /manage/inflow/group/{groupId}/metric/reset
|
||||
*/
|
||||
@PostMapping("/{groupId}/metric/reset")
|
||||
public ResponseEntity<?> resetGroupMetric(@PathVariable String groupId) {
|
||||
boolean ok = metricService.resetGroupMetric(groupId);
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", ok);
|
||||
result.put("message", ok ? "초기화 완료: " + groupId : "그룹을 찾을 수 없습니다: " + groupId);
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 그룹 메트릭 초기화
|
||||
* POST /manage/inflow/group/metric/reset
|
||||
*/
|
||||
@PostMapping("/metric/reset")
|
||||
public ResponseEntity<?> resetAllGroupMetrics() {
|
||||
metricService.resetAllGroupMetrics();
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("message", "전체 그룹 메트릭 초기화 완료");
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.eactive.eai.common.inflow.Bucket;
|
||||
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||
import com.eactive.eai.common.inflow.InflowGroupVO;
|
||||
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||
|
||||
@Service
|
||||
public class InflowGroupMetricService {
|
||||
|
||||
public GroupMetricDTO getGroupMetric(String groupId) {
|
||||
DualInflowControlManager manager = getManager();
|
||||
if (manager == null) return null;
|
||||
|
||||
InflowGroupVO groupVo = manager.getGroupInflowThreshold(groupId);
|
||||
if (groupVo == null) return null;
|
||||
|
||||
return buildDTO(groupId, groupVo, manager.getGroupMetrics(groupId));
|
||||
}
|
||||
|
||||
public List<GroupMetricDTO> getAllGroupMetrics() {
|
||||
DualInflowControlManager manager = getManager();
|
||||
if (manager == null) return new ArrayList<>();
|
||||
|
||||
List<GroupMetricDTO> result = new ArrayList<>();
|
||||
for (String groupId : manager.getGroupAllKeys()) {
|
||||
GroupMetricDTO dto = getGroupMetric(groupId);
|
||||
if (dto != null) result.add(dto);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean resetGroupMetric(String groupId) {
|
||||
DualInflowControlManager manager = getManager();
|
||||
if (manager == null) return false;
|
||||
if (manager.getGroupInflowThreshold(groupId) == null) return false;
|
||||
manager.resetGroupMetrics(groupId);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void resetAllGroupMetrics() {
|
||||
DualInflowControlManager manager = getManager();
|
||||
if (manager != null) manager.resetAllGroupMetrics();
|
||||
}
|
||||
|
||||
protected DualInflowControlManager getManager() {
|
||||
Bucket bucket = InflowControlUtil.getBucket();
|
||||
return (bucket instanceof DualInflowControlManager)
|
||||
? (DualInflowControlManager) bucket
|
||||
: null;
|
||||
}
|
||||
|
||||
private GroupMetricDTO buildDTO(String groupId, InflowGroupVO groupVo,
|
||||
DualInflowControlManager.TargetMetrics m) {
|
||||
GroupMetricDTO dto = new GroupMetricDTO();
|
||||
dto.setGroupId(groupId);
|
||||
dto.setGroupName(groupVo.getGroupName());
|
||||
dto.setActivate(groupVo.isActivate());
|
||||
|
||||
if (m != null) {
|
||||
long allowed = m.allowed.get();
|
||||
long rejPs = m.rejectedPerSecond.get();
|
||||
long rejTh = m.rejectedThreshold.get();
|
||||
long total = allowed + rejPs + rejTh;
|
||||
dto.setAllowed(allowed);
|
||||
dto.setRejectedPerSecond(rejPs);
|
||||
dto.setRejectedThreshold(rejTh);
|
||||
dto.setTotalRequests(total);
|
||||
dto.setRejectRatio(total > 0
|
||||
? Math.round((double)(rejPs + rejTh) / total * 10000) / 100.0
|
||||
: 0.0);
|
||||
dto.setLastResetTime(m.lastResetTime);
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 어댑터/인터페이스/클라이언트 버킷 상태 모니터링 API.
|
||||
*
|
||||
* DualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
|
||||
* 비활성화 환경에서는 success=false 또는 빈 목록을 반환한다.
|
||||
*
|
||||
* GET /manage/inflow/adapter/bucket-status → 전체 어댑터 버킷 상태
|
||||
* GET /manage/inflow/adapter/{adapterId}/bucket-status → 특정 어댑터 버킷 상태
|
||||
* GET /manage/inflow/interface/bucket-status → 전체 인터페이스 버킷 상태
|
||||
* GET /manage/inflow/interface/{interfaceId}/bucket-status → 특정 인터페이스 버킷 상태
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/manage/inflow")
|
||||
public class InflowTargetBucketController {
|
||||
|
||||
@Autowired
|
||||
private InflowTargetBucketService bucketService;
|
||||
|
||||
// =========================================================================
|
||||
// 어댑터
|
||||
// =========================================================================
|
||||
|
||||
@GetMapping("/adapter/bucket-status")
|
||||
public ResponseEntity<?> getAllAdapterBucketStatus() {
|
||||
List<TargetBucketStatusDTO> list = bucketService.getAllAdapterBucketStatus();
|
||||
return ok(list);
|
||||
}
|
||||
|
||||
@GetMapping("/adapter/{adapterId}/bucket-status")
|
||||
public ResponseEntity<?> getAdapterBucketStatus(@PathVariable String adapterId) {
|
||||
TargetBucketStatusDTO dto = bucketService.getAdapterBucketStatus(adapterId);
|
||||
return single(dto, "어댑터를 찾을 수 없습니다: " + adapterId);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 인터페이스
|
||||
// =========================================================================
|
||||
|
||||
@GetMapping("/interface/bucket-status")
|
||||
public ResponseEntity<?> getAllInterfaceBucketStatus() {
|
||||
List<TargetBucketStatusDTO> list = bucketService.getAllInterfaceBucketStatus();
|
||||
return ok(list);
|
||||
}
|
||||
|
||||
@GetMapping("/interface/{interfaceId}/bucket-status")
|
||||
public ResponseEntity<?> getInterfaceBucketStatus(@PathVariable String interfaceId) {
|
||||
TargetBucketStatusDTO dto = bucketService.getInterfaceBucketStatus(interfaceId);
|
||||
return single(dto, "인터페이스를 찾을 수 없습니다: " + interfaceId);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Helpers
|
||||
// =========================================================================
|
||||
|
||||
private ResponseEntity<?> ok(List<TargetBucketStatusDTO> list) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("data", list);
|
||||
result.put("count", list.size());
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> single(TargetBucketStatusDTO dto, String notFoundMsg) {
|
||||
if (dto == null) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", notFoundMsg);
|
||||
return ResponseEntity.ok(error);
|
||||
}
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("data", dto);
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
|
||||
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
|
||||
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||
|
||||
/**
|
||||
* 어댑터/인터페이스/클라이언트 버킷 상태 조회 서비스.
|
||||
*
|
||||
* DualInflowControlManager 가 활성화된 경우에만 동작한다.
|
||||
* InflowControlManager 가 기본 구현체인 경우 빈 목록 또는 null 을 반환한다.
|
||||
*/
|
||||
@Service
|
||||
public class InflowTargetBucketService {
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 어댑터
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public TargetBucketStatusDTO getAdapterBucketStatus(String adapterId) {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager == null) return null;
|
||||
DualCustomBucket bucket = manager.getAdapterBucket(adapterId);
|
||||
if (bucket == null) return null;
|
||||
return toDto(adapterId, "ADAPTER", bucket);
|
||||
}
|
||||
|
||||
public List<TargetBucketStatusDTO> getAllAdapterBucketStatus() {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager == null) return new ArrayList<>();
|
||||
return toDtoList("ADAPTER", manager.getAdapterBucketMap());
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 인터페이스
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public TargetBucketStatusDTO getInterfaceBucketStatus(String interfaceId) {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager == null) return null;
|
||||
DualCustomBucket bucket = manager.getInterfaceBucket(interfaceId);
|
||||
if (bucket == null) return null;
|
||||
return toDto(interfaceId, "INTERFACE", bucket);
|
||||
}
|
||||
|
||||
public List<TargetBucketStatusDTO> getAllInterfaceBucketStatus() {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager == null) return new ArrayList<>();
|
||||
return toDtoList("INTERFACE", manager.getInterfaceBucketMap());
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Private helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
protected DualInflowControlManager getDualManager() {
|
||||
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
|
||||
return (base instanceof DualInflowControlManager) ? (DualInflowControlManager) base : null;
|
||||
}
|
||||
|
||||
private TargetBucketStatusDTO toDto(String targetId, String targetType, DualCustomBucket bucket) {
|
||||
InflowTargetVO vo = bucket.getInflowTargetVo();
|
||||
List<GroupBucketStatusDTO.BucketInfo> buckets = new ArrayList<>();
|
||||
|
||||
if (vo.getThresholdPerSecond() > 0) {
|
||||
long capacity = vo.getThresholdPerSecond();
|
||||
long available = bucket.getPerSecondAvailableTokens();
|
||||
if (available < 0) available = capacity;
|
||||
buckets.add(new GroupBucketStatusDTO.BucketInfo(
|
||||
"perSecond", capacity, Math.min(available, capacity), "SEC"));
|
||||
}
|
||||
|
||||
if (vo.getThreshold() > 0) {
|
||||
long capacity = vo.getThreshold();
|
||||
long available = bucket.getThresholdAvailableTokens();
|
||||
if (available < 0) available = capacity;
|
||||
buckets.add(new GroupBucketStatusDTO.BucketInfo(
|
||||
"threshold", capacity, Math.min(available, capacity), vo.getThresholdTimeUnit()));
|
||||
}
|
||||
|
||||
TargetBucketStatusDTO dto = new TargetBucketStatusDTO();
|
||||
dto.setTargetId(targetId);
|
||||
dto.setTargetType(targetType);
|
||||
dto.setActivate(vo.isActivate());
|
||||
dto.setBuckets(buckets);
|
||||
return dto;
|
||||
}
|
||||
|
||||
private List<TargetBucketStatusDTO> toDtoList(String targetType, Map<String, DualCustomBucket> bucketMap) {
|
||||
List<TargetBucketStatusDTO> result = new ArrayList<>();
|
||||
for (Map.Entry<String, DualCustomBucket> entry : bucketMap.entrySet()) {
|
||||
result.add(toDto(entry.getKey(), targetType, entry.getValue()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 어댑터/인터페이스 유량제어 메트릭 API.
|
||||
*
|
||||
* DualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
|
||||
*
|
||||
* GET /manage/inflow/adapter/metric → 전체 어댑터 메트릭
|
||||
* GET /manage/inflow/adapter/{adapterId}/metric → 특정 어댑터 메트릭
|
||||
* POST /manage/inflow/adapter/metric/reset → 전체 어댑터 메트릭 초기화
|
||||
* POST /manage/inflow/adapter/{adapterId}/metric/reset → 특정 어댑터 메트릭 초기화
|
||||
*
|
||||
* GET /manage/inflow/interface/metric → 전체 인터페이스 메트릭
|
||||
* GET /manage/inflow/interface/{interfaceId}/metric → 특정 인터페이스 메트릭
|
||||
* POST /manage/inflow/interface/metric/reset → 전체 인터페이스 메트릭 초기화
|
||||
* POST /manage/inflow/interface/{interfaceId}/metric/reset → 특정 인터페이스 메트릭 초기화
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/manage/inflow")
|
||||
public class InflowTargetMetricController {
|
||||
|
||||
@Autowired
|
||||
private InflowTargetMetricService metricService;
|
||||
|
||||
// =========================================================================
|
||||
// 어댑터
|
||||
// =========================================================================
|
||||
|
||||
@GetMapping("/adapter/metric")
|
||||
public ResponseEntity<?> getAllAdapterMetrics() {
|
||||
List<TargetMetricDTO> list = metricService.getAllAdapterMetrics();
|
||||
return okList(list);
|
||||
}
|
||||
|
||||
@GetMapping("/adapter/{adapterId}/metric")
|
||||
public ResponseEntity<?> getAdapterMetric(@PathVariable String adapterId) {
|
||||
TargetMetricDTO dto = metricService.getAdapterMetric(adapterId);
|
||||
return okSingle(dto, "어댑터를 찾을 수 없습니다: " + adapterId);
|
||||
}
|
||||
|
||||
@PostMapping("/adapter/metric/reset")
|
||||
public ResponseEntity<?> resetAllAdapterMetrics() {
|
||||
metricService.resetAllAdapterMetrics();
|
||||
return okReset("전체 어댑터 메트릭 초기화 완료");
|
||||
}
|
||||
|
||||
@PostMapping("/adapter/{adapterId}/metric/reset")
|
||||
public ResponseEntity<?> resetAdapterMetric(@PathVariable String adapterId) {
|
||||
boolean ok = metricService.resetAdapterMetric(adapterId);
|
||||
return okResetSingle(ok, adapterId, "어댑터");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 인터페이스
|
||||
// =========================================================================
|
||||
|
||||
@GetMapping("/interface/metric")
|
||||
public ResponseEntity<?> getAllInterfaceMetrics() {
|
||||
List<TargetMetricDTO> list = metricService.getAllInterfaceMetrics();
|
||||
return okList(list);
|
||||
}
|
||||
|
||||
@GetMapping("/interface/{interfaceId}/metric")
|
||||
public ResponseEntity<?> getInterfaceMetric(@PathVariable String interfaceId) {
|
||||
TargetMetricDTO dto = metricService.getInterfaceMetric(interfaceId);
|
||||
return okSingle(dto, "인터페이스를 찾을 수 없습니다: " + interfaceId);
|
||||
}
|
||||
|
||||
@PostMapping("/interface/metric/reset")
|
||||
public ResponseEntity<?> resetAllInterfaceMetrics() {
|
||||
metricService.resetAllInterfaceMetrics();
|
||||
return okReset("전체 인터페이스 메트릭 초기화 완료");
|
||||
}
|
||||
|
||||
@PostMapping("/interface/{interfaceId}/metric/reset")
|
||||
public ResponseEntity<?> resetInterfaceMetric(@PathVariable String interfaceId) {
|
||||
boolean ok = metricService.resetInterfaceMetric(interfaceId);
|
||||
return okResetSingle(ok, interfaceId, "인터페이스");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Helpers
|
||||
// =========================================================================
|
||||
|
||||
private ResponseEntity<?> okList(List<TargetMetricDTO> list) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("data", list);
|
||||
result.put("count", list.size());
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> okSingle(TargetMetricDTO dto, String notFoundMsg) {
|
||||
if (dto == null) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", notFoundMsg);
|
||||
return ResponseEntity.ok(error);
|
||||
}
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("data", dto);
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> okReset(String message) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
result.put("message", message);
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> okResetSingle(boolean ok, String targetId, String targetLabel) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", ok);
|
||||
result.put("message", ok
|
||||
? "초기화 완료: " + targetId
|
||||
: targetLabel + "를 찾을 수 없습니다: " + targetId);
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
|
||||
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||
|
||||
@Service
|
||||
public class InflowTargetMetricService {
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 어댑터
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public TargetMetricDTO getAdapterMetric(String adapterId) {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager == null) return null;
|
||||
InflowTargetVO vo = manager.getAdapterInflowThreashold(adapterId);
|
||||
if (vo == null) return null;
|
||||
return buildDTO(adapterId, "ADAPTER", vo, manager.getAdapterMetrics(adapterId));
|
||||
}
|
||||
|
||||
public List<TargetMetricDTO> getAllAdapterMetrics() {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager == null) return new ArrayList<>();
|
||||
List<TargetMetricDTO> result = new ArrayList<>();
|
||||
for (String id : manager.getAdapterAllKeys()) {
|
||||
TargetMetricDTO dto = getAdapterMetric(id);
|
||||
if (dto != null) result.add(dto);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean resetAdapterMetric(String adapterId) {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager == null) return false;
|
||||
if (manager.getAdapterInflowThreashold(adapterId) == null) return false;
|
||||
manager.resetAdapterMetrics(adapterId);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void resetAllAdapterMetrics() {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager != null) manager.resetAllAdapterMetrics();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 인터페이스
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public TargetMetricDTO getInterfaceMetric(String interfaceId) {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager == null) return null;
|
||||
InflowTargetVO vo = manager.getInterfaceInflowThreashold(interfaceId);
|
||||
if (vo == null) return null;
|
||||
return buildDTO(interfaceId, "INTERFACE", vo, manager.getInterfaceMetrics(interfaceId));
|
||||
}
|
||||
|
||||
public List<TargetMetricDTO> getAllInterfaceMetrics() {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager == null) return new ArrayList<>();
|
||||
List<TargetMetricDTO> result = new ArrayList<>();
|
||||
for (String id : manager.getInterfaceAllKeys()) {
|
||||
TargetMetricDTO dto = getInterfaceMetric(id);
|
||||
if (dto != null) result.add(dto);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean resetInterfaceMetric(String interfaceId) {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager == null) return false;
|
||||
if (manager.getInterfaceInflowThreashold(interfaceId) == null) return false;
|
||||
manager.resetInterfaceMetrics(interfaceId);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void resetAllInterfaceMetrics() {
|
||||
DualInflowControlManager manager = getDualManager();
|
||||
if (manager != null) manager.resetAllInterfaceMetrics();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Private helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
protected DualInflowControlManager getDualManager() {
|
||||
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
|
||||
return (base instanceof DualInflowControlManager) ? (DualInflowControlManager) base : null;
|
||||
}
|
||||
|
||||
private TargetMetricDTO buildDTO(String targetId, String targetType,
|
||||
InflowTargetVO vo,
|
||||
DualInflowControlManager.TargetMetrics m) {
|
||||
TargetMetricDTO dto = new TargetMetricDTO();
|
||||
dto.setTargetId(targetId);
|
||||
dto.setTargetType(targetType);
|
||||
dto.setActivate(vo.isActivate());
|
||||
|
||||
if (m != null) {
|
||||
long allowed = m.allowed.get();
|
||||
long rejPs = m.rejectedPerSecond.get();
|
||||
long rejTh = m.rejectedThreshold.get();
|
||||
long total = allowed + rejPs + rejTh;
|
||||
dto.setAllowed(allowed);
|
||||
dto.setRejectedPerSecond(rejPs);
|
||||
dto.setRejectedThreshold(rejTh);
|
||||
dto.setTotalRequests(total);
|
||||
dto.setRejectRatio(total > 0
|
||||
? Math.round((double)(rejPs + rejTh) / total * 10000) / 100.0
|
||||
: 0.0);
|
||||
dto.setLastResetTime(m.lastResetTime);
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 어댑터/인터페이스/클라이언트 버킷 상태 DTO.
|
||||
* {@link GroupBucketStatusDTO}와 동일한 BucketInfo 구조를 공유한다.
|
||||
*/
|
||||
public class TargetBucketStatusDTO {
|
||||
|
||||
private String targetId; // 어댑터명 | 인터페이스ID | 클라이언트ID
|
||||
private String targetType; // "ADAPTER" | "INTERFACE" | "CLIENT"
|
||||
private boolean activate;
|
||||
private List<GroupBucketStatusDTO.BucketInfo> buckets;
|
||||
|
||||
public String getTargetId() { return targetId; }
|
||||
public void setTargetId(String targetId) { this.targetId = targetId; }
|
||||
|
||||
public String getTargetType() { return targetType; }
|
||||
public void setTargetType(String targetType) { this.targetType = targetType; }
|
||||
|
||||
public boolean isActivate() { return activate; }
|
||||
public void setActivate(boolean activate) { this.activate = activate; }
|
||||
|
||||
public List<GroupBucketStatusDTO.BucketInfo> getBuckets() { return buckets; }
|
||||
public void setBuckets(List<GroupBucketStatusDTO.BucketInfo> buckets) { this.buckets = buckets; }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
/**
|
||||
* 어댑터/인터페이스/클라이언트 메트릭 DTO.
|
||||
*/
|
||||
public class TargetMetricDTO {
|
||||
|
||||
private String targetId;
|
||||
private String targetType; // "ADAPTER" | "INTERFACE" | "CLIENT"
|
||||
private boolean activate;
|
||||
private long allowed;
|
||||
private long rejectedPerSecond;
|
||||
private long rejectedThreshold;
|
||||
private long totalRequests;
|
||||
private double rejectRatio;
|
||||
private long lastResetTime;
|
||||
|
||||
public String getTargetId() { return targetId; }
|
||||
public void setTargetId(String targetId) { this.targetId = targetId; }
|
||||
|
||||
public String getTargetType() { return targetType; }
|
||||
public void setTargetType(String targetType) { this.targetType = targetType; }
|
||||
|
||||
public boolean isActivate() { return activate; }
|
||||
public void setActivate(boolean activate) { this.activate = activate; }
|
||||
|
||||
public long getAllowed() { return allowed; }
|
||||
public void setAllowed(long allowed) { this.allowed = allowed; }
|
||||
|
||||
public long getRejectedPerSecond() { return rejectedPerSecond; }
|
||||
public void setRejectedPerSecond(long rejectedPerSecond) { this.rejectedPerSecond = rejectedPerSecond; }
|
||||
|
||||
public long getRejectedThreshold() { return rejectedThreshold; }
|
||||
public void setRejectedThreshold(long rejectedThreshold) { this.rejectedThreshold = rejectedThreshold; }
|
||||
|
||||
public long getTotalRequests() { return totalRequests; }
|
||||
public void setTotalRequests(long totalRequests) { this.totalRequests = totalRequests; }
|
||||
|
||||
public double getRejectRatio() { return rejectRatio; }
|
||||
public void setRejectRatio(double rejectRatio) { this.rejectRatio = rejectRatio; }
|
||||
|
||||
public long getLastResetTime() { return lastResetTime; }
|
||||
public void setLastResetTime(long lastResetTime) { this.lastResetTime = lastResetTime; }
|
||||
}
|
||||
@@ -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,20 +1,14 @@
|
||||
# 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
|
||||
requestProcessor.class=com.eactive.eai.custom.inbound.processor.DJBRequestProcessor
|
||||
# reader : parsing input data to StandardMessage
|
||||
reader.JSON=com.eactive.eai.message.parser.JsonReader
|
||||
reader.JSN=com.eactive.eai.message.parser.JsonReader
|
||||
@@ -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=
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.json.simple.JSONObject;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.context.support.GenericApplicationContext;
|
||||
|
||||
import com.eactive.eai.common.security.CryptoModuleService;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
|
||||
@TestMethodOrder(MethodOrderer.DisplayName.class)
|
||||
class DJBErpCryptoFilterTest {
|
||||
|
||||
private static final String MODULE_NAME = "TEST_MODULE";
|
||||
// 복호화 후 평문 (JSON 문자열)
|
||||
private static final String PLAIN_TEXT = "{\"userId\":\"U001\",\"name\":\"test\"}";
|
||||
private static final byte[] PLAIN_BYTES = PLAIN_TEXT.getBytes(StandardCharsets.UTF_8);
|
||||
// 더미 암호문 bytes + Base64 표현
|
||||
private static final byte[] CIPHER_BYTES = new byte[]{0x10, 0x20, 0x30, 0x40};
|
||||
private static final String ENC_BASE64 = Base64.getEncoder().encodeToString(CIPHER_BYTES);
|
||||
|
||||
// 기본 httpHeaderGroup 헤더 JSON (groupSeq|empNo 형태)
|
||||
private static final String HEADER_JSON_WITH_PIPE = "{\"x-emp-nm\":\"G001|E001\"}";
|
||||
private static final String HEADER_JSON_WITHOUT_PIPE = "{\"x-emp-nm\":\"G001\"}";
|
||||
|
||||
private static GenericApplicationContext ctx;
|
||||
private static CryptoModuleService mockCryptoService;
|
||||
|
||||
private DJBErpCryptoFilter filter;
|
||||
private HttpServletRequest mockRequest;
|
||||
private Properties prop;
|
||||
|
||||
// =========================================================================
|
||||
// 클래스 초기화 — Spring ApplicationContext + Mock CryptoModuleService
|
||||
// =========================================================================
|
||||
|
||||
@BeforeAll
|
||||
static void setUpClass() throws Exception {
|
||||
mockCryptoService = mock(CryptoModuleService.class);
|
||||
|
||||
ctx = new GenericApplicationContext();
|
||||
ctx.getBeanFactory().registerSingleton("cryptoModuleService", mockCryptoService);
|
||||
ctx.registerBeanDefinition("applicationContextProvider",
|
||||
BeanDefinitionBuilder.genericBeanDefinition(ApplicationContextProvider.class)
|
||||
.getBeanDefinition());
|
||||
ctx.refresh();
|
||||
|
||||
when(mockCryptoService.decrypt(anyString(), anyMap(), any(byte[].class)))
|
||||
.thenReturn(PLAIN_BYTES);
|
||||
when(mockCryptoService.encrypt(anyString(), anyMap(), any(byte[].class)))
|
||||
.thenReturn(CIPHER_BYTES);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownClass() {
|
||||
if (ctx != null) ctx.close();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
clearInvocations(mockCryptoService); // 이전 테스트의 호출 이력 초기화 (stubbing은 유지)
|
||||
filter = new DJBErpCryptoFilter();
|
||||
mockRequest = mock(HttpServletRequest.class);
|
||||
prop = new Properties();
|
||||
prop.setProperty(DJBErpCryptoFilter.PROP_MODULE_NAME, MODULE_NAME);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 1. buildRuntimeContext
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("1-1. x-emp-nm이 'groupSeq|empNo' 형태이면 '|' 앞부분만 groupSeq로 추출")
|
||||
void buildRuntimeContext_pipeFormat_extractsGroupSeqOnly() {
|
||||
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
|
||||
|
||||
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
|
||||
|
||||
assertEquals("G001", runtimeCtx.get("groupSeq"));
|
||||
assertEquals(1, runtimeCtx.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-2. x-emp-nm에 '|'가 없으면 전체 값을 groupSeq로 사용")
|
||||
void buildRuntimeContext_noPipe_usesFullValue() {
|
||||
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITHOUT_PIPE);
|
||||
|
||||
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
|
||||
|
||||
assertEquals("G001", runtimeCtx.get("groupSeq"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-3. httpHeaderGroup 헤더가 없으면 빈 Map 반환")
|
||||
void buildRuntimeContext_headerMissing_returnsEmptyMap() {
|
||||
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(null);
|
||||
|
||||
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
|
||||
|
||||
assertTrue(runtimeCtx.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-4. 헤더 JSON에 x-emp-nm 필드가 없으면 빈 Map 반환")
|
||||
void buildRuntimeContext_fieldMissingInJson_returnsEmptyMap() {
|
||||
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn("{\"other-field\":\"value\"}");
|
||||
|
||||
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
|
||||
|
||||
assertTrue(runtimeCtx.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-5. 프로퍼티로 헤더명/필드명/컨텍스트키를 커스터마이징할 수 있다")
|
||||
void buildRuntimeContext_customProps_overrideDefaults() {
|
||||
prop.setProperty(DJBErpCryptoFilter.PROP_CONTEXT_HEADER, "X-Custom-Header");
|
||||
prop.setProperty(DJBErpCryptoFilter.PROP_CONTEXT_HEADER_FIELD, "emp-id");
|
||||
prop.setProperty(DJBErpCryptoFilter.PROP_CONTEXT_KEY, "empGroup");
|
||||
|
||||
when(mockRequest.getHeader("X-Custom-Header")).thenReturn("{\"emp-id\":\"GRP99|EMP99\"}");
|
||||
|
||||
Map<String, String> runtimeCtx = filter.buildRuntimeContext(prop, mockRequest);
|
||||
|
||||
assertEquals("GRP99", runtimeCtx.get("empGroup"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 2. doPreFilter — 복호화
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("2-1. crypto.dec.enabled=N 이면 message를 그대로 반환하고 복호화하지 않는다")
|
||||
void doPreFilter_decDisabled_returnsOriginalWithoutDecrypt() throws Exception {
|
||||
prop.setProperty("crypto.dec.enabled", "N");
|
||||
String original = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
|
||||
|
||||
Object result = filter.doPreFilter(null, null, original, prop, mockRequest, null);
|
||||
|
||||
assertSame(original, result);
|
||||
verifyNoInteractions(mockCryptoService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-2. FIELD scope: /encryptedData 복호화 후 dec.to.path=/ 이면 body 전체를 평문으로 교체")
|
||||
void doPreFilter_fieldScope_toRoot_replacesEntireBody() throws Exception {
|
||||
setFieldDecryptProps("/encryptedData", "/");
|
||||
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
|
||||
|
||||
String body = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
|
||||
Object result = filter.doPreFilter(null, null, body, prop, mockRequest, null);
|
||||
|
||||
assertEquals(PLAIN_TEXT, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-3. FIELD scope: dec.to.path가 특정 경로이면 해당 필드에 복호화 결과를 설정")
|
||||
void doPreFilter_fieldScope_toSpecificPath_setsFieldInBody() throws Exception {
|
||||
setFieldDecryptProps("/encryptedData", "/plainData");
|
||||
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
|
||||
|
||||
String body = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
|
||||
String result = (String) filter.doPreFilter(null, null, body, prop, mockRequest, null);
|
||||
|
||||
assertTrue(result.contains("\"encryptedData\""), "원본 필드가 유지되어야 한다");
|
||||
assertTrue(result.contains("\"plainData\""), "복호화 결과 필드가 추가되어야 한다");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-4. FIELD scope: 복호화 대상 필드가 JSON에 없으면 원본 body를 그대로 반환")
|
||||
void doPreFilter_fieldScope_missingEncryptedField_returnsOriginalBody() throws Exception {
|
||||
setFieldDecryptProps("/encryptedData", "/");
|
||||
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
|
||||
|
||||
String body = "{\"otherField\":\"value\"}";
|
||||
Object result = filter.doPreFilter(null, null, body, prop, mockRequest, null);
|
||||
|
||||
assertEquals(body, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-5. BODY scope: message가 Base64 String이면 전체 복호화")
|
||||
void doPreFilter_bodyScope_stringMessage_decryptsWholeBody() throws Exception {
|
||||
prop.setProperty("crypto.scope", "BODY");
|
||||
|
||||
Object result = filter.doPreFilter(null, null, ENC_BASE64, prop, mockRequest, null);
|
||||
|
||||
assertEquals(PLAIN_TEXT, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-6. message가 byte[]이면 UTF-8 변환 후 FIELD 복호화 처리")
|
||||
void doPreFilter_fieldScope_byteArrayMessage_convertsAndDecrypts() throws Exception {
|
||||
setFieldDecryptProps("/encryptedData", "/");
|
||||
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
|
||||
|
||||
byte[] bodyBytes = ("{\"encryptedData\":\"" + ENC_BASE64 + "\"}").getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
Object result = filter.doPreFilter(null, null, bodyBytes, prop, mockRequest, null);
|
||||
|
||||
assertEquals(PLAIN_TEXT, result);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
@DisplayName("2-7. message가 JSONObject이면 toString() 변환 후 FIELD 복호화 처리")
|
||||
void doPreFilter_fieldScope_jsonObjectMessage_convertsAndDecrypts() throws Exception {
|
||||
setFieldDecryptProps("/encryptedData", "/");
|
||||
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
|
||||
|
||||
JSONObject jsonMsg = new JSONObject();
|
||||
jsonMsg.put("encryptedData", ENC_BASE64);
|
||||
|
||||
Object result = filter.doPreFilter(null, null, jsonMsg, prop, mockRequest, null);
|
||||
|
||||
assertEquals(PLAIN_TEXT, result);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
@DisplayName("2-8. FIELD scope: runtimeContext에 groupSeq가 올바르게 전달된다")
|
||||
void doPreFilter_fieldScope_runtimeContextPassedToDecrypt() throws Exception {
|
||||
setFieldDecryptProps("/encryptedData", "/");
|
||||
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
|
||||
|
||||
String body = "{\"encryptedData\":\"" + ENC_BASE64 + "\"}";
|
||||
filter.doPreFilter(null, null, body, prop, mockRequest, null);
|
||||
|
||||
ArgumentCaptor<Map> ctxCaptor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(mockCryptoService).decrypt(eq(MODULE_NAME), ctxCaptor.capture(), any(byte[].class));
|
||||
assertEquals("G001", ctxCaptor.getValue().get("groupSeq"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 3. doPostFilter — 암호화
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("3-1. crypto.enc.enabled 기본값(N) — resultMessage를 그대로 반환하고 암호화하지 않는다")
|
||||
void doPostFilter_encDisabledByDefault_returnsOriginalWithoutEncrypt() throws Exception {
|
||||
String original = "{\"result\":\"ok\"}";
|
||||
|
||||
Object result = filter.doPostFilter(null, null, original, prop, mockRequest, null);
|
||||
|
||||
assertSame(original, result);
|
||||
verifyNoInteractions(mockCryptoService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3-2. BODY scope, enc.enabled=Y — body 전체를 암호화하여 Base64 반환")
|
||||
void doPostFilter_bodyScope_encEnabled_returnsBase64() throws Exception {
|
||||
prop.setProperty("crypto.scope", "BODY");
|
||||
prop.setProperty("crypto.enc.enabled", "Y");
|
||||
|
||||
Object result = filter.doPostFilter(null, null, PLAIN_TEXT, prop, mockRequest, null);
|
||||
|
||||
assertEquals(ENC_BASE64, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3-3. FIELD scope, enc.from.path=/ — body 전체 암호화 후 enc.to.path 필드로 래핑")
|
||||
void doPostFilter_fieldScope_fromRoot_wrapsEncryptedInJson() throws Exception {
|
||||
prop.setProperty("crypto.scope", "FIELD");
|
||||
prop.setProperty("crypto.enc.enabled", "Y");
|
||||
prop.setProperty("crypto.enc.from.path", "/");
|
||||
prop.setProperty("crypto.enc.to.path", "/encryptedData");
|
||||
|
||||
Object result = filter.doPostFilter(null, null, PLAIN_TEXT, prop, mockRequest, null);
|
||||
|
||||
assertEquals("{\"encryptedData\":\"" + ENC_BASE64 + "\"}", result);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
@DisplayName("3-4. FIELD scope: runtimeContext에 groupSeq가 올바르게 전달된다")
|
||||
void doPostFilter_fieldScope_runtimeContextPassedToEncrypt() throws Exception {
|
||||
prop.setProperty("crypto.scope", "FIELD");
|
||||
prop.setProperty("crypto.enc.enabled", "Y");
|
||||
prop.setProperty("crypto.enc.from.path", "/");
|
||||
prop.setProperty("crypto.enc.to.path", "/encryptedData");
|
||||
when(mockRequest.getHeader("httpHeaderGroup")).thenReturn(HEADER_JSON_WITH_PIPE);
|
||||
|
||||
filter.doPostFilter(null, null, PLAIN_TEXT, prop, mockRequest, null);
|
||||
|
||||
ArgumentCaptor<Map> ctxCaptor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(mockCryptoService).encrypt(eq(MODULE_NAME), ctxCaptor.capture(), any(byte[].class));
|
||||
assertEquals("G001", ctxCaptor.getValue().get("groupSeq"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 헬퍼
|
||||
// =========================================================================
|
||||
|
||||
private void setFieldDecryptProps(String fromPath, String toPath) {
|
||||
prop.setProperty("crypto.scope", "FIELD");
|
||||
prop.setProperty("crypto.dec.from.path", fromPath);
|
||||
prop.setProperty("crypto.dec.to.path", toPath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package com.eactive.eai.custom.inbound.processor;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import com.eactive.eai.common.inflow.Bucket;
|
||||
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||
import com.eactive.eai.common.inflow.dual.ClientDualBucket;
|
||||
import com.eactive.eai.common.inflow.dual.DualBucket;
|
||||
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
|
||||
/**
|
||||
* DJBRequestProcessor 단위 테스트.
|
||||
*
|
||||
* <p>RequestProcessor 클래스는 static 초기화 블록에서 EAIServerManager.getInstance()를 호출한다.
|
||||
* @BeforeAll에서 mock ApplicationContext를 주입한 뒤 DJBRequestProcessor를 최초 로딩시킨다.
|
||||
*
|
||||
* <p>주의: DJBRequestProcessor를 필드 타입으로 선언하면 테스트 클래스 로딩 시 함께 로딩되어
|
||||
* @BeforeAll 실행 전에 NPE가 발생한다. 반드시 메서드 본문 내에서만 참조해야 한다.
|
||||
*/
|
||||
class DJBRequestProcessorTest {
|
||||
|
||||
@BeforeAll
|
||||
static void setupMockApplicationContext() {
|
||||
ApplicationContext mockContext = mock(ApplicationContext.class);
|
||||
EAIServerManager mockServerManager = mock(EAIServerManager.class);
|
||||
when(mockContext.getBean(EAIServerManager.class)).thenReturn(mockServerManager);
|
||||
when(mockServerManager.getLocalServerName()).thenReturn("TEST-SERVER");
|
||||
when(mockServerManager.getGroupInstId()).thenReturn("TEST-INST");
|
||||
|
||||
ReflectionTestUtils.setField(ApplicationContextProvider.class, "context", mockContext);
|
||||
}
|
||||
|
||||
private InflowTargetVO makeVO(String name, long perSec, long threshold, String unit) {
|
||||
InflowTargetVO vo = new InflowTargetVO();
|
||||
vo.setName(name);
|
||||
vo.setThresholdPerSecond(perSec);
|
||||
vo.setThreshold(threshold);
|
||||
vo.setThresholdTimeUnit(unit);
|
||||
vo.setActivate(true);
|
||||
return vo;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// checkAdapterInflow
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void checkAdapterInflow_dualBucket_pass_returnsNull() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
DualBucket mockBucket = mock(DualBucket.class);
|
||||
when(mockBucket.isAdapterPassDetail("ADAPTER_A")).thenReturn(null);
|
||||
|
||||
assertNull(processor.checkAdapterInflow(mockBucket, "ADAPTER_A"));
|
||||
verify(mockBucket).isAdapterPassDetail("ADAPTER_A");
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkAdapterInflow_dualBucket_blockedPerSecond() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
DualBucket mockBucket = mock(DualBucket.class);
|
||||
when(mockBucket.isAdapterPassDetail("ADAPTER_A")).thenReturn(DualCustomBucket.RESULT_BLOCKED_PER_SECOND);
|
||||
|
||||
assertEquals(DualCustomBucket.RESULT_BLOCKED_PER_SECOND,
|
||||
processor.checkAdapterInflow(mockBucket, "ADAPTER_A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkAdapterInflow_dualBucket_blockedThreshold() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
DualBucket mockBucket = mock(DualBucket.class);
|
||||
when(mockBucket.isAdapterPassDetail("ADAPTER_A")).thenReturn(DualCustomBucket.RESULT_BLOCKED_THRESHOLD);
|
||||
|
||||
assertEquals(DualCustomBucket.RESULT_BLOCKED_THRESHOLD,
|
||||
processor.checkAdapterInflow(mockBucket, "ADAPTER_A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkAdapterInflow_nonDualBucket_pass_returnsNull() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
Bucket mockBucket = mock(Bucket.class);
|
||||
when(mockBucket.isAdapterPass("ADAPTER_A")).thenReturn(true);
|
||||
|
||||
assertNull(processor.checkAdapterInflow(mockBucket, "ADAPTER_A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkAdapterInflow_nonDualBucket_blocked_returnsBlocked() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
Bucket mockBucket = mock(Bucket.class);
|
||||
when(mockBucket.isAdapterPass("ADAPTER_A")).thenReturn(false);
|
||||
|
||||
assertEquals("BLOCKED", processor.checkAdapterInflow(mockBucket, "ADAPTER_A"));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// checkInterfaceInflow
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void checkInterfaceInflow_dualBucket_pass_returnsNull() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
DualBucket mockBucket = mock(DualBucket.class);
|
||||
when(mockBucket.isInterfacePassDetail("IF_001")).thenReturn(null);
|
||||
|
||||
assertNull(processor.checkInterfaceInflow(mockBucket, "IF_001"));
|
||||
verify(mockBucket).isInterfacePassDetail("IF_001");
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkInterfaceInflow_dualBucket_blockedPerSecond() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
DualBucket mockBucket = mock(DualBucket.class);
|
||||
when(mockBucket.isInterfacePassDetail("IF_001")).thenReturn(DualCustomBucket.RESULT_BLOCKED_PER_SECOND);
|
||||
|
||||
assertEquals(DualCustomBucket.RESULT_BLOCKED_PER_SECOND,
|
||||
processor.checkInterfaceInflow(mockBucket, "IF_001"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkInterfaceInflow_nonDualBucket_pass_returnsNull() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
Bucket mockBucket = mock(Bucket.class);
|
||||
when(mockBucket.isInterfacePass("IF_001")).thenReturn(true);
|
||||
|
||||
assertNull(processor.checkInterfaceInflow(mockBucket, "IF_001"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkInterfaceInflow_nonDualBucket_blocked_returnsBlocked() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
Bucket mockBucket = mock(Bucket.class);
|
||||
when(mockBucket.isInterfacePass("IF_001")).thenReturn(false);
|
||||
|
||||
assertEquals("BLOCKED", processor.checkInterfaceInflow(mockBucket, "IF_001"));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// checkClientInflow — ClientDualBucket 기반
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void checkClientInflow_clientDualBucket_pass_returnsNull() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
ClientDualBucket mockBucket = mock(ClientDualBucket.class);
|
||||
when(mockBucket.isClientPassDetail("CLIENT_A")).thenReturn(null);
|
||||
|
||||
assertNull(processor.checkClientInflow(mockBucket, "CLIENT_A"));
|
||||
verify(mockBucket).isClientPassDetail("CLIENT_A");
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkClientInflow_clientDualBucket_blocked() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
ClientDualBucket mockBucket = mock(ClientDualBucket.class);
|
||||
when(mockBucket.isClientPassDetail("CLIENT_A")).thenReturn(DualCustomBucket.RESULT_BLOCKED_THRESHOLD);
|
||||
|
||||
assertEquals(DualCustomBucket.RESULT_BLOCKED_THRESHOLD,
|
||||
processor.checkClientInflow(mockBucket, "CLIENT_A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkClientInflow_nonClientDualBucket_returnsNull() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
Bucket mockBucket = mock(Bucket.class);
|
||||
|
||||
assertNull(processor.checkClientInflow(mockBucket, "CLIENT_A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkClientInflow_blankClientId_returnsNull() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
ClientDualBucket mockBucket = mock(ClientDualBucket.class);
|
||||
|
||||
assertNull(processor.checkClientInflow(mockBucket, ""));
|
||||
verify(mockBucket, never()).isClientPassDetail(any());
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// buildInflowTargetErrorMsg
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void buildInflowTargetErrorMsg_perSecond_includesReqPerSec() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
InflowTargetVO vo = makeVO("결제API", 30, 1000, "MIN");
|
||||
|
||||
String msg = processor.buildInflowTargetErrorMsg(vo, DualCustomBucket.RESULT_BLOCKED_PER_SECOND);
|
||||
|
||||
assertEquals("API 호출 한도 초과 [결제API: 30req/sec]", msg);
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildInflowTargetErrorMsg_threshold_includesReqPerUnit() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
InflowTargetVO vo = makeVO("결제API", 30, 1000, "MIN");
|
||||
|
||||
String msg = processor.buildInflowTargetErrorMsg(vo, DualCustomBucket.RESULT_BLOCKED_THRESHOLD);
|
||||
|
||||
assertEquals("API 호출 한도 초과 [결제API: 1000req/MIN]", msg);
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildInflowTargetErrorMsg_blockedFallback_simpleFormat() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
InflowTargetVO vo = makeVO("결제API", 30, 1000, "MIN");
|
||||
|
||||
String msg = processor.buildInflowTargetErrorMsg(vo, "BLOCKED");
|
||||
|
||||
assertEquals("API 호출 한도 초과 [결제API]", msg);
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildInflowTargetErrorMsg_nullBlockedType_simpleFormat() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
InflowTargetVO vo = makeVO("결제API", 30, 1000, "MIN");
|
||||
|
||||
String msg = processor.buildInflowTargetErrorMsg(vo, null);
|
||||
|
||||
assertEquals("API 호출 한도 초과 [결제API]", msg);
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildInflowTargetErrorMsg_hourUnit() {
|
||||
DJBRequestProcessor processor = new DJBRequestProcessor();
|
||||
InflowTargetVO vo = makeVO("조회API", 10, 500, "HOUR");
|
||||
|
||||
String msg = processor.buildInflowTargetErrorMsg(vo, DualCustomBucket.RESULT_BLOCKED_THRESHOLD);
|
||||
|
||||
assertEquals("API 호출 한도 초과 [조회API: 500req/HOUR]", msg);
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.eactive.eai.custom.inflow;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import com.eactive.eai.manage.inflow.TargetBucketStatusDTO;
|
||||
|
||||
/**
|
||||
* ClientInflowTargetBucketController 단위 테스트.
|
||||
*/
|
||||
class ClientInflowTargetBucketControllerTest {
|
||||
|
||||
private ClientInflowTargetBucketController controller;
|
||||
private ClientInflowTargetBucketService mockService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
controller = new ClientInflowTargetBucketController();
|
||||
mockService = mock(ClientInflowTargetBucketService.class);
|
||||
ReflectionTestUtils.setField(controller, "bucketService", mockService);
|
||||
}
|
||||
|
||||
private TargetBucketStatusDTO makeDTO(String id, String type) {
|
||||
TargetBucketStatusDTO dto = new TargetBucketStatusDTO();
|
||||
dto.setTargetId(id);
|
||||
dto.setTargetType(type);
|
||||
dto.setActivate(true);
|
||||
dto.setBuckets(Collections.emptyList());
|
||||
return dto;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> body(ResponseEntity<?> response) {
|
||||
return (Map<String, Object>) response.getBody();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 단일 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getClientBucketStatus_found_successTrueAndDataPresent() {
|
||||
TargetBucketStatusDTO dto = makeDTO("CLIENT_A", "CLIENT");
|
||||
when(mockService.getClientBucketStatus("CLIENT_A")).thenReturn(dto);
|
||||
|
||||
ResponseEntity<?> response = controller.getClientBucketStatus("CLIENT_A");
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(200, response.getStatusCodeValue());
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(dto, body.get("data"));
|
||||
assertFalse(body.containsKey("message"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getClientBucketStatus_notFound_successFalseWithClientId() {
|
||||
when(mockService.getClientBucketStatus("CLIENT_X")).thenReturn(null);
|
||||
|
||||
ResponseEntity<?> response = controller.getClientBucketStatus("CLIENT_X");
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(Boolean.FALSE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("CLIENT_X"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 전체 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllClientBucketStatus_returnsListAndCount() {
|
||||
List<TargetBucketStatusDTO> list = Arrays.asList(
|
||||
makeDTO("CLIENT_A", "CLIENT"),
|
||||
makeDTO("CLIENT_B", "CLIENT"),
|
||||
makeDTO("CLIENT_C", "CLIENT")
|
||||
);
|
||||
when(mockService.getAllClientBucketStatus()).thenReturn(list);
|
||||
|
||||
ResponseEntity<?> response = controller.getAllClientBucketStatus();
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(list, body.get("data"));
|
||||
assertEquals(3, body.get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllClientBucketStatus_emptyList_countZero() {
|
||||
when(mockService.getAllClientBucketStatus()).thenReturn(Collections.emptyList());
|
||||
|
||||
Map<String, Object> body = body(controller.getAllClientBucketStatus());
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertEquals(0, body.get("count"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package com.eactive.eai.custom.inflow;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
|
||||
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
|
||||
import com.eactive.eai.manage.inflow.GroupBucketStatusDTO;
|
||||
import com.eactive.eai.manage.inflow.TargetBucketStatusDTO;
|
||||
|
||||
import io.github.bucket4j.Bandwidth;
|
||||
import io.github.bucket4j.Bucket4j;
|
||||
import io.github.bucket4j.local.LocalBucket;
|
||||
|
||||
/**
|
||||
* ClientInflowTargetBucketService 단위 테스트.
|
||||
*/
|
||||
class ClientInflowTargetBucketServiceTest {
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 테스트용 서브클래스
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private static ClientInflowTargetBucketService serviceWith(ClientDualInflowControlManager manager) {
|
||||
return new ClientInflowTargetBucketService() {
|
||||
@Override
|
||||
protected ClientDualInflowControlManager getClientDualManager() { return manager; }
|
||||
};
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private InflowTargetVO makeVO(String name, long perSec, long threshold, String unit, boolean activate) {
|
||||
InflowTargetVO vo = new InflowTargetVO();
|
||||
vo.setName(name);
|
||||
vo.setThresholdPerSecond(perSec);
|
||||
vo.setThreshold(threshold);
|
||||
vo.setThresholdTimeUnit(unit);
|
||||
vo.setActivate(activate);
|
||||
return vo;
|
||||
}
|
||||
|
||||
private LocalBucket freshBucket(long capacity) {
|
||||
return Bucket4j.builder()
|
||||
.addLimit(Bandwidth.simple(capacity, Duration.ofSeconds(1)))
|
||||
.build();
|
||||
}
|
||||
|
||||
private LocalBucket exhaustedBucket(long capacity) {
|
||||
LocalBucket b = freshBucket(capacity);
|
||||
b.tryConsume(capacity);
|
||||
return b;
|
||||
}
|
||||
|
||||
private DualCustomBucket makeDualBucket(String name, long perSec, long threshold) {
|
||||
return new DualCustomBucket(freshBucket(perSec), freshBucket(threshold),
|
||||
makeVO(name, perSec, threshold, "DAY", true));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// ClientDualManager null (비활성 환경)
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getClientBucketStatus_managerIsNull_returnsNull() {
|
||||
assertNull(serviceWith(null).getClientBucketStatus("CLIENT_A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllClientBucketStatus_managerIsNull_returnsEmptyList() {
|
||||
assertTrue(serviceWith(null).getAllClientBucketStatus().isEmpty());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 버킷 미존재
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getClientBucketStatus_notFound_returnsNull() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientBucket("CLIENT_A")).thenReturn(null);
|
||||
|
||||
assertNull(serviceWith(manager).getClientBucketStatus("CLIENT_A"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 단일 조회 — targetType, targetId 매핑
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getClientBucketStatus_found_mapsClientType() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientBucket("CLIENT_A")).thenReturn(makeDualBucket("CLIENT_A", 50, 5000));
|
||||
|
||||
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("CLIENT_A");
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("CLIENT_A", dto.getTargetId());
|
||||
assertEquals("CLIENT", dto.getTargetType());
|
||||
assertTrue(dto.isActivate());
|
||||
assertEquals(2, dto.getBuckets().size());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// BucketInfo 타입별 포함 여부
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void toDto_onlyThreshold_bucketInfoHasOneThresholdEntry() {
|
||||
InflowTargetVO vo = makeVO("C1", 0, 1000, "DAY", true);
|
||||
DualCustomBucket bucket = new DualCustomBucket(null, freshBucket(1000), vo);
|
||||
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientBucket("C1")).thenReturn(bucket);
|
||||
|
||||
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C1");
|
||||
|
||||
assertEquals(1, dto.getBuckets().size());
|
||||
assertEquals("threshold", dto.getBuckets().get(0).getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void toDto_onlyPerSecond_bucketInfoHasOnePerSecondEntry() {
|
||||
InflowTargetVO vo = makeVO("C2", 100, 0, null, true);
|
||||
DualCustomBucket bucket = new DualCustomBucket(freshBucket(100), null, vo);
|
||||
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientBucket("C2")).thenReturn(bucket);
|
||||
|
||||
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C2");
|
||||
|
||||
assertEquals(1, dto.getBuckets().size());
|
||||
assertEquals("perSecond", dto.getBuckets().get(0).getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void toDto_bothBuckets_bucketInfoHasTwoEntries() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientBucket("C3")).thenReturn(makeDualBucket("C3", 100, 5000));
|
||||
|
||||
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C3");
|
||||
|
||||
assertEquals(2, dto.getBuckets().size());
|
||||
assertEquals("perSecond", dto.getBuckets().get(0).getType());
|
||||
assertEquals("threshold", dto.getBuckets().get(1).getType());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 사용률 계산
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void toDto_exhaustedThreshold_usagePercentIs100() {
|
||||
InflowTargetVO vo = makeVO("C4", 0, 100, "DAY", true);
|
||||
DualCustomBucket bucket = new DualCustomBucket(null, exhaustedBucket(100), vo);
|
||||
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientBucket("C4")).thenReturn(bucket);
|
||||
|
||||
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C4");
|
||||
|
||||
GroupBucketStatusDTO.BucketInfo info = dto.getBuckets().get(0);
|
||||
assertEquals(0, info.getAvailableTokens());
|
||||
assertEquals(100.0, info.getUsagePercent(), 0.01);
|
||||
}
|
||||
|
||||
@Test
|
||||
void toDto_freshBucket_usagePercentIsZero() {
|
||||
InflowTargetVO vo = makeVO("C5", 0, 100, "DAY", true);
|
||||
DualCustomBucket bucket = new DualCustomBucket(null, freshBucket(100), vo);
|
||||
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientBucket("C5")).thenReturn(bucket);
|
||||
|
||||
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C5");
|
||||
|
||||
GroupBucketStatusDTO.BucketInfo info = dto.getBuckets().get(0);
|
||||
assertEquals(100, info.getAvailableTokens());
|
||||
assertEquals(0.0, info.getUsagePercent(), 0.01);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 전체 목록 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllClientBucketStatus_twoEntries_returnsBoth() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
|
||||
map.put("CLIENT_A", makeDualBucket("CLIENT_A", 10, 1000));
|
||||
map.put("CLIENT_B", makeDualBucket("CLIENT_B", 20, 2000));
|
||||
when(manager.getClientBucketMap()).thenReturn(map);
|
||||
|
||||
List<TargetBucketStatusDTO> result = serviceWith(manager).getAllClientBucketStatus();
|
||||
|
||||
assertEquals(2, result.size());
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package com.eactive.eai.custom.inflow;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import com.eactive.eai.manage.inflow.TargetMetricDTO;
|
||||
|
||||
/**
|
||||
* ClientInflowTargetMetricController 단위 테스트.
|
||||
*
|
||||
* <p>Spring MVC를 기동하지 않고 컨트롤러를 직접 인스턴스화하여
|
||||
* 응답 구조(success, data, count, message)를 검증한다.
|
||||
*/
|
||||
class ClientInflowTargetMetricControllerTest {
|
||||
|
||||
private ClientInflowTargetMetricController controller;
|
||||
private ClientInflowTargetMetricService mockService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
controller = new ClientInflowTargetMetricController();
|
||||
mockService = mock(ClientInflowTargetMetricService.class);
|
||||
ReflectionTestUtils.setField(controller, "metricService", mockService);
|
||||
}
|
||||
|
||||
private TargetMetricDTO makeDTO(String targetId, String targetType,
|
||||
long allowed, long rejPs, long rejTh) {
|
||||
TargetMetricDTO dto = new TargetMetricDTO();
|
||||
dto.setTargetId(targetId);
|
||||
dto.setTargetType(targetType);
|
||||
dto.setActivate(true);
|
||||
dto.setAllowed(allowed);
|
||||
dto.setRejectedPerSecond(rejPs);
|
||||
dto.setRejectedThreshold(rejTh);
|
||||
long total = allowed + rejPs + rejTh;
|
||||
dto.setTotalRequests(total);
|
||||
dto.setRejectRatio(total > 0 ? (double)(rejPs + rejTh) / total * 100 : 0.0);
|
||||
return dto;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> body(ResponseEntity<?> response) {
|
||||
return (Map<String, Object>) response.getBody();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 단일 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getClientMetric_found_successTrueAndDataPresent() {
|
||||
TargetMetricDTO dto = makeDTO("C1", "CLIENT", 300, 50, 20);
|
||||
when(mockService.getClientMetric("C1")).thenReturn(dto);
|
||||
|
||||
Map<String, Object> body = body(controller.getClientMetric("C1"));
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(dto, body.get("data"));
|
||||
assertFalse(body.containsKey("message"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getClientMetric_notFound_successFalseWithMessage() {
|
||||
when(mockService.getClientMetric("GHOST")).thenReturn(null);
|
||||
|
||||
Map<String, Object> body = body(controller.getClientMetric("GHOST"));
|
||||
|
||||
assertEquals(Boolean.FALSE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 전체 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllClientMetrics_returnsListAndCount() {
|
||||
List<TargetMetricDTO> list = Arrays.asList(
|
||||
makeDTO("C1", "CLIENT", 100, 5, 5),
|
||||
makeDTO("C2", "CLIENT", 200, 0, 0),
|
||||
makeDTO("C3", "CLIENT", 50, 10, 0)
|
||||
);
|
||||
when(mockService.getAllClientMetrics()).thenReturn(list);
|
||||
|
||||
Map<String, Object> body = body(controller.getAllClientMetrics());
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(list, body.get("data"));
|
||||
assertEquals(3, body.get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllClientMetrics_emptyList_countZero() {
|
||||
when(mockService.getAllClientMetrics()).thenReturn(Collections.emptyList());
|
||||
|
||||
Map<String, Object> body = body(controller.getAllClientMetrics());
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertEquals(0, body.get("count"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// reset
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void resetClientMetric_success_successTrueWithTargetId() {
|
||||
when(mockService.resetClientMetric("C1")).thenReturn(true);
|
||||
|
||||
Map<String, Object> body = body(controller.resetClientMetric("C1"));
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("C1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetClientMetric_notFound_successFalseWithTargetId() {
|
||||
when(mockService.resetClientMetric("GHOST")).thenReturn(false);
|
||||
|
||||
Map<String, Object> body = body(controller.resetClientMetric("GHOST"));
|
||||
|
||||
assertEquals(Boolean.FALSE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAllClientMetrics_callsDelegateOnce() {
|
||||
doNothing().when(mockService).resetAllClientMetrics();
|
||||
|
||||
controller.resetAllClientMetrics();
|
||||
|
||||
verify(mockService, times(1)).resetAllClientMetrics();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package com.eactive.eai.custom.inflow;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||
import com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager;
|
||||
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||
import com.eactive.eai.manage.inflow.TargetMetricDTO;
|
||||
|
||||
class ClientInflowTargetMetricServiceTest {
|
||||
|
||||
private static ClientInflowTargetMetricService serviceWith(ClientDualInflowControlManager manager) {
|
||||
return new ClientInflowTargetMetricService() {
|
||||
@Override
|
||||
protected ClientDualInflowControlManager getClientDualManager() { return manager; }
|
||||
};
|
||||
}
|
||||
|
||||
private InflowTargetVO makeVO(String name) {
|
||||
InflowTargetVO vo = new InflowTargetVO();
|
||||
vo.setName(name);
|
||||
vo.setActivate(true);
|
||||
return vo;
|
||||
}
|
||||
|
||||
private DualInflowControlManager.TargetMetrics makeMetrics(long allowed, long rejPs, long rejTh) {
|
||||
DualInflowControlManager.TargetMetrics m = new DualInflowControlManager.TargetMetrics();
|
||||
m.allowed.set(allowed);
|
||||
m.rejectedPerSecond.set(rejPs);
|
||||
m.rejectedThreshold.set(rejTh);
|
||||
return m;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// null 관리자 (비활성 환경)
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getClientMetric_managerIsNull_returnsNull() {
|
||||
assertNull(serviceWith(null).getClientMetric("C1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllClientMetrics_managerIsNull_returnsEmptyList() {
|
||||
assertTrue(serviceWith(null).getAllClientMetrics().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetClientMetric_managerIsNull_returnsFalse() {
|
||||
assertFalse(serviceWith(null).resetClientMetric("C1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAllClientMetrics_managerIsNull_noException() {
|
||||
assertDoesNotThrow(() -> serviceWith(null).resetAllClientMetrics());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 단일 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getClientMetric_found_mapsFields() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
|
||||
when(manager.getClientMetrics("C1")).thenReturn(makeMetrics(200, 30, 20));
|
||||
|
||||
TargetMetricDTO dto = serviceWith(manager).getClientMetric("C1");
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("C1", dto.getTargetId());
|
||||
assertEquals("CLIENT", dto.getTargetType());
|
||||
assertTrue(dto.isActivate());
|
||||
assertEquals(200, dto.getAllowed());
|
||||
assertEquals(30, dto.getRejectedPerSecond());
|
||||
assertEquals(20, dto.getRejectedThreshold());
|
||||
assertEquals(250, dto.getTotalRequests());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getClientMetric_notRegistered_returnsNull() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientInflowThreshold("C1")).thenReturn(null);
|
||||
|
||||
assertNull(serviceWith(manager).getClientMetric("C1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getClientMetric_noMetricsYet_returnsZeroCounters() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
|
||||
when(manager.getClientMetrics("C1")).thenReturn(null);
|
||||
|
||||
TargetMetricDTO dto = serviceWith(manager).getClientMetric("C1");
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals(0, dto.getAllowed());
|
||||
assertEquals(0, dto.getTotalRequests());
|
||||
assertEquals(0.0, dto.getRejectRatio(), 0.001);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getClientMetric_rejectRatioCalculation() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
|
||||
// allowed=90, rejPs=5, rejTh=5 → reject=10/100 = 10.00%
|
||||
when(manager.getClientMetrics("C1")).thenReturn(makeMetrics(90, 5, 5));
|
||||
|
||||
TargetMetricDTO dto = serviceWith(manager).getClientMetric("C1");
|
||||
|
||||
assertEquals(10.0, dto.getRejectRatio(), 0.01);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 전체 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllClientMetrics_twoEntries_returnsBoth() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
java.util.Map<String, com.eactive.eai.common.inflow.dual.DualCustomBucket> bucketMap =
|
||||
new java.util.LinkedHashMap<>();
|
||||
bucketMap.put("C1", null);
|
||||
bucketMap.put("C2", null);
|
||||
when(manager.getClientBucketMap()).thenReturn(bucketMap);
|
||||
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
|
||||
when(manager.getClientInflowThreshold("C2")).thenReturn(makeVO("C2"));
|
||||
when(manager.getClientMetrics("C1")).thenReturn(makeMetrics(10, 0, 0));
|
||||
when(manager.getClientMetrics("C2")).thenReturn(makeMetrics(20, 5, 0));
|
||||
|
||||
List<TargetMetricDTO> result = serviceWith(manager).getAllClientMetrics();
|
||||
|
||||
assertEquals(2, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllClientMetrics_noKeys_returnsEmptyList() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientBucketMap()).thenReturn(new java.util.HashMap<>());
|
||||
|
||||
assertTrue(serviceWith(manager).getAllClientMetrics().isEmpty());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// reset
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void resetClientMetric_success_returnsTrueAndCallsManager() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
|
||||
|
||||
assertTrue(serviceWith(manager).resetClientMetric("C1"));
|
||||
verify(manager).resetClientMetrics("C1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetClientMetric_notRegistered_returnsFalseAndNoReset() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
when(manager.getClientInflowThreshold("C1")).thenReturn(null);
|
||||
|
||||
assertFalse(serviceWith(manager).resetClientMetric("C1"));
|
||||
verify(manager, never()).resetClientMetrics(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAllClientMetrics_callsManager() {
|
||||
ClientDualInflowControlManager manager = mock(ClientDualInflowControlManager.class);
|
||||
serviceWith(manager).resetAllClientMetrics();
|
||||
verify(manager).resetAllClientMetrics();
|
||||
}
|
||||
}
|
||||
@@ -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,173 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
/**
|
||||
* InflowGroupMetricController 단위 테스트.
|
||||
*
|
||||
* <p>Spring MVC를 기동하지 않고 컨트롤러를 직접 인스턴스화하여
|
||||
* 응답 구조(success, data, count, message)를 검증한다.
|
||||
*/
|
||||
class InflowGroupMetricControllerTest {
|
||||
|
||||
private InflowGroupMetricController controller;
|
||||
private InflowGroupMetricService mockService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
controller = new InflowGroupMetricController();
|
||||
mockService = mock(InflowGroupMetricService.class);
|
||||
ReflectionTestUtils.setField(controller, "metricService", mockService);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Helper
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private GroupMetricDTO makeDTO(String groupId, String groupName,
|
||||
long allowed, long rejPs, long rejTh) {
|
||||
GroupMetricDTO dto = new GroupMetricDTO();
|
||||
dto.setGroupId(groupId);
|
||||
dto.setGroupName(groupName);
|
||||
dto.setActivate(true);
|
||||
dto.setAllowed(allowed);
|
||||
dto.setRejectedPerSecond(rejPs);
|
||||
dto.setRejectedThreshold(rejTh);
|
||||
long total = allowed + rejPs + rejTh;
|
||||
dto.setTotalRequests(total);
|
||||
dto.setRejectRatio(total > 0 ? (double)(rejPs + rejTh) / total * 100 : 0.0);
|
||||
dto.setLastResetTime(System.currentTimeMillis());
|
||||
return dto;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> body(ResponseEntity<?> response) {
|
||||
return (Map<String, Object>) response.getBody();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// GET /{groupId}/metric
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getGroupMetric_found_successTrueAndDataPresent() {
|
||||
GroupMetricDTO dto = makeDTO("G1", "결제그룹", 900, 60, 40);
|
||||
when(mockService.getGroupMetric("G1")).thenReturn(dto);
|
||||
|
||||
ResponseEntity<?> response = controller.getGroupMetric("G1");
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(200, response.getStatusCodeValue());
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(dto, body.get("data"));
|
||||
assertFalse(body.containsKey("message"), "성공 응답에 message 필드는 없어야 합니다");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getGroupMetric_notFound_successFalseWithMessage() {
|
||||
when(mockService.getGroupMetric("GHOST")).thenReturn(null);
|
||||
|
||||
ResponseEntity<?> response = controller.getGroupMetric("GHOST");
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(200, response.getStatusCodeValue());
|
||||
assertEquals(Boolean.FALSE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("GHOST"),
|
||||
"오류 메시지에 groupId가 포함되어야 합니다");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// GET /metric
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllGroupMetrics_returnsListAndCount() {
|
||||
List<GroupMetricDTO> list = Arrays.asList(
|
||||
makeDTO("G1", "그룹1", 100, 5, 0),
|
||||
makeDTO("G2", "그룹2", 200, 0, 10)
|
||||
);
|
||||
when(mockService.getAllGroupMetrics()).thenReturn(list);
|
||||
|
||||
ResponseEntity<?> response = controller.getAllGroupMetrics();
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(list, body.get("data"));
|
||||
assertEquals(2, body.get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllGroupMetrics_emptyList_countZero() {
|
||||
when(mockService.getAllGroupMetrics()).thenReturn(Collections.emptyList());
|
||||
|
||||
ResponseEntity<?> response = controller.getAllGroupMetrics();
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertEquals(0, body.get("count"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// POST /{groupId}/metric/reset
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void resetGroupMetric_success_successTrueWithGroupId() {
|
||||
when(mockService.resetGroupMetric("G1")).thenReturn(true);
|
||||
|
||||
ResponseEntity<?> response = controller.resetGroupMetric("G1");
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("G1"),
|
||||
"성공 메시지에 groupId가 포함되어야 합니다");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetGroupMetric_notFound_successFalseWithGroupId() {
|
||||
when(mockService.resetGroupMetric("GHOST")).thenReturn(false);
|
||||
|
||||
ResponseEntity<?> response = controller.resetGroupMetric("GHOST");
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(Boolean.FALSE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("GHOST"),
|
||||
"오류 메시지에 groupId가 포함되어야 합니다");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// POST /metric/reset
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void resetAllGroupMetrics_alwaysSuccessTrue() {
|
||||
doNothing().when(mockService).resetAllGroupMetrics();
|
||||
|
||||
ResponseEntity<?> response = controller.resetAllGroupMetrics();
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertNotNull(body.get("message"));
|
||||
verify(mockService).resetAllGroupMetrics();
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAllGroupMetrics_callsDelegateOnce() {
|
||||
doNothing().when(mockService).resetAllGroupMetrics();
|
||||
|
||||
controller.resetAllGroupMetrics();
|
||||
|
||||
verify(mockService, times(1)).resetAllGroupMetrics();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.eactive.eai.common.inflow.InflowGroupVO;
|
||||
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||
|
||||
/**
|
||||
* InflowGroupMetricService 단위 테스트.
|
||||
*
|
||||
* <p>getManager()를 protected로 오버라이드하는 내부 테스트 서브클래스를 사용하여
|
||||
* mockito-inline(static mock) 없이 DualInflowControlManager 의존성을 주입한다.
|
||||
*/
|
||||
class InflowGroupMetricServiceTest {
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 테스트용 서브클래스 — getManager()를 오버라이드하여 mock 주입
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private static InflowGroupMetricService serviceWith(DualInflowControlManager manager) {
|
||||
return new InflowGroupMetricService() {
|
||||
@Override
|
||||
protected DualInflowControlManager getManager() {
|
||||
return manager;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private InflowGroupVO makeGroupVO(String groupId, String groupName) {
|
||||
InflowGroupVO vo = new InflowGroupVO();
|
||||
vo.setGroupId(groupId);
|
||||
vo.setGroupName(groupName);
|
||||
vo.setActivate(true);
|
||||
return vo;
|
||||
}
|
||||
|
||||
private DualInflowControlManager.TargetMetrics makeMetrics(long allowed, long rejPs, long rejTh) {
|
||||
DualInflowControlManager.TargetMetrics m = new DualInflowControlManager.TargetMetrics();
|
||||
m.allowed.set(allowed);
|
||||
m.rejectedPerSecond.set(rejPs);
|
||||
m.rejectedThreshold.set(rejTh);
|
||||
return m;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// getGroupMetric
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getGroupMetric_managerIsNull_returnsNull() {
|
||||
assertNull(serviceWith(null).getGroupMetric("G1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getGroupMetric_groupNotFound_returnsNull() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getGroupInflowThreshold("G1")).thenReturn(null);
|
||||
|
||||
assertNull(serviceWith(manager).getGroupMetric("G1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getGroupMetric_noMetricsYet_returnsZeroCounters() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "결제그룹"));
|
||||
when(manager.getGroupMetrics("G1")).thenReturn(null);
|
||||
|
||||
GroupMetricDTO dto = serviceWith(manager).getGroupMetric("G1");
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("G1", dto.getGroupId());
|
||||
assertEquals("결제그룹", dto.getGroupName());
|
||||
assertTrue(dto.isActivate());
|
||||
assertEquals(0, dto.getAllowed());
|
||||
assertEquals(0, dto.getRejectedPerSecond());
|
||||
assertEquals(0, dto.getRejectedThreshold());
|
||||
assertEquals(0, dto.getTotalRequests());
|
||||
assertEquals(0.0, dto.getRejectRatio());
|
||||
assertEquals(0, dto.getLastResetTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getGroupMetric_withMetrics_returnsCorrectValues() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "결제그룹"));
|
||||
when(manager.getGroupMetrics("G1")).thenReturn(makeMetrics(900, 60, 40));
|
||||
|
||||
GroupMetricDTO dto = serviceWith(manager).getGroupMetric("G1");
|
||||
|
||||
assertEquals(900, dto.getAllowed());
|
||||
assertEquals(60, dto.getRejectedPerSecond());
|
||||
assertEquals(40, dto.getRejectedThreshold());
|
||||
assertEquals(1000, dto.getTotalRequests());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getGroupMetric_rejectRatioCalculation() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "G1"));
|
||||
// allowed=90, rejPs=5, rejTh=5 → reject=10/100 = 10.00%
|
||||
when(manager.getGroupMetrics("G1")).thenReturn(makeMetrics(90, 5, 5));
|
||||
|
||||
GroupMetricDTO dto = serviceWith(manager).getGroupMetric("G1");
|
||||
|
||||
assertEquals(10.0, dto.getRejectRatio(), 0.01);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getGroupMetric_zeroTotal_rejectRatioIsZero() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "G1"));
|
||||
when(manager.getGroupMetrics("G1")).thenReturn(makeMetrics(0, 0, 0));
|
||||
|
||||
GroupMetricDTO dto = serviceWith(manager).getGroupMetric("G1");
|
||||
|
||||
assertEquals(0.0, dto.getRejectRatio(), 0.0001);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getGroupMetric_lastResetTimeIsPropagated() {
|
||||
DualInflowControlManager.TargetMetrics m = makeMetrics(10, 0, 0);
|
||||
m.lastResetTime = 1234567890L;
|
||||
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "G1"));
|
||||
when(manager.getGroupMetrics("G1")).thenReturn(m);
|
||||
|
||||
GroupMetricDTO dto = serviceWith(manager).getGroupMetric("G1");
|
||||
|
||||
assertEquals(1234567890L, dto.getLastResetTime());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// getAllGroupMetrics
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllGroupMetrics_managerIsNull_returnsEmptyList() {
|
||||
List<GroupMetricDTO> result = serviceWith(null).getAllGroupMetrics();
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllGroupMetrics_noGroups_returnsEmptyList() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getGroupAllKeys()).thenReturn(new String[]{});
|
||||
|
||||
assertTrue(serviceWith(manager).getAllGroupMetrics().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllGroupMetrics_twoGroups_returnsBoth() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getGroupAllKeys()).thenReturn(new String[]{"G1", "G2"});
|
||||
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "그룹1"));
|
||||
when(manager.getGroupInflowThreshold("G2")).thenReturn(makeGroupVO("G2", "그룹2"));
|
||||
when(manager.getGroupMetrics("G1")).thenReturn(makeMetrics(10, 0, 0));
|
||||
when(manager.getGroupMetrics("G2")).thenReturn(makeMetrics(20, 5, 0));
|
||||
|
||||
List<GroupMetricDTO> result = serviceWith(manager).getAllGroupMetrics();
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertEquals("G1", result.get(0).getGroupId());
|
||||
assertEquals("G2", result.get(1).getGroupId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllGroupMetrics_groupNotFoundIsSkipped() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getGroupAllKeys()).thenReturn(new String[]{"G1", "GHOST"});
|
||||
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "그룹1"));
|
||||
when(manager.getGroupInflowThreshold("GHOST")).thenReturn(null);
|
||||
when(manager.getGroupMetrics("G1")).thenReturn(makeMetrics(5, 0, 0));
|
||||
|
||||
List<GroupMetricDTO> result = serviceWith(manager).getAllGroupMetrics();
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("G1", result.get(0).getGroupId());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// resetGroupMetric
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void resetGroupMetric_managerIsNull_returnsFalse() {
|
||||
assertFalse(serviceWith(null).resetGroupMetric("G1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetGroupMetric_groupNotFound_returnsFalse() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getGroupInflowThreshold("G1")).thenReturn(null);
|
||||
|
||||
assertFalse(serviceWith(manager).resetGroupMetric("G1"));
|
||||
verify(manager, never()).resetGroupMetrics(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetGroupMetric_success_returnsTrueAndCallsManager() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "그룹1"));
|
||||
|
||||
assertTrue(serviceWith(manager).resetGroupMetric("G1"));
|
||||
verify(manager).resetGroupMetrics("G1");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// resetAllGroupMetrics
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void resetAllGroupMetrics_managerIsNull_noException() {
|
||||
assertDoesNotThrow(() -> serviceWith(null).resetAllGroupMetrics());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAllGroupMetrics_callsManagerReset() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
|
||||
serviceWith(manager).resetAllGroupMetrics();
|
||||
|
||||
verify(manager).resetAllGroupMetrics();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
/**
|
||||
* InflowTargetBucketController 단위 테스트.
|
||||
*
|
||||
* <p>Spring MVC를 기동하지 않고 컨트롤러를 직접 인스턴스화하여
|
||||
* 응답 구조(success, data, count, message)를 검증한다.
|
||||
* 클라이언트 관련 테스트는 ClientInflowTargetBucketControllerTest 에서 검증한다.
|
||||
*/
|
||||
class InflowTargetBucketControllerTest {
|
||||
|
||||
private InflowTargetBucketController controller;
|
||||
private InflowTargetBucketService mockService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
controller = new InflowTargetBucketController();
|
||||
mockService = mock(InflowTargetBucketService.class);
|
||||
ReflectionTestUtils.setField(controller, "bucketService", mockService);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Helper
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private TargetBucketStatusDTO makeDTO(String id, String type) {
|
||||
TargetBucketStatusDTO dto = new TargetBucketStatusDTO();
|
||||
dto.setTargetId(id);
|
||||
dto.setTargetType(type);
|
||||
dto.setActivate(true);
|
||||
dto.setBuckets(Collections.emptyList());
|
||||
return dto;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> body(ResponseEntity<?> response) {
|
||||
return (Map<String, Object>) response.getBody();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 어댑터 — 단일 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAdapterBucketStatus_found_successTrueAndDataPresent() {
|
||||
TargetBucketStatusDTO dto = makeDTO("ADAPTER_A", "ADAPTER");
|
||||
when(mockService.getAdapterBucketStatus("ADAPTER_A")).thenReturn(dto);
|
||||
|
||||
ResponseEntity<?> response = controller.getAdapterBucketStatus("ADAPTER_A");
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(200, response.getStatusCodeValue());
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(dto, body.get("data"));
|
||||
assertFalse(body.containsKey("message"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapterBucketStatus_notFound_successFalseWithAdapterId() {
|
||||
when(mockService.getAdapterBucketStatus("GHOST")).thenReturn(null);
|
||||
|
||||
ResponseEntity<?> response = controller.getAdapterBucketStatus("GHOST");
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(Boolean.FALSE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 어댑터 — 전체 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllAdapterBucketStatus_returnsListAndCount() {
|
||||
List<TargetBucketStatusDTO> list = Arrays.asList(
|
||||
makeDTO("A1", "ADAPTER"),
|
||||
makeDTO("A2", "ADAPTER")
|
||||
);
|
||||
when(mockService.getAllAdapterBucketStatus()).thenReturn(list);
|
||||
|
||||
ResponseEntity<?> response = controller.getAllAdapterBucketStatus();
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(list, body.get("data"));
|
||||
assertEquals(2, body.get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllAdapterBucketStatus_emptyList_countZero() {
|
||||
when(mockService.getAllAdapterBucketStatus()).thenReturn(Collections.emptyList());
|
||||
|
||||
Map<String, Object> body = body(controller.getAllAdapterBucketStatus());
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertEquals(0, body.get("count"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 인터페이스 — 단일 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getInterfaceBucketStatus_found_successTrue() {
|
||||
TargetBucketStatusDTO dto = makeDTO("IF_001", "INTERFACE");
|
||||
when(mockService.getInterfaceBucketStatus("IF_001")).thenReturn(dto);
|
||||
|
||||
ResponseEntity<?> response = controller.getInterfaceBucketStatus("IF_001");
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(dto, body.get("data"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInterfaceBucketStatus_notFound_successFalseWithInterfaceId() {
|
||||
when(mockService.getInterfaceBucketStatus("GHOST")).thenReturn(null);
|
||||
|
||||
Map<String, Object> body = body(controller.getInterfaceBucketStatus("GHOST"));
|
||||
|
||||
assertEquals(Boolean.FALSE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 인터페이스 — 전체 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllInterfaceBucketStatus_returnsListAndCount() {
|
||||
List<TargetBucketStatusDTO> list = Collections.singletonList(makeDTO("IF_001", "INTERFACE"));
|
||||
when(mockService.getAllInterfaceBucketStatus()).thenReturn(list);
|
||||
|
||||
Map<String, Object> body = body(controller.getAllInterfaceBucketStatus());
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertEquals(1, body.get("count"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
|
||||
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||
|
||||
import io.github.bucket4j.Bandwidth;
|
||||
import io.github.bucket4j.Bucket4j;
|
||||
import io.github.bucket4j.local.LocalBucket;
|
||||
|
||||
/**
|
||||
* InflowTargetBucketService 단위 테스트.
|
||||
*
|
||||
* <p>어댑터/인터페이스: getDualManager()를 오버라이드하는 서브클래스 사용.
|
||||
* 클라이언트 관련 테스트는 ClientInflowTargetBucketServiceTest 에서 검증한다.
|
||||
*/
|
||||
class InflowTargetBucketServiceTest {
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 테스트용 서브클래스
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private static InflowTargetBucketService serviceWith(DualInflowControlManager manager) {
|
||||
return new InflowTargetBucketService() {
|
||||
@Override
|
||||
protected DualInflowControlManager getDualManager() { return manager; }
|
||||
};
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private InflowTargetVO makeVO(String name, long perSec, long threshold, String unit, boolean activate) {
|
||||
InflowTargetVO vo = new InflowTargetVO();
|
||||
vo.setName(name);
|
||||
vo.setThresholdPerSecond(perSec);
|
||||
vo.setThreshold(threshold);
|
||||
vo.setThresholdTimeUnit(unit);
|
||||
vo.setActivate(activate);
|
||||
return vo;
|
||||
}
|
||||
|
||||
private LocalBucket freshBucket(long capacity) {
|
||||
return Bucket4j.builder()
|
||||
.addLimit(Bandwidth.simple(capacity, Duration.ofSeconds(1)))
|
||||
.build();
|
||||
}
|
||||
|
||||
private LocalBucket exhaustedBucket(long capacity) {
|
||||
LocalBucket b = freshBucket(capacity);
|
||||
b.tryConsume(capacity);
|
||||
return b;
|
||||
}
|
||||
|
||||
private DualCustomBucket makeDualBucket(String name, long perSec, long threshold) {
|
||||
return new DualCustomBucket(freshBucket(perSec), freshBucket(threshold),
|
||||
makeVO(name, perSec, threshold, "DAY", true));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// DualManager null (비활성 환경)
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAdapterBucketStatus_managerIsNull_returnsNull() {
|
||||
assertNull(serviceWith(null).getAdapterBucketStatus("ADAPTER_A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllAdapterBucketStatus_managerIsNull_returnsEmptyList() {
|
||||
List<TargetBucketStatusDTO> result = serviceWith(null).getAllAdapterBucketStatus();
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInterfaceBucketStatus_managerIsNull_returnsNull() {
|
||||
assertNull(serviceWith(null).getInterfaceBucketStatus("IF_001"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllInterfaceBucketStatus_managerIsNull_returnsEmptyList() {
|
||||
assertTrue(serviceWith(null).getAllInterfaceBucketStatus().isEmpty());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 버킷 미존재
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAdapterBucketStatus_notFound_returnsNull() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterBucket("ADAPTER_A")).thenReturn(null);
|
||||
|
||||
assertNull(serviceWith(manager).getAdapterBucketStatus("ADAPTER_A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInterfaceBucketStatus_notFound_returnsNull() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getInterfaceBucket("IF_001")).thenReturn(null);
|
||||
|
||||
assertNull(serviceWith(manager).getInterfaceBucketStatus("IF_001"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 단일 조회 — targetType, targetId 매핑
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAdapterBucketStatus_found_mapsAdapterType() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterBucket("ADAPTER_A")).thenReturn(makeDualBucket("ADAPTER_A", 10, 1000));
|
||||
|
||||
TargetBucketStatusDTO dto = serviceWith(manager).getAdapterBucketStatus("ADAPTER_A");
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("ADAPTER_A", dto.getTargetId());
|
||||
assertEquals("ADAPTER", dto.getTargetType());
|
||||
assertTrue(dto.isActivate());
|
||||
assertEquals(2, dto.getBuckets().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInterfaceBucketStatus_found_mapsInterfaceType() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getInterfaceBucket("IF_001")).thenReturn(makeDualBucket("IF_001", 20, 2000));
|
||||
|
||||
TargetBucketStatusDTO dto = serviceWith(manager).getInterfaceBucketStatus("IF_001");
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("IF_001", dto.getTargetId());
|
||||
assertEquals("INTERFACE", dto.getTargetType());
|
||||
assertTrue(dto.isActivate());
|
||||
assertEquals(2, dto.getBuckets().size());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// BucketInfo 용량/시간단위 매핑
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void toDto_capacity_perSecondBucketInfoCapacityMatchesVO() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterBucket("A1")).thenReturn(makeDualBucket("A1", 30, 3000));
|
||||
|
||||
TargetBucketStatusDTO dto = serviceWith(manager).getAdapterBucketStatus("A1");
|
||||
|
||||
GroupBucketStatusDTO.BucketInfo ps = dto.getBuckets().get(0);
|
||||
assertEquals(30, ps.getCapacity());
|
||||
assertEquals("SEC", ps.getTimeUnit());
|
||||
|
||||
GroupBucketStatusDTO.BucketInfo th = dto.getBuckets().get(1);
|
||||
assertEquals(3000, th.getCapacity());
|
||||
assertEquals("DAY", th.getTimeUnit());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 전체 목록 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllAdapterBucketStatus_emptyMap_returnsEmptyList() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterBucketMap()).thenReturn(new ConcurrentHashMap<>());
|
||||
|
||||
assertTrue(serviceWith(manager).getAllAdapterBucketStatus().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllInterfaceBucketStatus_oneEntry_targetTypeIsInterface() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
|
||||
map.put("IF_001", makeDualBucket("IF_001", 10, 1000));
|
||||
when(manager.getInterfaceBucketMap()).thenReturn(map);
|
||||
|
||||
List<TargetBucketStatusDTO> result = serviceWith(manager).getAllInterfaceBucketStatus();
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("INTERFACE", result.get(0).getTargetType());
|
||||
assertEquals("IF_001", result.get(0).getTargetId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
/**
|
||||
* InflowTargetMetricController 단위 테스트.
|
||||
*
|
||||
* <p>Spring MVC를 기동하지 않고 컨트롤러를 직접 인스턴스화하여
|
||||
* 응답 구조(success, data, count, message)를 검증한다.
|
||||
*/
|
||||
class InflowTargetMetricControllerTest {
|
||||
|
||||
private InflowTargetMetricController controller;
|
||||
private InflowTargetMetricService mockService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
controller = new InflowTargetMetricController();
|
||||
mockService = mock(InflowTargetMetricService.class);
|
||||
ReflectionTestUtils.setField(controller, "metricService", mockService);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Helper
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private TargetMetricDTO makeDTO(String targetId, String targetType,
|
||||
long allowed, long rejPs, long rejTh) {
|
||||
TargetMetricDTO dto = new TargetMetricDTO();
|
||||
dto.setTargetId(targetId);
|
||||
dto.setTargetType(targetType);
|
||||
dto.setActivate(true);
|
||||
dto.setAllowed(allowed);
|
||||
dto.setRejectedPerSecond(rejPs);
|
||||
dto.setRejectedThreshold(rejTh);
|
||||
long total = allowed + rejPs + rejTh;
|
||||
dto.setTotalRequests(total);
|
||||
dto.setRejectRatio(total > 0 ? (double)(rejPs + rejTh) / total * 100 : 0.0);
|
||||
return dto;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> body(ResponseEntity<?> response) {
|
||||
return (Map<String, Object>) response.getBody();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 어댑터 — 단일 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAdapterMetric_found_successTrueAndDataPresent() {
|
||||
TargetMetricDTO dto = makeDTO("A1", "ADAPTER", 900, 60, 40);
|
||||
when(mockService.getAdapterMetric("A1")).thenReturn(dto);
|
||||
|
||||
ResponseEntity<?> response = controller.getAdapterMetric("A1");
|
||||
Map<String, Object> body = body(response);
|
||||
|
||||
assertEquals(200, response.getStatusCodeValue());
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(dto, body.get("data"));
|
||||
assertFalse(body.containsKey("message"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapterMetric_notFound_successFalseWithMessage() {
|
||||
when(mockService.getAdapterMetric("GHOST")).thenReturn(null);
|
||||
|
||||
Map<String, Object> body = body(controller.getAdapterMetric("GHOST"));
|
||||
|
||||
assertEquals(Boolean.FALSE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 어댑터 — 전체 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllAdapterMetrics_returnsListAndCount() {
|
||||
List<TargetMetricDTO> list = Arrays.asList(
|
||||
makeDTO("A1", "ADAPTER", 100, 5, 0),
|
||||
makeDTO("A2", "ADAPTER", 200, 0, 10)
|
||||
);
|
||||
when(mockService.getAllAdapterMetrics()).thenReturn(list);
|
||||
|
||||
Map<String, Object> body = body(controller.getAllAdapterMetrics());
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(list, body.get("data"));
|
||||
assertEquals(2, body.get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllAdapterMetrics_emptyList_countZero() {
|
||||
when(mockService.getAllAdapterMetrics()).thenReturn(Collections.emptyList());
|
||||
|
||||
Map<String, Object> body = body(controller.getAllAdapterMetrics());
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertEquals(0, body.get("count"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 어댑터 — reset
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void resetAdapterMetric_success_successTrueWithTargetId() {
|
||||
when(mockService.resetAdapterMetric("A1")).thenReturn(true);
|
||||
|
||||
Map<String, Object> body = body(controller.resetAdapterMetric("A1"));
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("A1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAdapterMetric_notFound_successFalseWithTargetId() {
|
||||
when(mockService.resetAdapterMetric("GHOST")).thenReturn(false);
|
||||
|
||||
Map<String, Object> body = body(controller.resetAdapterMetric("GHOST"));
|
||||
|
||||
assertEquals(Boolean.FALSE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAllAdapterMetrics_alwaysSuccessTrue() {
|
||||
doNothing().when(mockService).resetAllAdapterMetrics();
|
||||
|
||||
Map<String, Object> body = body(controller.resetAllAdapterMetrics());
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertNotNull(body.get("message"));
|
||||
verify(mockService).resetAllAdapterMetrics();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 인터페이스 — 단일 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getInterfaceMetric_found_successTrueAndDataPresent() {
|
||||
TargetMetricDTO dto = makeDTO("IF1", "INTERFACE", 500, 20, 10);
|
||||
when(mockService.getInterfaceMetric("IF1")).thenReturn(dto);
|
||||
|
||||
Map<String, Object> body = body(controller.getInterfaceMetric("IF1"));
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertSame(dto, body.get("data"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInterfaceMetric_notFound_successFalseWithMessage() {
|
||||
when(mockService.getInterfaceMetric("GHOST")).thenReturn(null);
|
||||
|
||||
Map<String, Object> body = body(controller.getInterfaceMetric("GHOST"));
|
||||
|
||||
assertEquals(Boolean.FALSE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 인터페이스 — 전체 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllInterfaceMetrics_returnsListAndCount() {
|
||||
List<TargetMetricDTO> list = Collections.singletonList(
|
||||
makeDTO("IF1", "INTERFACE", 100, 0, 0));
|
||||
when(mockService.getAllInterfaceMetrics()).thenReturn(list);
|
||||
|
||||
Map<String, Object> body = body(controller.getAllInterfaceMetrics());
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertEquals(1, body.get("count"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 인터페이스 — reset
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void resetInterfaceMetric_success_successTrue() {
|
||||
when(mockService.resetInterfaceMetric("IF1")).thenReturn(true);
|
||||
|
||||
Map<String, Object> body = body(controller.resetInterfaceMetric("IF1"));
|
||||
|
||||
assertEquals(Boolean.TRUE, body.get("success"));
|
||||
assertTrue(body.get("message").toString().contains("IF1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAllInterfaceMetrics_callsDelegateOnce() {
|
||||
doNothing().when(mockService).resetAllInterfaceMetrics();
|
||||
|
||||
controller.resetAllInterfaceMetrics();
|
||||
|
||||
verify(mockService, times(1)).resetAllInterfaceMetrics();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package com.eactive.eai.manage.inflow;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||
|
||||
/**
|
||||
* InflowTargetMetricService 단위 테스트.
|
||||
*
|
||||
* <p>어댑터/인터페이스 테스트는 getDualManager()를 오버라이드하여 DualInflowControlManager 주입.
|
||||
*/
|
||||
class InflowTargetMetricServiceTest {
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 테스트용 서브클래스 — 어댑터/인터페이스용
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private static InflowTargetMetricService serviceWith(DualInflowControlManager manager) {
|
||||
return new InflowTargetMetricService() {
|
||||
@Override
|
||||
protected DualInflowControlManager getDualManager() { return manager; }
|
||||
};
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private InflowTargetVO makeVO(String name) {
|
||||
InflowTargetVO vo = new InflowTargetVO();
|
||||
vo.setName(name);
|
||||
vo.setActivate(true);
|
||||
return vo;
|
||||
}
|
||||
|
||||
private DualInflowControlManager.TargetMetrics makeMetrics(long allowed, long rejPs, long rejTh) {
|
||||
DualInflowControlManager.TargetMetrics m = new DualInflowControlManager.TargetMetrics();
|
||||
m.allowed.set(allowed);
|
||||
m.rejectedPerSecond.set(rejPs);
|
||||
m.rejectedThreshold.set(rejTh);
|
||||
return m;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// DualManager null (비활성 환경)
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAdapterMetric_managerIsNull_returnsNull() {
|
||||
assertNull(serviceWith(null).getAdapterMetric("A1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllAdapterMetrics_managerIsNull_returnsEmptyList() {
|
||||
assertTrue(serviceWith(null).getAllAdapterMetrics().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAdapterMetric_managerIsNull_returnsFalse() {
|
||||
assertFalse(serviceWith(null).resetAdapterMetric("A1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAllAdapterMetrics_managerIsNull_noException() {
|
||||
assertDoesNotThrow(() -> serviceWith(null).resetAllAdapterMetrics());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInterfaceMetric_managerIsNull_returnsNull() {
|
||||
assertNull(serviceWith(null).getInterfaceMetric("IF1"));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 어댑터 — 단일 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAdapterMetric_notRegistered_returnsNull() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterInflowThreashold("A1")).thenReturn(null);
|
||||
|
||||
assertNull(serviceWith(manager).getAdapterMetric("A1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapterMetric_found_mapsFields() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||
when(manager.getAdapterMetrics("A1")).thenReturn(makeMetrics(900, 60, 40));
|
||||
|
||||
TargetMetricDTO dto = serviceWith(manager).getAdapterMetric("A1");
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("A1", dto.getTargetId());
|
||||
assertEquals("ADAPTER", dto.getTargetType());
|
||||
assertTrue(dto.isActivate());
|
||||
assertEquals(900, dto.getAllowed());
|
||||
assertEquals(60, dto.getRejectedPerSecond());
|
||||
assertEquals(40, dto.getRejectedThreshold());
|
||||
assertEquals(1000, dto.getTotalRequests());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapterMetric_noMetricsYet_returnsZeroCounters() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||
when(manager.getAdapterMetrics("A1")).thenReturn(null);
|
||||
|
||||
TargetMetricDTO dto = serviceWith(manager).getAdapterMetric("A1");
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals(0, dto.getAllowed());
|
||||
assertEquals(0, dto.getTotalRequests());
|
||||
assertEquals(0.0, dto.getRejectRatio(), 0.001);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapterMetric_rejectRatioCalculation() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||
// allowed=90, rejPs=5, rejTh=5 → reject=10/100 = 10.00%
|
||||
when(manager.getAdapterMetrics("A1")).thenReturn(makeMetrics(90, 5, 5));
|
||||
|
||||
TargetMetricDTO dto = serviceWith(manager).getAdapterMetric("A1");
|
||||
|
||||
assertEquals(10.0, dto.getRejectRatio(), 0.01);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAdapterMetric_zeroTotal_rejectRatioIsZero() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||
when(manager.getAdapterMetrics("A1")).thenReturn(makeMetrics(0, 0, 0));
|
||||
|
||||
TargetMetricDTO dto = serviceWith(manager).getAdapterMetric("A1");
|
||||
|
||||
assertEquals(0.0, dto.getRejectRatio(), 0.0001);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 어댑터 — 전체 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getAllAdapterMetrics_twoEntries_returnsBoth() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterAllKeys()).thenReturn(new String[]{"A1", "A2"});
|
||||
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||
when(manager.getAdapterInflowThreashold("A2")).thenReturn(makeVO("A2"));
|
||||
when(manager.getAdapterMetrics("A1")).thenReturn(makeMetrics(10, 0, 0));
|
||||
when(manager.getAdapterMetrics("A2")).thenReturn(makeMetrics(20, 5, 0));
|
||||
|
||||
List<TargetMetricDTO> result = serviceWith(manager).getAllAdapterMetrics();
|
||||
|
||||
assertEquals(2, result.size());
|
||||
assertEquals("A1", result.get(0).getTargetId());
|
||||
assertEquals("A2", result.get(1).getTargetId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllAdapterMetrics_noKeys_returnsEmptyList() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterAllKeys()).thenReturn(new String[]{});
|
||||
|
||||
assertTrue(serviceWith(manager).getAllAdapterMetrics().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllAdapterMetrics_notRegisteredSkipped() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterAllKeys()).thenReturn(new String[]{"A1", "GHOST"});
|
||||
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||
when(manager.getAdapterInflowThreashold("GHOST")).thenReturn(null);
|
||||
when(manager.getAdapterMetrics("A1")).thenReturn(null);
|
||||
|
||||
List<TargetMetricDTO> result = serviceWith(manager).getAllAdapterMetrics();
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("A1", result.get(0).getTargetId());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 어댑터 — reset
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void resetAdapterMetric_notRegistered_returnsFalse() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterInflowThreashold("A1")).thenReturn(null);
|
||||
|
||||
assertFalse(serviceWith(manager).resetAdapterMetric("A1"));
|
||||
verify(manager, never()).resetAdapterMetrics(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAdapterMetric_success_returnsTrueAndCallsManager() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||
|
||||
assertTrue(serviceWith(manager).resetAdapterMetric("A1"));
|
||||
verify(manager).resetAdapterMetrics("A1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAllAdapterMetrics_callsManager() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
|
||||
serviceWith(manager).resetAllAdapterMetrics();
|
||||
|
||||
verify(manager).resetAllAdapterMetrics();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 인터페이스 — 단일 조회
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void getInterfaceMetric_found_mapsFields() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getInterfaceInflowThreashold("IF1")).thenReturn(makeVO("IF1"));
|
||||
when(manager.getInterfaceMetrics("IF1")).thenReturn(makeMetrics(50, 10, 5));
|
||||
|
||||
TargetMetricDTO dto = serviceWith(manager).getInterfaceMetric("IF1");
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("IF1", dto.getTargetId());
|
||||
assertEquals("INTERFACE", dto.getTargetType());
|
||||
assertEquals(50, dto.getAllowed());
|
||||
assertEquals(65, dto.getTotalRequests());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInterfaceMetric_notRegistered_returnsNull() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getInterfaceInflowThreashold("IF1")).thenReturn(null);
|
||||
|
||||
assertNull(serviceWith(manager).getInterfaceMetric("IF1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetInterfaceMetric_success_returnsTrueAndCallsManager() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getInterfaceInflowThreashold("IF1")).thenReturn(makeVO("IF1"));
|
||||
|
||||
assertTrue(serviceWith(manager).resetInterfaceMetric("IF1"));
|
||||
verify(manager).resetInterfaceMetrics("IF1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetInterfaceMetric_notRegistered_returnsFalse() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
when(manager.getInterfaceInflowThreashold("IF1")).thenReturn(null);
|
||||
|
||||
assertFalse(serviceWith(manager).resetInterfaceMetric("IF1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAllInterfaceMetrics_callsManager() {
|
||||
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||
serviceWith(manager).resetAllInterfaceMetrics();
|
||||
verify(manager).resetAllInterfaceMetrics();
|
||||
}
|
||||
}
|
||||
@@ -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