Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b552df62c3 |
@@ -235,7 +235,3 @@ gradle-app.setting
|
||||
# End of https://www.gitignore.io/api/java,macos,gradle,intellij
|
||||
/EAISIMWeb/
|
||||
/.apt_generated_tests/
|
||||
|
||||
# Claude Code
|
||||
.claude/
|
||||
/작업내역*.md
|
||||
|
||||
@@ -25,9 +25,6 @@
|
||||
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 />
|
||||
|
||||
@@ -11,7 +11,7 @@ hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
|
||||
# eLink default functions
|
||||
# set System property in real system
|
||||
#inst.Name=${HOSTNAME}
|
||||
inst.Name=agwSvr11
|
||||
inst.Name=agwSvr63
|
||||
eai.jdbc.Name=jdbc/dsOBP_AGW
|
||||
eai.rmiport=30111
|
||||
eai.rmiserviceport=30112
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
<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>
|
||||
|
||||
|
||||
+6
-2
@@ -20,13 +20,17 @@ def queryDslVersion = "5.0.0"
|
||||
def hibernateVersion = "5.6.15.Final"
|
||||
|
||||
def generatedJavaDir = "$buildDir/generated/java"
|
||||
def nexusUrl = "https://nexus.eactive.synology.me:8090"
|
||||
def reposiliteUrl = "http://localhost:8080"
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
maven {
|
||||
url "${nexusUrl}/repository/maven-public/"
|
||||
url "${reposiliteUrl}/private"
|
||||
allowInsecureProtocol = true
|
||||
credentials {
|
||||
username = reposiliteUser
|
||||
password = reposilitePassword
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
# JWT 서명 검증 및 인증서 관리
|
||||
|
||||
## 1. 전체 구조
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Authorization Server (elink-oauth) │
|
||||
│ elink-oauth-dev.jks │
|
||||
│ ├── 개인키 (RSA Private Key) ← JWT 서명 생성용 │
|
||||
│ └── 공개키 인증서 (Certificate) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
│ 공개키만 추출
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ API Gateway (ApiAuthFilter) │
|
||||
│ elink-oauth-dev.pub │
|
||||
│ └── 공개키만 (RSA Public Key) ← JWT 서명 검증용만 │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. JKS vs PUB 파일 차이점
|
||||
|
||||
| 항목 | `.jks` (Java KeyStore) | `.pub` (Public Key) |
|
||||
|------|----------------------|---------------------|
|
||||
| 형식 | 바이너리 (Java 전용) | PEM 텍스트 (`-----BEGIN PUBLIC KEY-----`) |
|
||||
| 포함 내용 | 개인키 + 공개키 인증서 | 공개키만 |
|
||||
| 보호 | KeyStore 비밀번호 + Key 비밀번호 | 없음 (공개 가능) |
|
||||
| 사용처 | AuthorizationServerConfig - **토큰 서명** | ApiAuthFilter - **토큰 검증** |
|
||||
| 코드 로딩 | `KeyStoreKeyFactory` → `KeyPair` | `X509EncodedKeySpec` → `RSAPublicKey` |
|
||||
| 보안 등급 | **극비** (노출 시 토큰 위조 가능) | 공개 배포 가능 |
|
||||
|
||||
### 코드에서의 사용 위치
|
||||
|
||||
```java
|
||||
// AuthorizationServerConfig.java - JKS로 JWT 서명
|
||||
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(keystore, keystorePassword.toCharArray());
|
||||
KeyPair keyPair = keyStoreKeyFactory.getKeyPair(keyAlias, keyPassword.toCharArray());
|
||||
converter.setKeyPair(keyPair); // 개인키로 JWT 서명
|
||||
|
||||
// ApiAuthFilter.java - PUB로 JWT 검증
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
jwsVerifier = new RSASSAVerifier((RSAPublicKey) keyFactory.generatePublic(keySpec)); // 공개키로 검증만
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. JWT 서명 검증 상세 동작 (`signedJWT.verify(jwsVerifier)`)
|
||||
|
||||
### JWT 구조
|
||||
|
||||
```
|
||||
eyJhbGciOiJSUzI1NiJ9 . eyJzdWIiOiJ1c2VyMSIsImV4cCI6...} . MEUCIQDx...
|
||||
Header Payload Signature
|
||||
(Base64url) (Base64url) (Base64url)
|
||||
```
|
||||
|
||||
### 서명 생성 과정 (Authorization 서버 측)
|
||||
|
||||
```
|
||||
[Header].[Payload]
|
||||
↓
|
||||
SHA-256 해싱
|
||||
↓
|
||||
digest (32 bytes)
|
||||
↓
|
||||
RSA 개인키로 암호화 (PKCS#1 v1.5 패딩)
|
||||
↓
|
||||
Signature (Base64url 인코딩)
|
||||
```
|
||||
|
||||
### 서명 검증 과정 (ApiAuthFilter 측)
|
||||
|
||||
```
|
||||
JWT 수신
|
||||
↓
|
||||
① Header + Payload 분리
|
||||
"eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyMSIs..."
|
||||
↓
|
||||
② Signature 파트를 Base64url 디코딩
|
||||
→ 바이너리 서명값 확보
|
||||
↓
|
||||
③ RSA 공개키로 서명값 복호화 ← RSASSAVerifier (Nimbus JOSE)
|
||||
→ digest_from_signature 추출
|
||||
↓
|
||||
④ ①의 "Header.Payload" 문자열을 SHA-256 해싱
|
||||
→ digest_from_message 계산
|
||||
↓
|
||||
⑤ digest_from_signature == digest_from_message ?
|
||||
→ true : 서명 유효 (개인키 소유자가 서명한 것 확인)
|
||||
→ false : 서명 불일치 → Token invalid 예외
|
||||
```
|
||||
|
||||
### Nimbus JOSE 라이브러리 내부 흐름
|
||||
|
||||
```java
|
||||
// RSASSAVerifier.verify() 내부
|
||||
public boolean verify(JWSHeader header, byte[] signingInput, Base64URL signature) {
|
||||
String jcaAlg = "SHA256withRSA"; // RS256 알고리즘
|
||||
Signature verifier = Signature.getInstance(jcaAlg);
|
||||
verifier.initVerify(publicKey); // RSA 공개키 초기화
|
||||
verifier.update(signingInput); // [Header].[Payload] 바이트 입력
|
||||
return verifier.verify(signature.decode()); // Signature 바이트와 대조 검증
|
||||
}
|
||||
```
|
||||
|
||||
### 보안 원리 (RSA 비대칭 키)
|
||||
|
||||
| 시도 | 결과 |
|
||||
|------|------|
|
||||
| Payload 변조 후 전송 | digest 불일치 → 검증 실패 |
|
||||
| 개인키 없이 서명 위조 | RSA 수학적으로 불가능 |
|
||||
| 공개키로 새 서명 생성 | 공개키로는 암호화 불가 |
|
||||
| 만료된 토큰 재사용 | exp 체크에서 차단 |
|
||||
|
||||
### ApiAuthFilter 검증 흐름
|
||||
|
||||
```
|
||||
클라이언트 요청
|
||||
↓
|
||||
Bearer 토큰 추출 (Authorization 헤더 or access_token 파라미터)
|
||||
↓
|
||||
SignedJWT.parse(token) ← JWT 파싱
|
||||
↓
|
||||
만료시간(exp) 확인
|
||||
↓
|
||||
signedJWT.verify(jwsVerifier) ← RSA 공개키로 서명 검증
|
||||
↓
|
||||
Scope 검증 (oob/public이면 패스, 아니면 API별 허용 scope 확인)
|
||||
↓
|
||||
client_id 확인 (헤더 vs 토큰 payload 비교)
|
||||
↓
|
||||
등록된 APP 및 API 접근 권한 확인
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Self-Signed 인증서 생성 방법
|
||||
|
||||
### 사전 요구사항
|
||||
|
||||
- **JDK** (keytool 포함)
|
||||
- **OpenSSL**
|
||||
|
||||
### 1단계: JKS 파일 생성
|
||||
|
||||
```bash
|
||||
keytool -genkeypair \
|
||||
-alias elink-oauth \
|
||||
-keyalg RSA \
|
||||
-keysize 2048 \
|
||||
-sigalg SHA256withRSA \
|
||||
-validity 3650 \
|
||||
-keystore elink-oauth-dev.jks \
|
||||
-storepass elink1234 \
|
||||
-keypass elink1234 \
|
||||
-dname "CN=elink-oauth, OU=eActive, O=eActive, L=Seoul, ST=Seoul, C=KR"
|
||||
```
|
||||
|
||||
> 옵션 설명
|
||||
> - `-alias` : 키 별칭 (코드의 `certification.keyAlias` 설정값과 일치해야 함)
|
||||
> - `-keysize 2048` : RSA 키 길이 (최소 2048 권장)
|
||||
> - `-validity 3650` : 유효기간 (일 단위, 3650 = 10년)
|
||||
> - `-storepass` : KeyStore 전체 비밀번호 (`certification.keystorePassword`)
|
||||
> - `-keypass` : 개별 키 비밀번호 (`certification.keyPassword`)
|
||||
|
||||
### 2단계: JKS에서 공개키(.pub) 추출
|
||||
|
||||
**방법 A: keytool + openssl 조합**
|
||||
|
||||
```bash
|
||||
# JKS → 인증서(CER) 추출
|
||||
keytool -exportcert \
|
||||
-alias elink-oauth \
|
||||
-keystore elink-oauth-dev.jks \
|
||||
-storepass elink1234 \
|
||||
-file elink-oauth-dev.cer
|
||||
|
||||
# CER에서 공개키 추출 → PEM 형식(.pub)
|
||||
openssl x509 \
|
||||
-inform DER \
|
||||
-in elink-oauth-dev.cer \
|
||||
-pubkey -noout \
|
||||
-out elink-oauth-dev.pub
|
||||
```
|
||||
|
||||
**방법 B: JKS → PKCS12 변환 후 openssl**
|
||||
|
||||
```bash
|
||||
# JKS → PKCS12 변환
|
||||
keytool -importkeystore \
|
||||
-srckeystore elink-oauth-dev.jks \
|
||||
-destkeystore elink-oauth-dev.p12 \
|
||||
-deststoretype PKCS12 \
|
||||
-srcalias elink-oauth \
|
||||
-srcstorepass elink1234 \
|
||||
-deststorepass elink1234
|
||||
|
||||
# PKCS12에서 공개키 추출
|
||||
openssl pkcs12 \
|
||||
-in elink-oauth-dev.p12 \
|
||||
-passin pass:elink1234 \
|
||||
-nokeys \
|
||||
-out temp-cert.pem
|
||||
|
||||
openssl x509 \
|
||||
-in temp-cert.pem \
|
||||
-pubkey -noout \
|
||||
-out elink-oauth-dev.pub
|
||||
```
|
||||
|
||||
### 3단계: 생성 결과 확인
|
||||
|
||||
```bash
|
||||
# JKS 내용 확인
|
||||
keytool -list -v \
|
||||
-keystore elink-oauth-dev.jks \
|
||||
-storepass elink1234
|
||||
|
||||
# 공개키 내용 확인
|
||||
cat elink-oauth-dev.pub
|
||||
# 결과:
|
||||
# -----BEGIN PUBLIC KEY-----
|
||||
# MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
|
||||
# -----END PUBLIC KEY-----
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 파일 배치
|
||||
|
||||
```
|
||||
Authorization Server (elink-oauth)
|
||||
└── src/main/resources/certificate/
|
||||
└── elink-oauth-dev.jks ← 개인키 포함, 절대 외부 노출 금지
|
||||
|
||||
API Gateway (elink-online-common)
|
||||
└── src/main/resources/certificate/
|
||||
└── elink-oauth-dev.pub ← 공개키만, 배포 가능
|
||||
```
|
||||
|
||||
## 6. 설정 파일 (`OAuthServer` PropGroup)
|
||||
|
||||
| 프로퍼티 키 | 설명 | 사용 위치 |
|
||||
|------------|------|----------|
|
||||
| `certification.keystorePath` | JKS 파일 경로 | AuthorizationServerConfig |
|
||||
| `certification.keystorePassword` | KeyStore 비밀번호 | AuthorizationServerConfig |
|
||||
| `certification.keyAlias` | 키 별칭 | AuthorizationServerConfig |
|
||||
| `certification.keyPassword` | 키 비밀번호 | AuthorizationServerConfig |
|
||||
| `certification.publicKeyPath` | PUB 파일 경로 | ApiAuthFilter |
|
||||
+1
-1
Submodule elink-online-common updated: e208a2d64b...1f24dc24b5
+1
-1
Submodule elink-online-core updated: b27138d8f7...8b24475d2d
+1
-1
Submodule elink-online-core-jpa updated: 9620845daf...76342bfaef
+1
-1
Submodule elink-online-transformer updated: 82c7c2bc8c...c8a58fdf5b
+2
-1
@@ -1,6 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
|
||||
#distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
|
||||
distributionUrl=file:///D:/installs/gradle-8.7-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
networkTimeout=10000
|
||||
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
# Reposilite 3 연동 가이드
|
||||
|
||||
## 구성 개요
|
||||
|
||||
기존 Nexus(`https://nexus.eactive.synology.me:8090`) 대신 로컬 Reposilite 3(`http://localhost:8080`)를 통해 의존성을 다운로드한다.
|
||||
Reposilite의 `private` 레포지토리에 Nexus `maven-public`을 Mirror로 등록하여 캐싱한다.
|
||||
|
||||
---
|
||||
|
||||
## 1. Reposilite 3 설정
|
||||
|
||||
관리자 패널 → **Repositories** → `private` 저장소 → **Edit**
|
||||
|
||||
**Mirrored repositories** 항목에 추가:
|
||||
```
|
||||
https://nexus.eactive.synology.me:8090/repository/maven-public/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 변경된 파일
|
||||
|
||||
### `build.gradle` (루트)
|
||||
|
||||
- `nexusUrl` → `reposiliteUrl` 변수명 변경
|
||||
- `allprojects.repositories` URL을 Reposilite로 변경
|
||||
- credentials를 `gradle.properties` 변수로 참조
|
||||
|
||||
```groovy
|
||||
def reposiliteUrl = "http://localhost:8080"
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
maven {
|
||||
url "${reposiliteUrl}/private"
|
||||
allowInsecureProtocol = true
|
||||
credentials {
|
||||
username = reposiliteUser
|
||||
password = reposilitePassword
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `elink-online-core/build.gradle`
|
||||
|
||||
- 단독 빌드용 `repositories` 블록의 URL 및 credentials 동일하게 변경
|
||||
|
||||
```groovy
|
||||
// FOR LOCAL
|
||||
repositories {
|
||||
maven {
|
||||
url "${nexusUrl}/private"
|
||||
allowInsecureProtocol = true
|
||||
credentials {
|
||||
username = reposiliteUser
|
||||
password = reposilitePassword
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `gradle.properties` (신규 생성)
|
||||
|
||||
인증 정보를 별도 파일로 분리. `.gitignore`에 이미 등록되어 있어 git에 올라가지 않는다.
|
||||
|
||||
```properties
|
||||
reposiliteUser=admin
|
||||
reposilitePassword=<reposilite-token>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 서브모듈별 repositories 현황
|
||||
|
||||
| 모듈 | repositories 블록 | 비고 |
|
||||
|------|------------------|------|
|
||||
| `build.gradle` (root) | `allprojects { ... }` | 모든 서브모듈에 상속 |
|
||||
| `elink-online-core` | 별도 정의 | 단독 빌드 대응용 (`// FOR LOCAL`) |
|
||||
| `elink-online-core-jpa` | 없음 | root 상속 |
|
||||
| `elink-online-emsclient` | 없음 | root 상속 |
|
||||
| `elink-online-transformer` | 없음 | root 상속 |
|
||||
| `elink-online-common` | 없음 | root 상속 |
|
||||
| `kjb-errors` | 없음 | root 상속 (기존 `mavenCentral()` 제거) |
|
||||
|
||||
---
|
||||
|
||||
## 4. 빌드 방법
|
||||
|
||||
```bash
|
||||
# 캐시 삭제 후 Reposilite에서 새로 받기
|
||||
./gradlew build --refresh-dependencies
|
||||
|
||||
# 테스트 스킵
|
||||
./gradlew build -x test --refresh-dependencies
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 참고
|
||||
|
||||
- `publishing` 블록(아티팩트 배포)은 각 서브모듈에서 여전히 Nexus URL을 사용 중
|
||||
- Reposilite로 배포까지 전환하려면 각 서브모듈의 `nexusUrl` 및 `publishing` 블록 수정 필요
|
||||
@@ -1,380 +1,380 @@
|
||||
//package com.eactive.eai.adapter.controller;
|
||||
//
|
||||
//import java.util.ArrayList;
|
||||
//import java.util.Collections;
|
||||
//import java.util.Date;
|
||||
//import java.util.Enumeration;
|
||||
//import java.util.HashMap;
|
||||
//import java.util.List;
|
||||
//import java.util.Map;
|
||||
//import java.util.Properties;
|
||||
//
|
||||
//import javax.servlet.http.HttpServletRequest;
|
||||
//import javax.servlet.http.HttpServletResponse;
|
||||
//
|
||||
//import org.apache.commons.lang3.StringUtils;
|
||||
//// jwhong
|
||||
//import org.json.simple.JSONObject;
|
||||
//import org.springframework.beans.factory.annotation.Autowired;
|
||||
//import org.springframework.http.HttpStatus;
|
||||
//import org.springframework.http.MediaType;
|
||||
//import org.springframework.http.ResponseEntity;
|
||||
//import org.springframework.util.AntPathMatcher;
|
||||
//import org.springframework.web.bind.annotation.RequestMapping;
|
||||
//import org.springframework.web.bind.annotation.RestController;
|
||||
//
|
||||
//import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
//import com.eactive.eai.adapter.AdapterManager;
|
||||
//import com.eactive.eai.adapter.AdapterPropManager;
|
||||
//import com.eactive.eai.adapter.AdapterVO;
|
||||
//import com.eactive.eai.adapter.Keys;
|
||||
//import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
//import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
//import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
//import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
||||
//import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
||||
//import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
//import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilterFactoryKjb;
|
||||
//import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
//import com.eactive.eai.adapter.service.ApiAdapterService;
|
||||
//import com.eactive.eai.common.TransactionContextKeys;
|
||||
//import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
//import com.eactive.eai.common.server.EAIServerManager;
|
||||
//import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||
//import com.eactive.eai.common.stdmessage.STDMsgInfoAddOnVO;
|
||||
//import com.eactive.eai.common.util.DatetimeUtil;
|
||||
//import com.eactive.eai.common.util.InboundErrorLogger;
|
||||
//import com.eactive.eai.common.util.Logger;
|
||||
//import com.eactive.eai.common.util.MessageUtil;
|
||||
//import com.eactive.eai.common.util.UUIDGenerator;
|
||||
//import com.eactive.eai.inbound.action.ActionException;
|
||||
//import com.eactive.eai.inbound.action.ActionFactory;
|
||||
//import com.eactive.eai.inbound.action.RequestAction;
|
||||
//import com.eactive.eai.inbound.error.InboundErrorInfoVO;
|
||||
//
|
||||
//@RestController
|
||||
//public class ApiAdapterController implements HttpAdapterServiceKey {
|
||||
// static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
//
|
||||
// @Autowired
|
||||
// ApiAdapterService service;
|
||||
//
|
||||
// /**
|
||||
// * KJBANK 요구사항으로 /mapi/oauth2/token 과 같은 형태로 토큰 발급거래를 수행해야해서 예외처리함
|
||||
// *
|
||||
// * @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
|
||||
// * endpoints)
|
||||
// */
|
||||
// @RequestMapping(value = { "/api/*", "/mapi/*", "/api/*/{path:^(?!.*oauth).*$}/**",
|
||||
// "/mapi/{path:^(?!.*oauth2).*$}/**" })
|
||||
//// @RequestMapping(value = {"/api/**"})
|
||||
// public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
||||
// throws Exception {
|
||||
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
||||
// String apiUri = servletRequest.getRequestURI();
|
||||
// // /api/v1/public/getUserInfo.svc
|
||||
// apiUri = StringUtils.removeStart(apiUri, servletRequest.getContextPath());
|
||||
// apiUri = StringUtils.removeEnd(apiUri, "/");
|
||||
//
|
||||
// HttpDynamicInAdapterUri adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), "");
|
||||
//
|
||||
// if (logger.isDebug()) {
|
||||
// logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
||||
// }
|
||||
//
|
||||
// if (adptUri == null) {
|
||||
// logError(servletRequest);
|
||||
// String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
||||
// "can not find Adapter Uri");
|
||||
// return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(errorMsg);
|
||||
// }
|
||||
//
|
||||
// // Received time , jwhong
|
||||
// long receivedTimeMillis = System.currentTimeMillis(); // 밀리세컨 단위로 보내야함
|
||||
// String receivedTimeStr = String.valueOf(receivedTimeMillis);
|
||||
//
|
||||
// String adapterGroupName = adptUri.getAdptGrpName();
|
||||
// String adapterName = adptUri.getAdptName();
|
||||
// AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
// AdapterVO adapterVO = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName);
|
||||
// if (adapterVO == null) {
|
||||
// String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR,
|
||||
// "Adapter not found error");
|
||||
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
|
||||
// .body(errorMsg);
|
||||
// }
|
||||
//
|
||||
// Properties httpProp = AdapterPropManager.getInstance().getProperties(adapterVO.getPropGroupName());
|
||||
//
|
||||
// String adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
// String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||
// MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
||||
// String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||
//
|
||||
// String responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
|
||||
// ResponseEntity responseEntity = null;
|
||||
// Properties transactionProp = new Properties();
|
||||
// // jwhong, put api received time, eaiSvcCode
|
||||
// transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
||||
//
|
||||
// // ** jwhong TSEAIHS04의 api full path와 비교하여 adapter를 가져온다
|
||||
//// String bzwkSvcKeyName = ""; // Adapter Group별 Action Class에 따라 구성이 달라짐. 예)
|
||||
//// // _AGW_IN_RST_SyS:POST/account/{acc_no}
|
||||
//// String adapterGrpName = ""; // Adapter Group명 예) _AGW_IN_RST_SyS : API_PATH(/api/test)
|
||||
// String apiSvcCode = ""; // eaiSvcCd 예) LONNCHCON00005S2
|
||||
// String apiFullPathKey = ""; // 예) POST|/api/test/account/list, POST|/api/test/account/{acc_no}
|
||||
// Map<String, String> pathVariables = null;
|
||||
// try {
|
||||
// // PathVariable(ex:/api/test/account/{acc_no}) 대응 및 DAO조회 제거.
|
||||
// // /api/test/account/1234567 호출시 /api/test/account/{acc_no} API 로 식별.
|
||||
//
|
||||
//// String methodAndUri = getRequestRuledPath(servletRequest, apiUri, adapterVO, transactionProp);
|
||||
// String methodAndUri = servletRequest.getMethod() + "|" + apiUri;
|
||||
// STDMessageManager manager = STDMessageManager.getInstance();
|
||||
// STDMsgInfoAddOnVO stdMsgInfo = manager.getStdMsgInfoAddOn(methodAndUri);
|
||||
//// bzwkSvcKeyName = stdMsgInfo.getBzwksvckeyname();
|
||||
// apiSvcCode = stdMsgInfo.getEaiSvcCd();
|
||||
// transactionProp.put(API_SERVICE_CODE, apiSvcCode);
|
||||
//
|
||||
//// adapterGrpName = stdMsgInfo.gAdapterGroupName();
|
||||
// apiFullPathKey = stdMsgInfo.getApiFullPath();
|
||||
// if (STDMessageManager.isPathVariable(apiFullPathKey)) {
|
||||
// pathVariables = new AntPathMatcher().extractUriTemplateVariables(apiFullPathKey, methodAndUri);
|
||||
// }
|
||||
//
|
||||
//// adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), adapterGrpName);
|
||||
// } catch (Exception e) {
|
||||
//// adptUri = null;
|
||||
// }
|
||||
// // ***
|
||||
// if (pathVariables != null) {
|
||||
// transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||
// transactionProp);
|
||||
// // if (RESPONSE_TYPE_ASYNC.equals(responseType)) { // table의 값이 ASYNC 로 들어가 있는데
|
||||
// // response_type_async는 ASYN 로 되어 있어 아래처럼 비교함 jwhong 2025
|
||||
// if ("ASYNC".equals(responseType)) {
|
||||
// // responseEntity = ResponseEntity.ok("dummy"); // comment by jwhong
|
||||
// // servletResponse.addHeader("traceId", responseData); // uuid를 response header에
|
||||
// servletResponse.addHeader("traceId",
|
||||
// transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
// int httpStatus = servletResponse.getStatus();
|
||||
// if (httpStatus == 200) {
|
||||
// // 업체별 aync response message 가 다르다.
|
||||
// String asyncMsgStyle = httpProp.getProperty("ASYNC_RTNMSG_TYPE", "");
|
||||
// String responseBody = "";
|
||||
// boolean encryptAsyncAckApply = StringUtils
|
||||
// .equalsIgnoreCase(httpProp.getProperty("ASYNC_ENCRYPT_ACK", "N"), "Y");
|
||||
//
|
||||
// if (asyncMsgStyle == null || asyncMsgStyle.trim().isEmpty()) {
|
||||
// responseBody = makeResponseBodyMsg();
|
||||
// } else {
|
||||
// responseBody = asyncMsgStyle;
|
||||
// }
|
||||
// if (encryptAsyncAckApply) {
|
||||
// responseBody = service.doPostEncryption(responseBody, transactionProp, servletRequest);
|
||||
// }
|
||||
//
|
||||
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseBody);
|
||||
// // jwhong
|
||||
// } else {
|
||||
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
// }
|
||||
// } else {
|
||||
//// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
//// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
|
||||
//// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
|
||||
//
|
||||
// servletResponse.addHeader("traceId",
|
||||
// transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
// int httpStatus = servletResponse.getStatus();
|
||||
// if (httpStatus != 200) {
|
||||
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
// } else {
|
||||
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// } catch (Exception e) {
|
||||
//
|
||||
//
|
||||
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
//
|
||||
// String errorMsg = null;
|
||||
//
|
||||
// if( e instanceof HttpStatusException ) {
|
||||
// logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||
// HttpStatusException e1 = (HttpStatusException) e;
|
||||
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
// MessageUtil.ERROR_CODE_AP_ERROR, e1.getMessage(), errorResponseFormat);
|
||||
// responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||
// }
|
||||
// else if( e instanceof JwtAuthException )
|
||||
// {
|
||||
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
// MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage(), errorResponseFormat);
|
||||
// responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
// MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
||||
// responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType)
|
||||
// .body(errorMsg);
|
||||
// }
|
||||
// String postFilterNames = httpProp.getProperty("POST_FILTERS","");
|
||||
//
|
||||
// if( postFilterNames.contains("HMAC_SHA256") ) {
|
||||
// HttpAdapterFilter filter = HttpAdapterFilterFactoryKjb.createFilter("HMAC_SHA256");
|
||||
// filter.doPostFilter(adapterGroupName, postFilterNames, errorMsg, transactionProp, servletRequest, servletResponse);
|
||||
// }
|
||||
//
|
||||
//
|
||||
// } finally {
|
||||
// /**
|
||||
// * 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
||||
// * 추후 더 좋은방법이 생길경우 개선 요망
|
||||
// */
|
||||
// try {
|
||||
//
|
||||
// servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
||||
//
|
||||
// if (!"ASYNC".equals(responseType)) {
|
||||
// String uuid = transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
// String url = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
|
||||
// String method = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
|
||||
// int httpStatusCode = servletResponse.getStatus();
|
||||
//
|
||||
// Map<Object, Object> headerMap = new HashMap<>();
|
||||
// // 응답 헤더 로깅
|
||||
// for (String headerName : servletResponse.getHeaderNames()) {
|
||||
// String headerValue = servletResponse.getHeader(headerName);
|
||||
// logger.debug(String.format("httpHeader logging headerKey=%s, headerValue=%s",
|
||||
// headerName, headerValue));
|
||||
// headerMap.put(headerName, headerValue);
|
||||
// }
|
||||
// //HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName,adapterName, headerMap, url, method, httpStatusCode);
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// logger.warn("http header db logging fail.", e);
|
||||
// }
|
||||
// }
|
||||
// return responseEntity;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
|
||||
// * /api/v1/public/getUserInfo.svc
|
||||
// *
|
||||
// * @param apiUri
|
||||
// * @return
|
||||
// */
|
||||
// private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager,
|
||||
// String adapterGrpName) throws Exception {
|
||||
// if (StringUtils.isBlank(apiUri)) {
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// // * manager 출력
|
||||
// logger.warn("===== adptUriMap 상세 내용 =====");
|
||||
// for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
||||
// HttpDynamicInAdapterUri uriObj = entry.getValue();
|
||||
// logger.warn("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
||||
// + uriObj.getUri());
|
||||
// }
|
||||
// logger.warn("================================");
|
||||
//
|
||||
// //
|
||||
// for (int i = 0; i < 10; i++) {
|
||||
// HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
|
||||
// if (adptUri != null) {
|
||||
// if (StringUtils.isNotEmpty(adapterGrpName)) {
|
||||
// if(adptUri.getAdptGrpName().equals(adapterGrpName)) {
|
||||
// return adptUri;
|
||||
// }
|
||||
// } else {
|
||||
// return adptUri;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // /api/v1/public
|
||||
// apiUri = StringUtils.substringBeforeLast(apiUri, "/");
|
||||
// if (apiUri.length() < 4) { // /api
|
||||
// return null;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// private void logError(HttpServletRequest request) {
|
||||
// InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||
//
|
||||
// EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||
// String serverName = eaiServerManager.getLocalServerName();
|
||||
// String uuid = null;
|
||||
// StringBuffer sb = new StringBuffer();
|
||||
//
|
||||
// String instanceid1 = serverName.substring(0, 2);
|
||||
// String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||
// String instid = instanceid1 + instanceid2;
|
||||
// uuid = instid + UUIDGenerator.getUUID();
|
||||
//
|
||||
// String[] msgArgs = new String[1];
|
||||
// msgArgs[0] = request.getRequestURI();
|
||||
//
|
||||
// String errorCode = "RECEAIIRP010";
|
||||
// String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
|
||||
//
|
||||
// errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
||||
// errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
|
||||
// errorInfoVO.setErrCd(errorCode); // 에러코드
|
||||
// errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||
// errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
||||
// errorInfoVO.setErrDstcd(" ");
|
||||
// sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
|
||||
// .append(request.getRequestURI());
|
||||
// errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
||||
// errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
||||
//
|
||||
// InboundErrorLogger.error(errorInfoVO);
|
||||
// }
|
||||
//
|
||||
// private String makeResponseBodyMsg() {
|
||||
//
|
||||
// Map<String, Object> dataMap = new HashMap<>();
|
||||
// dataMap.put("result", 1);
|
||||
// Map<String, Object> map = new HashMap<>();
|
||||
//
|
||||
// map.put("code", "200");
|
||||
// map.put("data", dataMap);
|
||||
// map.put("message", "정상 처리 되었습니다.");
|
||||
//
|
||||
// JSONObject json = new JSONObject();
|
||||
// json.putAll(map);
|
||||
//
|
||||
// return json.toJSONString();
|
||||
// }
|
||||
//
|
||||
// /*
|
||||
// * private String makeResponseBodyMsg(String asyncMsgStyle) {
|
||||
// *
|
||||
// * Map<String, Object> dataMap = new HashMap<>(); dataMap.put("result", 1);
|
||||
// * Map<String, Object> map = new HashMap<>();
|
||||
// *
|
||||
// * switch (asyncMsgStyle) { case "TB_SUC": map.put("rspCode", "TB_SUC_000");
|
||||
// * map.put("rspMsg", "정상"); map.put("data", dataMap); break; case "ONLYDATA":
|
||||
// * map.put("data", dataMap); map.put("success", "true"); break; default:
|
||||
// * map.put("code", "200"); map.put("data", dataMap); map.put("message",
|
||||
// * "정상 처리 되었습니다."); break; }
|
||||
// *
|
||||
// * JSONObject json = new JSONObject(); json.putAll(map);
|
||||
// *
|
||||
// * return json.toJSONString(); }
|
||||
// */
|
||||
//}
|
||||
package com.eactive.eai.adapter.controller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
// jwhong
|
||||
import org.json.simple.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.Keys;
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilterFactoryKjb;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.adapter.service.ApiAdapterService;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||
import com.eactive.eai.common.stdmessage.STDMsgInfoAddOnVO;
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.common.util.InboundErrorLogger;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.common.util.UUIDGenerator;
|
||||
import com.eactive.eai.inbound.action.ActionException;
|
||||
import com.eactive.eai.inbound.action.ActionFactory;
|
||||
import com.eactive.eai.inbound.action.RequestAction;
|
||||
import com.eactive.eai.inbound.error.InboundErrorInfoVO;
|
||||
|
||||
@RestController
|
||||
public class ApiAdapterController implements HttpAdapterServiceKey {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
@Autowired
|
||||
ApiAdapterService service;
|
||||
|
||||
/**
|
||||
* KJBANK 요구사항으로 /mapi/oauth2/token 과 같은 형태로 토큰 발급거래를 수행해야해서 예외처리함
|
||||
*
|
||||
* @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
|
||||
* endpoints)
|
||||
*/
|
||||
@RequestMapping(value = { "/api/*", "/mapi/*", "/api/*/{path:^(?!.*oauth).*$}/**",
|
||||
"/mapi/{path:^(?!.*oauth2).*$}/**" })
|
||||
// @RequestMapping(value = {"/api/**"})
|
||||
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
||||
throws Exception {
|
||||
// /ONLWeb/api/v1/public/getUserInfo.svc
|
||||
String apiUri = servletRequest.getRequestURI();
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
apiUri = StringUtils.removeStart(apiUri, servletRequest.getContextPath());
|
||||
apiUri = StringUtils.removeEnd(apiUri, "/");
|
||||
|
||||
HttpDynamicInAdapterUri adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), "");
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
||||
}
|
||||
|
||||
if (adptUri == null) {
|
||||
logError(servletRequest);
|
||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
||||
"can not find Adapter Uri");
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(errorMsg);
|
||||
}
|
||||
|
||||
// Received time , jwhong
|
||||
long receivedTimeMillis = System.currentTimeMillis(); // 밀리세컨 단위로 보내야함
|
||||
String receivedTimeStr = String.valueOf(receivedTimeMillis);
|
||||
|
||||
String adapterGroupName = adptUri.getAdptGrpName();
|
||||
String adapterName = adptUri.getAdptName();
|
||||
AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
AdapterVO adapterVO = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName);
|
||||
if (adapterVO == null) {
|
||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR,
|
||||
"Adapter not found error");
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
|
||||
.body(errorMsg);
|
||||
}
|
||||
|
||||
Properties httpProp = AdapterPropManager.getInstance().getProperties(adapterVO.getPropGroupName());
|
||||
|
||||
String adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||
MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
||||
String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||
|
||||
String responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
|
||||
ResponseEntity responseEntity = null;
|
||||
Properties transactionProp = new Properties();
|
||||
// jwhong, put api received time, eaiSvcCode
|
||||
transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
||||
|
||||
// ** jwhong TSEAIHS04의 api full path와 비교하여 adapter를 가져온다
|
||||
// String bzwkSvcKeyName = ""; // Adapter Group별 Action Class에 따라 구성이 달라짐. 예)
|
||||
// // _AGW_IN_RST_SyS:POST/account/{acc_no}
|
||||
// String adapterGrpName = ""; // Adapter Group명 예) _AGW_IN_RST_SyS : API_PATH(/api/test)
|
||||
String apiSvcCode = ""; // eaiSvcCd 예) LONNCHCON00005S2
|
||||
String apiFullPathKey = ""; // 예) POST|/api/test/account/list, POST|/api/test/account/{acc_no}
|
||||
Map<String, String> pathVariables = null;
|
||||
try {
|
||||
// PathVariable(ex:/api/test/account/{acc_no}) 대응 및 DAO조회 제거.
|
||||
// /api/test/account/1234567 호출시 /api/test/account/{acc_no} API 로 식별.
|
||||
|
||||
// String methodAndUri = getRequestRuledPath(servletRequest, apiUri, adapterVO, transactionProp);
|
||||
String methodAndUri = servletRequest.getMethod() + "|" + apiUri;
|
||||
STDMessageManager manager = STDMessageManager.getInstance();
|
||||
STDMsgInfoAddOnVO stdMsgInfo = manager.getStdMsgInfoAddOn(methodAndUri);
|
||||
// bzwkSvcKeyName = stdMsgInfo.getBzwksvckeyname();
|
||||
apiSvcCode = stdMsgInfo.getEaiSvcCd();
|
||||
transactionProp.put(API_SERVICE_CODE, apiSvcCode);
|
||||
|
||||
// adapterGrpName = stdMsgInfo.gAdapterGroupName();
|
||||
apiFullPathKey = stdMsgInfo.getApiFullPath();
|
||||
if (STDMessageManager.isPathVariable(apiFullPathKey)) {
|
||||
pathVariables = new AntPathMatcher().extractUriTemplateVariables(apiFullPathKey, methodAndUri);
|
||||
}
|
||||
|
||||
// adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), adapterGrpName);
|
||||
} catch (Exception e) {
|
||||
// adptUri = null;
|
||||
}
|
||||
// ***
|
||||
if (pathVariables != null) {
|
||||
transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
||||
}
|
||||
|
||||
try {
|
||||
String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||
transactionProp);
|
||||
// if (RESPONSE_TYPE_ASYNC.equals(responseType)) { // table의 값이 ASYNC 로 들어가 있는데
|
||||
// response_type_async는 ASYN 로 되어 있어 아래처럼 비교함 jwhong 2025
|
||||
if ("ASYNC".equals(responseType)) {
|
||||
// responseEntity = ResponseEntity.ok("dummy"); // comment by jwhong
|
||||
// servletResponse.addHeader("traceId", responseData); // uuid를 response header에
|
||||
servletResponse.addHeader("traceId",
|
||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
int httpStatus = servletResponse.getStatus();
|
||||
if (httpStatus == 200) {
|
||||
// 업체별 aync response message 가 다르다.
|
||||
String asyncMsgStyle = httpProp.getProperty("ASYNC_RTNMSG_TYPE", "");
|
||||
String responseBody = "";
|
||||
boolean encryptAsyncAckApply = StringUtils
|
||||
.equalsIgnoreCase(httpProp.getProperty("ASYNC_ENCRYPT_ACK", "N"), "Y");
|
||||
|
||||
if (asyncMsgStyle == null || asyncMsgStyle.trim().isEmpty()) {
|
||||
responseBody = makeResponseBodyMsg();
|
||||
} else {
|
||||
responseBody = asyncMsgStyle;
|
||||
}
|
||||
if (encryptAsyncAckApply) {
|
||||
responseBody = service.doPostEncryption(responseBody, transactionProp, servletRequest);
|
||||
}
|
||||
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseBody);
|
||||
// jwhong
|
||||
} else {
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
}
|
||||
} else {
|
||||
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
|
||||
// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
|
||||
|
||||
servletResponse.addHeader("traceId",
|
||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
int httpStatus = servletResponse.getStatus();
|
||||
if (httpStatus != 200) {
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
} else {
|
||||
responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
|
||||
String errorMsg = null;
|
||||
|
||||
if( e instanceof HttpStatusException ) {
|
||||
logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||
HttpStatusException e1 = (HttpStatusException) e;
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AP_ERROR, e1.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||
}
|
||||
else if( e instanceof JwtAuthException )
|
||||
{
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType)
|
||||
.body(errorMsg);
|
||||
}
|
||||
String postFilterNames = httpProp.getProperty("POST_FILTERS","");
|
||||
|
||||
if( postFilterNames.contains("HMAC_SHA256") ) {
|
||||
HttpAdapterFilter filter = HttpAdapterFilterFactoryKjb.createFilter("HMAC_SHA256");
|
||||
filter.doPostFilter(adapterGroupName, postFilterNames, errorMsg, transactionProp, servletRequest, servletResponse);
|
||||
}
|
||||
|
||||
|
||||
} finally {
|
||||
/**
|
||||
* 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
||||
* 추후 더 좋은방법이 생길경우 개선 요망
|
||||
*/
|
||||
try {
|
||||
|
||||
servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
||||
|
||||
if (!"ASYNC".equals(responseType)) {
|
||||
String uuid = transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
String url = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
|
||||
String method = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
|
||||
int httpStatusCode = servletResponse.getStatus();
|
||||
|
||||
Map<Object, Object> headerMap = new HashMap<>();
|
||||
// 응답 헤더 로깅
|
||||
for (String headerName : servletResponse.getHeaderNames()) {
|
||||
String headerValue = servletResponse.getHeader(headerName);
|
||||
logger.debug(String.format("httpHeader logging headerKey=%s, headerValue=%s",
|
||||
headerName, headerValue));
|
||||
headerMap.put(headerName, headerValue);
|
||||
}
|
||||
//HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName,adapterName, headerMap, url, method, httpStatusCode);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("http header db logging fail.", e);
|
||||
}
|
||||
}
|
||||
return responseEntity;
|
||||
}
|
||||
|
||||
/**
|
||||
* url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
|
||||
* /api/v1/public/getUserInfo.svc
|
||||
*
|
||||
* @param apiUri
|
||||
* @return
|
||||
*/
|
||||
private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager,
|
||||
String adapterGrpName) throws Exception {
|
||||
if (StringUtils.isBlank(apiUri)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// * manager 출력
|
||||
logger.warn("===== adptUriMap 상세 내용 =====");
|
||||
for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
||||
HttpDynamicInAdapterUri uriObj = entry.getValue();
|
||||
logger.warn("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
||||
+ uriObj.getUri());
|
||||
}
|
||||
logger.warn("================================");
|
||||
|
||||
//
|
||||
for (int i = 0; i < 10; i++) {
|
||||
HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
|
||||
if (adptUri != null) {
|
||||
if (StringUtils.isNotEmpty(adapterGrpName)) {
|
||||
if(adptUri.getAdptGrpName().equals(adapterGrpName)) {
|
||||
return adptUri;
|
||||
}
|
||||
} else {
|
||||
return adptUri;
|
||||
}
|
||||
}
|
||||
|
||||
// /api/v1/public
|
||||
apiUri = StringUtils.substringBeforeLast(apiUri, "/");
|
||||
if (apiUri.length() < 4) { // /api
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void logError(HttpServletRequest request) {
|
||||
InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||
|
||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||
String serverName = eaiServerManager.getLocalServerName();
|
||||
String uuid = null;
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
String instanceid1 = serverName.substring(0, 2);
|
||||
String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||
String instid = instanceid1 + instanceid2;
|
||||
uuid = instid + UUIDGenerator.getUUID();
|
||||
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = request.getRequestURI();
|
||||
|
||||
String errorCode = "RECEAIIRP010";
|
||||
String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
|
||||
|
||||
errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
||||
errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
|
||||
errorInfoVO.setErrCd(errorCode); // 에러코드
|
||||
errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||
errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
||||
errorInfoVO.setErrDstcd(" ");
|
||||
sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
|
||||
.append(request.getRequestURI());
|
||||
errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
||||
errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
||||
|
||||
InboundErrorLogger.error(errorInfoVO);
|
||||
}
|
||||
|
||||
private String makeResponseBodyMsg() {
|
||||
|
||||
Map<String, Object> dataMap = new HashMap<>();
|
||||
dataMap.put("result", 1);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
|
||||
map.put("code", "200");
|
||||
map.put("data", dataMap);
|
||||
map.put("message", "정상 처리 되었습니다.");
|
||||
|
||||
JSONObject json = new JSONObject();
|
||||
json.putAll(map);
|
||||
|
||||
return json.toJSONString();
|
||||
}
|
||||
|
||||
/*
|
||||
* private String makeResponseBodyMsg(String asyncMsgStyle) {
|
||||
*
|
||||
* Map<String, Object> dataMap = new HashMap<>(); dataMap.put("result", 1);
|
||||
* Map<String, Object> map = new HashMap<>();
|
||||
*
|
||||
* switch (asyncMsgStyle) { case "TB_SUC": map.put("rspCode", "TB_SUC_000");
|
||||
* map.put("rspMsg", "정상"); map.put("data", dataMap); break; case "ONLYDATA":
|
||||
* map.put("data", dataMap); map.put("success", "true"); break; default:
|
||||
* map.put("code", "200"); map.put("data", dataMap); map.put("message",
|
||||
* "정상 처리 되었습니다."); break; }
|
||||
*
|
||||
* JSONObject json = new JSONObject(); json.putAll(map);
|
||||
*
|
||||
* return json.toJSONString(); }
|
||||
*/
|
||||
}
|
||||
@@ -1,370 +0,0 @@
|
||||
package com.eactive.eai.adapter.controller;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
// jwhong
|
||||
import org.json.simple.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilterFactoryKjb;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.adapter.service.DJErpApiAdapterService;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||
import com.eactive.eai.common.stdmessage.STDMsgInfoAddOnVO;
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.common.util.InboundErrorLogger;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.common.util.UUIDGenerator;
|
||||
import com.eactive.eai.inbound.error.InboundErrorInfoVO;
|
||||
|
||||
@RestController
|
||||
public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
@Autowired
|
||||
DJErpApiAdapterService service;
|
||||
|
||||
/**
|
||||
* DJErp OAuth 조기 적용을 위한 Controller
|
||||
*
|
||||
* @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
|
||||
* endpoints)
|
||||
*/
|
||||
@RequestMapping(value = { "/dj/{path:^(?!oauth).*$}", "/dj/{path:^(?!oauth).*$}/**" })
|
||||
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
||||
throws Exception {
|
||||
// /ONLWeb/api/v1/public/getUserInfo.svc
|
||||
String apiUri = servletRequest.getRequestURI();
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
apiUri = StringUtils.removeStart(apiUri, servletRequest.getContextPath());
|
||||
apiUri = StringUtils.removeEnd(apiUri, "/");
|
||||
|
||||
HttpDynamicInAdapterUri adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), "");
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
||||
}
|
||||
|
||||
if (adptUri == null) {
|
||||
logError(servletRequest);
|
||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
||||
"can not find Adapter Uri");
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(errorMsg);
|
||||
}
|
||||
|
||||
// Received time , jwhong
|
||||
long receivedTimeMillis = System.currentTimeMillis(); // 밀리세컨 단위로 보내야함
|
||||
String receivedTimeStr = String.valueOf(receivedTimeMillis);
|
||||
|
||||
String adapterGroupName = adptUri.getAdptGrpName();
|
||||
String adapterName = adptUri.getAdptName();
|
||||
AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
AdapterVO adapterVO = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName);
|
||||
if (adapterVO == null) {
|
||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR,
|
||||
"Adapter not found error");
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
|
||||
.body(errorMsg);
|
||||
}
|
||||
|
||||
Properties httpProp = AdapterPropManager.getInstance().getProperties(adapterVO.getPropGroupName());
|
||||
|
||||
String adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||
MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
||||
String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||
|
||||
String responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
|
||||
ResponseEntity responseEntity = null;
|
||||
Properties transactionProp = new Properties();
|
||||
// jwhong, put api received time, eaiSvcCode
|
||||
transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
||||
|
||||
// ** jwhong TSEAIHS04의 api full path와 비교하여 adapter를 가져온다
|
||||
// String bzwkSvcKeyName = ""; // Adapter Group별 Action Class에 따라 구성이 달라짐. 예)
|
||||
// // _AGW_IN_RST_SyS:POST/account/{acc_no}
|
||||
// String adapterGrpName = ""; // Adapter Group명 예) _AGW_IN_RST_SyS : API_PATH(/api/test)
|
||||
String apiSvcCode = ""; // eaiSvcCd 예) LONNCHCON00005S2
|
||||
String apiFullPathKey = ""; // 예) POST|/api/test/account/list, POST|/api/test/account/{acc_no}
|
||||
Map<String, String> pathVariables = null;
|
||||
try {
|
||||
// PathVariable(ex:/api/test/account/{acc_no}) 대응 및 DAO조회 제거.
|
||||
// /api/test/account/1234567 호출시 /api/test/account/{acc_no} API 로 식별.
|
||||
|
||||
// String methodAndUri = getRequestRuledPath(servletRequest, apiUri, adapterVO, transactionProp);
|
||||
String methodAndUri = servletRequest.getMethod() + "|" + apiUri;
|
||||
STDMessageManager manager = STDMessageManager.getInstance();
|
||||
STDMsgInfoAddOnVO stdMsgInfo = manager.getStdMsgInfoAddOn(methodAndUri);
|
||||
// bzwkSvcKeyName = stdMsgInfo.getBzwksvckeyname();
|
||||
apiSvcCode = stdMsgInfo.getEaiSvcCd();
|
||||
transactionProp.put(API_SERVICE_CODE, apiSvcCode);
|
||||
|
||||
// adapterGrpName = stdMsgInfo.gAdapterGroupName();
|
||||
apiFullPathKey = stdMsgInfo.getApiFullPath();
|
||||
if (STDMessageManager.isPathVariable(apiFullPathKey)) {
|
||||
pathVariables = new AntPathMatcher().extractUriTemplateVariables(apiFullPathKey, methodAndUri);
|
||||
}
|
||||
|
||||
// adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), adapterGrpName);
|
||||
} catch (Exception e) {
|
||||
// adptUri = null;
|
||||
}
|
||||
// ***
|
||||
if (pathVariables != null) {
|
||||
transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
||||
}
|
||||
|
||||
try {
|
||||
String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||
transactionProp);
|
||||
// if (RESPONSE_TYPE_ASYNC.equals(responseType)) { // table의 값이 ASYNC 로 들어가 있는데
|
||||
// response_type_async는 ASYN 로 되어 있어 아래처럼 비교함 jwhong 2025
|
||||
if ("ASYNC".equals(responseType)) {
|
||||
// responseEntity = ResponseEntity.ok("dummy"); // comment by jwhong
|
||||
// servletResponse.addHeader("traceId", responseData); // uuid를 response header에
|
||||
servletResponse.addHeader("traceId",
|
||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
int httpStatus = servletResponse.getStatus();
|
||||
if (httpStatus == 200) {
|
||||
// 업체별 aync response message 가 다르다.
|
||||
String asyncMsgStyle = httpProp.getProperty("ASYNC_RTNMSG_TYPE", "");
|
||||
String responseBody = "";
|
||||
boolean encryptAsyncAckApply = StringUtils
|
||||
.equalsIgnoreCase(httpProp.getProperty("ASYNC_ENCRYPT_ACK", "N"), "Y");
|
||||
|
||||
if (asyncMsgStyle == null || asyncMsgStyle.trim().isEmpty()) {
|
||||
responseBody = makeResponseBodyMsg();
|
||||
} else {
|
||||
responseBody = asyncMsgStyle;
|
||||
}
|
||||
if (encryptAsyncAckApply) {
|
||||
responseBody = service.doPostEncryption(responseBody, transactionProp, servletRequest);
|
||||
}
|
||||
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseBody);
|
||||
// jwhong
|
||||
} else {
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
}
|
||||
} else {
|
||||
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
|
||||
// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
|
||||
|
||||
servletResponse.addHeader("traceId",
|
||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||
int httpStatus = servletResponse.getStatus();
|
||||
if (httpStatus != 200) {
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
} else {
|
||||
responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
|
||||
String errorMsg = null;
|
||||
|
||||
if( e instanceof HttpStatusException ) {
|
||||
logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||
HttpStatusException e1 = (HttpStatusException) e;
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AP_ERROR, e1.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||
}
|
||||
else if( e instanceof JwtAuthException )
|
||||
{
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType)
|
||||
.body(errorMsg);
|
||||
}
|
||||
String postFilterNames = httpProp.getProperty("POST_FILTERS","");
|
||||
|
||||
if( postFilterNames.contains("HMAC_SHA256") ) {
|
||||
HttpAdapterFilter filter = HttpAdapterFilterFactoryKjb.createFilter("HMAC_SHA256");
|
||||
filter.doPostFilter(adapterGroupName, postFilterNames, errorMsg, transactionProp, servletRequest, servletResponse);
|
||||
}
|
||||
|
||||
|
||||
} finally {
|
||||
/**
|
||||
* 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
||||
* 추후 더 좋은방법이 생길경우 개선 요망
|
||||
*/
|
||||
try {
|
||||
|
||||
servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
||||
|
||||
if (!"ASYNC".equals(responseType)) {
|
||||
String uuid = transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
String url = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
|
||||
String method = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
|
||||
int httpStatusCode = servletResponse.getStatus();
|
||||
|
||||
Map<Object, Object> headerMap = new HashMap<>();
|
||||
// 응답 헤더 로깅
|
||||
for (String headerName : servletResponse.getHeaderNames()) {
|
||||
String headerValue = servletResponse.getHeader(headerName);
|
||||
logger.debug(String.format("httpHeader logging headerKey=%s, headerValue=%s",
|
||||
headerName, headerValue));
|
||||
headerMap.put(headerName, headerValue);
|
||||
}
|
||||
//HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName,adapterName, headerMap, url, method, httpStatusCode);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("http header db logging fail.", e);
|
||||
}
|
||||
}
|
||||
return responseEntity;
|
||||
}
|
||||
|
||||
/**
|
||||
* url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
|
||||
* /api/v1/public/getUserInfo.svc
|
||||
*
|
||||
* @param apiUri
|
||||
* @return
|
||||
*/
|
||||
private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager,
|
||||
String adapterGrpName) throws Exception {
|
||||
if (StringUtils.isBlank(apiUri)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// * manager 출력
|
||||
logger.warn("===== adptUriMap 상세 내용 =====");
|
||||
for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
||||
HttpDynamicInAdapterUri uriObj = entry.getValue();
|
||||
logger.warn("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
||||
+ uriObj.getUri());
|
||||
}
|
||||
logger.warn("================================");
|
||||
|
||||
//
|
||||
for (int i = 0; i < 10; i++) {
|
||||
HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
|
||||
if (adptUri != null) {
|
||||
if (StringUtils.isNotEmpty(adapterGrpName)) {
|
||||
if(adptUri.getAdptGrpName().equals(adapterGrpName)) {
|
||||
return adptUri;
|
||||
}
|
||||
} else {
|
||||
return adptUri;
|
||||
}
|
||||
}
|
||||
|
||||
// /api/v1/public
|
||||
apiUri = StringUtils.substringBeforeLast(apiUri, "/");
|
||||
if (apiUri.length() < 3) { // /api
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void logError(HttpServletRequest request) {
|
||||
InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||
|
||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||
String serverName = eaiServerManager.getLocalServerName();
|
||||
String uuid = null;
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
String instanceid1 = serverName.substring(0, 2);
|
||||
String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||
String instid = instanceid1 + instanceid2;
|
||||
uuid = instid + UUIDGenerator.getUUID();
|
||||
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = request.getRequestURI();
|
||||
|
||||
String errorCode = "RECEAIIRP010";
|
||||
String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
|
||||
|
||||
errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
||||
errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
|
||||
errorInfoVO.setErrCd(errorCode); // 에러코드
|
||||
errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||
errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
||||
errorInfoVO.setErrDstcd(" ");
|
||||
sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
|
||||
.append(request.getRequestURI());
|
||||
errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
||||
errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
||||
|
||||
InboundErrorLogger.error(errorInfoVO);
|
||||
}
|
||||
|
||||
private String makeResponseBodyMsg() {
|
||||
|
||||
Map<String, Object> dataMap = new HashMap<>();
|
||||
dataMap.put("result", 1);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
|
||||
map.put("code", "200");
|
||||
map.put("data", dataMap);
|
||||
map.put("message", "정상 처리 되었습니다.");
|
||||
|
||||
JSONObject json = new JSONObject();
|
||||
json.putAll(map);
|
||||
|
||||
return json.toJSONString();
|
||||
}
|
||||
|
||||
/*
|
||||
* private String makeResponseBodyMsg(String asyncMsgStyle) {
|
||||
*
|
||||
* Map<String, Object> dataMap = new HashMap<>(); dataMap.put("result", 1);
|
||||
* Map<String, Object> map = new HashMap<>();
|
||||
*
|
||||
* switch (asyncMsgStyle) { case "TB_SUC": map.put("rspCode", "TB_SUC_000");
|
||||
* map.put("rspMsg", "정상"); map.put("data", dataMap); break; case "ONLYDATA":
|
||||
* map.put("data", dataMap); map.put("success", "true"); break; default:
|
||||
* map.put("code", "200"); map.put("data", dataMap); map.put("message",
|
||||
* "정상 처리 되었습니다."); break; }
|
||||
*
|
||||
* JSONObject json = new JSONObject(); json.putAll(map);
|
||||
*
|
||||
* return json.toJSONString(); }
|
||||
*/
|
||||
}
|
||||
+1
-7
@@ -18,18 +18,12 @@ import java.util.Properties;
|
||||
public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
|
||||
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
private static boolean httpHeaderLogMode = HttpAdapterExtraLogUtil.isHttpHeaderMode();
|
||||
|
||||
@Override
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
|
||||
|
||||
logger.debug("httpHeader logging Interceptor start");
|
||||
|
||||
if (!httpHeaderLogMode) {
|
||||
logger.info("httpHeader logging off - use.http.header.log");
|
||||
return;
|
||||
}
|
||||
|
||||
Properties transactionProp = (Properties) request.getAttribute(TransactionContextKeys.TRANSACTION_PROP);
|
||||
if(transactionProp == null || "ASYN".equals(transactionProp.getProperty(HttpAdapterServiceKey.INBOUND_SYNC_ASYNC_TYPE))){
|
||||
logger.debug("httpHeader logging Interceptor ASYNC");
|
||||
|
||||
@@ -1,984 +0,0 @@
|
||||
package com.eactive.eai.adapter.service;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.Keys;
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.CryptoFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthFilter;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.inbound.action.ActionFactory;
|
||||
import com.eactive.eai.inbound.action.RequestAction;
|
||||
import com.eactive.eai.inbound.processor.Processor;
|
||||
import com.eactive.eai.message.StandardMessageUtil;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.mina.common.ByteBuffer;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.*;
|
||||
|
||||
//for encrypt/decrypt jwhong
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.kjbank.encrypt.exchange.crypto.AES256Cipher;
|
||||
import com.kjbank.encrypt.exchange.crypto.AESCipher;
|
||||
import com.kjbank.encrypt.exchange.crypto.AES256GCMCipher;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
import com.eactive.eai.common.context.ElinkTransactionContext;
|
||||
|
||||
|
||||
@Service
|
||||
public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||
public static final String HTTP_STATUS = "HTTP_STATUS"; // jwhong
|
||||
// HEADER_GROUP JSON에 추가할 항목 정의, 없으면 전체 header 추가
|
||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||
public static final String PROPERTIES_NAME_HTTP_REQUEST_METHOD = "httpRequestMethod";
|
||||
|
||||
private static final String JSON_CONTENT_TYPE = "application/json";
|
||||
private static final String JSON_FIELD_NAME = "json-body";
|
||||
private static final String FILE_GROUP_NAME = "image-file";
|
||||
private static final String UPLOAD_ROOT_PATH = "UPLOAD_ROOT_PATH";
|
||||
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id"; // jwhong
|
||||
private boolean encryptResponseApply; // inbound에 대한 응답 암호화 여부 flag
|
||||
|
||||
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp, AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
|
||||
int traceLevel = 0;
|
||||
|
||||
AdapterPropManager manager = null;
|
||||
String adptGrpName = adapterGroupVO.getName();
|
||||
String adptName = adapterVO.getName();
|
||||
|
||||
String urlDecodeYn = httpProp.getProperty(URL_DECODE_YN, "N");
|
||||
String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||
|
||||
String traceLevelTemp = httpProp.getProperty(TRACE_LEVEL, "0");
|
||||
String relayRequestHeaderKeys = httpProp.getProperty(HEADER_KEYS);
|
||||
String headerGroupName = httpProp.getProperty(HEADER_GROUP);
|
||||
|
||||
boolean isParameterType = false;
|
||||
String message = null;
|
||||
|
||||
String paramValue = null;
|
||||
String adptMsgType = null;
|
||||
|
||||
transactionProp.put(INBOUND_METHOD, request.getMethod());
|
||||
transactionProp.put(INBOUND_URI, request.getRequestURI());
|
||||
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(request.getQueryString()));
|
||||
transactionProp.put(INBOUND_HEADER, getHeaders(request));
|
||||
transactionProp.put(INBOUND_EXTPARAMS, StringUtils.defaultString(request.getQueryString()));
|
||||
if (StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_REST)
|
||||
|| StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_HTTP_CUSTOM)) {
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
String extUrl = StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
|
||||
transactionProp.put(INBOUND_EXTURI, extUrl);
|
||||
} else {
|
||||
transactionProp.put(INBOUND_EXTURI, getExtUri(request));
|
||||
}
|
||||
transactionProp.put(INBOUND_CLIENT_IP, getClientIp(request)); // Client IP 추가
|
||||
transactionProp.put(Processor.REQUEST_ACTION, adapterVO.getAdapterGroupVO().getRefClass());
|
||||
transactionProp.put(API_PATH, httpProp.getProperty(API_PATH, ""));
|
||||
|
||||
//djerp bypass
|
||||
transactionProp.put(INBOUND_REWRITE_PATH,
|
||||
getRewritePath(transactionProp.getProperty(INBOUND_EXTURI), transactionProp.getProperty(API_PATH)));
|
||||
transactionProp.put(INBOUND_REMOTE_ADDR, request.getRemoteAddr());
|
||||
transactionProp.put(INBOUND_SCHEME, request.getScheme());
|
||||
|
||||
transactionProp.put(PRE_FILTERS, httpProp.getProperty(PRE_FILTERS, ""));
|
||||
transactionProp.put(POST_FILTERS, httpProp.getProperty(POST_FILTERS, ""));
|
||||
transactionProp.put(PROPERTIES_NAME_HTTP_REQUEST_METHOD, request.getMethod());
|
||||
transactionProp.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
|
||||
transactionProp.put("BLOCK_IP", httpProp.getProperty("BLOCK_IP", ""));
|
||||
|
||||
//djerp bypass
|
||||
Map<String, String> pathVariables = assignPathVariables(request, adptGrpName, adptName, null, transactionProp);
|
||||
if (pathVariables != null) {
|
||||
transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
||||
}
|
||||
|
||||
transactionProp.put(ENC_PATHS, httpProp.getProperty(ENC_PATHS, ""));
|
||||
|
||||
transactionProp.put(ENCRYPT_ALGORITHM, httpProp.getProperty(ENCRYPT_ALGORITHM, "")); //jwhong
|
||||
if (getHeaders(request).get(HEADER_NAME_CLIENT_ID) != null) { // jwhong
|
||||
transactionProp.put(HEADER_NAME_CLIENT_ID, getHeaders(request).get(HEADER_NAME_CLIENT_ID));
|
||||
}
|
||||
transactionProp.put(ENCRYPT_BASE_TYPE, httpProp.getProperty(ENCRYPT_BASE_TYPE, "")); //jwhong
|
||||
// //transactionProp.put(INBOUND_TOKEN, getHeaders(request).get(INBOUND_TOKEN)); // jwhong
|
||||
// transactionProp.put(INBOUND_TOKEN, getHeaders(request).get(INBOUND_TOKEN) != null ? getHeaders(request).get(INBOUND_TOKEN) : ""); //jwhong , null 이면 default로 "" put
|
||||
String inboundToken = getHeaders(request).getOrDefault(INBOUND_TOKEN, "").toString();
|
||||
if (StringUtils.isNotBlank(inboundToken) && StringUtils.startsWith(inboundToken, "Bearer ")) {
|
||||
inboundToken = inboundToken.substring(7);
|
||||
}
|
||||
transactionProp.put(INBOUND_TOKEN, inboundToken);
|
||||
transactionProp.put(ENCRYPT_AES256_IV, httpProp.getProperty(ENCRYPT_AES256_IV, "")); //jwhong
|
||||
transactionProp.put(ENCRYPT_AES256_KEY, httpProp.getProperty(ENCRYPT_AES256_KEY, "")); //jwhong
|
||||
|
||||
transactionProp.put(CryptoFilter.PROP_MODULE_NAME, httpProp.getProperty(CryptoFilter.PROP_MODULE_NAME, ""));
|
||||
|
||||
// SEED 컬럼암호하 시 Key로 사용함
|
||||
String seedkey = getHeaders(request).getOrDefault("x-obp-partnercode", "").toString();
|
||||
ElinkTransactionContext.setSeedKey(seedkey);
|
||||
|
||||
try {
|
||||
traceLevel = Integer.parseInt(traceLevelTemp);
|
||||
} catch (Exception e) {
|
||||
traceLevel = 0;
|
||||
}
|
||||
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
logger.debug("시작 >> encode = [" + encode + "]");
|
||||
|
||||
switch (HttpMethodType.getValue(request.getMethod())) {
|
||||
case GET:
|
||||
case DELETE:
|
||||
isParameterType = true;
|
||||
break;
|
||||
case POST:
|
||||
case PUT:
|
||||
if (StringUtils.contains(request.getContentType(), "application/x-www-form-urlencoded")) {
|
||||
isParameterType = true;
|
||||
} else if ( StringUtils.isNoneBlank(request.getQueryString()) ) { // jwhong
|
||||
isParameterType = true;
|
||||
} else {
|
||||
isParameterType = false;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (isParameterType) {
|
||||
paramValue = request.getQueryString();
|
||||
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(paramValue)); // Filter에서 QueryString 검증을 위해 저장
|
||||
if (paramValue == null)
|
||||
paramValue = "";
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(paramValue));
|
||||
}
|
||||
|
||||
// json으로 변환
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("{");
|
||||
Map<String, String[]> paramMap = assignParameterMap(request, adptGrpName, adptName, null, transactionProp);
|
||||
int i = 0;
|
||||
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
|
||||
if (i > 0) {
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append("\"").append(entry.getKey()).append("\":");
|
||||
String[] values = entry.getValue();
|
||||
if (values.length > 1) {
|
||||
// ["111", "222"]
|
||||
sb.append("[");
|
||||
for (int j = 0; j < values.length; j++) {
|
||||
if (j > 0) {
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append("\"").append(JSONValue.escape(values[j])).append("\"");
|
||||
}
|
||||
sb.append("]");
|
||||
} else {
|
||||
sb.append("\"").append(JSONValue.escape(values[0])).append("\"");
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
sb.append("}");
|
||||
|
||||
paramValue = sb.toString();
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
||||
+ CommonLib.getDumpMessage(paramValue.getBytes(encode)));
|
||||
}
|
||||
} else {
|
||||
if (request.getContentLength() > 0) {
|
||||
ServletInputStream sis = request.getInputStream();
|
||||
ByteBuffer bb = ByteBuffer.allocate(1024).setAutoExpand(true);
|
||||
int i = 0;
|
||||
byte[] cbuf = new byte[1024];
|
||||
while ((i = sis.read(cbuf, 0, 1024)) != -1) {
|
||||
if (i == 1024) {
|
||||
bb.put(cbuf);
|
||||
} else {
|
||||
byte[] tail = new byte[i];
|
||||
System.arraycopy(cbuf, 0, tail, 0, i);
|
||||
bb.put(tail);
|
||||
}
|
||||
}
|
||||
byte[] data = new byte[bb.position()];
|
||||
bb.position(0);
|
||||
bb.get(data);
|
||||
String bodyEncode = encode;
|
||||
String contentTypeHeader = request.getContentType();
|
||||
if (StringUtils.isNotBlank(contentTypeHeader)) {
|
||||
try {
|
||||
MediaType mediaType = MediaType.parseMediaType(contentTypeHeader);
|
||||
if (mediaType.getCharset() != null) {
|
||||
bodyEncode = mediaType.getCharset().name();
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
paramValue = new String(data, bodyEncode);
|
||||
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(data));
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
||||
+ CommonLib.getDumpMessage(data));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (paramValue == null) { // parameter가 없는 경우때문에 처리
|
||||
paramValue = "";
|
||||
}
|
||||
// 순수한 Body값을 저장을 위해 위치 변경.
|
||||
transactionProp.put(INBOUND_REQUEST_MESSAGE, paramValue);
|
||||
|
||||
// paramValue가 null이 아닌 빈문자열(""," ")인 경우에 대비하여 조건 수정.
|
||||
// if (StringUtils.isNotBlank(paramValue)) { // jwhong decrypt
|
||||
// paramValue = doPreDecryption(paramValue, transactionProp, request);
|
||||
// }
|
||||
|
||||
if ("Y".equals(urlDecodeYn) && isParameterType) {
|
||||
message = URLDecoder.decode(paramValue);
|
||||
} else {
|
||||
message = paramValue;
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
String[] msgArgs = new String[2];
|
||||
msgArgs[0] = adptGrpName;
|
||||
msgArgs[1] = message;
|
||||
String resMsg = ExceptionUtil.make("RICEAIAHA005", msgArgs);
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
|
||||
|
||||
adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
// HttpHeaders responseHeaders = new HttpHeaders();
|
||||
// responseHeaders.setContentType(MediaType.valueOf("application/json;charset=" + encode));
|
||||
|
||||
|
||||
// HEADER_GROUP 셋팅
|
||||
if (MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)
|
||||
&& StringUtils.isNotBlank(relayRequestHeaderKeys)) {
|
||||
JSONObject jsonMessage = (JSONObject) JSONValue.parse(message);
|
||||
JSONObject headerJson = new JSONObject();
|
||||
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
||||
String key = e.nextElement();
|
||||
headerJson.put(key, request.getHeader(key));
|
||||
}
|
||||
} else {
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils
|
||||
.tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
||||
|
||||
for (String key : relayKeyArr) {
|
||||
String headerValue = request.getHeader(key);
|
||||
if (StringUtils.isNotBlank(headerValue)) {
|
||||
headerJson.put(key, headerValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (headerJson.size() > 0) {
|
||||
jsonMessage.put(headerGroupName, headerJson);
|
||||
message = jsonMessage.toJSONString();
|
||||
}
|
||||
}
|
||||
|
||||
if (message == null) {
|
||||
message = "";
|
||||
}
|
||||
|
||||
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
|
||||
// transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
|
||||
// 로컬 서비스 호출 ,encoding 처리 추가
|
||||
String result = (String) service(adptGrpName, adptName, message, transactionProp, request, response);
|
||||
|
||||
applyOutboundResponseHeaders(transactionProp, response);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] result " + encode + " (" + adptGrpName + ") = [" + result + "]");
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
String syncAsyncType = transactionProp.getProperty(INBOUND_SYNC_ASYNC_TYPE);
|
||||
|
||||
if (!"ASYN".equals(syncAsyncType) && MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode rootNode = (ObjectNode) mapper.readTree(result);
|
||||
JsonNode headerGroup = rootNode.get(headerGroupName);
|
||||
if(headerGroup != null) {
|
||||
for(Iterator<String> it = headerGroup.fieldNames(); it.hasNext();) {
|
||||
String name = it.next();
|
||||
String value = headerGroup.get(name).asText();
|
||||
response.addHeader(name, value);
|
||||
}
|
||||
rootNode.remove(headerGroupName);
|
||||
result = mapper.writeValueAsString(rootNode);
|
||||
}
|
||||
}
|
||||
|
||||
// KJBank는 요청에 대한 응답 (Sync응답, Aync 에 대한 Ack응답) 에 대하여 암호화 하지 않는다. 무조건 안한다. 따라서 아래부분은 구현은 했지만 사용하지 않는다.
|
||||
// 위 2가지 경우 암호화 하는걸로 요청 변경되어 아래 암호화 수행하도록 수정함
|
||||
// encryptResponseApply = StringUtils.equalsIgnoreCase(httpProp.getProperty("ENCRYPT_RESPONSE_APPLY", "N"), "Y");
|
||||
// if ( encryptResponseApply) {
|
||||
// result = doPostEncryption(result, transactionProp, request); // jwhong Encrypt
|
||||
// }
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* HttpClientAdapterServiceBypass.assignRelayDataToInbound() 에서
|
||||
* transactionProp에 저장한 OUTBOUND_RESPONSE_HEADERS를 response에 적용한다.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private void applyOutboundResponseHeaders(Properties transactionProp, HttpServletResponse response) {
|
||||
Map<String, Object> outboundPropertyMap = (Map<String, Object>) transactionProp.get(OUTBOUND_PROPERTY_MAP);
|
||||
if (outboundPropertyMap == null) {
|
||||
return;
|
||||
}
|
||||
Properties headerProp = (Properties) outboundPropertyMap.get(OUTBOUND_RESPONSE_HEADERS);
|
||||
if (headerProp == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String[] hopByHopHeaders = { "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization",
|
||||
"TE", "Trailers", "Transfer-Encoding", "Upgrade" };
|
||||
|
||||
for (Map.Entry<Object, Object> entry : headerProp.entrySet()) {
|
||||
String key = (String) entry.getKey();
|
||||
String value = (String) entry.getValue();
|
||||
|
||||
if (StringUtils.equalsAnyIgnoreCase(key, hopByHopHeaders)) {
|
||||
continue;
|
||||
}
|
||||
if (StringUtils.equalsIgnoreCase(key, HttpHeaders.CONTENT_LENGTH)) {
|
||||
continue;
|
||||
}
|
||||
if (StringUtils.equalsIgnoreCase(key, HTTP_STATUS)) {
|
||||
if (StringUtils.isNotBlank(value)) {
|
||||
try {
|
||||
response.setStatus(Integer.parseInt(value));
|
||||
} catch (NumberFormatException ex) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
response.addHeader(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
// jwhong decrypt
|
||||
|
||||
private String doPreDecryption(String eaiBody, Properties transactionProp, HttpServletRequest request) throws Exception {
|
||||
String decryptAlgorithm = transactionProp.getProperty(ENCRYPT_ALGORITHM, "");
|
||||
String xElinkClientId = transactionProp.getProperty(HEADER_NAME_CLIENT_ID, ""); // 이 값이 OAuth의 client id 값이다 . http header 에 포함되어 온다. jwhong
|
||||
String encryptBaseKeyType = transactionProp.getProperty(ENCRYPT_BASE_TYPE);
|
||||
//String inboundToken2 = transactionProp.getProperty(INBOUND_TOKEN, ""); // 이건 token 값이 아니고 authorization 값이다
|
||||
String inboundToken = "";
|
||||
|
||||
String secretAES256Iv = transactionProp.getProperty("ENCRYPT_AES256_IV");
|
||||
String secretAES256Key = transactionProp.getProperty("ENCRYPT_AES256_KEY");
|
||||
|
||||
if ( decryptAlgorithm == "" ) { // 복호화 대상이 아님
|
||||
return eaiBody;
|
||||
}
|
||||
|
||||
inboundToken = JwtTokenExtractor(request);
|
||||
xElinkClientId = JwtClientIdExtractor(inboundToken); // token에서 client id를 추출함
|
||||
|
||||
// 암호화 key를 token 내용으로 할지 client secret 내용으로 할지 결정함. adapter property에 정의함
|
||||
// ENCRYPT_ALGORITHM 을 설정했는데 ENCRYPT_BASE_TYPE을 설정안하면 Decrypt 수행시 Exception 발생함
|
||||
String clientSecret = "";
|
||||
if ("TOKEN".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||
clientSecret = inboundToken;
|
||||
} else if ( "SECRETKEY".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||
ClientDetails clientDetail = manager.getClientDeatilsStore().get(xElinkClientId);
|
||||
|
||||
if ( clientDetail != null ) { // 여기서 not null 이라는 것은 apim oauth server에서 발급된 token 임.
|
||||
// 즉 KJBank 에서 요청이 들어온 것이다.
|
||||
clientSecret = clientDetail.getClientSecret();
|
||||
} // 그럼 업체에서 요청이 들어오면?? 업체도 apim oauth server에서 발급된 token을 사용하는것이다.
|
||||
}
|
||||
|
||||
byte[] decryptedMessage = null;
|
||||
decryptedMessage = doInboundPreDecrypt(eaiBody, decryptAlgorithm,clientSecret,secretAES256Iv, secretAES256Key );
|
||||
|
||||
if (decryptedMessage == null) {
|
||||
throw new Exception("[ApiAdapterService] Decrypt Error : Invalid encrypted message");
|
||||
}
|
||||
|
||||
|
||||
String resultMessage = new String(decryptedMessage, StandardCharsets.UTF_8 );
|
||||
return resultMessage;
|
||||
//return new String(decryptedMessage, StandardCharsets.UTF_8 );
|
||||
}
|
||||
|
||||
|
||||
// jwhong encrypt
|
||||
public String doPostEncryption(String eaiBody, Properties transactionProp, HttpServletRequest request) throws Exception {
|
||||
|
||||
String decryptAlgorithm = transactionProp.getProperty(ENCRYPT_ALGORITHM, "");
|
||||
String xElinkClientId = transactionProp.getProperty(HEADER_NAME_CLIENT_ID, ""); // 이 값이 OAuth의 client id 값이다 . http header 에 포함되어 온다. jwhong
|
||||
String encryptBaseKeyType = transactionProp.getProperty(ENCRYPT_BASE_TYPE);
|
||||
String inboundToken = "";
|
||||
|
||||
String secretAES256Iv = transactionProp.getProperty("ENCRYPT_AES256_IV");
|
||||
String secretAES256Key = transactionProp.getProperty("ENCRYPT_AES256_KEY");
|
||||
|
||||
if ( decryptAlgorithm == "" ) { // 복호화 대상이 아님
|
||||
return eaiBody;
|
||||
}
|
||||
|
||||
inboundToken = JwtTokenExtractor(request);
|
||||
xElinkClientId = JwtClientIdExtractor(inboundToken); // token에서 client id를 추출함
|
||||
|
||||
// 암호화 key를 token 내용으로 할지 client secret 내용으로 할지 결정함. adapter property에 정의함
|
||||
// ENCRYPT_ALGORITHM 을 설정했는데 ENCRYPT_BASE_TYPE을 설정안하면 Decrypt 수행시 Exception 발생함
|
||||
String clientSecret = "";
|
||||
if ("TOKEN".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||
clientSecret = inboundToken;
|
||||
} else if ( "SECRETKEY".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||
ClientDetails clientDetail = manager.getClientDeatilsStore().get(xElinkClientId);
|
||||
|
||||
if ( clientDetail != null ) {
|
||||
clientSecret = clientDetail.getClientSecret();
|
||||
}
|
||||
}
|
||||
|
||||
String encryptedMessage = null;
|
||||
encryptedMessage = doInboundPostEncrypt(eaiBody, decryptAlgorithm,clientSecret,secretAES256Iv, secretAES256Key );
|
||||
|
||||
if (encryptedMessage == null) {
|
||||
throw new Exception("[ApiAdapterService] Encrypt Error : Invalid PlainText message");
|
||||
}
|
||||
|
||||
return encryptedMessage;
|
||||
//String resultMessage = new String(encryptedMessage, StandardCharsets.UTF_8 );
|
||||
//return resultMessage;
|
||||
}
|
||||
|
||||
|
||||
private byte[] convertObjectToBytes(Object obj) throws IOException {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(bos);
|
||||
oos.writeObject(obj);
|
||||
oos.flush();
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
private byte[] convertObjectToBase64Bytes(Object obj) throws IOException {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(bos);
|
||||
oos.writeObject(obj);
|
||||
oos.flush();
|
||||
oos.close();
|
||||
|
||||
// 직렬화된 byte[] → Base64 문자열 → 다시 byte[]로 변환
|
||||
String base64String = Base64.getEncoder().encodeToString(bos.toByteArray());
|
||||
return base64String.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public static Object convertBytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
|
||||
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
|
||||
ObjectInputStream ois = new ObjectInputStream(bis)) {
|
||||
return ois.readObject();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private byte[] doInboundPreDecrypt(String eaiStringBody, String decryptAlgorithm, String clientSecretKey, String secretAES256Iv, String secretAES256Key) throws Exception {
|
||||
|
||||
byte[] decryptedMessage = null;
|
||||
//String eaiStringBody = new String(eaiBody, StandardCharsets.UTF_8);
|
||||
|
||||
eaiStringBody = extractBodyMsg(decryptAlgorithm, eaiStringBody);
|
||||
|
||||
if (eaiStringBody == null) {
|
||||
throw new Exception("[ApiAdapterService] Cannot decrypt Error : input is plain text");
|
||||
}
|
||||
|
||||
//test source
|
||||
logger.debug("Base64 문자열: " + eaiStringBody);
|
||||
logger.debug("Base64 문자열 길이: " + eaiStringBody.length());
|
||||
logger.debug("Base64 문자열 끝: " + eaiStringBody.substring(eaiStringBody.length() - 10));
|
||||
|
||||
// Base64 디코딩 테스트
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(eaiStringBody);
|
||||
logger.debug("디코딩 성공, 길이: " + decoded.length);
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.debug("Base64 디코딩 실패: " + e.getMessage());
|
||||
}
|
||||
// end test source
|
||||
|
||||
switch (decryptAlgorithm) {
|
||||
case "AES128":
|
||||
case "AES128-TOSS":
|
||||
try {
|
||||
String key128 = clientSecretKey.substring(22,38); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||
//String decryptedStrMessage = AESCipher.decrypt(eaiStringBody, key128);
|
||||
String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES128-TOGETHER":
|
||||
try {
|
||||
String key128 = clientSecretKey.substring(44,60); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||
//String decryptedStrMessage = AESCipher.decrypt(eaiStringBody, key128);
|
||||
String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256":
|
||||
try {
|
||||
String key = clientSecretKey.substring(10,42);
|
||||
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, key);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256-KAKAO":
|
||||
try {
|
||||
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256-TOSS":
|
||||
try {
|
||||
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
|
||||
case "AES256GCM":
|
||||
try {
|
||||
byte[] key = AES256GCMCipher.generateKey();
|
||||
AES256GCMCipher cipher = new AES256GCMCipher(key);
|
||||
byte[] aad = "metadata".getBytes();
|
||||
|
||||
String decryptedStrMessage = cipher.decrypt(eaiStringBody , aad);
|
||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
try {
|
||||
decryptedMessage = eaiStringBody.getBytes();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] doOutboundPostFilter Array copy error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return decryptedMessage;
|
||||
}
|
||||
|
||||
private String extractBodyMsg(String decryptAlgorithm, String eaiStringBody) {
|
||||
|
||||
String decryptedJsonKey = "";
|
||||
String decryptedBodyMessage = "";
|
||||
|
||||
decryptedJsonKey = getJsonKey(decryptAlgorithm);
|
||||
|
||||
try {
|
||||
JSONParser parser = new JSONParser();
|
||||
JSONObject jsonObject = (JSONObject) parser.parse(eaiStringBody);
|
||||
decryptedBodyMessage = (String) jsonObject.get(decryptedJsonKey);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClient5AdapterServiceRest] extractBodyMsg error : " + e.getMessage());
|
||||
}
|
||||
|
||||
return decryptedBodyMessage;
|
||||
|
||||
}
|
||||
|
||||
private String getJsonKey(String Algorithm) {
|
||||
|
||||
String jsonKey = "";
|
||||
|
||||
switch (Algorithm) {
|
||||
case "AES128":
|
||||
case "AES128-TOSS":
|
||||
jsonKey = "preScreeningRequest";
|
||||
break;
|
||||
case "AES128-TOGETHER":
|
||||
jsonKey = "obpTxData";
|
||||
break;
|
||||
case "AES256":
|
||||
jsonKey = "preScreeningRequest";
|
||||
break;
|
||||
case "AES256-KAKAO":
|
||||
jsonKey = "encrypted_data";
|
||||
break;
|
||||
case "AES256-TOSS":
|
||||
jsonKey = "encryptedData";
|
||||
break;
|
||||
case "AES256-NICEON":
|
||||
jsonKey = "enc_data";
|
||||
break;
|
||||
case "AES256GCM":
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return jsonKey;
|
||||
}
|
||||
|
||||
private String doInboundPostEncrypt(String eaiStringBody, String encryptAlgorithm, String clientSecretKey, String secretAES256Iv, String secretAES256Key) {
|
||||
|
||||
//byte[] encryptedMessage = null;
|
||||
String encryptedStrMessage = null;
|
||||
String encryptedJsonKey = "";
|
||||
|
||||
encryptedJsonKey = getJsonKey(encryptAlgorithm);
|
||||
|
||||
switch (encryptAlgorithm) {
|
||||
case "AES128":
|
||||
case "AES128-TOSS":
|
||||
try {
|
||||
String key128 = clientSecretKey.substring(22,38); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||
encryptedStrMessage = AESCipher.encrypt(eaiStringBody, key128);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES128-TOGETHER":
|
||||
try {
|
||||
String key128 = clientSecretKey.substring(44,60); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||
encryptedStrMessage = AESCipher.encrypt(eaiStringBody, key128);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256":
|
||||
try {
|
||||
String key = clientSecretKey.substring(10,42);
|
||||
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, key);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256-KAKAO":
|
||||
try {
|
||||
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
case "AES256-TOSS":
|
||||
try {
|
||||
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
|
||||
case "AES256GCM":
|
||||
try {
|
||||
byte[] key = AES256GCMCipher.generateKey();
|
||||
AES256GCMCipher cipher = new AES256GCMCipher(key);
|
||||
byte[] aad = "metadata".getBytes();
|
||||
|
||||
encryptedStrMessage = cipher.encrypt(eaiStringBody , aad);
|
||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
try {
|
||||
encryptedStrMessage = eaiStringBody;
|
||||
//encryptedMessage = eaiStringBody.getBytes();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("HttpClientAdapterServiceRest] doOutboundPostFilter Array copy error=" + e.getMessage());
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put(encryptedJsonKey, encryptedStrMessage);
|
||||
JSONObject json = new JSONObject();
|
||||
json.putAll(map);
|
||||
return json.toJSONString();
|
||||
//return encryptedMessage;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private String JwtTokenExtractor(HttpServletRequest request) {
|
||||
|
||||
String Token = "";
|
||||
try {
|
||||
Token = JwtAuthFilter.extractJWTToken(request);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
logger.debug("Token is: " + Token);
|
||||
return Token;
|
||||
|
||||
}
|
||||
|
||||
private String JwtClientIdExtractor(String inboundToken) {
|
||||
|
||||
String tokenClientId ="";
|
||||
try {
|
||||
SignedJWT signedJWT = SignedJWT.parse(inboundToken);
|
||||
tokenClientId = (String) signedJWT.getJWTClaimsSet().getClaim(PAYLOAD_PARAM_NAME_CLIENT_ID);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
tokenClientId = "";
|
||||
}
|
||||
|
||||
logger.debug("Token Client ID: " + tokenClientId);
|
||||
return tokenClientId;
|
||||
|
||||
}
|
||||
|
||||
// jwhong until here
|
||||
|
||||
|
||||
private Map<String, String[]> assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName,
|
||||
Object requestBytes, Properties prop) {
|
||||
// PathVariable 체크
|
||||
if (StringUtils.equalsAnyIgnoreCase(request.getMethod(), HttpMethod.GET.name(), HttpMethod.DELETE.name())
|
||||
&& StringUtils.isBlank(request.getQueryString())) {
|
||||
try {
|
||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||
RequestAction action = ActionFactory.createAction(actionName);
|
||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||
String[] keys = action.perform(requestBytes);
|
||||
String requestPath = keys[0];
|
||||
|
||||
// PathVariable 지원 추가
|
||||
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
||||
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
||||
Map<String, String> paramMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath,
|
||||
requestPath);
|
||||
if (paramMap != null && paramMap.size() > 0) {
|
||||
Map<String, String[]> returnMap = new HashMap<>();
|
||||
for (String key : paramMap.keySet()) {
|
||||
if (StringUtils.equalsIgnoreCase(key, "method")) {
|
||||
continue;
|
||||
}
|
||||
returnMap.put(key, new String[] { paramMap.get(key) });
|
||||
}
|
||||
|
||||
return returnMap;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
return request.getParameterMap();
|
||||
}
|
||||
|
||||
private String getRewritePath(String extUri, String basePath) {
|
||||
return StringUtils.removeStart(extUri, StringUtils.removeEnd(basePath, "/"));
|
||||
}
|
||||
|
||||
private Map<String, String> assignPathVariables(HttpServletRequest request, String adptGrpName, String adptName,
|
||||
Object requestBytes, Properties prop) {
|
||||
Map<String, String> variablesMap = null;
|
||||
// QueryString 있을때는 체크(X)
|
||||
if (StringUtils.isBlank(request.getQueryString())) {
|
||||
try {
|
||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||
RequestAction action = ActionFactory.createAction(actionName);
|
||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||
String[] keys = action.perform(requestBytes);
|
||||
String requestPath = keys[0];
|
||||
|
||||
// PathVariable 지원 추가
|
||||
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
||||
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
||||
variablesMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath, requestPath);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
return variablesMap;
|
||||
}
|
||||
|
||||
private Properties getHeaders(HttpServletRequest request) {
|
||||
Properties prop = new Properties();
|
||||
|
||||
Enumeration<String> headerNames = request.getHeaderNames();
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String key = headerNames.nextElement();
|
||||
// 동일 이름의 헤더가 여러 개인 경우 콤마로 합침 (RFC 7230)
|
||||
Enumeration<String> values = request.getHeaders(key);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
while (values.hasMoreElements()) {
|
||||
if (sb.length() > 0) sb.append(", ");
|
||||
sb.append(values.nextElement());
|
||||
}
|
||||
prop.setProperty(key, sb.toString());
|
||||
}
|
||||
|
||||
return prop;
|
||||
}
|
||||
|
||||
private String getExtUri(HttpServletRequest request) {
|
||||
String orgUri = request.getRequestURI().replaceAll(request.getContextPath(), "");
|
||||
String uri = getExtUri(orgUri, 3);
|
||||
if (uri != null && uri.trim().length() > 0) {
|
||||
return "/" + uri;
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static String getExtUri(String url, int length) {
|
||||
String[] urls = url.split("/");
|
||||
List<String> newUrls = new ArrayList<>();
|
||||
Collections.addAll(newUrls, urls);
|
||||
return StringUtils.join(newUrls.subList(length, urls.length).toArray(), "/");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Deprecated
|
||||
public void service(String adptGrpName, String adptName, HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP 요청에서 클라이언트 IP를 추출합니다.
|
||||
* X-Forwarded-For 헤더가 있는 경우 이를 우선적으로 사용하고,
|
||||
* 없는 경우 remoteAddr을 사용합니다.
|
||||
*/
|
||||
private String getClientIp(HttpServletRequest request) {
|
||||
String ipAddress = request.getHeader("X-Forwarded-For");
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getRemoteAddr();
|
||||
}
|
||||
return ipAddress;
|
||||
}
|
||||
|
||||
private String assignApiId(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request) {
|
||||
String apiId = null;
|
||||
try {
|
||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||
RequestAction action = ActionFactory.createAction(actionName);
|
||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||
String[] keys = action.perform(message);
|
||||
apiId = keys[0];
|
||||
|
||||
// PathVariable 지원 추가
|
||||
apiId = StandardMessageUtil.getMatchedKey(apiId, actionName);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
// // header 에서 확보
|
||||
// String apiId = request.getHeader(HEADER_NAME_API_CODE);
|
||||
// if (StringUtils.isBlank(apiId)) {
|
||||
// // url에서 확보
|
||||
// // /ONLWeb/api/v1/public/getUserInfo.svc/
|
||||
// apiId = request.getRequestURI();
|
||||
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
||||
// apiId = StringUtils.removeEnd(apiId, "/");
|
||||
// // getUserInfo.svc
|
||||
// apiId = StringUtils.substringAfterLast(apiId, "/");
|
||||
// }
|
||||
|
||||
return apiId;
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class DJErpOAuth2AccessTokenRequest implements Serializable {
|
||||
|
||||
@JsonProperty("grant_type")
|
||||
private String grantType;
|
||||
@JsonProperty("client_id")
|
||||
private String clientId;
|
||||
@JsonProperty("client_secret")
|
||||
private String clientSecret;
|
||||
private String scope;
|
||||
|
||||
public String getGrantType() {
|
||||
return grantType;
|
||||
}
|
||||
|
||||
public void setGrantType(String grantType) {
|
||||
this.grantType = grantType;
|
||||
}
|
||||
|
||||
public String getClientId() {
|
||||
return clientId;
|
||||
}
|
||||
|
||||
public void setClientId(String clientId) {
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
public String getClientSecret() {
|
||||
return clientSecret;
|
||||
}
|
||||
|
||||
public void setClientSecret(String clientSecret) {
|
||||
this.clientSecret = clientSecret;
|
||||
}
|
||||
|
||||
public String getScope() {
|
||||
return scope;
|
||||
}
|
||||
|
||||
public void setScope(String scope) {
|
||||
this.scope = scope;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DJErpOAuth2AccessTokenRequest [grantType=" + grantType + ", clientId=" + clientId
|
||||
+ ", clientSecret=" + clientSecret + ", scope=" + scope + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
@JsonInclude(Include.NON_NULL)
|
||||
@JsonPropertyOrder({ "access_token", "token_type", "expires_in", "scope", "jti", "client_id" })
|
||||
public class DJErpOAuth2AccessTokenResponse implements Serializable {
|
||||
|
||||
@JsonProperty("access_token")
|
||||
private String accessToken;
|
||||
@JsonProperty("token_type")
|
||||
private String tokenType;
|
||||
@JsonProperty("expires_in")
|
||||
private Long expiresIn;
|
||||
private String scope;
|
||||
private String jti;
|
||||
@JsonProperty("client_id")
|
||||
private String clientId;
|
||||
|
||||
public String getAccessToken() {
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
public void setAccessToken(String accessToken) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
|
||||
public String getTokenType() {
|
||||
return tokenType;
|
||||
}
|
||||
|
||||
public void setTokenType(String tokenType) {
|
||||
this.tokenType = tokenType;
|
||||
}
|
||||
|
||||
public Long getExpiresIn() {
|
||||
return expiresIn;
|
||||
}
|
||||
|
||||
public void setExpiresIn(Long expiresIn) {
|
||||
this.expiresIn = expiresIn;
|
||||
}
|
||||
|
||||
public String getScope() {
|
||||
return scope;
|
||||
}
|
||||
|
||||
public void setScope(String scope) {
|
||||
this.scope = scope;
|
||||
}
|
||||
|
||||
public String getJti() {
|
||||
return jti;
|
||||
}
|
||||
|
||||
public void setJti(String jti) {
|
||||
this.jti = jti;
|
||||
}
|
||||
|
||||
public String getClientId() {
|
||||
return clientId;
|
||||
}
|
||||
|
||||
public void setClientId(String clientId) {
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DJErpOAuth2AccessTokenResponse [accessToken=" + accessToken + ", tokenType=" + tokenType
|
||||
+ ", expiresIn=" + expiresIn + ", scope=" + scope + ", jti=" + jti + ", clientId=" + clientId + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,279 +0,0 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.util.OAuth2Utils;
|
||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Request;
|
||||
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.UnkownMessageLogUtils;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.authserver.config.RequestContextData;
|
||||
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.util.BeanUtils;
|
||||
import com.eactive.eai.authserver.vo.ClientVO;
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.logger.EAIDBLogControl;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.common.util.UUID;
|
||||
import com.eactive.eai.data.entity.onl.authserver.TokenIssuanceLog;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@Controller
|
||||
public class DJErpOAuth2Controller {
|
||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
private static final String HEADER_TRACEID = "traceId";
|
||||
private static final String SERVICE_CODE_ACCESS_TOKEN = "00";
|
||||
|
||||
@Autowired
|
||||
private TokenIssuanceLogDAO tokenIssuanceLogDAO;
|
||||
|
||||
@RequestMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, method = RequestMethod.POST,
|
||||
consumes = "application/json", produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<?> tokenJson(@RequestBody DJErpOAuth2AccessTokenRequest tokenRequest,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
@RequestMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, method = RequestMethod.POST,
|
||||
consumes = "application/x-www-form-urlencoded", produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<?> tokenForm(@RequestParam Map<String, String> params,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
DJErpOAuth2AccessTokenRequest tokenRequest = new DJErpOAuth2AccessTokenRequest();
|
||||
tokenRequest.setGrantType(params.get("grant_type"));
|
||||
tokenRequest.setClientId(params.get("client_id"));
|
||||
tokenRequest.setClientSecret(params.get("client_secret"));
|
||||
tokenRequest.setScope(params.get("scope"));
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
@GetMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<?> tokenGet(@RequestParam Map<String, String> params,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
DJErpOAuth2AccessTokenRequest tokenRequest = new DJErpOAuth2AccessTokenRequest();
|
||||
tokenRequest.setGrantType(params.get("grant_type"));
|
||||
tokenRequest.setClientId(params.get("client_id"));
|
||||
tokenRequest.setClientSecret(params.get("client_secret"));
|
||||
tokenRequest.setScope(params.get("scope"));
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> issueToken(DJErpOAuth2AccessTokenRequest tokenRequest,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(tokenRequest.toString());
|
||||
}
|
||||
|
||||
RequestContextData data = new RequestContextData();
|
||||
data.setClientId(tokenRequest.getClientId());
|
||||
data.setIpAddress(extractIpAddress(request));
|
||||
data.setGrantType(tokenRequest.getGrantType());
|
||||
data.setScope(tokenRequest.getScope());
|
||||
data.setUsername("none");
|
||||
data.setResource("none");
|
||||
RequestContextData.ThreadLocalRequestContext.set(data);
|
||||
|
||||
String grantType = tokenRequest.getGrantType();
|
||||
String clientId = tokenRequest.getClientId();
|
||||
String clientSecret = tokenRequest.getClientSecret();
|
||||
String scopes = tokenRequest.getScope();
|
||||
|
||||
try {
|
||||
if (!StringUtils.equals(grantType, "client_credentials")) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {grant_type}");
|
||||
}
|
||||
|
||||
String[] scopeArr = org.springframework.util.StringUtils.tokenizeToStringArray(scopes, " ");
|
||||
Set<String> scopeSet = new HashSet<>();
|
||||
for (String scope : scopeArr) {
|
||||
scopeSet.add(scope);
|
||||
}
|
||||
|
||||
ClientDetails clientDetails = OAuth2Manager.getInstance().getClientDeatilsStore().get(clientId);
|
||||
verifyClient(clientDetails, clientId, clientSecret, scopeSet);
|
||||
|
||||
String traceId = UUID.randomUUID().toString().replace("-", "");
|
||||
response.setHeader(HEADER_TRACEID, traceId);
|
||||
|
||||
HashMap<String, String> authorizationParameters = new HashMap<>();
|
||||
authorizationParameters.put(OAuth2Utils.GRANT_TYPE, grantType);
|
||||
authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
|
||||
authorizationParameters.put("client_secret", clientSecret);
|
||||
|
||||
Set<String> responseType = new HashSet<>();
|
||||
responseType.add(grantType);
|
||||
|
||||
OAuth2Request authorizationRequest = new OAuth2Request(authorizationParameters, clientId, null, true,
|
||||
scopeSet, null, "", responseType, null);
|
||||
|
||||
Principal principal = new OAuth2Authentication(authorizationRequest, null);
|
||||
ResponseEntity<OAuth2AccessToken> result = tokenEndpoint().postAccessToken(principal, authorizationParameters);
|
||||
OAuth2AccessToken token = result.getBody();
|
||||
|
||||
DJErpOAuth2AccessTokenResponse responseToken = new DJErpOAuth2AccessTokenResponse();
|
||||
responseToken.setAccessToken(token.getValue());
|
||||
responseToken.setTokenType(token.getTokenType());
|
||||
responseToken.setExpiresIn(Long.valueOf(token.getExpiresIn()));
|
||||
responseToken.setScope(StringUtils.join(token.getScope(), " "));
|
||||
responseToken.setJti((String) token.getAdditionalInformation().get("jti"));
|
||||
responseToken.setClientId((String) token.getAdditionalInformation().get("client_id"));
|
||||
|
||||
//logTokenIssuance(true, false, "Token issued successfully", token.getValue());
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
return ResponseEntity.ok(mapper.writeValueAsString(responseToken));
|
||||
|
||||
} catch (JwtAuthException e) {
|
||||
logger.info("Token request[/dj/oauth2/token] => clientId: {}, grantType: {}, scope: {}",
|
||||
clientId, grantType, scopes);
|
||||
logger.error(e.getMessage());
|
||||
logTokenIssuance(false, false, e.getMessage(), null);
|
||||
|
||||
Properties logProp = new Properties();
|
||||
logProp.put("clientId", clientId);
|
||||
UnkownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
|
||||
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
|
||||
|
||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage());
|
||||
int statusCode = NumberUtils.toInt(StringUtils.left(e.getCode(), 3), HttpStatus.UNAUTHORIZED.value());
|
||||
return ResponseEntity.status(statusCode).body(errorJson);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.info("Token request[/dj/oauth2/token] => clientId: {}, grantType: {}, scope: {}",
|
||||
clientId, grantType, scopes);
|
||||
logger.error(e.getMessage());
|
||||
logTokenIssuance(false, false, e.getMessage(), null);
|
||||
|
||||
Properties logProp = new Properties();
|
||||
logProp.put("clientId", clientId);
|
||||
UnkownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
|
||||
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
|
||||
|
||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, "Unauthorized. [Unknown]");
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorJson);
|
||||
|
||||
} finally {
|
||||
RequestContextData.ThreadLocalRequestContext.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private void verifyClient(ClientDetails clientDetails, String clientId, String clientSecret, Set<String> scopeSet)
|
||||
throws JwtAuthException {
|
||||
|
||||
if (StringUtils.isBlank(clientId)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {client_id}");
|
||||
}
|
||||
if (clientDetails == null) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [client not found]");
|
||||
}
|
||||
if (StringUtils.isBlank(clientSecret)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {client_secret}");
|
||||
}
|
||||
if (!StringUtils.equals(clientDetails.getClientSecret(), clientSecret)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [Bad client credentials(Client Secret is not match)]");
|
||||
}
|
||||
if (scopeSet.isEmpty()) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {scope}");
|
||||
}
|
||||
if (!clientDetails.getScope().containsAll(scopeSet)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [Bad client credentials(Include unacceptable scope)]");
|
||||
}
|
||||
}
|
||||
|
||||
private String extractIpAddress(HttpServletRequest request) {
|
||||
String ip = request.getHeader("X-Forwarded-For");
|
||||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("Proxy-Client-IP");
|
||||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("HTTP_CLIENT_IP");
|
||||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getRemoteAddr();
|
||||
return ip;
|
||||
}
|
||||
|
||||
private TokenEndpoint tokenEndpoint() {
|
||||
return BeanUtils.getBean("tokenEndpoint", TokenEndpoint.class);
|
||||
}
|
||||
|
||||
private void logTokenIssuance(boolean isSuccess, boolean isRestrictionExempt, String resultMessage, String accessToken) {
|
||||
try {
|
||||
if (!EAIDBLogControl.isEnable()) {
|
||||
logger.warn("DB logging is disabled. Skipping token issuance logging.");
|
||||
return;
|
||||
}
|
||||
RequestContextData data = RequestContextData.ThreadLocalRequestContext.get();
|
||||
|
||||
TokenIssuanceLog log = new TokenIssuanceLog();
|
||||
String clientId = data.getClientId();
|
||||
log.setClientId(clientId);
|
||||
|
||||
if (StringUtils.isNotBlank(clientId)) {
|
||||
try {
|
||||
ClientVO clientVO = OAuth2Manager.getInstance().getClientInfo(clientId);
|
||||
log.setAppName(clientVO.getClientName());
|
||||
log.setOrgId(clientVO.getOrgId());
|
||||
log.setOrgName(clientVO.getOrgName());
|
||||
} catch (DAOException e) {
|
||||
logger.warn("cannot find clientVO - " + clientId);
|
||||
}
|
||||
}
|
||||
|
||||
log.setGrantType(data.getGrantType());
|
||||
log.setScope(data.getScope());
|
||||
log.setIpAddress(data.getIpAddress());
|
||||
log.setSuccessYn(isSuccess ? "Y" : "N");
|
||||
log.setIssuanceDateTime(LocalDateTime.now());
|
||||
log.setRestrictionExemptYn(isRestrictionExempt ? "Y" : "N");
|
||||
log.setResultMessage(resultMessage);
|
||||
log.setAccessToken(accessToken);
|
||||
|
||||
tokenIssuanceLogDAO.saveTokenIssuanceLog(log);
|
||||
} catch (Throwable th) {
|
||||
logger.error("Error while logging token issuance: " + th.getMessage(), th);
|
||||
}
|
||||
}
|
||||
}
|
||||
-680
@@ -1,680 +0,0 @@
|
||||
package com.eactive.eai.custom.adapter.http.client.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.BitSet;
|
||||
import java.util.Formatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
||||
import com.eactive.eai.adapter.http.client.impl.HttpClientAdapterServiceRest;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.impl.HttpAdapterServiceBypass;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
|
||||
public class HttpClient5AdapterServiceBypass extends HttpClient5AdapterServiceSupport
|
||||
implements HttpClientAdapterServiceKey {
|
||||
public static final String TYPE_BYPASS_REQUEST = "bypassRequest";
|
||||
public static final String REST_OPTION = "REST_OPTION";
|
||||
|
||||
protected boolean doSendUrlFragment = true;
|
||||
protected boolean doHandleCompression = false;
|
||||
protected boolean doForwardIP = false;
|
||||
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
||||
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
||||
|
||||
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
||||
|
||||
// ex) $.dataHeader.GW_RSLT_CD
|
||||
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
||||
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
||||
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
||||
* - type : simpleRequest, variableUrlRequest
|
||||
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
||||
* - method : get, delete, post, put
|
||||
* - contentType : application/json, application/x-www-form-urlencoded
|
||||
* - adapterTokenUseYn: Y, N(default)
|
||||
* ex)
|
||||
* {"type":"variableUrlRequest","extraPath":"/aaa/{userId}","uriVariables":["userId"]}
|
||||
* @formatter:on
|
||||
*/
|
||||
String restOptionData = tempProp.getProperty(REST_OPTION, "{}");
|
||||
|
||||
JSONObject restOptionObject = parseJson(restOptionData);
|
||||
|
||||
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
||||
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
||||
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
||||
}
|
||||
|
||||
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
||||
String inboundRewritePath = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_REWRITE_PATH, "");
|
||||
String inboundQueryString = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_QUERY_STRING, "");
|
||||
Properties inboundHeaders = (Properties) tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
||||
Map<String, String> inboundPathVariables = (Map<String, String>) tempProp
|
||||
.get(HttpAdapterServiceKey.INBOUND_PATH_VARIABLES);
|
||||
|
||||
String restMethod = (String) restOptionObject.get("method");
|
||||
if (StringUtils.isBlank(restMethod)) {
|
||||
restMethod = inboundMethod;
|
||||
}
|
||||
|
||||
String url = getRewriteUrl(vo, inboundRewritePath, inboundQueryString, restOptionObject, inboundPathVariables);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] url = [" + url + "]");
|
||||
}
|
||||
|
||||
HttpClient mclient = this.client;
|
||||
HttpUriRequestBase method = generateMethod(restMethod, url);
|
||||
|
||||
assignRequestHeaders(method, inboundHeaders, tempProp);
|
||||
|
||||
if (hasBody(data, method)) {
|
||||
byte[] bodyBytes;
|
||||
if (data instanceof byte[]) {
|
||||
bodyBytes = (byte[]) data;
|
||||
} else if (data instanceof String) {
|
||||
bodyBytes = ((String) data).getBytes(vo.getEncode());
|
||||
} else {
|
||||
bodyBytes = new byte[0];
|
||||
}
|
||||
method.setEntity(new ByteArrayEntity(bodyBytes, null));
|
||||
}
|
||||
|
||||
String contentType = (String) restOptionObject.get("contentType");
|
||||
if (StringUtils.isBlank(contentType) && inboundHeaders != null) {
|
||||
contentType = getIgnoreCaseProp(inboundHeaders, HttpHeaders.CONTENT_TYPE);
|
||||
contentType = StringUtils.substringBefore(contentType, ";");
|
||||
}
|
||||
|
||||
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
|
||||
configureHttpClient(requestConfigBuilder, vo, method);
|
||||
|
||||
OAuth2AccessTokenVO accessToken = null;
|
||||
if (useAdapterToken) {
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
||||
|
||||
// 토큰이 없거나 만료 됐으면 재발급
|
||||
if (accessToken == null || accessToken.isExpired()) {
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
||||
oldToken);
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
||||
+ accessToken + "]");
|
||||
}
|
||||
|
||||
setAuthHeaders(method, accessToken);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RequestHeader [Authorization=" + method.getFirstHeader("Authorization") + "]");
|
||||
}
|
||||
}
|
||||
|
||||
// 로깅 인터셉터에 전달할 컨텍스트 정보 설정
|
||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
HttpContext context = new BasicHttpContext();
|
||||
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
||||
Integer logProcessNo = (Integer) tempProp.get(HttpClientAdapterServiceKey.LOG_PROCESS_NO);
|
||||
if (logProcessNo != null && logProcessNo > 0) {
|
||||
context.setAttribute(HttpClientAdapterServiceKey.LOG_PROCESS_NO, logProcessNo);
|
||||
}
|
||||
|
||||
int status = -1;
|
||||
|
||||
try {
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
byte[] responseMessage = null;
|
||||
Header[] responseHeaders = null;
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"SEND [Bypass Request..]" + CommonLib.getDumpMessage(data));
|
||||
}
|
||||
try {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[method getName]" + method.getMethod());
|
||||
logger.debug("[method getRequestHeaders]" + java.util.Arrays.toString(method.getHeaders()));
|
||||
logger.debug("[method getURI]" + method.getPath());
|
||||
}
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = response.getCode();
|
||||
responseHeaders = response.getHeaders();
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
}
|
||||
}
|
||||
} catch (ConnectException e) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
||||
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
||||
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
||||
*
|
||||
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
||||
* __ex) $.dataHeader.resultCode
|
||||
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
||||
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
||||
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
||||
* @formatter:on
|
||||
*/
|
||||
boolean needReissue = false;
|
||||
|
||||
if (status == 200) {
|
||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
} else if (status >= 400 && status < 500) {
|
||||
if (useAdapterToken) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
|
||||
if (!needReissue) {
|
||||
// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
|
||||
if (responseMessage == null || responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
} else if (status != 200) {
|
||||
responseMessage = responseMessage != null ? responseMessage : new byte[0];
|
||||
// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
|
||||
if (responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
if (useAdapterToken) {
|
||||
if (responseMessage == null) {
|
||||
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
||||
}
|
||||
|
||||
// OAuth 토큰 재요청 코드 확인
|
||||
if (needReissue) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] retry access token response code = ["
|
||||
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
}
|
||||
|
||||
// 토큰 재발급
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
OAuth2AccessTokenVO newAccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||
method.setHeader("Authorization", newAccessToken.getAuthorization());
|
||||
setAuthHeaders(method, newAccessToken);
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RETRY TOKEN = [" + newAccessToken + "]");
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse retryResponse = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = retryResponse.getCode();
|
||||
responseHeaders = retryResponse.getHeaders();
|
||||
responseMessage = EntityUtils.toByteArray(retryResponse.getEntity());
|
||||
} catch (IOException e) {
|
||||
throw new Exception("retry excuteMethod Exception = " + e.getMessage());
|
||||
}
|
||||
|
||||
if (status != 200) {
|
||||
responseMessage = responseMessage != null ? responseMessage : new byte[0];
|
||||
if (responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod,
|
||||
responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RETRY responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"RECV [Bypass Request..]" + CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
// 응답 Content-Type charset 기반 인코딩 결정, 없으면 어댑터 encoding 사용
|
||||
String responseEncode = vo.getEncode();
|
||||
if (responseHeaders != null) {
|
||||
for (Header header : responseHeaders) {
|
||||
if (StringUtils.equalsIgnoreCase(header.getName(), HttpHeaders.CONTENT_TYPE)) {
|
||||
try {
|
||||
MediaType mediaType = MediaType.parseMediaType(header.getValue());
|
||||
if (mediaType.getCharset() != null) {
|
||||
responseEncode = mediaType.getCharset().name();
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assignRelayDataToInbound(tempProp, responseHeaders, status);
|
||||
return responseMessage != null ? new String(responseMessage, responseEncode) : "";
|
||||
} catch (SocketTimeoutException ste) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClient5AdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(),
|
||||
ste);
|
||||
}
|
||||
logger.error("HttpClient5AdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(), ste);
|
||||
throw ste;
|
||||
} catch (ConnectException ce) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClient5AdapterServiceBypass] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(),
|
||||
ce);
|
||||
}
|
||||
logger.error("HttpClient5AdapterServiceBypass] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(), ce);
|
||||
throw ce;
|
||||
} catch (Exception e) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
||||
}
|
||||
logger.error(
|
||||
"HttpClient5AdapterServiceBypass] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
||||
e);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status != HttpStatus.SC_OK) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = String.valueOf(status);
|
||||
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasBody(Object data, HttpUriRequestBase method) {
|
||||
if (data == null) {
|
||||
return false;
|
||||
}
|
||||
// GET, DELETE는 표준 HTTP에서 body를 지원하지 않음
|
||||
return method instanceof HttpPost || method instanceof HttpPut;
|
||||
}
|
||||
|
||||
private HttpUriRequestBase generateMethod(String restMethod, String url) {
|
||||
switch (HttpMethodType.getValue(restMethod)) {
|
||||
case GET:
|
||||
return new HttpGet(url);
|
||||
case DELETE:
|
||||
return new HttpDelete(url);
|
||||
case POST:
|
||||
return new HttpPost(url);
|
||||
case PUT:
|
||||
return new HttpPut(url);
|
||||
default:
|
||||
return new HttpPost(url);
|
||||
}
|
||||
}
|
||||
|
||||
private String getRewriteUrl(HttpClientAdapterVO vo, String inboundRewritePath, String queryString,
|
||||
JSONObject restOptionObject, Map<String, String> inboundPathVariables) {
|
||||
String fragment = null;
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
int fragIdx = queryString.indexOf('#');
|
||||
if (fragIdx >= 0) {
|
||||
fragment = queryString.substring(fragIdx + 1);
|
||||
queryString = queryString.substring(0, fragIdx);
|
||||
}
|
||||
}
|
||||
|
||||
String restExtraPath = (String) restOptionObject.get("extraPath");
|
||||
if (StringUtils.isBlank(restExtraPath)) {
|
||||
StringBuilder uri = new StringBuilder(500);
|
||||
String baseUrl = StringUtils.removeEnd(vo.getUrl(), "/");
|
||||
String rewritePath = inboundRewritePath != null && !inboundRewritePath.startsWith("/")
|
||||
? "/" + inboundRewritePath : inboundRewritePath;
|
||||
uri.append(baseUrl).append(StringUtils.defaultString(rewritePath));
|
||||
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
uri.append('?');
|
||||
uri.append(encodeUriQuery(queryString, false));
|
||||
}
|
||||
|
||||
if (doSendUrlFragment && fragment != null) {
|
||||
uri.append('#');
|
||||
uri.append(encodeUriQuery(fragment, false));
|
||||
}
|
||||
|
||||
return uri.toString();
|
||||
} else {
|
||||
String type = (String) restOptionObject.get("type");
|
||||
String url = getUrl(vo.getUrl(), restExtraPath);
|
||||
|
||||
if (StringUtils.equalsIgnoreCase(type, HttpClientAdapterServiceRest.TYPE_VARIABLE_URL_REQUEST)) {
|
||||
inboundPathVariables = mergeInboundPathVariables(inboundPathVariables, queryString);
|
||||
List<String> urlVariableValueList = new ArrayList<>();
|
||||
JSONArray uriVariables = (JSONArray) restOptionObject.get("uriVariables");
|
||||
if (uriVariables != null && !uriVariables.isEmpty() && inboundPathVariables != null
|
||||
&& !inboundPathVariables.isEmpty()) {
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
String uriVariableValue = inboundPathVariables.get(urlVaribleId);
|
||||
urlVariableValueList.add(uriVariableValue);
|
||||
}
|
||||
|
||||
if (!urlVariableValueList.isEmpty()) {
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
||||
Object[] urls = urlVariableValueList.toArray();
|
||||
url = uriComponents.expand(urls).toUriString();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
url += "?" + encodeUriQuery(queryString, false);
|
||||
}
|
||||
|
||||
if (doSendUrlFragment && fragment != null) {
|
||||
url += "#" + encodeUriQuery(fragment, false);
|
||||
}
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> mergeInboundPathVariables(Map<String, String> inboundPathVariables,
|
||||
String queryString) {
|
||||
if (StringUtils.isBlank(queryString)) {
|
||||
return inboundPathVariables;
|
||||
}
|
||||
|
||||
if (inboundPathVariables == null) {
|
||||
inboundPathVariables = new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
String[] pairs = queryString.split("&");
|
||||
for (String pair : pairs) {
|
||||
int idx = pair.indexOf("=");
|
||||
inboundPathVariables.put(pair.substring(0, idx), pair.substring(idx + 1));
|
||||
}
|
||||
|
||||
return inboundPathVariables;
|
||||
}
|
||||
|
||||
private String getUrl(String baseUrl, String extraPath) {
|
||||
if (StringUtils.isBlank(extraPath)) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
||||
return extraPath;
|
||||
}
|
||||
|
||||
String targetUrl = baseUrl;
|
||||
if (!targetUrl.endsWith("/")) {
|
||||
targetUrl += "/";
|
||||
}
|
||||
if (extraPath.startsWith("/")) {
|
||||
targetUrl += extraPath.substring(1);
|
||||
} else {
|
||||
targetUrl += extraPath;
|
||||
}
|
||||
|
||||
return targetUrl;
|
||||
}
|
||||
|
||||
protected CharSequence encodeUriQuery(CharSequence in, boolean encodePercent) {
|
||||
StringBuilder outBuf = null;
|
||||
Formatter formatter = null;
|
||||
for (int i = 0; i < in.length(); i++) {
|
||||
char c = in.charAt(i);
|
||||
boolean escape = true;
|
||||
if (c < 128) {
|
||||
if (asciiQueryChars.get(c) && !(encodePercent && c == '%')) {
|
||||
escape = false;
|
||||
}
|
||||
} else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {
|
||||
escape = false;
|
||||
}
|
||||
if (!escape) {
|
||||
if (outBuf != null)
|
||||
outBuf.append(c);
|
||||
} else {
|
||||
if (outBuf == null) {
|
||||
outBuf = new StringBuilder(in.length() + 5 * 3);
|
||||
outBuf.append(in, 0, i);
|
||||
formatter = new Formatter(outBuf);
|
||||
}
|
||||
formatter.format("%%%02X", (int) c);
|
||||
}
|
||||
}
|
||||
return outBuf != null ? outBuf : in;
|
||||
}
|
||||
|
||||
protected static final BitSet asciiQueryChars;
|
||||
static {
|
||||
char[] c_unreserved = "_-!.~'()*".toCharArray();
|
||||
char[] c_punct = ",;:$&+=".toCharArray();
|
||||
char[] c_reserved = "/@".toCharArray();
|
||||
asciiQueryChars = new BitSet(128);
|
||||
for (char c = 'a'; c <= 'z'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c = 'A'; c <= 'Z'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c = '0'; c <= '9'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_unreserved)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_punct)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_reserved)
|
||||
asciiQueryChars.set(c);
|
||||
asciiQueryChars.set('%');
|
||||
}
|
||||
|
||||
private void assignRelayDataToInbound(Properties prop, Header[] responseHeaders, int status) {
|
||||
Properties headerProp = new Properties();
|
||||
if (responseHeaders != null) {
|
||||
for (Header header : responseHeaders) {
|
||||
String name = header.getName();
|
||||
String value = header.getValue();
|
||||
String existing = headerProp.getProperty(name);
|
||||
if (existing != null) {
|
||||
// 동일 이름의 헤더가 여러 개인 경우 콤마로 합침 (RFC 7230)
|
||||
headerProp.put(name, existing + ", " + value);
|
||||
} else {
|
||||
headerProp.put(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
headerProp.put(HttpAdapterServiceBypass.HTTP_STATUS, String.valueOf(status));
|
||||
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, headerProp);
|
||||
|
||||
prop.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
}
|
||||
|
||||
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||
String encode) {
|
||||
if (responseMessage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
||||
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
||||
if (StringUtils.isBlank(responseCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
||||
return ArrayUtils.contains(arr, responseCode);
|
||||
} catch (Exception e) {
|
||||
logger.error("HttpClient5AdapterServiceBypass] checkTokenRetry error=" + e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void assignRequestHeaders(HttpUriRequestBase method, Properties headerProp, Properties inProp) {
|
||||
if (headerProp == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (Entry<Object, Object> e : headerProp.entrySet()) {
|
||||
String key = (String) e.getKey();
|
||||
String value = (String) e.getValue();
|
||||
|
||||
if (StringUtils.equalsAnyIgnoreCase(key, HttpAdapterServiceBypass.HOP_BY_HOP_HEADERS)
|
||||
|| StringUtils.equalsIgnoreCase(key, HttpHeaders.CONTENT_LENGTH)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (doHandleCompression && StringUtils.equalsIgnoreCase(key, HttpHeaders.ACCEPT_ENCODING)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
method.addHeader(key, value);
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request Header :" + key + "=[" + value + "]");
|
||||
}
|
||||
}
|
||||
|
||||
if (doForwardIP) {
|
||||
String forHeaderName = "X-Forwarded-For";
|
||||
String forHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_REMOTE_ADDR);
|
||||
if (StringUtils.isNotBlank(forHeader)) {
|
||||
String existingForHeader = headerProp.getProperty(forHeaderName);
|
||||
if (existingForHeader != null) {
|
||||
forHeader = existingForHeader + ", " + forHeader;
|
||||
}
|
||||
method.addHeader(forHeaderName, forHeader);
|
||||
}
|
||||
|
||||
String protoHeaderName = "X-Forwarded-Proto";
|
||||
String protoHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_SCHEME);
|
||||
if (StringUtils.isNotBlank(protoHeader)) {
|
||||
method.addHeader(protoHeaderName, protoHeader);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private JSONObject parseJson(String message) throws Exception {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (JSONObject) JSONValue.parse(message);
|
||||
}
|
||||
|
||||
public static final String getIgnoreCaseProp(Properties prop, String key) {
|
||||
if (prop == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (Entry<Object, Object> e : prop.entrySet()) {
|
||||
if (StringUtils.equalsIgnoreCase(key, (String) e.getKey())) {
|
||||
return (String) e.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
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
@@ -1,40 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-104
@@ -1,104 +0,0 @@
|
||||
package com.eactive.eai.custom.inbound.action;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.Keys;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.impl.HttpAdapterServiceRest;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||
import com.eactive.eai.common.util.MessageKeyExtractor;
|
||||
import com.eactive.eai.inbound.action.ActionException;
|
||||
import com.eactive.eai.inbound.action.RequestActionSupport;
|
||||
|
||||
public class RestAdapterMethodUrlFallbackRequestAction extends RequestActionSupport {
|
||||
|
||||
/**
|
||||
* 1. 기능 : Inbound Adapter를 통해 전달받은 비표준메시지에서 표준메시지를 생성하기 위한 키값을 추출
|
||||
* 2. 처리 개요 :
|
||||
* - TYPE_HTTP_CUSTOM / TYPE_REST: 전체 URI로 키를 먼저 조회하고,
|
||||
* 없으면 뒤 경로를 하나씩 제거하면서 일치하는 키를 탐색한다.
|
||||
* - 그 외: MessageKeyExtractor를 통해 추출
|
||||
*
|
||||
* @param message Object 타입의 요청메시지
|
||||
* @return String 비표준메시지의 메시지키값
|
||||
**/
|
||||
public String[] perform(Object message) throws ActionException {
|
||||
String[] key = null;
|
||||
|
||||
AdapterManager adapterManager = AdapterManager.getInstance();
|
||||
AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(adapterGroupName);
|
||||
String adptGrpName = adptGrpVO.getName();
|
||||
|
||||
if (StringUtils.equals(adptGrpVO.getType(), Keys.TYPE_HTTP_CUSTOM)
|
||||
|| StringUtils.equals(adptGrpVO.getType(), Keys.TYPE_REST)) {
|
||||
try {
|
||||
String requestMethod = prop
|
||||
.getProperty(HttpAdapterServiceRest.PROPERTIES_NAME_HTTP_REQUEST_METHOD);
|
||||
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
String inboundUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
|
||||
String apiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH);
|
||||
|
||||
// /getUserInfo.svc
|
||||
String apiUri = org.apache.commons.lang.StringUtils.removeStart(inboundUri, apiPath);
|
||||
|
||||
Set<String> allKeys = new HashSet<>(Arrays.asList(
|
||||
STDMessageManager.getInstance().getAllSTDMessageKeys()));
|
||||
|
||||
// 전체 URI부터 시작해서 뒤 경로를 하나씩 제거하며 일치하는 키를 탐색
|
||||
String searchUri = apiUri;
|
||||
for (int i = 0; i < 10; i++) {
|
||||
String candidateKey = adptGrpName + ":" + requestMethod + "|"
|
||||
+ StringUtils.removeStart(searchUri, "/");
|
||||
if (allKeys.contains(candidateKey)) {
|
||||
return new String[] { candidateKey };
|
||||
}
|
||||
String shortened = StringUtils.substringBeforeLast(searchUri, "/");
|
||||
if (StringUtils.isBlank(shortened)) {
|
||||
break;
|
||||
}
|
||||
searchUri = shortened;
|
||||
}
|
||||
|
||||
// 일치하는 키가 없으면 원래 키로 fallback
|
||||
String apiKey = adptGrpName + ":" + requestMethod + "|"
|
||||
+ StringUtils.removeStart(apiUri, "/");
|
||||
return new String[] { apiKey };
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new ActionException(ExceptionUtil.getErrorCode(e, "RECEAIIRA001"));
|
||||
}
|
||||
}
|
||||
|
||||
if (message instanceof byte[]) {
|
||||
try {
|
||||
key = MessageKeyExtractor.getMessageKeyValueForRest(this.adapterGroupName, message, prop, "url", true);
|
||||
} catch (Exception e) {
|
||||
throw new ActionException(ExceptionUtil.getErrorCode(e, "RECEAIIRA001"));
|
||||
}
|
||||
if (logger.isDebug())
|
||||
logger.debug(adapterName + "] received data >> [" + new String((byte[]) message) + "]");
|
||||
} else {
|
||||
try {
|
||||
key = MessageKeyExtractor.getMessageKeyValueForRest(this.adapterGroupName, message, prop, "url", true);
|
||||
} catch (Exception e) {
|
||||
throw new ActionException(ExceptionUtil.getErrorCode(e, "RECEAIIRA001"));
|
||||
}
|
||||
if (logger.isDebug())
|
||||
logger.debug(adapterName + "] received data >> [" + message + "]");
|
||||
}
|
||||
|
||||
for (int i = 0; i < key.length; i++) {
|
||||
key[i] = adptGrpName.trim() + key[i];
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
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(' ', '_');
|
||||
}
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,319 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
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,20 +1,21 @@
|
||||
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.InflowControlUtil;
|
||||
import com.eactive.eai.common.inflow.InflowControlManager;
|
||||
import com.eactive.eai.common.inflow.InflowGroupVO;
|
||||
|
||||
@Service
|
||||
public class InflowGroupBucketService {
|
||||
|
||||
public GroupBucketStatusDTO getGroupBucketStatus(String groupId) {
|
||||
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
|
||||
InflowControlManager manager = InflowControlManager.getInstance();
|
||||
|
||||
InflowGroupVO groupVo = manager.getGroupInflowThreshold(groupId);
|
||||
if (groupVo == null) {
|
||||
@@ -71,12 +72,25 @@ public class InflowGroupBucketService {
|
||||
return dto;
|
||||
}
|
||||
|
||||
/**
|
||||
* 그룹 버킷 조회 (리플렉션 사용)
|
||||
*/
|
||||
public CustomGroupBucket getCustomGroupBucket(String groupId) {
|
||||
return InflowControlUtil.getInflowControlManager().getGroupBucket(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;
|
||||
}
|
||||
}
|
||||
|
||||
public List<GroupBucketStatusDTO> getAllGroupBucketStatus() {
|
||||
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
|
||||
InflowControlManager manager = InflowControlManager.getInstance();
|
||||
String[] groupIds = manager.getGroupAllKeys();
|
||||
|
||||
List<GroupBucketStatusDTO> result = new ArrayList<>();
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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; }
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
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; }
|
||||
}
|
||||
Binary file not shown.
@@ -1,9 +1,9 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqteC0VxYMc9Q4kYZpklI
|
||||
8Zt/iqul2ccsvRV82U0m10RDmzR2zHHaw2sP/qtbx8l/gIpwP8pwGwVJ6tvYkH3i
|
||||
6f17P4vkPhdV2OdqweDixOibkuytfbiNPpK5wVxs535Ps+9yVsPoTUyCcMEtLcBD
|
||||
f5N+DmGpIm+OzJPzf95kpCHw7aVrStFu3KEgIJ8ppSZ6FCkj5Th4KnqtHl5kiYjv
|
||||
Pda5tSqqpQd7fgRVvDsYdLP8HJYLsL2cMjAmrkdUtE/Gkkp3T93JUQf82tYc8df5
|
||||
KO/nD3r1MAhiKHpfdaDD8vaXSL2fJmKVQcENA+2PXg5/0/axMcGn0CQbjsATxvWa
|
||||
mQIDAQAB
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAix2aE0JUkUDGfGAWH23S
|
||||
uVqh+yRzxVTZ8yy8gtz1MOUSLOFOtme6AgVyfVmOs7p/HyNl6oe9Iw3FM/70Mpn0
|
||||
0HLsPr38VL1e5Ez1gkONCmqx5YIVbVYgBmdfYtOhKyjRZl7nsprngq6pHeETNqHa
|
||||
ama1WpZjrUQtdPya6bSrXbx0mnK3JhuFpuJqUL7oEqFOMuz3OxCN053iJnDyNNmT
|
||||
SlI0XB78old2VbTY0l67FW4Kmp8YVMFm7mrxlnhUh2bhh49r1C9tsOTTXppNdyOk
|
||||
0DjZ9jjwLFGUYNsFa4HeRHMg1YioyT2luw2gDoe06D6+CAYc893tgNa32+K+KURd
|
||||
dQIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration scan="true" scanPeriod="10 seconds">
|
||||
<!-- Wire 로그 차단 -->
|
||||
<logger name="org.apache.hc.client5.http.impl.Wire" level="OFF" additivity="false" />
|
||||
|
||||
<!-- HttpClient 내부 로그 차단 -->
|
||||
<logger name="org.apache.hc.core5.http.impl.io" level="INFO" additivity="false" />
|
||||
<logger name="org.apache.hc.client5.http.impl" level="INFO" additivity="false" />
|
||||
|
||||
<!-- 콘솔 로그 Appender -->
|
||||
<!--
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
-->
|
||||
|
||||
<!-- 파일 로그 Appender -->
|
||||
<!--
|
||||
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>logs/app.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>logs/app.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||
<maxHistory>30</maxHistory>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
-->
|
||||
|
||||
<!-- 루트 로거 설정 -->
|
||||
<!--
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="FILE" />
|
||||
</root>
|
||||
-->
|
||||
|
||||
</configuration>
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
#-----------------------------------------------------------------------------
|
||||
# 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,14 +1,20 @@
|
||||
# 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.InterfaceMapperDJB
|
||||
mapper.definition=standard-message-mapping-config-djb.properties
|
||||
#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
|
||||
# StandardMessage Coordinator implementation
|
||||
message.coordinator.class=com.eactive.eai.custom.message.StandardMessageCoordinatorDJB
|
||||
message.coordinator.class=com.eactive.eai.custom.message.StandardMessageCoordinatorKJB
|
||||
# RequestProcessor implementation
|
||||
requestProcessor.class=com.eactive.eai.custom.inbound.processor.DJBRequestProcessor
|
||||
#requestProcessor.class=com.eactive.eai.inbound.processor.RequestProcessor
|
||||
# reader : parsing input data to StandardMessage
|
||||
reader.JSON=com.eactive.eai.message.parser.JsonReader
|
||||
reader.JSN=com.eactive.eai.message.parser.JsonReader
|
||||
@@ -19,3 +25,7 @@ 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
|
||||
@@ -1,26 +0,0 @@
|
||||
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
@@ -1,317 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
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
@@ -1,106 +0,0 @@
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
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
@@ -1,144 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -1,357 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,422 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,544 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,508 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,718 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,291 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,269 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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