Compare commits
106 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1240b24c90 | |||
| 7346c3070d | |||
| 9a597a52ac | |||
| 5653a183eb | |||
| 0e3a612bc0 | |||
| 68c29b962e | |||
| dafe80f8bc | |||
| 9e78a0e199 | |||
| 3ec18b17e8 | |||
| 90464ee33f | |||
| 60e6b30c9b | |||
| 7d89d6d43e | |||
| 7109c56623 | |||
| 6a53e29710 | |||
| eff7b31490 | |||
| e2950a339f | |||
| 01e4e36345 | |||
| 698b3ca7b6 | |||
| c74d1777df | |||
| c95307901e | |||
| c12ff0a64a | |||
| 1c82f0121c | |||
| 82998b475c | |||
| 7336267b32 | |||
| 8d69c459d9 | |||
| 4f54ee5259 | |||
| 912a282b54 | |||
| e8c379f3c7 | |||
| 6ab138b63a | |||
| c2ad7be7e4 | |||
| aea4134437 | |||
| bf91d02be7 | |||
| 9fcce55966 | |||
| 1f285c3bfd | |||
| 13608ebc8e | |||
| 202538c50c | |||
| ade012a1f7 | |||
| abe3756f69 | |||
| 65fc0d0df4 | |||
| c34a2c019b | |||
| 6dbe557584 | |||
| 1185329b78 | |||
| a86d1ba30f | |||
| 17a343c4ac | |||
| dd352fef42 | |||
| 656cd39d30 | |||
| 7be74095c5 | |||
| 28b233aeff | |||
| 7a5958481f | |||
| ac15633b21 | |||
| 158987b367 | |||
| bf9f865508 | |||
| 9c9ad8c19c | |||
| 8ace28675b | |||
| 1ab36c077b | |||
| 547232bb26 | |||
| ebd89afa0d | |||
| 407eccc827 | |||
| cebdfd6a19 | |||
| 1fd8712de0 | |||
| be204abb5e | |||
| c2ad6d2423 | |||
| b6954139fe | |||
| d46fa8bd1a | |||
| 31171d0187 | |||
| 45ad9d8b6f | |||
| dd02c5902e | |||
| c225104711 | |||
| efcc7fe208 | |||
| 8bcbee7e52 | |||
| 04aa0df977 | |||
| 2eeee58d35 | |||
| 5f24bacd48 | |||
| 21c3bcbc6a | |||
| aff3ed6658 | |||
| 8947fc248f | |||
| 58f659a179 | |||
| 745df6d073 | |||
| 4a41398f03 | |||
| 3a578b3c70 | |||
| 4d479e4fd6 | |||
| 780b9bd934 | |||
| 42f52a4974 | |||
| 1a79c39e76 | |||
| bfda9ef610 | |||
| df1b1f2667 | |||
| a891676617 | |||
| cd2ab33a0d | |||
| b39a26350e | |||
| 65d61e646b | |||
| 68bc6fa47a | |||
| 787f9a4f42 | |||
| bca28dbd1b | |||
| bc79b8b166 | |||
| 2d17387def | |||
| 1508d01afb | |||
| 17d533fe06 | |||
| 7e7d107dde | |||
| 557a071b1e | |||
| 18b3e781b1 | |||
| 1efd2deb9d | |||
| f9a520eacc | |||
| dc1ee33517 | |||
| 7fbe64f562 | |||
| 42cbafd67d | |||
| e21f134c11 |
@@ -235,3 +235,9 @@ gradle-app.setting
|
|||||||
# End of https://www.gitignore.io/api/java,macos,gradle,intellij
|
# End of https://www.gitignore.io/api/java,macos,gradle,intellij
|
||||||
/EAISIMWeb/
|
/EAISIMWeb/
|
||||||
/.apt_generated_tests/
|
/.apt_generated_tests/
|
||||||
|
|
||||||
|
# Claude Code
|
||||||
|
.claude/
|
||||||
|
/작업내역*.md
|
||||||
|
/설계서*.md
|
||||||
|
/분석서*.md
|
||||||
|
|||||||
@@ -25,6 +25,9 @@
|
|||||||
base-package="com.eactive.eai.adapter" />
|
base-package="com.eactive.eai.adapter" />
|
||||||
<context:component-scan
|
<context:component-scan
|
||||||
base-package="com.eactive.eai.manage" />
|
base-package="com.eactive.eai.manage" />
|
||||||
|
<context:component-scan
|
||||||
|
base-package="com.eactive.eai.custom.inflow" />
|
||||||
|
|
||||||
<context:annotation-config />
|
<context:annotation-config />
|
||||||
<mvc:annotation-driven />
|
<mvc:annotation-driven />
|
||||||
<mvc:default-servlet-handler />
|
<mvc:default-servlet-handler />
|
||||||
|
|||||||
@@ -11,12 +11,12 @@ hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
|
|||||||
# eLink default functions
|
# eLink default functions
|
||||||
# set System property in real system
|
# set System property in real system
|
||||||
#inst.Name=${HOSTNAME}
|
#inst.Name=${HOSTNAME}
|
||||||
inst.Name=agwSvr63
|
inst.Name=agwSvr11
|
||||||
eai.jdbc.Name=jdbc/dsOBP_AGW
|
eai.jdbc.Name=jdbc/dsOBP_AGW
|
||||||
eai.rmiport=30111
|
eai.rmiport=30111
|
||||||
eai.rmiserviceport=30112
|
eai.rmiserviceport=30112
|
||||||
eai.systemmode=D
|
eai.systemmode=D
|
||||||
# EAI FEP MCI GW ...
|
# EAI FEP MCI GW ...
|
||||||
eai.systemtype=API
|
eai.systemtype=API
|
||||||
eai.tableowner=AGWADM
|
eai.tableowner=AGWAPP
|
||||||
eai.server.extractor=[0,2],[0,2],[-2]
|
eai.server.extractor=[0,2],[0,2],[-2]
|
||||||
|
|||||||
@@ -1,2 +1,2 @@
|
|||||||
#\uae30\uc874 ENV \ud56d\ubaa9 \uc678 \uae30\ud0c0 \uc2dc\uc2a4\ud15c \ud504\ub85c\ud37c\ud2f0\ub85c \uc815\uc758\uac00 \ud544\uc694\ud55c \ud544\ub4dc\ub97c \uc815\uc758
|
#\uae30\uc874 ENV \ud56d\ubaa9 \uc678 \uae30\ud0c0 \uc2dc\uc2a4\ud15c \ud504\ub85c\ud37c\ud2f0\ub85c \uc815\uc758\uac00 \ud544\uc694\ud55c \ud544\ub4dc\ub97c \uc815\uc758
|
||||||
transformer.validation=false
|
transformer.validation=true
|
||||||
@@ -19,6 +19,7 @@
|
|||||||
<url-pattern>/agent/*</url-pattern>
|
<url-pattern>/agent/*</url-pattern>
|
||||||
<url-pattern>/common/*</url-pattern>
|
<url-pattern>/common/*</url-pattern>
|
||||||
<url-pattern>/management/*</url-pattern>
|
<url-pattern>/management/*</url-pattern>
|
||||||
|
<url-pattern>/manage/*</url-pattern>
|
||||||
<url-pattern>/mgr/*</url-pattern>
|
<url-pattern>/mgr/*</url-pattern>
|
||||||
</filter-mapping>
|
</filter-mapping>
|
||||||
|
|
||||||
@@ -29,7 +30,7 @@
|
|||||||
<filter-mapping>
|
<filter-mapping>
|
||||||
<filter-name>ApiRequestBodyFilter</filter-name>
|
<filter-name>ApiRequestBodyFilter</filter-name>
|
||||||
<url-pattern>/api/*</url-pattern> <!-- 필요한 URL 패턴 -->
|
<url-pattern>/api/*</url-pattern> <!-- 필요한 URL 패턴 -->
|
||||||
<url-pattern>/mapi/*</url-pattern> <!-- 필요한 URL 패턴 -->
|
<url-pattern>/dj/*</url-pattern> <!-- 필요한 URL 패턴 -->
|
||||||
</filter-mapping>
|
</filter-mapping>
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+2
-6
@@ -20,17 +20,13 @@ def queryDslVersion = "5.0.0"
|
|||||||
def hibernateVersion = "5.6.15.Final"
|
def hibernateVersion = "5.6.15.Final"
|
||||||
|
|
||||||
def generatedJavaDir = "$buildDir/generated/java"
|
def generatedJavaDir = "$buildDir/generated/java"
|
||||||
def reposiliteUrl = "http://localhost:8080"
|
def nexusUrl = "https://nexus.eactive.synology.me:8090"
|
||||||
|
|
||||||
allprojects {
|
allprojects {
|
||||||
repositories {
|
repositories {
|
||||||
maven {
|
maven {
|
||||||
url "${reposiliteUrl}/private"
|
url "${nexusUrl}/repository/maven-public/"
|
||||||
allowInsecureProtocol = true
|
allowInsecureProtocol = true
|
||||||
credentials {
|
|
||||||
username = reposiliteUser
|
|
||||||
password = reposilitePassword
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,252 +0,0 @@
|
|||||||
# 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: 1f24dc24b5...037fcd6302
+1
-1
Submodule elink-online-core updated: 8b24475d2d...658f2a0485
+1
-1
Submodule elink-online-core-jpa updated: 76342bfaef...9620845daf
+1
-1
Submodule elink-online-transformer updated: c8a58fdf5b...05e887f7f1
+1
-2
@@ -1,7 +1,6 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
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
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
networkTimeout=10000
|
networkTimeout=10000
|
||||||
|
|||||||
-104
@@ -1,104 +0,0 @@
|
|||||||
# 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,26 +0,0 @@
|
|||||||
# comment start with #
|
|
||||||
# level; // 0 : root ~ n
|
|
||||||
# type; // 0: Message, 1: Field, 2:Group 3, Array, 4 : BIZ DATA
|
|
||||||
# size // 0 : variable, > 0 fixed
|
|
||||||
# fieldType; // 0: ELEMENT, 1: ATTRIBUTE,
|
|
||||||
# length;
|
|
||||||
# dataType; // 0: String, 1: Number
|
|
||||||
#name,level,type,size,fieldType,length,dataType,refPath,refValue,value
|
|
||||||
ElinkHeader ,0,0,1,0, 0,0,,,
|
|
||||||
Header ,1,2,1,1, 0,0,,,
|
|
||||||
StndCicsTrncd ,2,1,1,1,10,0,,,
|
|
||||||
StndIntnlStndTelgmLen,2,1,1,1,10,11,,,0
|
|
||||||
StndTranBaseYmd ,2,1,1,1,10,0,,,
|
|
||||||
Common ,1,2,0,0, 0,0,Header.StndCicsTrncd,JI6H,null
|
|
||||||
TranInfo ,2,2,1,0, 0,0,,,
|
|
||||||
StndCicsTrncd ,3,1,1,0, 3,0,,,
|
|
||||||
StndTelgmRecvTranCd ,3,1,1,0,10,0,,,
|
|
||||||
StndPrcssRtdTranCd ,3,1,1,0,10,0,,,
|
|
||||||
Array ,1,3,0,0, 3,0,,,
|
|
||||||
Item1 ,2,1,1,0,10,0,,,JI6H
|
|
||||||
Group ,2,3,1,0, 1,0,,,
|
|
||||||
gitem1 ,3,1,1,0,10,1,,,726
|
|
||||||
gitem2 ,3,1,1,0,10,0,,,20220905
|
|
||||||
FArray ,1,4,0,0,10,0,,,
|
|
||||||
bizData ,1,9,1,0, 0,0,,,
|
|
||||||
zzData ,1,1,1,0, 2,10,,,ZZ
|
|
||||||
|
@@ -1,41 +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; // 0: String, 1: Number,10: ZZ String, 11: LL Number
|
|
||||||
#-----------------------------------------------------------------------------
|
|
||||||
# name ,level ,type ,size ,fieldType ,length ,dataType ,,refPath, refValue,value
|
|
||||||
#-----------------------------------------------------------------------------
|
|
||||||
# name ,level ,type ,size ,fieldType ,length ,dataType ,refPath, refValue, value
|
|
||||||
STD_HNCPHEADER_REQ ,0 ,0 ,1 ,0 ,0 ,0 , , ,
|
|
||||||
msg_len ,1 ,1 ,1 ,0 ,6 ,1 , , ,199
|
|
||||||
global_id ,1 ,1 ,1 ,0 ,29 ,0 , , ,GIDNO00000000001111
|
|
||||||
service_id ,1 ,1 ,1 ,0 ,10 ,0 , , ,ELINKSVC01
|
|
||||||
service_cmt ,1 ,1 ,1 ,0 ,100 ,0 , , ,ELINK TEST Service
|
|
||||||
service_tn ,1 ,1 ,1 ,0 ,1 ,0 , , ,0
|
|
||||||
Session_id ,1 ,1 ,1 ,0 ,100 ,0 , , ,SESSIONID001
|
|
||||||
encrypt_yn ,1 ,1 ,1 ,0 ,2 ,0 , , ,NO
|
|
||||||
http_url ,1 ,1 ,1 ,0 ,100 ,0 , , ,
|
|
||||||
screen_id ,1 ,1 ,1 ,0 ,13 ,0 , , ,SCREEN0000001
|
|
||||||
scr_no ,1 ,1 ,1 ,0 ,30 ,0 , , ,000000000100000000020000000003
|
|
||||||
scr_dsc ,1 ,1 ,1 ,0 ,100 ,0 , , ,
|
|
||||||
usr_id ,1 ,1 ,1 ,0 ,10 ,0 , , ,USER000001
|
|
||||||
ip_addr ,1 ,1 ,1 ,0 ,47 ,0 , , ,
|
|
||||||
ip_mac ,1 ,1 ,1 ,0 ,12 ,0 , , ,
|
|
||||||
com_code ,1 ,1 ,1 ,0 ,4 ,0 , , ,EACT
|
|
||||||
head_code ,1 ,1 ,1 ,0 ,7 ,0 , , ,EACT001
|
|
||||||
dept_cd ,1 ,1 ,1 ,0 ,7 ,0 , , ,ELINK01
|
|
||||||
conn_tp ,1 ,1 ,1 ,0 ,2 ,0 , , ,CH
|
|
||||||
Inter_chn ,1 ,1 ,1 ,0 ,2 ,0 , , ,EA
|
|
||||||
recv_tm ,1 ,1 ,1 ,0 ,17 ,0 , , ,20220928000000000
|
|
||||||
send_tm ,1 ,1 ,1 ,0 ,17 ,0 , , ,
|
|
||||||
return_gubun ,1 ,1 ,1 ,0 ,1 ,0 , , ,S
|
|
||||||
return_value ,1 ,1 ,1 ,0 ,1 ,0 , , ,
|
|
||||||
msg_id ,1 ,1 ,1 ,0 ,7 ,0 , , ,
|
|
||||||
msg_nm ,1 ,1 ,1 ,0 ,250 ,0 , , ,
|
|
||||||
filler ,1 ,1 ,1 ,0 ,125 ,0 , , ,
|
|
||||||
bizData ,1 ,9 ,0 ,0 ,0 ,0 , , ,
|
|
||||||
|
|
||||||
|
@@ -1,11 +0,0 @@
|
|||||||
layout.file.type=CSV
|
|
||||||
layout.file.path=./resources/standard-layout-sample.csv
|
|
||||||
mapper.class=com.eactive.eai.message.test.TestInterfaceMapper
|
|
||||||
mapper.definition=./resources/standard-message-mapping-config.properties
|
|
||||||
reader.JSON=com.eactive.eai.message.parser.JsonReader
|
|
||||||
reader.JSN=com.eactive.eai.message.parser.JsonReader
|
|
||||||
reader.UJN=com.eactive.eai.message.parser.JsonReader
|
|
||||||
reader.XML=com.eactive.eai.message.parser.XmlReader
|
|
||||||
reader.UXL=com.eactive.eai.message.parser.XmlReader
|
|
||||||
reader.ASC=com.eactive.eai.message.parser.FlatReader
|
|
||||||
reader.FLAT=com.eactive.eai.message.parser.FlatReader
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
# layout : StandardMessage layout definition
|
|
||||||
#layout.file.type=CSV
|
|
||||||
layout.file.type=DB
|
|
||||||
#layout.file.path=standard-layout-sbi.csv
|
|
||||||
#layout.file.path=standard-layout-elk.csv
|
|
||||||
#layout.filter.FLAT=com.eactive.eai.custom.message.FlatMessageFilterSBI
|
|
||||||
layout.filter.FLAT=com.eactive.eai.message.filter.FlatMessageFilter
|
|
||||||
# mapper : StandardMessage's fields getter/setter interface
|
|
||||||
#mapper.class=com.eactive.eai.custom.message.InterfaceMapperSBI
|
|
||||||
mapper.class=com.eactive.eai.message.service.DefaultInterfaceMapper
|
|
||||||
#mapper.definition=standard-message-mapping-config-sbi.properties
|
|
||||||
#mapper.definition=standard-message-mapping-config-elk.properties
|
|
||||||
mapper.definition=standard-message-mapping-config-elk.properties
|
|
||||||
# StandardMessage Coordinator implementation
|
|
||||||
#message.coordinator.class=com.eactive.eai.custom.message.StandardMessageCoordinatorSBI
|
|
||||||
# RequestProcessor implementation
|
|
||||||
#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
|
|
||||||
reader.UJN=com.eactive.eai.message.parser.JsonReader
|
|
||||||
reader.XML=com.eactive.eai.message.parser.XmlReader
|
|
||||||
reader.UXL=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
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
# layout : StandardMessage layout definition
|
|
||||||
layout.file.type=DB
|
|
||||||
layout.db.testLayoutName=
|
|
||||||
layout.file.path=/development/intellij/elink-4.5/elink-online-multi/resources/standard-layout.csv
|
|
||||||
# mapper : StandardMessage's fields getter/setter interface
|
|
||||||
mapper.class=com.eactive.eai.message.service.DefaultInterfaceMapper
|
|
||||||
mapper.definition=/development/intellij/elink-4.5/elink-online-multi/resources/standard-message-mapping-config-elk.properties
|
|
||||||
# reader : parsing input data to StandardMessage
|
|
||||||
reader.JSON=com.eactive.eai.message.parser.JsonReader
|
|
||||||
reader.JSN=com.eactive.eai.message.parser.JsonReader
|
|
||||||
reader.UJN=com.eactive.eai.message.parser.JsonReader
|
|
||||||
reader.XML=com.eactive.eai.message.parser.XmlReader
|
|
||||||
reader.UXL=com.eactive.eai.message.parser.XmlReader
|
|
||||||
reader.ASC=com.eactive.eai.message.parser.FlatReader
|
|
||||||
reader.FLAT=com.eactive.eai.message.parser.FlatReader
|
|
||||||
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
REQ_SYS_CODE=commonHeader.firstReqSystemCode
|
|
||||||
CHANNEL_TYPE_CD=
|
|
||||||
CHANNEL_DETAIL_CD=
|
|
||||||
SEND_TIME=
|
|
||||||
GUID=commonHeader.globalId
|
|
||||||
SYSTEM_TYPE=
|
|
||||||
RECV_TIME=
|
|
||||||
RETURN_VALUE=
|
|
||||||
GUID_ORG=
|
|
||||||
GUID_SEQ=commonHeader.traceSeqNo
|
|
||||||
SERVICE_ID=commonHeader.serviceCode
|
|
||||||
RETURN_SERVICE_ID=
|
|
||||||
INTERFACE_ID=commonHeader.serviceCode
|
|
||||||
SESSION_ID=
|
|
||||||
SEND_RECV_DIVISION=commonHeader.reqResTypeCode
|
|
||||||
IN_EX_DIVISION=
|
|
||||||
OPERATION_ENV=
|
|
||||||
FIRST_REQ_IP=commonHeader.firstReqSystemIp
|
|
||||||
RECOVER_YN=
|
|
||||||
INST_CODE=
|
|
||||||
TIMEOUT=
|
|
||||||
ERROR_CODE=commonHeader.msgList[0].resultCode
|
|
||||||
ERROR_MSG=commonHeader.msgList[0].resultMsg
|
|
||||||
USER_ID=
|
|
||||||
RESPONSE_TYPE=
|
|
||||||
SYNC_ASYNC_TYPE=
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
REQ_SYS_CODE=systemHeader.DMND_SYS_CD
|
|
||||||
CHANNEL_TYPE_CD=stdcommon.chnlTycd
|
|
||||||
CHANNEL_DETAIL_CD=stdcommon.chnlDtlsClcd
|
|
||||||
SEND_TIME=stdheader.send_tm
|
|
||||||
GUID=stdheader.global_id
|
|
||||||
SYSTEM_TYPE=stdheader.Inter_chn
|
|
||||||
RECV_TIME=stdheader.recv_tm
|
|
||||||
RETURN_TYPE=stdheader.return_gubun
|
|
||||||
RETURN_VALUE=stdheader.return_value
|
|
||||||
GUID_ORG=stdcommon.ortrGuid
|
|
||||||
GUID_SEQ=stdheader.global_id
|
|
||||||
#SERVICE_ID=stdheader.service_id
|
|
||||||
SERVICE_ID=service_id
|
|
||||||
RETURN_SERVICE_ID=stdcommon.procsRsltRcmsSrvcId
|
|
||||||
INTERFACE_ID=stdheader.service_id
|
|
||||||
SESSION_ID=stdheader.Session_id
|
|
||||||
#SEND_RECV_DIVISION=stdheader.return_gubun
|
|
||||||
SEND_RECV_DIVISION=service_tn
|
|
||||||
IN_EX_DIVISION=stdcommon.hmabDvcd
|
|
||||||
OPERATION_ENV=stdcommon.sysOprtEnvDvcd
|
|
||||||
FIRST_REQ_IP=stdheader.ip_addr
|
|
||||||
RECOVER_YN=stdcommon.ortrRestrYn
|
|
||||||
INST_CODE=stdheader.com_code
|
|
||||||
TIMEOUT=stdheader.gnrzTmotTktm
|
|
||||||
ERROR_CODE=stdheader.msg_id
|
|
||||||
ERROR_MSG=stdheader.msg_nm
|
|
||||||
USER_ID=stdheader.usr_id
|
|
||||||
RESPONSE_TYPE=stdcommon.procsRsltDvcd
|
|
||||||
SYNC_ASYNC_TYPE=stdcommon.txSynzDvcd
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
REQ_SYS_CODE=Inter_chn
|
|
||||||
CHANNEL_TYPE_CD=
|
|
||||||
CHANNEL_DETAIL_CD=conn_tp
|
|
||||||
SEND_TIME=send_tm
|
|
||||||
GUID=global_id
|
|
||||||
SYSTEM_TYPE=service_tn
|
|
||||||
RECV_TIME=recv_tm
|
|
||||||
RETURN_TYPE=return_gubun
|
|
||||||
RETURN_VALUE=return_value
|
|
||||||
GUID_ORG=stdcommon.ortrGuid
|
|
||||||
GUID_SEQ=stdheader.global_id
|
|
||||||
SERVICE_ID=service_id
|
|
||||||
RETURN_SERVICE_ID=stdcommon.procsRsltRcmsSrvcId
|
|
||||||
INTERFACE_ID=stdheader.service_id
|
|
||||||
SESSION_ID=Session_id
|
|
||||||
SEND_RECV_DIVISION=service_tn
|
|
||||||
IN_EX_DIVISION=stdcommon.hmabDvcd
|
|
||||||
OPERATION_ENV=stdcommon.sysOprtEnvDvcd
|
|
||||||
FIRST_REQ_IP=ip_addr
|
|
||||||
RECOVER_YN=stdcommon.ortrRestrYn
|
|
||||||
INST_CODE=stdheader.com_code
|
|
||||||
TIMEOUT=stdheader.gnrzTmotTktm
|
|
||||||
ERROR_CODE=msg_id
|
|
||||||
ERROR_MSG=msg_nm
|
|
||||||
USER_ID=usr_id
|
|
||||||
RESPONSE_TYPE=stdcommon.procsRsltDvcd
|
|
||||||
SYNC_ASYNC_TYPE=stdcommon.txSynzDvcd
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
REQ_SYS_CODE=Inter_chn
|
|
||||||
CHANNEL_TYPE_CD=
|
|
||||||
CHANNEL_DETAIL_CD=conn_tp
|
|
||||||
SEND_TIME=send_tm
|
|
||||||
GUID=global_id
|
|
||||||
SYSTEM_TYPE=service_tn
|
|
||||||
RECV_TIME=recv_tm
|
|
||||||
RETURN_VALUE=return_value
|
|
||||||
GUID_ORG=stdcommon.ortrGuid
|
|
||||||
GUID_SEQ=stdheader.global_id
|
|
||||||
SERVICE_ID=service_id
|
|
||||||
RETURN_SERVICE_ID=stdcommon.procsRsltRcmsSrvcId
|
|
||||||
INTERFACE_ID=stdheader.service_id
|
|
||||||
SESSION_ID=Session_id
|
|
||||||
SEND_RECV_DIVISION=service_tn
|
|
||||||
IN_EX_DIVISION=return_gubun
|
|
||||||
OPERATION_ENV=stdcommon.sysOprtEnvDvcd
|
|
||||||
FIRST_REQ_IP=ip_addr
|
|
||||||
RECOVER_YN=stdcommon.ortrRestrYn
|
|
||||||
INST_CODE=stdheader.com_code
|
|
||||||
TIMEOUT=stdheader.gnrzTmotTktm
|
|
||||||
ERROR_CODE=msg_id
|
|
||||||
ERROR_MSG=msg_nm
|
|
||||||
USER_ID=usr_id
|
|
||||||
RESPONSE_TYPE=stdcommon.procsRsltDvcd
|
|
||||||
SYNC_ASYNC_TYPE=stdcommon.txSynzDvcd
|
|
||||||
@@ -1,380 +1,380 @@
|
|||||||
package com.eactive.eai.adapter.controller;
|
//package com.eactive.eai.adapter.controller;
|
||||||
|
//
|
||||||
import java.util.ArrayList;
|
//import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
//import java.util.Collections;
|
||||||
import java.util.Date;
|
//import java.util.Date;
|
||||||
import java.util.Enumeration;
|
//import java.util.Enumeration;
|
||||||
import java.util.HashMap;
|
//import java.util.HashMap;
|
||||||
import java.util.List;
|
//import java.util.List;
|
||||||
import java.util.Map;
|
//import java.util.Map;
|
||||||
import java.util.Properties;
|
//import java.util.Properties;
|
||||||
|
//
|
||||||
import javax.servlet.http.HttpServletRequest;
|
//import javax.servlet.http.HttpServletRequest;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
//import javax.servlet.http.HttpServletResponse;
|
||||||
|
//
|
||||||
import org.apache.commons.lang3.StringUtils;
|
//import org.apache.commons.lang3.StringUtils;
|
||||||
// jwhong
|
//// jwhong
|
||||||
import org.json.simple.JSONObject;
|
//import org.json.simple.JSONObject;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
//import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.http.HttpStatus;
|
//import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.MediaType;
|
//import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
//import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.util.AntPathMatcher;
|
//import org.springframework.util.AntPathMatcher;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
//import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
//import org.springframework.web.bind.annotation.RestController;
|
||||||
|
//
|
||||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
//import com.eactive.eai.adapter.AdapterGroupVO;
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
//import com.eactive.eai.adapter.AdapterManager;
|
||||||
import com.eactive.eai.adapter.AdapterPropManager;
|
//import com.eactive.eai.adapter.AdapterPropManager;
|
||||||
import com.eactive.eai.adapter.AdapterVO;
|
//import com.eactive.eai.adapter.AdapterVO;
|
||||||
import com.eactive.eai.adapter.Keys;
|
//import com.eactive.eai.adapter.Keys;
|
||||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
//import com.eactive.eai.adapter.http.HttpStatusException;
|
||||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
//import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
//import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
//import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
//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.HttpAdapterFilter;
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilterFactoryKjb;
|
//import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilterFactoryKjb;
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
//import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||||
import com.eactive.eai.adapter.service.ApiAdapterService;
|
//import com.eactive.eai.adapter.service.ApiAdapterService;
|
||||||
import com.eactive.eai.common.TransactionContextKeys;
|
//import com.eactive.eai.common.TransactionContextKeys;
|
||||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
//import com.eactive.eai.common.exception.ExceptionUtil;
|
||||||
import com.eactive.eai.common.server.EAIServerManager;
|
//import com.eactive.eai.common.server.EAIServerManager;
|
||||||
import com.eactive.eai.common.stdmessage.STDMessageManager;
|
//import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||||
import com.eactive.eai.common.stdmessage.STDMsgInfoAddOnVO;
|
//import com.eactive.eai.common.stdmessage.STDMsgInfoAddOnVO;
|
||||||
import com.eactive.eai.common.util.DatetimeUtil;
|
//import com.eactive.eai.common.util.DatetimeUtil;
|
||||||
import com.eactive.eai.common.util.InboundErrorLogger;
|
//import com.eactive.eai.common.util.InboundErrorLogger;
|
||||||
import com.eactive.eai.common.util.Logger;
|
//import com.eactive.eai.common.util.Logger;
|
||||||
import com.eactive.eai.common.util.MessageUtil;
|
//import com.eactive.eai.common.util.MessageUtil;
|
||||||
import com.eactive.eai.common.util.UUIDGenerator;
|
//import com.eactive.eai.common.util.UUIDGenerator;
|
||||||
import com.eactive.eai.inbound.action.ActionException;
|
//import com.eactive.eai.inbound.action.ActionException;
|
||||||
import com.eactive.eai.inbound.action.ActionFactory;
|
//import com.eactive.eai.inbound.action.ActionFactory;
|
||||||
import com.eactive.eai.inbound.action.RequestAction;
|
//import com.eactive.eai.inbound.action.RequestAction;
|
||||||
import com.eactive.eai.inbound.error.InboundErrorInfoVO;
|
//import com.eactive.eai.inbound.error.InboundErrorInfoVO;
|
||||||
|
//
|
||||||
@RestController
|
//@RestController
|
||||||
public class ApiAdapterController implements HttpAdapterServiceKey {
|
//public class ApiAdapterController implements HttpAdapterServiceKey {
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
// static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||||
|
//
|
||||||
@Autowired
|
// @Autowired
|
||||||
ApiAdapterService service;
|
// ApiAdapterService service;
|
||||||
|
//
|
||||||
/**
|
// /**
|
||||||
* KJBANK 요구사항으로 /mapi/oauth2/token 과 같은 형태로 토큰 발급거래를 수행해야해서 예외처리함
|
// * KJBANK 요구사항으로 /mapi/oauth2/token 과 같은 형태로 토큰 발급거래를 수행해야해서 예외처리함
|
||||||
*
|
// *
|
||||||
* @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
|
// * @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
|
||||||
* endpoints)
|
// * endpoints)
|
||||||
*/
|
// */
|
||||||
@RequestMapping(value = { "/api/*", "/mapi/*", "/api/*/{path:^(?!.*oauth).*$}/**",
|
// @RequestMapping(value = { "/api/*", "/mapi/*", "/api/*/{path:^(?!.*oauth).*$}/**",
|
||||||
"/mapi/{path:^(?!.*oauth2).*$}/**" })
|
// "/mapi/{path:^(?!.*oauth2).*$}/**" })
|
||||||
// @RequestMapping(value = {"/api/**"})
|
//// @RequestMapping(value = {"/api/**"})
|
||||||
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
// public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
||||||
throws Exception {
|
// throws Exception {
|
||||||
// /ONLWeb/api/v1/public/getUserInfo.svc
|
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
||||||
String apiUri = servletRequest.getRequestURI();
|
// String apiUri = servletRequest.getRequestURI();
|
||||||
// /api/v1/public/getUserInfo.svc
|
// // /api/v1/public/getUserInfo.svc
|
||||||
apiUri = StringUtils.removeStart(apiUri, servletRequest.getContextPath());
|
// apiUri = StringUtils.removeStart(apiUri, servletRequest.getContextPath());
|
||||||
apiUri = StringUtils.removeEnd(apiUri, "/");
|
// apiUri = StringUtils.removeEnd(apiUri, "/");
|
||||||
|
//
|
||||||
HttpDynamicInAdapterUri adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), "");
|
// HttpDynamicInAdapterUri adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), "");
|
||||||
|
//
|
||||||
if (logger.isDebug()) {
|
// if (logger.isDebug()) {
|
||||||
logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
// logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
if (adptUri == null) {
|
// if (adptUri == null) {
|
||||||
logError(servletRequest);
|
// logError(servletRequest);
|
||||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
// String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
||||||
"can not find Adapter Uri");
|
// "can not find Adapter Uri");
|
||||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(errorMsg);
|
// return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(errorMsg);
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
// Received time , jwhong
|
// // Received time , jwhong
|
||||||
long receivedTimeMillis = System.currentTimeMillis(); // 밀리세컨 단위로 보내야함
|
// long receivedTimeMillis = System.currentTimeMillis(); // 밀리세컨 단위로 보내야함
|
||||||
String receivedTimeStr = String.valueOf(receivedTimeMillis);
|
// String receivedTimeStr = String.valueOf(receivedTimeMillis);
|
||||||
|
//
|
||||||
String adapterGroupName = adptUri.getAdptGrpName();
|
// String adapterGroupName = adptUri.getAdptGrpName();
|
||||||
String adapterName = adptUri.getAdptName();
|
// String adapterName = adptUri.getAdptName();
|
||||||
AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
// AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||||
AdapterVO adapterVO = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName);
|
// AdapterVO adapterVO = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName);
|
||||||
if (adapterVO == null) {
|
// if (adapterVO == null) {
|
||||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR,
|
// String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR,
|
||||||
"Adapter not found error");
|
// "Adapter not found error");
|
||||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
|
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
|
||||||
.body(errorMsg);
|
// .body(errorMsg);
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
Properties httpProp = AdapterPropManager.getInstance().getProperties(adapterVO.getPropGroupName());
|
// Properties httpProp = AdapterPropManager.getInstance().getProperties(adapterVO.getPropGroupName());
|
||||||
|
//
|
||||||
String adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
// String adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||||
String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
// String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||||
MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
// MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
||||||
String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
// String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||||
|
//
|
||||||
String responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
|
// String responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
|
||||||
ResponseEntity responseEntity = null;
|
// ResponseEntity responseEntity = null;
|
||||||
Properties transactionProp = new Properties();
|
// Properties transactionProp = new Properties();
|
||||||
// jwhong, put api received time, eaiSvcCode
|
// // jwhong, put api received time, eaiSvcCode
|
||||||
transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
// transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
||||||
|
//
|
||||||
// ** jwhong TSEAIHS04의 api full path와 비교하여 adapter를 가져온다
|
// // ** jwhong TSEAIHS04의 api full path와 비교하여 adapter를 가져온다
|
||||||
// String bzwkSvcKeyName = ""; // Adapter Group별 Action Class에 따라 구성이 달라짐. 예)
|
//// String bzwkSvcKeyName = ""; // Adapter Group별 Action Class에 따라 구성이 달라짐. 예)
|
||||||
// // _AGW_IN_RST_SyS:POST/account/{acc_no}
|
//// // _AGW_IN_RST_SyS:POST/account/{acc_no}
|
||||||
// String adapterGrpName = ""; // Adapter Group명 예) _AGW_IN_RST_SyS : API_PATH(/api/test)
|
//// String adapterGrpName = ""; // Adapter Group명 예) _AGW_IN_RST_SyS : API_PATH(/api/test)
|
||||||
String apiSvcCode = ""; // eaiSvcCd 예) LONNCHCON00005S2
|
// String apiSvcCode = ""; // eaiSvcCd 예) LONNCHCON00005S2
|
||||||
String apiFullPathKey = ""; // 예) POST|/api/test/account/list, POST|/api/test/account/{acc_no}
|
// String apiFullPathKey = ""; // 예) POST|/api/test/account/list, POST|/api/test/account/{acc_no}
|
||||||
Map<String, String> pathVariables = null;
|
// Map<String, String> pathVariables = null;
|
||||||
try {
|
// try {
|
||||||
// PathVariable(ex:/api/test/account/{acc_no}) 대응 및 DAO조회 제거.
|
// // PathVariable(ex:/api/test/account/{acc_no}) 대응 및 DAO조회 제거.
|
||||||
// /api/test/account/1234567 호출시 /api/test/account/{acc_no} API 로 식별.
|
// // /api/test/account/1234567 호출시 /api/test/account/{acc_no} API 로 식별.
|
||||||
|
//
|
||||||
// String methodAndUri = getRequestRuledPath(servletRequest, apiUri, adapterVO, transactionProp);
|
//// String methodAndUri = getRequestRuledPath(servletRequest, apiUri, adapterVO, transactionProp);
|
||||||
String methodAndUri = servletRequest.getMethod() + "|" + apiUri;
|
// String methodAndUri = servletRequest.getMethod() + "|" + apiUri;
|
||||||
STDMessageManager manager = STDMessageManager.getInstance();
|
// STDMessageManager manager = STDMessageManager.getInstance();
|
||||||
STDMsgInfoAddOnVO stdMsgInfo = manager.getStdMsgInfoAddOn(methodAndUri);
|
// STDMsgInfoAddOnVO stdMsgInfo = manager.getStdMsgInfoAddOn(methodAndUri);
|
||||||
// bzwkSvcKeyName = stdMsgInfo.getBzwksvckeyname();
|
//// bzwkSvcKeyName = stdMsgInfo.getBzwksvckeyname();
|
||||||
apiSvcCode = stdMsgInfo.getEaiSvcCd();
|
// apiSvcCode = stdMsgInfo.getEaiSvcCd();
|
||||||
transactionProp.put(API_SERVICE_CODE, apiSvcCode);
|
// transactionProp.put(API_SERVICE_CODE, apiSvcCode);
|
||||||
|
//
|
||||||
// adapterGrpName = stdMsgInfo.gAdapterGroupName();
|
//// adapterGrpName = stdMsgInfo.gAdapterGroupName();
|
||||||
apiFullPathKey = stdMsgInfo.getApiFullPath();
|
// apiFullPathKey = stdMsgInfo.getApiFullPath();
|
||||||
if (STDMessageManager.isPathVariable(apiFullPathKey)) {
|
// if (STDMessageManager.isPathVariable(apiFullPathKey)) {
|
||||||
pathVariables = new AntPathMatcher().extractUriTemplateVariables(apiFullPathKey, methodAndUri);
|
// pathVariables = new AntPathMatcher().extractUriTemplateVariables(apiFullPathKey, methodAndUri);
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
// adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), adapterGrpName);
|
//// adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), adapterGrpName);
|
||||||
} catch (Exception e) {
|
// } catch (Exception e) {
|
||||||
// adptUri = null;
|
//// adptUri = null;
|
||||||
}
|
// }
|
||||||
// ***
|
// // ***
|
||||||
if (pathVariables != null) {
|
// if (pathVariables != null) {
|
||||||
transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
// transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
try {
|
// try {
|
||||||
String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
// String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||||
transactionProp);
|
// transactionProp);
|
||||||
// if (RESPONSE_TYPE_ASYNC.equals(responseType)) { // table의 값이 ASYNC 로 들어가 있는데
|
// // if (RESPONSE_TYPE_ASYNC.equals(responseType)) { // table의 값이 ASYNC 로 들어가 있는데
|
||||||
// response_type_async는 ASYN 로 되어 있어 아래처럼 비교함 jwhong 2025
|
// // response_type_async는 ASYN 로 되어 있어 아래처럼 비교함 jwhong 2025
|
||||||
if ("ASYNC".equals(responseType)) {
|
// if ("ASYNC".equals(responseType)) {
|
||||||
// responseEntity = ResponseEntity.ok("dummy"); // comment by jwhong
|
// // responseEntity = ResponseEntity.ok("dummy"); // comment by jwhong
|
||||||
// servletResponse.addHeader("traceId", responseData); // uuid를 response header에
|
// // servletResponse.addHeader("traceId", responseData); // uuid를 response header에
|
||||||
servletResponse.addHeader("traceId",
|
// servletResponse.addHeader("traceId",
|
||||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
// transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||||
int httpStatus = servletResponse.getStatus();
|
// int httpStatus = servletResponse.getStatus();
|
||||||
if (httpStatus == 200) {
|
// if (httpStatus == 200) {
|
||||||
// 업체별 aync response message 가 다르다.
|
// // 업체별 aync response message 가 다르다.
|
||||||
String asyncMsgStyle = httpProp.getProperty("ASYNC_RTNMSG_TYPE", "");
|
// String asyncMsgStyle = httpProp.getProperty("ASYNC_RTNMSG_TYPE", "");
|
||||||
String responseBody = "";
|
// String responseBody = "";
|
||||||
boolean encryptAsyncAckApply = StringUtils
|
// boolean encryptAsyncAckApply = StringUtils
|
||||||
.equalsIgnoreCase(httpProp.getProperty("ASYNC_ENCRYPT_ACK", "N"), "Y");
|
// .equalsIgnoreCase(httpProp.getProperty("ASYNC_ENCRYPT_ACK", "N"), "Y");
|
||||||
|
//
|
||||||
if (asyncMsgStyle == null || asyncMsgStyle.trim().isEmpty()) {
|
// if (asyncMsgStyle == null || asyncMsgStyle.trim().isEmpty()) {
|
||||||
responseBody = makeResponseBodyMsg();
|
// responseBody = makeResponseBodyMsg();
|
||||||
} else {
|
// } else {
|
||||||
responseBody = asyncMsgStyle;
|
// responseBody = asyncMsgStyle;
|
||||||
}
|
// }
|
||||||
if (encryptAsyncAckApply) {
|
// if (encryptAsyncAckApply) {
|
||||||
responseBody = service.doPostEncryption(responseBody, transactionProp, servletRequest);
|
// responseBody = service.doPostEncryption(responseBody, transactionProp, servletRequest);
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseBody);
|
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseBody);
|
||||||
// jwhong
|
// // jwhong
|
||||||
} else {
|
// } else {
|
||||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||||
}
|
// }
|
||||||
} else {
|
// } else {
|
||||||
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
//// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||||
// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
|
//// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
|
||||||
// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
|
//// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
|
||||||
|
//
|
||||||
servletResponse.addHeader("traceId",
|
// servletResponse.addHeader("traceId",
|
||||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
// transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||||
int httpStatus = servletResponse.getStatus();
|
// int httpStatus = servletResponse.getStatus();
|
||||||
if (httpStatus != 200) {
|
// if (httpStatus != 200) {
|
||||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||||
} else {
|
// } else {
|
||||||
responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
} catch (Exception e) {
|
// } catch (Exception e) {
|
||||||
|
//
|
||||||
|
//
|
||||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||||
|
//
|
||||||
String errorMsg = null;
|
// String errorMsg = null;
|
||||||
|
//
|
||||||
if( e instanceof HttpStatusException ) {
|
// if( e instanceof HttpStatusException ) {
|
||||||
logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
// logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||||
HttpStatusException e1 = (HttpStatusException) e;
|
// HttpStatusException e1 = (HttpStatusException) e;
|
||||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||||
MessageUtil.ERROR_CODE_AP_ERROR, e1.getMessage(), errorResponseFormat);
|
// MessageUtil.ERROR_CODE_AP_ERROR, e1.getMessage(), errorResponseFormat);
|
||||||
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
// responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||||
}
|
// }
|
||||||
else if( e instanceof JwtAuthException )
|
// else if( e instanceof JwtAuthException )
|
||||||
{
|
// {
|
||||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||||
MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage(), errorResponseFormat);
|
// MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage(), errorResponseFormat);
|
||||||
responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
// responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||||
}
|
// }
|
||||||
else
|
// else
|
||||||
{
|
// {
|
||||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||||
errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||||
MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
// MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
||||||
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType)
|
// responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType)
|
||||||
.body(errorMsg);
|
// .body(errorMsg);
|
||||||
}
|
// }
|
||||||
String postFilterNames = httpProp.getProperty("POST_FILTERS","");
|
// String postFilterNames = httpProp.getProperty("POST_FILTERS","");
|
||||||
|
//
|
||||||
if( postFilterNames.contains("HMAC_SHA256") ) {
|
// if( postFilterNames.contains("HMAC_SHA256") ) {
|
||||||
HttpAdapterFilter filter = HttpAdapterFilterFactoryKjb.createFilter("HMAC_SHA256");
|
// HttpAdapterFilter filter = HttpAdapterFilterFactoryKjb.createFilter("HMAC_SHA256");
|
||||||
filter.doPostFilter(adapterGroupName, postFilterNames, errorMsg, transactionProp, servletRequest, servletResponse);
|
// filter.doPostFilter(adapterGroupName, postFilterNames, errorMsg, transactionProp, servletRequest, servletResponse);
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
|
//
|
||||||
} finally {
|
// } finally {
|
||||||
/**
|
// /**
|
||||||
* 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
// * 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
||||||
* 추후 더 좋은방법이 생길경우 개선 요망
|
// * 추후 더 좋은방법이 생길경우 개선 요망
|
||||||
*/
|
// */
|
||||||
try {
|
// try {
|
||||||
|
//
|
||||||
servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
// servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
||||||
|
//
|
||||||
if (!"ASYNC".equals(responseType)) {
|
// if (!"ASYNC".equals(responseType)) {
|
||||||
String uuid = transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
// String uuid = transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||||
String url = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
|
// String url = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
|
||||||
String method = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
|
// String method = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
|
||||||
int httpStatusCode = servletResponse.getStatus();
|
// int httpStatusCode = servletResponse.getStatus();
|
||||||
|
//
|
||||||
Map<Object, Object> headerMap = new HashMap<>();
|
// Map<Object, Object> headerMap = new HashMap<>();
|
||||||
// 응답 헤더 로깅
|
// // 응답 헤더 로깅
|
||||||
for (String headerName : servletResponse.getHeaderNames()) {
|
// for (String headerName : servletResponse.getHeaderNames()) {
|
||||||
String headerValue = servletResponse.getHeader(headerName);
|
// String headerValue = servletResponse.getHeader(headerName);
|
||||||
logger.debug(String.format("httpHeader logging headerKey=%s, headerValue=%s",
|
// logger.debug(String.format("httpHeader logging headerKey=%s, headerValue=%s",
|
||||||
headerName, headerValue));
|
// headerName, headerValue));
|
||||||
headerMap.put(headerName, headerValue);
|
// headerMap.put(headerName, headerValue);
|
||||||
}
|
// }
|
||||||
//HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName,adapterName, headerMap, url, method, httpStatusCode);
|
// //HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName,adapterName, headerMap, url, method, httpStatusCode);
|
||||||
}
|
// }
|
||||||
} catch (Exception e) {
|
// } catch (Exception e) {
|
||||||
logger.warn("http header db logging fail.", e);
|
// logger.warn("http header db logging fail.", e);
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
return responseEntity;
|
// return responseEntity;
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
/**
|
// /**
|
||||||
* url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
|
// * url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
|
||||||
* /api/v1/public/getUserInfo.svc
|
// * /api/v1/public/getUserInfo.svc
|
||||||
*
|
// *
|
||||||
* @param apiUri
|
// * @param apiUri
|
||||||
* @return
|
// * @return
|
||||||
*/
|
// */
|
||||||
private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager,
|
// private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager,
|
||||||
String adapterGrpName) throws Exception {
|
// String adapterGrpName) throws Exception {
|
||||||
if (StringUtils.isBlank(apiUri)) {
|
// if (StringUtils.isBlank(apiUri)) {
|
||||||
return null;
|
// return null;
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
// * manager 출력
|
// // * manager 출력
|
||||||
logger.warn("===== adptUriMap 상세 내용 =====");
|
// logger.warn("===== adptUriMap 상세 내용 =====");
|
||||||
for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
// for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
||||||
HttpDynamicInAdapterUri uriObj = entry.getValue();
|
// HttpDynamicInAdapterUri uriObj = entry.getValue();
|
||||||
logger.warn("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
// logger.warn("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
||||||
+ uriObj.getUri());
|
// + uriObj.getUri());
|
||||||
}
|
// }
|
||||||
logger.warn("================================");
|
// logger.warn("================================");
|
||||||
|
//
|
||||||
//
|
// //
|
||||||
for (int i = 0; i < 10; i++) {
|
// for (int i = 0; i < 10; i++) {
|
||||||
HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
|
// HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
|
||||||
if (adptUri != null) {
|
// if (adptUri != null) {
|
||||||
if (StringUtils.isNotEmpty(adapterGrpName)) {
|
// if (StringUtils.isNotEmpty(adapterGrpName)) {
|
||||||
if(adptUri.getAdptGrpName().equals(adapterGrpName)) {
|
// if(adptUri.getAdptGrpName().equals(adapterGrpName)) {
|
||||||
return adptUri;
|
// return adptUri;
|
||||||
}
|
// }
|
||||||
} else {
|
// } else {
|
||||||
return adptUri;
|
// return adptUri;
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
// /api/v1/public
|
// // /api/v1/public
|
||||||
apiUri = StringUtils.substringBeforeLast(apiUri, "/");
|
// apiUri = StringUtils.substringBeforeLast(apiUri, "/");
|
||||||
if (apiUri.length() < 4) { // /api
|
// if (apiUri.length() < 4) { // /api
|
||||||
return null;
|
// return null;
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
return null;
|
// return null;
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
private void logError(HttpServletRequest request) {
|
// private void logError(HttpServletRequest request) {
|
||||||
InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
// InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||||
|
//
|
||||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
// EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||||
String serverName = eaiServerManager.getLocalServerName();
|
// String serverName = eaiServerManager.getLocalServerName();
|
||||||
String uuid = null;
|
// String uuid = null;
|
||||||
StringBuffer sb = new StringBuffer();
|
// StringBuffer sb = new StringBuffer();
|
||||||
|
//
|
||||||
String instanceid1 = serverName.substring(0, 2);
|
// String instanceid1 = serverName.substring(0, 2);
|
||||||
String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
// String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||||
String instid = instanceid1 + instanceid2;
|
// String instid = instanceid1 + instanceid2;
|
||||||
uuid = instid + UUIDGenerator.getUUID();
|
// uuid = instid + UUIDGenerator.getUUID();
|
||||||
|
//
|
||||||
String[] msgArgs = new String[1];
|
// String[] msgArgs = new String[1];
|
||||||
msgArgs[0] = request.getRequestURI();
|
// msgArgs[0] = request.getRequestURI();
|
||||||
|
//
|
||||||
String errorCode = "RECEAIIRP010";
|
// String errorCode = "RECEAIIRP010";
|
||||||
String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
|
// String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
|
||||||
|
//
|
||||||
errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
// errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
||||||
errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
|
// errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
|
||||||
errorInfoVO.setErrCd(errorCode); // 에러코드
|
// errorInfoVO.setErrCd(errorCode); // 에러코드
|
||||||
errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
// errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||||
errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
// errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
||||||
errorInfoVO.setErrDstcd(" ");
|
// errorInfoVO.setErrDstcd(" ");
|
||||||
sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
|
// sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
|
||||||
.append(request.getRequestURI());
|
// .append(request.getRequestURI());
|
||||||
errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
// errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
||||||
errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
// errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
||||||
|
//
|
||||||
InboundErrorLogger.error(errorInfoVO);
|
// InboundErrorLogger.error(errorInfoVO);
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
private String makeResponseBodyMsg() {
|
// private String makeResponseBodyMsg() {
|
||||||
|
//
|
||||||
Map<String, Object> dataMap = new HashMap<>();
|
// Map<String, Object> dataMap = new HashMap<>();
|
||||||
dataMap.put("result", 1);
|
// dataMap.put("result", 1);
|
||||||
Map<String, Object> map = new HashMap<>();
|
// Map<String, Object> map = new HashMap<>();
|
||||||
|
//
|
||||||
map.put("code", "200");
|
// map.put("code", "200");
|
||||||
map.put("data", dataMap);
|
// map.put("data", dataMap);
|
||||||
map.put("message", "정상 처리 되었습니다.");
|
// map.put("message", "정상 처리 되었습니다.");
|
||||||
|
//
|
||||||
JSONObject json = new JSONObject();
|
// JSONObject json = new JSONObject();
|
||||||
json.putAll(map);
|
// json.putAll(map);
|
||||||
|
//
|
||||||
return json.toJSONString();
|
// return json.toJSONString();
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
/*
|
// /*
|
||||||
* private String makeResponseBodyMsg(String asyncMsgStyle) {
|
// * private String makeResponseBodyMsg(String asyncMsgStyle) {
|
||||||
*
|
// *
|
||||||
* Map<String, Object> dataMap = new HashMap<>(); dataMap.put("result", 1);
|
// * Map<String, Object> dataMap = new HashMap<>(); dataMap.put("result", 1);
|
||||||
* Map<String, Object> map = new HashMap<>();
|
// * Map<String, Object> map = new HashMap<>();
|
||||||
*
|
// *
|
||||||
* switch (asyncMsgStyle) { case "TB_SUC": map.put("rspCode", "TB_SUC_000");
|
// * switch (asyncMsgStyle) { case "TB_SUC": map.put("rspCode", "TB_SUC_000");
|
||||||
* map.put("rspMsg", "정상"); map.put("data", dataMap); break; case "ONLYDATA":
|
// * map.put("rspMsg", "정상"); map.put("data", dataMap); break; case "ONLYDATA":
|
||||||
* map.put("data", dataMap); map.put("success", "true"); break; default:
|
// * map.put("data", dataMap); map.put("success", "true"); break; default:
|
||||||
* map.put("code", "200"); map.put("data", dataMap); map.put("message",
|
// * map.put("code", "200"); map.put("data", dataMap); map.put("message",
|
||||||
* "정상 처리 되었습니다."); break; }
|
// * "정상 처리 되었습니다."); break; }
|
||||||
*
|
// *
|
||||||
* JSONObject json = new JSONObject(); json.putAll(map);
|
// * JSONObject json = new JSONObject(); json.putAll(map);
|
||||||
*
|
// *
|
||||||
* return json.toJSONString(); }
|
// * return json.toJSONString(); }
|
||||||
*/
|
// */
|
||||||
}
|
//}
|
||||||
@@ -21,6 +21,9 @@ import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
|||||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
||||||
import com.eactive.eai.common.stdmessage.STDMessageManager;
|
import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||||
import com.eactive.eai.common.stdmessage.STDMsgInfoAddOnVO;
|
import com.eactive.eai.common.stdmessage.STDMsgInfoAddOnVO;
|
||||||
|
import com.fasterxml.jackson.core.JsonFactory;
|
||||||
|
import com.fasterxml.jackson.core.JsonParser;
|
||||||
|
import com.fasterxml.jackson.core.JsonToken;
|
||||||
|
|
||||||
|
|
||||||
public class ApiRequestBodyFilter extends OncePerRequestFilter {
|
public class ApiRequestBodyFilter extends OncePerRequestFilter {
|
||||||
@@ -32,17 +35,12 @@ public class ApiRequestBodyFilter extends OncePerRequestFilter {
|
|||||||
HttpServletResponse response,
|
HttpServletResponse response,
|
||||||
FilterChain filterChain)
|
FilterChain filterChain)
|
||||||
throws ServletException, IOException {
|
throws ServletException, IOException {
|
||||||
|
System.out.println("ApiRequestBodyFilter : " + request.getRequestURI());
|
||||||
if (!isTarget(request)) {
|
if (!isTarget(request)) {
|
||||||
filterChain.doFilter(request, response);
|
filterChain.doFilter(request, response);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
String encoding = getInboundGroupAdapterEncoding(request);
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//원본 바디를 byte[]로 읽기 (개행 포함 그대로) 왜? 뒤에 필터에서 HMAC값 계산할수도 있어서 변조되면 안됨. 개행문자도 그대로 가야함.
|
//원본 바디를 byte[]로 읽기 (개행 포함 그대로) 왜? 뒤에 필터에서 HMAC값 계산할수도 있어서 변조되면 안됨. 개행문자도 그대로 가야함.
|
||||||
byte[] rawBody = readBodyAsBytes(request);
|
byte[] rawBody = readBodyAsBytes(request);
|
||||||
|
|
||||||
@@ -54,14 +52,16 @@ public class ApiRequestBodyFilter extends OncePerRequestFilter {
|
|||||||
byte[] finalBody = rawBody;
|
byte[] finalBody = rawBody;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
if(isJsonArray(rawBody)) {
|
||||||
|
String encoding = getInboundGroupAdapterEncoding(request);
|
||||||
|
String bodyStr = new String(rawBody, encoding);
|
||||||
|
Object json = JSONValue.parse(bodyStr);
|
||||||
|
|
||||||
String bodyStr = new String(rawBody, encoding);
|
if (json instanceof JSONArray) {
|
||||||
Object json = JSONValue.parse(bodyStr);
|
bodyStr = DJB_ROOTLESS_ARRAY + bodyStr + "}";
|
||||||
|
finalBody = bodyStr.getBytes(encoding);
|
||||||
if (json instanceof JSONArray) {
|
}
|
||||||
bodyStr = DJB_ROOTLESS_ARRAY + bodyStr + "}";
|
}
|
||||||
finalBody = bodyStr.getBytes(encoding);
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// JSON 파싱 실패 시 원본 유지
|
// JSON 파싱 실패 시 원본 유지
|
||||||
@@ -75,6 +75,14 @@ public class ApiRequestBodyFilter extends OncePerRequestFilter {
|
|||||||
filterChain.doFilter(wrapped, response);
|
filterChain.doFilter(wrapped, response);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static boolean isJsonArray(byte[] json) {
|
||||||
|
try (JsonParser parser = new JsonFactory().createParser(json)) {
|
||||||
|
return parser.nextToken() == JsonToken.START_ARRAY;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private boolean isTarget(HttpServletRequest request) {
|
private boolean isTarget(HttpServletRequest request) {
|
||||||
String uri = request.getRequestURI();
|
String uri = request.getRequestURI();
|
||||||
// token 이 포함되면 무조건 제외
|
// token 이 포함되면 무조건 제외
|
||||||
|
|||||||
@@ -0,0 +1,302 @@
|
|||||||
|
package com.eactive.eai.adapter.controller;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
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.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.handler.AdapterErrorMessageHandler;
|
||||||
|
import com.eactive.eai.adapter.handler.AdapterErrorMessageHandlerFactory;
|
||||||
|
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||||
|
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.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.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.TxFileLogger;
|
||||||
|
import com.eactive.eai.common.util.TxSiftContext;
|
||||||
|
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).*$}/**",
|
||||||
|
"/kp/{path:^(?!oauth).*$}", "/kp/{path:^(?!oauth).*$}/**",
|
||||||
|
"/kkb/{path:^(?!oauth).*$}", "/kkb/{path:^(?!oauth).*$}/**",
|
||||||
|
"/nf/{path:^(?!oauth).*$}", "/nf/{path:^(?!oauth).*$}/**",
|
||||||
|
"/bsd/{path:^(?!oauth).*$}", "/bsd/{path:^(?!oauth).*$}/**",
|
||||||
|
"/tss/{path:^(?!oauth).*$}", "/tss/{path:^(?!oauth).*$}/**",
|
||||||
|
"/tsb/{path:^(?!oauth).*$}", "/tsb/{path:^(?!oauth).*$}/**",
|
||||||
|
"/shb/{path:^(?!oauth).*$}", "/shb/{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);
|
||||||
|
|
||||||
|
ResponseEntity<String> responseEntity = null;
|
||||||
|
Properties transactionProp = new Properties();
|
||||||
|
String uuid = UUIDGenerator.getUUID().toString().replaceAll("-", "");
|
||||||
|
transactionProp.setProperty(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||||
|
|
||||||
|
TxSiftContext.begin(uuid);
|
||||||
|
|
||||||
|
// jwhong, put api received time, eaiSvcCode
|
||||||
|
transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
||||||
|
|
||||||
|
String responseData = "";
|
||||||
|
try {
|
||||||
|
responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||||
|
transactionProp);
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
errorMsg = genErrorResponseMessage(adapterGroupName, adapterName,
|
||||||
|
transactionProp, e, adptMsgType, encode, errorResponseFormat);
|
||||||
|
if (e instanceof HttpStatusException) {
|
||||||
|
logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||||
|
HttpStatusException e1 = (HttpStatusException) e;
|
||||||
|
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||||
|
} else if (e instanceof JwtAuthException) {
|
||||||
|
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||||
|
responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||||
|
} else {
|
||||||
|
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||||
|
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType).body(errorMsg);
|
||||||
|
}
|
||||||
|
responseData = errorMsg;
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
/**
|
||||||
|
* 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
||||||
|
* 추후 더 좋은방법이 생길경우 개선 요망
|
||||||
|
*/
|
||||||
|
try {
|
||||||
|
TxFileLogger.logTxFile(transactionProp, responseData, "[IN_SEND]");
|
||||||
|
servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.warn("http header db logging fail.", e);
|
||||||
|
} finally {
|
||||||
|
TxSiftContext.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return responseEntity;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String genErrorResponseMessage(String adapterGroupName, String adapterName,
|
||||||
|
Properties callProp, Throwable e, String adptMsgType, String encode, String errorResponseFormat) {
|
||||||
|
String errorHandlerClass = AdapterPropManager.getInstance().getProperty(adapterName, "ERR_MSG_HANDLER");
|
||||||
|
if (StringUtils.isNotBlank(errorHandlerClass)) {
|
||||||
|
if (logger.isInfo())
|
||||||
|
logger.info("ExceptionHandler] errorSyncSend ERR_MSG_HANDLER=" + errorHandlerClass);
|
||||||
|
AdapterErrorMessageHandler handler = AdapterErrorMessageHandlerFactory.createHandler(errorHandlerClass);
|
||||||
|
if (handler != null) {
|
||||||
|
Object resposne;
|
||||||
|
try {
|
||||||
|
resposne = handler.generateNonStandardInboundErrorResponseMessage(adapterGroupName, adapterName,
|
||||||
|
callProp, null, null, e);
|
||||||
|
return (String)resposne;
|
||||||
|
} catch (Exception e1) {
|
||||||
|
logger.warn("AdapterErrorMessageHandler error.", e);
|
||||||
|
// handler 실패시 아래에서 처리한
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||||
|
MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
|
||||||
|
* /api/v1/public/getUserInfo.svc
|
||||||
|
*
|
||||||
|
* @param apiUri
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager,
|
||||||
|
String adapterGrpName) throws Exception {
|
||||||
|
if (StringUtils.isBlank(apiUri)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// * manager 출력
|
||||||
|
logger.warn("===== adptUriMap 상세 내용 =====");
|
||||||
|
for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
||||||
|
HttpDynamicInAdapterUri uriObj = entry.getValue();
|
||||||
|
logger.warn("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
||||||
|
+ uriObj.getUri());
|
||||||
|
}
|
||||||
|
logger.warn("================================");
|
||||||
|
|
||||||
|
//
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
|
||||||
|
if (adptUri != null) {
|
||||||
|
if (StringUtils.isNotEmpty(adapterGrpName)) {
|
||||||
|
if(adptUri.getAdptGrpName().equals(adapterGrpName)) {
|
||||||
|
return adptUri;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return adptUri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// /api/v1/public
|
||||||
|
apiUri = StringUtils.substringBeforeLast(apiUri, "/");
|
||||||
|
if (apiUri.length() < 3) { // /api
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void logError(HttpServletRequest request) {
|
||||||
|
InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||||
|
|
||||||
|
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||||
|
String serverName = eaiServerManager.getLocalServerName();
|
||||||
|
String uuid = null;
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
|
||||||
|
String instanceid1 = serverName.substring(0, 2);
|
||||||
|
String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||||
|
String instid = instanceid1 + instanceid2;
|
||||||
|
uuid = instid + UUIDGenerator.getUUID();
|
||||||
|
|
||||||
|
String[] msgArgs = new String[1];
|
||||||
|
msgArgs[0] = request.getRequestURI();
|
||||||
|
|
||||||
|
String errorCode = "RECEAIIRP010";
|
||||||
|
String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
|
||||||
|
|
||||||
|
errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
||||||
|
errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
|
||||||
|
errorInfoVO.setErrCd(errorCode); // 에러코드
|
||||||
|
errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||||
|
errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
||||||
|
errorInfoVO.setErrDstcd(" ");
|
||||||
|
sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
|
||||||
|
.append(request.getRequestURI());
|
||||||
|
errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
||||||
|
errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
||||||
|
|
||||||
|
InboundErrorLogger.error(errorInfoVO);
|
||||||
|
}
|
||||||
|
|
||||||
|
// private String makeResponseBodyMsg() {
|
||||||
|
//
|
||||||
|
// Map<String, Object> dataMap = new HashMap<>();
|
||||||
|
// dataMap.put("result", 1);
|
||||||
|
// Map<String, Object> map = new HashMap<>();
|
||||||
|
//
|
||||||
|
// map.put("code", "200");
|
||||||
|
// map.put("data", dataMap);
|
||||||
|
// map.put("message", "정상 처리 되었습니다.");
|
||||||
|
//
|
||||||
|
// JSONObject json = new JSONObject();
|
||||||
|
// json.putAll(map);
|
||||||
|
//
|
||||||
|
// return json.toJSONString();
|
||||||
|
// }
|
||||||
|
|
||||||
|
/*
|
||||||
|
* private String makeResponseBodyMsg(String asyncMsgStyle) {
|
||||||
|
*
|
||||||
|
* Map<String, Object> dataMap = new HashMap<>(); dataMap.put("result", 1);
|
||||||
|
* Map<String, Object> map = new HashMap<>();
|
||||||
|
*
|
||||||
|
* switch (asyncMsgStyle) { case "TB_SUC": map.put("rspCode", "TB_SUC_000");
|
||||||
|
* map.put("rspMsg", "정상"); map.put("data", dataMap); break; case "ONLYDATA":
|
||||||
|
* map.put("data", dataMap); map.put("success", "true"); break; default:
|
||||||
|
* map.put("code", "200"); map.put("data", dataMap); map.put("message",
|
||||||
|
* "정상 처리 되었습니다."); break; }
|
||||||
|
*
|
||||||
|
* JSONObject json = new JSONObject(); json.putAll(map);
|
||||||
|
*
|
||||||
|
* return json.toJSONString(); }
|
||||||
|
*/
|
||||||
|
}
|
||||||
+7
-1
@@ -18,12 +18,18 @@ import java.util.Properties;
|
|||||||
public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
|
public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
|
||||||
|
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
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 {
|
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
|
||||||
|
|
||||||
logger.debug("httpHeader logging Interceptor start");
|
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);
|
Properties transactionProp = (Properties) request.getAttribute(TransactionContextKeys.TRANSACTION_PROP);
|
||||||
if(transactionProp == null || "ASYN".equals(transactionProp.getProperty(HttpAdapterServiceKey.INBOUND_SYNC_ASYNC_TYPE))){
|
if(transactionProp == null || "ASYN".equals(transactionProp.getProperty(HttpAdapterServiceKey.INBOUND_SYNC_ASYNC_TYPE))){
|
||||||
logger.debug("httpHeader logging Interceptor ASYNC");
|
logger.debug("httpHeader logging Interceptor ASYNC");
|
||||||
|
|||||||
@@ -0,0 +1,787 @@
|
|||||||
|
package com.eactive.eai.adapter.service;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
import java.net.URLDecoder;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import javax.servlet.ServletInputStream;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.apache.commons.lang3.time.StopWatch;
|
||||||
|
import org.apache.mina.common.ByteBuffer;
|
||||||
|
import org.dom4j.Document;
|
||||||
|
import org.dom4j.DocumentException;
|
||||||
|
import org.dom4j.DocumentHelper;
|
||||||
|
import org.dom4j.Element;
|
||||||
|
import org.dom4j.Node;
|
||||||
|
import org.dom4j.io.OutputFormat;
|
||||||
|
import org.dom4j.io.XMLWriter;
|
||||||
|
import org.json.simple.JSONObject;
|
||||||
|
import org.json.simple.JSONValue;
|
||||||
|
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 com.eactive.eai.adapter.AdapterGroupVO;
|
||||||
|
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.ApiKeyExtractFilter;
|
||||||
|
import com.eactive.eai.adapter.http.filter.AbstractCryptoFilter;
|
||||||
|
import com.eactive.eai.common.context.ElinkTransactionContext;
|
||||||
|
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.JSONUtils;
|
||||||
|
import com.eactive.eai.common.util.Logger;
|
||||||
|
import com.eactive.eai.common.util.TxFileLogger;
|
||||||
|
import com.eactive.eai.common.util.XMLUtils;
|
||||||
|
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;
|
||||||
|
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||||
|
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||||
|
static Logger siftLogger = Logger.getLogger(Logger.LOGGER_SIFT);
|
||||||
|
|
||||||
|
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";
|
||||||
|
|
||||||
|
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id"; // jwhong
|
||||||
|
|
||||||
|
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp,
|
||||||
|
AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
|
||||||
|
int traceLevel = 0;
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
Properties inboundHeaderProp = getHeaders(request);
|
||||||
|
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, inboundHeaderProp);
|
||||||
|
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 (inboundHeaderProp.get(HEADER_NAME_CLIENT_ID) != null) { // jwhong
|
||||||
|
transactionProp.put(HEADER_NAME_CLIENT_ID, inboundHeaderProp.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 = inboundHeaderProp.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(AbstractCryptoFilter.PROP_MODULE_NAME, httpProp.getProperty(AbstractCryptoFilter.PROP_MODULE_NAME, ""));
|
||||||
|
|
||||||
|
transactionProp.put(HEADER_GROUP, headerGroupName);
|
||||||
|
transactionProp.put(HEADER_KEYS, relayRequestHeaderKeys);
|
||||||
|
|
||||||
|
// SEED 컬럼암호하 시 Key로 사용함
|
||||||
|
String seedkey = inboundHeaderProp.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;
|
||||||
|
}
|
||||||
|
|
||||||
|
TxFileLogger.logTxFile(transactionProp, message, "[IN_RECV]");
|
||||||
|
|
||||||
|
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();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
Object reqObject = assignHeaderGroupRequestHeaders(adptGrpName, adptName, message,
|
||||||
|
transactionProp, request, response, adptMsgType);
|
||||||
|
|
||||||
|
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
|
||||||
|
// transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
|
||||||
|
// 로컬 서비스 호출 ,encoding 처리 추가
|
||||||
|
|
||||||
|
ApiKeyExtractFilter apiKeyExtractor = new ApiKeyExtractFilter();
|
||||||
|
apiKeyExtractor.doPreFilter(adptGrpName, adptName, reqObject, transactionProp, request, response);
|
||||||
|
|
||||||
|
String result = (String) service(adptGrpName, adptName, reqObject, transactionProp, request, response);
|
||||||
|
|
||||||
|
// bypass만 필요
|
||||||
|
applyOutboundResponseHeaders(transactionProp, response);
|
||||||
|
|
||||||
|
result = applyHeaderGroupResponseHeaders(adptGrpName, adptName, result, transactionProp, request, response, adptMsgType);
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private Object assignHeaderGroupRequestHeaders(String adptGrpName, String adptName, Object message, Properties prop,
|
||||||
|
HttpServletRequest request, HttpServletResponse response, String adptMsgType) throws DocumentException, IOException {
|
||||||
|
// XML 지원 개발
|
||||||
|
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
||||||
|
String relayRequestHeaderKeys = prop.getProperty(HEADER_KEYS);
|
||||||
|
if(StringUtils.isNotBlank(headerGroupName) && StringUtils.isNotBlank(relayRequestHeaderKeys)) {
|
||||||
|
if (MessageType.JSON.equals(adptMsgType)) {
|
||||||
|
if(message instanceof String && StringUtils.isEmpty((String)message))
|
||||||
|
message = "{}";
|
||||||
|
|
||||||
|
JSONObject jsonMessage = JSONUtils.parseJson(message);
|
||||||
|
JSONObject headerJson = JSONUtils.getChildJson(jsonMessage, headerGroupName);
|
||||||
|
if (headerJson == null)
|
||||||
|
headerJson = new JSONObject();
|
||||||
|
|
||||||
|
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||||
|
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
||||||
|
String key = e.nextElement();
|
||||||
|
headerJson.put(StringUtils.lowerCase(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(StringUtils.lowerCase(key), headerValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (headerJson.size() > 0) {
|
||||||
|
jsonMessage.put(headerGroupName, headerJson);
|
||||||
|
message = jsonMessage.toJSONString();
|
||||||
|
}
|
||||||
|
} else if(MessageType.XML.equals(adptMsgType)) {
|
||||||
|
Document document = XMLUtils.convertXmlDocument(message);
|
||||||
|
if(document != null) {
|
||||||
|
Element rootElement = document.getRootElement();
|
||||||
|
Element headerElement = rootElement.element(headerGroupName);
|
||||||
|
if(headerElement == null)
|
||||||
|
headerElement = DocumentHelper.createElement(headerGroupName);
|
||||||
|
|
||||||
|
boolean hasHeaderValues = false;
|
||||||
|
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||||
|
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
||||||
|
String key = e.nextElement();
|
||||||
|
String value = request.getHeader(key);
|
||||||
|
/*
|
||||||
|
* IBK 표준안에 따라 <{key}>{value}</{key}> 형태로 저장, KEY 는 소문자로 변경한다
|
||||||
|
* 대상 사이트의 표준안에 따라 작성 할 것
|
||||||
|
*
|
||||||
|
* HTTP 헤더 변환 예시
|
||||||
|
*
|
||||||
|
* 일반적인 HTTP 헤더 변환 예시:
|
||||||
|
* Content-Type: application/json
|
||||||
|
* X-Forwarded-For: 10.0.0.1
|
||||||
|
*
|
||||||
|
* <root>
|
||||||
|
* <data> original content </data>
|
||||||
|
* <httpHeaderGroup>
|
||||||
|
* <content-type>application/json</content-type>
|
||||||
|
* <x-forwarded-for>10.0.0.1</x-forwarded-for>
|
||||||
|
* </httpHeaderGroup>
|
||||||
|
* </root>
|
||||||
|
*/
|
||||||
|
if(StringUtils.isNotBlank(value)) {
|
||||||
|
Element headerItem = headerElement.addElement(key);
|
||||||
|
headerItem.setText(value);
|
||||||
|
hasHeaderValues = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
String[] relayKeyArr = org.springframework.util.StringUtils
|
||||||
|
.tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
||||||
|
|
||||||
|
for (String key : relayKeyArr) {
|
||||||
|
String headerValue = request.getHeader(key);
|
||||||
|
if (StringUtils.isNotBlank(headerValue)) {
|
||||||
|
String value = request.getHeader(key);
|
||||||
|
String keyName = StringUtils.lowerCase(key);
|
||||||
|
Element headerItem = headerElement.addElement(keyName);
|
||||||
|
headerItem.setText(value);
|
||||||
|
hasHeaderValues = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasHeaderValues) {
|
||||||
|
rootElement.add(headerElement);
|
||||||
|
OutputFormat format = OutputFormat.createPrettyPrint();
|
||||||
|
StringWriter writer = new StringWriter();
|
||||||
|
XMLWriter xmlWriter = new XMLWriter(writer, format);
|
||||||
|
xmlWriter.write(document);
|
||||||
|
message = writer.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (message == null) {
|
||||||
|
message = "";
|
||||||
|
} // XML 지원 개발
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String applyHeaderGroupResponseHeaders(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||||
|
HttpServletRequest request, HttpServletResponse response, String adptMsgType) throws Exception {
|
||||||
|
// body headergroup -> http header 세팅
|
||||||
|
String headerGroupName = prop.getProperty(ApiAdapterService.HEADER_GROUP);
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(headerGroupName)) {
|
||||||
|
if (resultMessage instanceof Node) {
|
||||||
|
adptMsgType = MessageType.XML;
|
||||||
|
} else if (resultMessage instanceof String) {
|
||||||
|
String strMessage = (String) resultMessage;
|
||||||
|
if (StringUtils.startsWith(strMessage, "<")) {
|
||||||
|
adptMsgType = MessageType.XML;
|
||||||
|
}
|
||||||
|
} else if (resultMessage instanceof byte[]) {
|
||||||
|
String strMessage = new String((byte[]) resultMessage);
|
||||||
|
if (StringUtils.startsWith(strMessage, "<")) {
|
||||||
|
adptMsgType = MessageType.XML;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (MessageType.JSON.equals(adptMsgType)) {
|
||||||
|
JSONObject jsonObject = JSONUtils.parseJson(resultMessage);
|
||||||
|
JSONObject headerGroup = (JSONObject)jsonObject.get(headerGroupName);
|
||||||
|
if (headerGroup != null) {
|
||||||
|
Set<Map.Entry<String, Object>> fieldEntrySet = JSONUtils.getField(headerGroup);
|
||||||
|
|
||||||
|
for (Map.Entry<String, Object> fieldEntry : fieldEntrySet) {
|
||||||
|
logger.info("header group entry : {} , {}", fieldEntry.getKey(), fieldEntry.getValue());
|
||||||
|
|
||||||
|
if (fieldEntry.getValue() instanceof String) {
|
||||||
|
if(fieldEntry.getKey().equalsIgnoreCase("content-type")) {
|
||||||
|
logger.debug("set content-type {}: {}", fieldEntry.getKey(), fieldEntry.getValue());
|
||||||
|
response.setContentType((String) fieldEntry.getValue());
|
||||||
|
} else {
|
||||||
|
logger.debug("add header {}: {}", fieldEntry.getKey(), fieldEntry.getValue());
|
||||||
|
response.addHeader(fieldEntry.getKey(), (String) fieldEntry.getValue());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.info("fieldEntry value is not String. {}", fieldEntry.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.info("headerGroup is null");
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonObject.remove(headerGroupName);
|
||||||
|
return jsonObject.toJSONString();
|
||||||
|
} else if(MessageType.XML.equals(adptMsgType)) {
|
||||||
|
Document document = XMLUtils.convertXmlDocument(resultMessage);
|
||||||
|
if(document != null) {
|
||||||
|
Element rootElement = document.getRootElement();
|
||||||
|
Element headerGroupElement = rootElement.element(headerGroupName);
|
||||||
|
|
||||||
|
if(headerGroupElement != null) {
|
||||||
|
//헤더그룹의 모든 하위 엘리먼트를 HTTP 응답 헤더로 설정
|
||||||
|
for(Iterator<Element> it = headerGroupElement.elementIterator(); it.hasNext();) {
|
||||||
|
Element headerElement = it.next();
|
||||||
|
String name = headerElement.getName();
|
||||||
|
String value = headerElement.getTextTrim();
|
||||||
|
|
||||||
|
if(StringUtils.isNoneBlank(value)) {
|
||||||
|
if(value.equalsIgnoreCase("content-type")) {
|
||||||
|
response.setContentType(value);
|
||||||
|
} else {
|
||||||
|
logger.debug("add header {}: {}", name, value);
|
||||||
|
response.addHeader(name, value);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.info("value is not String. {}", value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.info("headerGroup is null");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 헤더그룹 삭제
|
||||||
|
rootElement.remove(headerGroupElement);
|
||||||
|
|
||||||
|
return document.asXML();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.info("headerGroupName is blank");
|
||||||
|
}
|
||||||
|
|
||||||
|
return (String)resultMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, String[]> assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName,
|
||||||
|
Object requestBytes, Properties prop) {
|
||||||
|
// PathVariable 체크
|
||||||
|
if (StringUtils.equalsAnyIgnoreCase(request.getMethod(), HttpMethod.GET.name(), HttpMethod.DELETE.name())
|
||||||
|
&& StringUtils.isBlank(request.getQueryString())) {
|
||||||
|
try {
|
||||||
|
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||||
|
RequestAction action = ActionFactory.createAction(actionName);
|
||||||
|
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||||
|
String[] keys = action.perform(requestBytes);
|
||||||
|
String requestPath = keys[0];
|
||||||
|
|
||||||
|
// PathVariable 지원 추가
|
||||||
|
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
||||||
|
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
||||||
|
Map<String, String> paramMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath,
|
||||||
|
requestPath);
|
||||||
|
if (paramMap != null && paramMap.size() > 0) {
|
||||||
|
Map<String, String[]> returnMap = new HashMap<>();
|
||||||
|
for (String key : paramMap.keySet()) {
|
||||||
|
if (StringUtils.equalsIgnoreCase(key, "method")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
returnMap.put(key, new String[] { paramMap.get(key) });
|
||||||
|
}
|
||||||
|
|
||||||
|
return returnMap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return request.getParameterMap();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getRewritePath(String extUri, String basePath) {
|
||||||
|
return StringUtils.removeStart(extUri, StringUtils.removeEnd(basePath, "/"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, String> assignPathVariables(HttpServletRequest request, String adptGrpName, String adptName,
|
||||||
|
Object requestBytes, Properties prop) {
|
||||||
|
Map<String, String> variablesMap = null;
|
||||||
|
// QueryString 있을때는 체크(X)
|
||||||
|
if (StringUtils.isBlank(request.getQueryString())) {
|
||||||
|
try {
|
||||||
|
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||||
|
RequestAction action = ActionFactory.createAction(actionName);
|
||||||
|
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||||
|
String[] keys = action.perform(requestBytes);
|
||||||
|
String requestPath = keys[0];
|
||||||
|
|
||||||
|
// PathVariable 지원 추가
|
||||||
|
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
||||||
|
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
||||||
|
variablesMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath, requestPath);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return variablesMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Properties getHeaders(HttpServletRequest request) {
|
||||||
|
Properties prop = new Properties();
|
||||||
|
|
||||||
|
Enumeration<String> headerNames = request.getHeaderNames();
|
||||||
|
while (headerNames.hasMoreElements()) {
|
||||||
|
String key = headerNames.nextElement();
|
||||||
|
// 동일 이름의 헤더가 여러 개인 경우 콤마로 합침 (RFC 7230)
|
||||||
|
Enumeration<String> values = request.getHeaders(key);
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
while (values.hasMoreElements()) {
|
||||||
|
if (sb.length() > 0) sb.append(", ");
|
||||||
|
sb.append(values.nextElement());
|
||||||
|
}
|
||||||
|
prop.setProperty(key, sb.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
return prop;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getExtUri(HttpServletRequest request) {
|
||||||
|
String orgUri = request.getRequestURI().replaceAll(request.getContextPath(), "");
|
||||||
|
String uri = getExtUri(orgUri, 3);
|
||||||
|
if (uri != null && uri.trim().length() > 0) {
|
||||||
|
return "/" + uri;
|
||||||
|
} else {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String getExtUri(String url, int length) {
|
||||||
|
String[] urls = url.split("/");
|
||||||
|
List<String> newUrls = new ArrayList<>();
|
||||||
|
Collections.addAll(newUrls, urls);
|
||||||
|
return StringUtils.join(newUrls.subList(length, urls.length).toArray(), "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Deprecated
|
||||||
|
public void service(String adptGrpName, String adptName, HttpServletRequest request, HttpServletResponse response) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP 요청에서 클라이언트 IP를 추출합니다.
|
||||||
|
* X-Forwarded-For 헤더가 있는 경우 이를 우선적으로 사용하고,
|
||||||
|
* 없는 경우 remoteAddr을 사용합니다.
|
||||||
|
*/
|
||||||
|
private String getClientIp(HttpServletRequest request) {
|
||||||
|
String ipAddress = request.getHeader("X-Forwarded-For");
|
||||||
|
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||||
|
ipAddress = request.getHeader("Proxy-Client-IP");
|
||||||
|
}
|
||||||
|
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||||
|
ipAddress = request.getHeader("WL-Proxy-Client-IP");
|
||||||
|
}
|
||||||
|
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||||
|
ipAddress = request.getHeader("HTTP_CLIENT_IP");
|
||||||
|
}
|
||||||
|
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||||
|
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||||
|
}
|
||||||
|
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||||
|
ipAddress = request.getRemoteAddr();
|
||||||
|
}
|
||||||
|
return ipAddress;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String assignApiId(String adptGrpName, String adptName, Object message, Properties prop,
|
||||||
|
HttpServletRequest request) {
|
||||||
|
String apiId = null;
|
||||||
|
try {
|
||||||
|
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||||
|
RequestAction action = ActionFactory.createAction(actionName);
|
||||||
|
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||||
|
String[] keys = action.perform(message);
|
||||||
|
apiId = keys[0];
|
||||||
|
|
||||||
|
// PathVariable 지원 추가
|
||||||
|
apiId = StandardMessageUtil.getMatchedKey(apiId, actionName);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// // header 에서 확보
|
||||||
|
// String apiId = request.getHeader(HEADER_NAME_API_CODE);
|
||||||
|
// if (StringUtils.isBlank(apiId)) {
|
||||||
|
// // url에서 확보
|
||||||
|
// // /ONLWeb/api/v1/public/getUserInfo.svc/
|
||||||
|
// apiId = request.getRequestURI();
|
||||||
|
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
||||||
|
// apiId = StringUtils.removeEnd(apiId, "/");
|
||||||
|
// // getUserInfo.svc
|
||||||
|
// apiId = StringUtils.substringAfterLast(apiId, "/");
|
||||||
|
// }
|
||||||
|
|
||||||
|
return apiId;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.eactive.eai.agent.inflow;
|
||||||
|
|
||||||
|
import com.eactive.eai.agent.command.Command;
|
||||||
|
import com.eactive.eai.agent.command.CommandException;
|
||||||
|
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
|
||||||
|
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||||
|
import com.eactive.eai.common.util.Logger;
|
||||||
|
import com.eactive.eai.custom.inflow.ClientDualInflowControlManager;
|
||||||
|
|
||||||
|
public class ReloadInflowClientControlCommand extends Command {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public ReloadInflowClientControlCommand() {
|
||||||
|
super("ReloadInflowClientControlCommand");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object execute() throws CommandException {
|
||||||
|
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||||
|
if (logger.isInfo())
|
||||||
|
logger.info(this.name + " is executed");
|
||||||
|
|
||||||
|
if (!(args instanceof String)) {
|
||||||
|
String rspErrorCode = "RECEAIMCM001";
|
||||||
|
String msg = makeException(rspErrorCode, null);
|
||||||
|
if (logger.isError())
|
||||||
|
logger.error(msg);
|
||||||
|
throw new CommandException(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
String keyName = (String) args;
|
||||||
|
try {
|
||||||
|
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
|
||||||
|
if (!(base instanceof ClientDualInflowControlManager)) {
|
||||||
|
throw new IllegalStateException("ClientDualInflowControlManager 가 활성화되지 않았습니다.");
|
||||||
|
}
|
||||||
|
ClientDualInflowControlManager manager = (ClientDualInflowControlManager) base;
|
||||||
|
|
||||||
|
if (keyName != null) {
|
||||||
|
if ("ALL".equals(keyName)) {
|
||||||
|
manager.reloadClient();
|
||||||
|
if (logger.isWarn())
|
||||||
|
logger.warn(this.name + "] all rule Reload.");
|
||||||
|
} else {
|
||||||
|
manager.reloadClient(keyName);
|
||||||
|
if (logger.isWarn())
|
||||||
|
logger.warn(this.name + "] " + keyName + " Reload.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
String rspErrorCode = "RECEAIMCM002";
|
||||||
|
String msg = makeException(rspErrorCode, e);
|
||||||
|
if (logger.isError())
|
||||||
|
logger.error(msg, e);
|
||||||
|
throw new CommandException(msg);
|
||||||
|
}
|
||||||
|
return "success";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package com.eactive.eai.agent.inflow;
|
||||||
|
|
||||||
|
import com.eactive.eai.agent.command.Command;
|
||||||
|
import com.eactive.eai.agent.command.CommandException;
|
||||||
|
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
|
||||||
|
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||||
|
import com.eactive.eai.common.util.Logger;
|
||||||
|
import com.eactive.eai.custom.inflow.ClientDualInflowControlManager;
|
||||||
|
|
||||||
|
public class RemoveInflowClientControlCommand extends Command {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public RemoveInflowClientControlCommand() {
|
||||||
|
super("RemoveInflowClientControlCommand");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object execute() throws CommandException {
|
||||||
|
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||||
|
if (logger.isInfo())
|
||||||
|
logger.info(this.name + " is executed");
|
||||||
|
|
||||||
|
if (!(args instanceof String)) {
|
||||||
|
String rspErrorCode = "RECEAIMCM001";
|
||||||
|
String msg = makeException(rspErrorCode, null);
|
||||||
|
if (logger.isError())
|
||||||
|
logger.error(msg);
|
||||||
|
throw new CommandException(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
String key = (String) args;
|
||||||
|
try {
|
||||||
|
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
|
||||||
|
if (!(base instanceof ClientDualInflowControlManager)) {
|
||||||
|
throw new IllegalStateException("ClientDualInflowControlManager 가 활성화되지 않았습니다.");
|
||||||
|
}
|
||||||
|
ClientDualInflowControlManager manager = (ClientDualInflowControlManager) base;
|
||||||
|
manager.removeClient(key);
|
||||||
|
if (logger.isWarn())
|
||||||
|
logger.warn(this.name + "] " + key + " removed.");
|
||||||
|
} catch (Exception e) {
|
||||||
|
String rspErrorCode = "RECEAIMCM002";
|
||||||
|
String msg = makeException(rspErrorCode, e);
|
||||||
|
if (logger.isError())
|
||||||
|
logger.error(msg, e);
|
||||||
|
throw new CommandException(msg);
|
||||||
|
}
|
||||||
|
return "success";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.eactive.eai.authserver.config;
|
package com.eactive.eai.authserver.config;
|
||||||
|
|
||||||
import java.security.KeyPair;
|
import java.security.KeyPair;
|
||||||
|
import java.security.interfaces.RSAPrivateKey;
|
||||||
|
import java.security.interfaces.RSAPublicKey;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
|
||||||
@@ -35,6 +37,7 @@ import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
|
|||||||
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
|
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
|
||||||
|
|
||||||
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
||||||
|
import com.eactive.eai.authserver.jwt.PssJwtAccessTokenConverter;
|
||||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||||
import com.eactive.eai.authserver.vo.ClientVO;
|
import com.eactive.eai.authserver.vo.ClientVO;
|
||||||
import com.eactive.eai.common.dao.DAOException;
|
import com.eactive.eai.common.dao.DAOException;
|
||||||
@@ -139,9 +142,10 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
|
|||||||
Resource keystore = new ClassPathResource(keystorePath);
|
Resource keystore = new ClassPathResource(keystorePath);
|
||||||
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(keystore, keystorePassword.toCharArray());
|
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(keystore, keystorePassword.toCharArray());
|
||||||
KeyPair keyPair = keyStoreKeyFactory.getKeyPair(keyAlias, keyPassword.toCharArray());
|
KeyPair keyPair = keyStoreKeyFactory.getKeyPair(keyAlias, keyPassword.toCharArray());
|
||||||
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
|
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
|
||||||
converter.setKeyPair(keyPair);
|
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
|
||||||
return converter;
|
|
||||||
|
return new PssJwtAccessTokenConverter(privateKey, publicKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.eactive.eai.authserver.custom;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
|
||||||
|
@SuppressWarnings("serial")
|
||||||
|
public class DJErpOAuth2AccessTokenRequest implements Serializable {
|
||||||
|
|
||||||
|
@JsonProperty("grant_type")
|
||||||
|
private String grantType;
|
||||||
|
@JsonProperty("client_id")
|
||||||
|
private String clientId;
|
||||||
|
@JsonProperty("client_secret")
|
||||||
|
private String clientSecret;
|
||||||
|
private String scope;
|
||||||
|
|
||||||
|
public String getGrantType() {
|
||||||
|
return grantType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGrantType(String grantType) {
|
||||||
|
this.grantType = grantType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getClientId() {
|
||||||
|
return clientId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setClientId(String clientId) {
|
||||||
|
this.clientId = clientId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getClientSecret() {
|
||||||
|
return clientSecret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setClientSecret(String clientSecret) {
|
||||||
|
this.clientSecret = clientSecret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getScope() {
|
||||||
|
return scope;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setScope(String scope) {
|
||||||
|
this.scope = scope;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "DJErpOAuth2AccessTokenRequest [grantType=" + grantType + ", clientId=" + clientId
|
||||||
|
+ ", clientSecret=" + clientSecret + ", scope=" + scope + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package com.eactive.eai.authserver.custom;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||||
|
|
||||||
|
@SuppressWarnings("serial")
|
||||||
|
@JsonInclude(Include.NON_NULL)
|
||||||
|
@JsonPropertyOrder({ "access_token", "token_type", "expires_in", "scope", "jti", "client_id" })
|
||||||
|
public class DJErpOAuth2AccessTokenResponse implements Serializable {
|
||||||
|
|
||||||
|
@JsonProperty("access_token")
|
||||||
|
private String accessToken;
|
||||||
|
@JsonProperty("token_type")
|
||||||
|
private String tokenType;
|
||||||
|
@JsonProperty("expires_in")
|
||||||
|
private Long expiresIn;
|
||||||
|
private String scope;
|
||||||
|
private String jti;
|
||||||
|
@JsonProperty("client_id")
|
||||||
|
private String clientId;
|
||||||
|
|
||||||
|
public String getAccessToken() {
|
||||||
|
return accessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAccessToken(String accessToken) {
|
||||||
|
this.accessToken = accessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTokenType() {
|
||||||
|
return tokenType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTokenType(String tokenType) {
|
||||||
|
this.tokenType = tokenType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getExpiresIn() {
|
||||||
|
return expiresIn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setExpiresIn(Long expiresIn) {
|
||||||
|
this.expiresIn = expiresIn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getScope() {
|
||||||
|
return scope;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setScope(String scope) {
|
||||||
|
this.scope = scope;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getJti() {
|
||||||
|
return jti;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setJti(String jti) {
|
||||||
|
this.jti = jti;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getClientId() {
|
||||||
|
return clientId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setClientId(String clientId) {
|
||||||
|
this.clientId = clientId;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "DJErpOAuth2AccessTokenResponse [accessToken=" + accessToken + ", tokenType=" + tokenType
|
||||||
|
+ ", expiresIn=" + expiresIn + ", scope=" + scope + ", jti=" + jti + ", clientId=" + clientId + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,52 +1,52 @@
|
|||||||
package com.eactive.eai.custom.adapter.handler;
|
//package com.eactive.eai.custom.adapter.handler;
|
||||||
|
//
|
||||||
import java.util.Properties;
|
//import java.util.Properties;
|
||||||
|
//
|
||||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
//import com.eactive.eai.adapter.AdapterGroupVO;
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
//import com.eactive.eai.adapter.AdapterManager;
|
||||||
import com.eactive.eai.adapter.handler.AdapterErrorMessageHandler;
|
//import com.eactive.eai.adapter.handler.AdapterErrorMessageHandler;
|
||||||
import com.eactive.eai.common.message.MessageType;
|
//import com.eactive.eai.common.message.MessageType;
|
||||||
import com.eactive.eai.message.StandardMessage;
|
//import com.eactive.eai.message.StandardMessage;
|
||||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
//import com.eactive.eai.message.manager.StandardMessageManager;
|
||||||
import com.eactive.eai.message.service.InterfaceMapper;
|
//import com.eactive.eai.message.service.InterfaceMapper;
|
||||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
//import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
//import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
//import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
//import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
//
|
||||||
public class LonErrorMsgHandler implements AdapterErrorMessageHandler {
|
//public class LonErrorMsgHandler implements AdapterErrorMessageHandler {
|
||||||
|
//
|
||||||
@Override
|
// @Override
|
||||||
public Object generateNonStandardErrorResponseMessage(String inboudnAdapterGroupName, String inboudnAdapterName,
|
// public Object generateNonStandardErrorResponseMessage(String inboudnAdapterGroupName, String inboudnAdapterName,
|
||||||
Properties callProp, Object outboundRequestData, StandardMessage resStandardMessage) throws Exception{
|
// Properties callProp, Object outboundRequestData, StandardMessage resStandardMessage) throws Exception{
|
||||||
|
//
|
||||||
if(resStandardMessage != null && isErrorMessage(resStandardMessage)) {
|
// if(resStandardMessage != null && isErrorMessage(resStandardMessage)) {
|
||||||
AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(inboudnAdapterGroupName);
|
// AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(inboudnAdapterGroupName);
|
||||||
if(MessageType.JSON.equals(adapterGroupVO.getMessageType())) {
|
// if(MessageType.JSON.equals(adapterGroupVO.getMessageType())) {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
// ObjectMapper objectMapper = new ObjectMapper();
|
||||||
String requestMessage = (String) outboundRequestData;
|
// String requestMessage = (String) outboundRequestData;
|
||||||
JsonNode requestJson = objectMapper.readTree(requestMessage);
|
// JsonNode requestJson = objectMapper.readTree(requestMessage);
|
||||||
String alncInstCd = requestJson.get("dataCmn").get("alncInstCd").asText();
|
// String alncInstCd = requestJson.get("dataCmn").get("alncInstCd").asText();
|
||||||
|
//
|
||||||
ObjectNode responseJson = objectMapper.createObjectNode();
|
// ObjectNode responseJson = objectMapper.createObjectNode();
|
||||||
ObjectNode dataCmnNode = objectMapper.createObjectNode();
|
// ObjectNode dataCmnNode = objectMapper.createObjectNode();
|
||||||
responseJson.set("dataCmn", dataCmnNode);
|
// responseJson.set("dataCmn", dataCmnNode);
|
||||||
dataCmnNode.put("fnclInstCd", "KBK");
|
// dataCmnNode.put("fnclInstCd", "KBK");
|
||||||
dataCmnNode.put("alncInstCd", alncInstCd);
|
// dataCmnNode.put("alncInstCd", alncInstCd);
|
||||||
dataCmnNode.put("tlgrRspnsCd", "0210");
|
// dataCmnNode.put("tlgrRspnsCd", "0210");
|
||||||
|
//
|
||||||
return responseJson.toString();
|
// return responseJson.toString();
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
|
//
|
||||||
return "";
|
// return "";
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
private boolean isErrorMessage(StandardMessage standardMessage) {
|
// private boolean isErrorMessage(StandardMessage standardMessage) {
|
||||||
InterfaceMapper mapper = StandardMessageManager.getInstance().getMapper();
|
// InterfaceMapper mapper = StandardMessageManager.getInstance().getMapper();
|
||||||
String responseType = mapper.getResponseType(standardMessage);
|
// String responseType = mapper.getResponseType(standardMessage);
|
||||||
return STDMessageKeys.RESPONSE_TYPE_CODE_E.equals(responseType);
|
// return STDMessageKeys.RESPONSE_TYPE_CODE_E.equals(responseType);
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
}
|
//}
|
||||||
|
|||||||
+680
@@ -0,0 +1,680 @@
|
|||||||
|
package com.eactive.eai.custom.adapter.http.client.impl;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.ConnectException;
|
||||||
|
import java.net.SocketTimeoutException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.BitSet;
|
||||||
|
import java.util.Formatter;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.ArrayUtils;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.apache.commons.lang3.time.StopWatch;
|
||||||
|
import org.apache.hc.client5.http.classic.HttpClient;
|
||||||
|
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||||
|
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||||
|
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||||
|
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||||
|
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||||
|
import org.apache.hc.client5.http.config.RequestConfig;
|
||||||
|
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||||
|
import org.apache.hc.core5.http.Header;
|
||||||
|
import org.apache.hc.core5.http.HttpStatus;
|
||||||
|
import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
|
||||||
|
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||||
|
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||||
|
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||||
|
import org.json.simple.JSONArray;
|
||||||
|
import org.json.simple.JSONObject;
|
||||||
|
import org.json.simple.JSONValue;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.util.UriComponents;
|
||||||
|
import org.springframework.web.util.UriComponentsBuilder;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||||
|
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||||
|
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
||||||
|
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||||
|
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
||||||
|
import com.eactive.eai.adapter.http.client.impl.HttpClientAdapterServiceRest;
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.impl.HttpAdapterServiceBypass;
|
||||||
|
import com.eactive.eai.common.TransactionContextKeys;
|
||||||
|
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||||
|
import com.eactive.eai.common.util.CommonLib;
|
||||||
|
import com.jayway.jsonpath.DocumentContext;
|
||||||
|
import com.jayway.jsonpath.JsonPath;
|
||||||
|
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||||
|
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||||
|
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||||
|
|
||||||
|
public class HttpClient5AdapterServiceBypass extends HttpClient5AdapterServiceSupport
|
||||||
|
implements HttpClientAdapterServiceKey {
|
||||||
|
public static final String TYPE_BYPASS_REQUEST = "bypassRequest";
|
||||||
|
public static final String REST_OPTION = "REST_OPTION";
|
||||||
|
|
||||||
|
protected boolean doSendUrlFragment = true;
|
||||||
|
protected boolean doHandleCompression = false;
|
||||||
|
protected boolean doForwardIP = false;
|
||||||
|
|
||||||
|
@SuppressWarnings({ "unchecked" })
|
||||||
|
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
||||||
|
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
||||||
|
|
||||||
|
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
||||||
|
|
||||||
|
// ex) $.dataHeader.GW_RSLT_CD
|
||||||
|
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
||||||
|
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
||||||
|
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @formatter:off
|
||||||
|
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
||||||
|
* - type : simpleRequest, variableUrlRequest
|
||||||
|
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
||||||
|
* - method : get, delete, post, put
|
||||||
|
* - contentType : application/json, application/x-www-form-urlencoded
|
||||||
|
* - adapterTokenUseYn: Y, N(default)
|
||||||
|
* ex)
|
||||||
|
* {"type":"variableUrlRequest","extraPath":"/aaa/{userId}","uriVariables":["userId"]}
|
||||||
|
* @formatter:on
|
||||||
|
*/
|
||||||
|
String restOptionData = tempProp.getProperty(REST_OPTION, "{}");
|
||||||
|
|
||||||
|
JSONObject restOptionObject = parseJson(restOptionData);
|
||||||
|
|
||||||
|
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
||||||
|
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
||||||
|
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
||||||
|
}
|
||||||
|
|
||||||
|
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
||||||
|
String inboundRewritePath = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_REWRITE_PATH, "");
|
||||||
|
String inboundQueryString = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_QUERY_STRING, "");
|
||||||
|
Properties inboundHeaders = (Properties) tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
||||||
|
Map<String, String> inboundPathVariables = (Map<String, String>) tempProp
|
||||||
|
.get(HttpAdapterServiceKey.INBOUND_PATH_VARIABLES);
|
||||||
|
|
||||||
|
String restMethod = (String) restOptionObject.get("method");
|
||||||
|
if (StringUtils.isBlank(restMethod)) {
|
||||||
|
restMethod = inboundMethod;
|
||||||
|
}
|
||||||
|
|
||||||
|
String url = getRewriteUrl(vo, inboundRewritePath, inboundQueryString, restOptionObject, inboundPathVariables);
|
||||||
|
if (logger.isDebug()) {
|
||||||
|
logger.debug("HttpClient5AdapterServiceBypass] url = [" + url + "]");
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpClient mclient = this.client;
|
||||||
|
HttpUriRequestBase method = generateMethod(restMethod, url);
|
||||||
|
|
||||||
|
assignRequestHeaders(method, inboundHeaders, tempProp);
|
||||||
|
|
||||||
|
if (hasBody(data, method)) {
|
||||||
|
byte[] bodyBytes;
|
||||||
|
if (data instanceof byte[]) {
|
||||||
|
bodyBytes = (byte[]) data;
|
||||||
|
} else if (data instanceof String) {
|
||||||
|
bodyBytes = ((String) data).getBytes(vo.getEncode());
|
||||||
|
} else {
|
||||||
|
bodyBytes = new byte[0];
|
||||||
|
}
|
||||||
|
method.setEntity(new ByteArrayEntity(bodyBytes, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
String contentType = (String) restOptionObject.get("contentType");
|
||||||
|
if (StringUtils.isBlank(contentType) && inboundHeaders != null) {
|
||||||
|
contentType = getIgnoreCaseProp(inboundHeaders, HttpHeaders.CONTENT_TYPE);
|
||||||
|
contentType = StringUtils.substringBefore(contentType, ";");
|
||||||
|
}
|
||||||
|
|
||||||
|
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
|
||||||
|
configureHttpClient(requestConfigBuilder, vo, method);
|
||||||
|
|
||||||
|
OAuth2AccessTokenVO accessToken = null;
|
||||||
|
if (useAdapterToken) {
|
||||||
|
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||||
|
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
||||||
|
|
||||||
|
// 토큰이 없거나 만료 됐으면 재발급
|
||||||
|
if (accessToken == null || accessToken.isExpired()) {
|
||||||
|
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||||
|
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
||||||
|
oldToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (logger.isDebug()) {
|
||||||
|
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
||||||
|
+ accessToken + "]");
|
||||||
|
}
|
||||||
|
|
||||||
|
setAuthHeaders(method, accessToken);
|
||||||
|
|
||||||
|
if (logger.isDebug()) {
|
||||||
|
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName()
|
||||||
|
+ ") RequestHeader [Authorization=" + method.getFirstHeader("Authorization") + "]");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 로깅 인터셉터에 전달할 컨텍스트 정보 설정
|
||||||
|
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||||
|
HttpContext context = new BasicHttpContext();
|
||||||
|
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||||
|
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
||||||
|
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
||||||
|
Integer logProcessNo = (Integer) tempProp.get(HttpClientAdapterServiceKey.LOG_PROCESS_NO);
|
||||||
|
if (logProcessNo != null && logProcessNo > 0) {
|
||||||
|
context.setAttribute(HttpClientAdapterServiceKey.LOG_PROCESS_NO, logProcessNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
int status = -1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
StopWatch stopWatch = new StopWatch();
|
||||||
|
stopWatch.start();
|
||||||
|
|
||||||
|
byte[] responseMessage = null;
|
||||||
|
Header[] responseHeaders = null;
|
||||||
|
|
||||||
|
if (vo.getTraceLevel() >= 3) {
|
||||||
|
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||||
|
"SEND [Bypass Request..]" + CommonLib.getDumpMessage(data));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (logger.isDebug()) {
|
||||||
|
logger.debug("[method getName]" + method.getMethod());
|
||||||
|
logger.debug("[method getRequestHeaders]" + java.util.Arrays.toString(method.getHeaders()));
|
||||||
|
logger.debug("[method getURI]" + method.getPath());
|
||||||
|
}
|
||||||
|
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||||
|
status = response.getCode();
|
||||||
|
responseHeaders = response.getHeaders();
|
||||||
|
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||||
|
if (logger.isDebug()) {
|
||||||
|
logger.debug("[received status]" + status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (ConnectException e) {
|
||||||
|
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||||
|
logger.debug("HttpClient5AdapterServiceBypass] responseType =" + vo.getResponseType());
|
||||||
|
logger.debug("HttpClient5AdapterServiceBypass] RECV (" + vo.getAdapterGroupName() + ") = "
|
||||||
|
+ CommonLib.getDumpMessage(responseMessage));
|
||||||
|
}
|
||||||
|
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
stopWatch.stop();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @formatter:off
|
||||||
|
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
||||||
|
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
||||||
|
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
||||||
|
*
|
||||||
|
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
||||||
|
* __ex) $.dataHeader.resultCode
|
||||||
|
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
||||||
|
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
||||||
|
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
||||||
|
* @formatter:on
|
||||||
|
*/
|
||||||
|
boolean needReissue = false;
|
||||||
|
|
||||||
|
if (status == 200) {
|
||||||
|
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||||
|
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||||
|
vo.getEncode());
|
||||||
|
}
|
||||||
|
} else if (status >= 400 && status < 500) {
|
||||||
|
if (useAdapterToken) {
|
||||||
|
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||||
|
vo.getEncode());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!needReissue) {
|
||||||
|
// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
|
||||||
|
if (responseMessage == null || responseMessage.length == 0) {
|
||||||
|
String errMsg = String.format(
|
||||||
|
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||||
|
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod, responseMessage);
|
||||||
|
throw new Exception(errMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (status != 200) {
|
||||||
|
responseMessage = responseMessage != null ? responseMessage : new byte[0];
|
||||||
|
// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
|
||||||
|
if (responseMessage.length == 0) {
|
||||||
|
String errMsg = String.format(
|
||||||
|
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||||
|
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod, responseMessage);
|
||||||
|
throw new Exception(errMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (useAdapterToken) {
|
||||||
|
if (responseMessage == null) {
|
||||||
|
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
||||||
|
}
|
||||||
|
|
||||||
|
// OAuth 토큰 재요청 코드 확인
|
||||||
|
if (needReissue) {
|
||||||
|
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||||
|
logger.debug("HttpClient5AdapterServiceBypass] retry access token response code = ["
|
||||||
|
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
||||||
|
+ "]");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 토큰 재발급
|
||||||
|
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||||
|
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||||
|
OAuth2AccessTokenVO newAccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||||
|
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||||
|
method.setHeader("Authorization", newAccessToken.getAuthorization());
|
||||||
|
setAuthHeaders(method, newAccessToken);
|
||||||
|
|
||||||
|
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||||
|
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName()
|
||||||
|
+ ") RETRY TOKEN = [" + newAccessToken + "]");
|
||||||
|
}
|
||||||
|
|
||||||
|
try (CloseableHttpResponse retryResponse = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||||
|
status = retryResponse.getCode();
|
||||||
|
responseHeaders = retryResponse.getHeaders();
|
||||||
|
responseMessage = EntityUtils.toByteArray(retryResponse.getEntity());
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new Exception("retry excuteMethod Exception = " + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status != 200) {
|
||||||
|
responseMessage = responseMessage != null ? responseMessage : new byte[0];
|
||||||
|
if (responseMessage.length == 0) {
|
||||||
|
String errMsg = String.format(
|
||||||
|
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||||
|
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod,
|
||||||
|
responseMessage);
|
||||||
|
throw new Exception(errMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||||
|
logger.debug("HttpClient5AdapterServiceBypass] RETRY responseType =" + vo.getResponseType());
|
||||||
|
logger.debug("HttpClient5AdapterServiceBypass] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
||||||
|
+ CommonLib.getDumpMessage(responseMessage));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vo.getTraceLevel() >= 3) {
|
||||||
|
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||||
|
"RECV [Bypass Request..]" + CommonLib.getDumpMessage(responseMessage));
|
||||||
|
}
|
||||||
|
// 응답 Content-Type charset 기반 인코딩 결정, 없으면 어댑터 encoding 사용
|
||||||
|
String responseEncode = vo.getEncode();
|
||||||
|
if (responseHeaders != null) {
|
||||||
|
for (Header header : responseHeaders) {
|
||||||
|
if (StringUtils.equalsIgnoreCase(header.getName(), HttpHeaders.CONTENT_TYPE)) {
|
||||||
|
try {
|
||||||
|
MediaType mediaType = MediaType.parseMediaType(header.getValue());
|
||||||
|
if (mediaType.getCharset() != null) {
|
||||||
|
responseEncode = mediaType.getCharset().name();
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assignRelayDataToInbound(tempProp, responseHeaders, status);
|
||||||
|
return responseMessage != null ? new String(responseMessage, responseEncode) : "";
|
||||||
|
} catch (SocketTimeoutException ste) {
|
||||||
|
if (vo.getTraceLevel() >= 3) {
|
||||||
|
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||||
|
"HttpClient5AdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||||
|
+ ste.toString(),
|
||||||
|
ste);
|
||||||
|
}
|
||||||
|
logger.error("HttpClient5AdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||||
|
+ ste.toString(), ste);
|
||||||
|
throw ste;
|
||||||
|
} catch (ConnectException ce) {
|
||||||
|
if (vo.getTraceLevel() >= 3) {
|
||||||
|
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||||
|
"HttpClient5AdapterServiceBypass] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||||
|
+ ce.toString(),
|
||||||
|
ce);
|
||||||
|
}
|
||||||
|
logger.error("HttpClient5AdapterServiceBypass] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||||
|
+ ce.toString(), ce);
|
||||||
|
throw ce;
|
||||||
|
} catch (Exception e) {
|
||||||
|
if (vo.getTraceLevel() >= 3) {
|
||||||
|
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
||||||
|
}
|
||||||
|
logger.error(
|
||||||
|
"HttpClient5AdapterServiceBypass] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
||||||
|
e);
|
||||||
|
throw e;
|
||||||
|
} finally {
|
||||||
|
if (status != HttpStatus.SC_OK) {
|
||||||
|
String[] msgArgs = new String[1];
|
||||||
|
msgArgs[0] = String.valueOf(status);
|
||||||
|
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
||||||
|
if (logger.isDebug()) {
|
||||||
|
logger.debug(resMsg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasBody(Object data, HttpUriRequestBase method) {
|
||||||
|
if (data == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// GET, DELETE는 표준 HTTP에서 body를 지원하지 않음
|
||||||
|
return method instanceof HttpPost || method instanceof HttpPut;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpUriRequestBase generateMethod(String restMethod, String url) {
|
||||||
|
switch (HttpMethodType.getValue(restMethod)) {
|
||||||
|
case GET:
|
||||||
|
return new HttpGet(url);
|
||||||
|
case DELETE:
|
||||||
|
return new HttpDelete(url);
|
||||||
|
case POST:
|
||||||
|
return new HttpPost(url);
|
||||||
|
case PUT:
|
||||||
|
return new HttpPut(url);
|
||||||
|
default:
|
||||||
|
return new HttpPost(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getRewriteUrl(HttpClientAdapterVO vo, String inboundRewritePath, String queryString,
|
||||||
|
JSONObject restOptionObject, Map<String, String> inboundPathVariables) {
|
||||||
|
String fragment = null;
|
||||||
|
if (StringUtils.isNotBlank(queryString)) {
|
||||||
|
int fragIdx = queryString.indexOf('#');
|
||||||
|
if (fragIdx >= 0) {
|
||||||
|
fragment = queryString.substring(fragIdx + 1);
|
||||||
|
queryString = queryString.substring(0, fragIdx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String restExtraPath = (String) restOptionObject.get("extraPath");
|
||||||
|
if (StringUtils.isBlank(restExtraPath)) {
|
||||||
|
StringBuilder uri = new StringBuilder(500);
|
||||||
|
String baseUrl = StringUtils.removeEnd(vo.getUrl(), "/");
|
||||||
|
String rewritePath = inboundRewritePath != null && !inboundRewritePath.startsWith("/")
|
||||||
|
? "/" + inboundRewritePath : inboundRewritePath;
|
||||||
|
uri.append(baseUrl).append(StringUtils.defaultString(rewritePath));
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(queryString)) {
|
||||||
|
uri.append('?');
|
||||||
|
uri.append(encodeUriQuery(queryString, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (doSendUrlFragment && fragment != null) {
|
||||||
|
uri.append('#');
|
||||||
|
uri.append(encodeUriQuery(fragment, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
return uri.toString();
|
||||||
|
} else {
|
||||||
|
String type = (String) restOptionObject.get("type");
|
||||||
|
String url = getUrl(vo.getUrl(), restExtraPath);
|
||||||
|
|
||||||
|
if (StringUtils.equalsIgnoreCase(type, HttpClientAdapterServiceRest.TYPE_VARIABLE_URL_REQUEST)) {
|
||||||
|
inboundPathVariables = mergeInboundPathVariables(inboundPathVariables, queryString);
|
||||||
|
List<String> urlVariableValueList = new ArrayList<>();
|
||||||
|
JSONArray uriVariables = (JSONArray) restOptionObject.get("uriVariables");
|
||||||
|
if (uriVariables != null && !uriVariables.isEmpty() && inboundPathVariables != null
|
||||||
|
&& !inboundPathVariables.isEmpty()) {
|
||||||
|
for (Object tempObject : uriVariables) {
|
||||||
|
String urlVaribleId = (String) tempObject;
|
||||||
|
String uriVariableValue = inboundPathVariables.get(urlVaribleId);
|
||||||
|
urlVariableValueList.add(uriVariableValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!urlVariableValueList.isEmpty()) {
|
||||||
|
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
||||||
|
Object[] urls = urlVariableValueList.toArray();
|
||||||
|
url = uriComponents.expand(urls).toUriString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (StringUtils.isNotBlank(queryString)) {
|
||||||
|
url += "?" + encodeUriQuery(queryString, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (doSendUrlFragment && fragment != null) {
|
||||||
|
url += "#" + encodeUriQuery(fragment, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, String> mergeInboundPathVariables(Map<String, String> inboundPathVariables,
|
||||||
|
String queryString) {
|
||||||
|
if (StringUtils.isBlank(queryString)) {
|
||||||
|
return inboundPathVariables;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inboundPathVariables == null) {
|
||||||
|
inboundPathVariables = new LinkedHashMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
String[] pairs = queryString.split("&");
|
||||||
|
for (String pair : pairs) {
|
||||||
|
int idx = pair.indexOf("=");
|
||||||
|
inboundPathVariables.put(pair.substring(0, idx), pair.substring(idx + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
return inboundPathVariables;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getUrl(String baseUrl, String extraPath) {
|
||||||
|
if (StringUtils.isBlank(extraPath)) {
|
||||||
|
return baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
||||||
|
return extraPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
String targetUrl = baseUrl;
|
||||||
|
if (!targetUrl.endsWith("/")) {
|
||||||
|
targetUrl += "/";
|
||||||
|
}
|
||||||
|
if (extraPath.startsWith("/")) {
|
||||||
|
targetUrl += extraPath.substring(1);
|
||||||
|
} else {
|
||||||
|
targetUrl += extraPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
return targetUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected CharSequence encodeUriQuery(CharSequence in, boolean encodePercent) {
|
||||||
|
StringBuilder outBuf = null;
|
||||||
|
Formatter formatter = null;
|
||||||
|
for (int i = 0; i < in.length(); i++) {
|
||||||
|
char c = in.charAt(i);
|
||||||
|
boolean escape = true;
|
||||||
|
if (c < 128) {
|
||||||
|
if (asciiQueryChars.get(c) && !(encodePercent && c == '%')) {
|
||||||
|
escape = false;
|
||||||
|
}
|
||||||
|
} else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {
|
||||||
|
escape = false;
|
||||||
|
}
|
||||||
|
if (!escape) {
|
||||||
|
if (outBuf != null)
|
||||||
|
outBuf.append(c);
|
||||||
|
} else {
|
||||||
|
if (outBuf == null) {
|
||||||
|
outBuf = new StringBuilder(in.length() + 5 * 3);
|
||||||
|
outBuf.append(in, 0, i);
|
||||||
|
formatter = new Formatter(outBuf);
|
||||||
|
}
|
||||||
|
formatter.format("%%%02X", (int) c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return outBuf != null ? outBuf : in;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static final BitSet asciiQueryChars;
|
||||||
|
static {
|
||||||
|
char[] c_unreserved = "_-!.~'()*".toCharArray();
|
||||||
|
char[] c_punct = ",;:$&+=".toCharArray();
|
||||||
|
char[] c_reserved = "/@".toCharArray();
|
||||||
|
asciiQueryChars = new BitSet(128);
|
||||||
|
for (char c = 'a'; c <= 'z'; c++)
|
||||||
|
asciiQueryChars.set(c);
|
||||||
|
for (char c = 'A'; c <= 'Z'; c++)
|
||||||
|
asciiQueryChars.set(c);
|
||||||
|
for (char c = '0'; c <= '9'; c++)
|
||||||
|
asciiQueryChars.set(c);
|
||||||
|
for (char c : c_unreserved)
|
||||||
|
asciiQueryChars.set(c);
|
||||||
|
for (char c : c_punct)
|
||||||
|
asciiQueryChars.set(c);
|
||||||
|
for (char c : c_reserved)
|
||||||
|
asciiQueryChars.set(c);
|
||||||
|
asciiQueryChars.set('%');
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assignRelayDataToInbound(Properties prop, Header[] responseHeaders, int status) {
|
||||||
|
Properties headerProp = new Properties();
|
||||||
|
if (responseHeaders != null) {
|
||||||
|
for (Header header : responseHeaders) {
|
||||||
|
String name = header.getName();
|
||||||
|
String value = header.getValue();
|
||||||
|
String existing = headerProp.getProperty(name);
|
||||||
|
if (existing != null) {
|
||||||
|
// 동일 이름의 헤더가 여러 개인 경우 콤마로 합침 (RFC 7230)
|
||||||
|
headerProp.put(name, existing + ", " + value);
|
||||||
|
} else {
|
||||||
|
headerProp.put(name, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
headerProp.put(HttpAdapterServiceBypass.HTTP_STATUS, String.valueOf(status));
|
||||||
|
|
||||||
|
Map<String, Object> map = new HashMap<String, Object>();
|
||||||
|
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, headerProp);
|
||||||
|
|
||||||
|
prop.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
||||||
|
method.setHeader("Authorization",
|
||||||
|
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||||
|
String encode) {
|
||||||
|
if (responseMessage == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
||||||
|
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
||||||
|
if (StringUtils.isBlank(responseCode)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
||||||
|
return ArrayUtils.contains(arr, responseCode);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("HttpClient5AdapterServiceBypass] checkTokenRetry error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assignRequestHeaders(HttpUriRequestBase method, Properties headerProp, Properties inProp) {
|
||||||
|
if (headerProp == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Entry<Object, Object> e : headerProp.entrySet()) {
|
||||||
|
String key = (String) e.getKey();
|
||||||
|
String value = (String) e.getValue();
|
||||||
|
|
||||||
|
if (StringUtils.equalsAnyIgnoreCase(key, HttpAdapterServiceBypass.HOP_BY_HOP_HEADERS)
|
||||||
|
|| StringUtils.equalsIgnoreCase(key, HttpHeaders.CONTENT_LENGTH)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (doHandleCompression && StringUtils.equalsIgnoreCase(key, HttpHeaders.ACCEPT_ENCODING)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
method.addHeader(key, value);
|
||||||
|
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("Request Header :" + key + "=[" + value + "]");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (doForwardIP) {
|
||||||
|
String forHeaderName = "X-Forwarded-For";
|
||||||
|
String forHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_REMOTE_ADDR);
|
||||||
|
if (StringUtils.isNotBlank(forHeader)) {
|
||||||
|
String existingForHeader = headerProp.getProperty(forHeaderName);
|
||||||
|
if (existingForHeader != null) {
|
||||||
|
forHeader = existingForHeader + ", " + forHeader;
|
||||||
|
}
|
||||||
|
method.addHeader(forHeaderName, forHeader);
|
||||||
|
}
|
||||||
|
|
||||||
|
String protoHeaderName = "X-Forwarded-Proto";
|
||||||
|
String protoHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_SCHEME);
|
||||||
|
if (StringUtils.isNotBlank(protoHeader)) {
|
||||||
|
method.addHeader(protoHeaderName, protoHeader);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("deprecation")
|
||||||
|
private JSONObject parseJson(String message) throws Exception {
|
||||||
|
if (message == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (JSONObject) JSONValue.parse(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final String getIgnoreCaseProp(Properties prop, String key) {
|
||||||
|
if (prop == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Entry<Object, Object> e : prop.entrySet()) {
|
||||||
|
if (StringUtils.equalsIgnoreCase(key, (String) e.getKey())) {
|
||||||
|
return (String) e.getValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package com.eactive.eai.custom.adapter.http.client.impl.filter;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.http.client.impl.filter.HttpClientAdapterFilter;
|
||||||
|
import com.eactive.eai.adapter.http.client.impl.filter.OutCryptoFilter;
|
||||||
|
/**
|
||||||
|
* 제주은행 Open API 기본 암복호화 필더
|
||||||
|
*/
|
||||||
|
public class EncFieldOutCryptoFilter implements HttpClientAdapterFilter {
|
||||||
|
|
||||||
|
private final OutCryptoFilter filter = new OutCryptoFilter();
|
||||||
|
|
||||||
|
protected Properties setProp(Properties p) {
|
||||||
|
p.setProperty(OutCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
|
||||||
|
p.setProperty(OutCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
||||||
|
throws Exception {
|
||||||
|
return filter.doPreFilter(adptGrpName, adptName, prop, message, setProp(tempProp));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
||||||
|
Properties tempProp) throws Exception {
|
||||||
|
return filter.doPostFilter(adptGrpName, adptName, prop, message, setProp(tempProp));
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package com.eactive.eai.custom.adapter.http.client.impl.filter;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.http.client.impl.filter.OutCryptoFilter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 카카오뱅크 암복호화에 맟추어 커스텀
|
||||||
|
*/
|
||||||
|
public class KakaobankEncFieldOutCryptoFilter extends EncFieldOutCryptoFilter {
|
||||||
|
|
||||||
|
protected Properties setProp(Properties p) {
|
||||||
|
p.setProperty(OutCryptoFilter.PROP_DEC_FROM_PATH, "/encrypted_data");
|
||||||
|
p.setProperty(OutCryptoFilter.PROP_ENC_TO_PATH, "/encrypted_data");
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.eactive.eai.custom.adapter.http.client.impl.filter;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.http.client.impl.filter.OutCryptoFilter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 토스 암복호화에 맟추어 커스텀
|
||||||
|
*/
|
||||||
|
public class TossEncFieldOutCryptoFilter extends EncFieldOutCryptoFilter {
|
||||||
|
|
||||||
|
protected Properties setProp(Properties p) {
|
||||||
|
p.setProperty(OutCryptoFilter.PROP_DEC_FROM_PATH, "/encrypted_data");
|
||||||
|
p.setProperty(OutCryptoFilter.PROP_ENC_TO_PATH, "/encrypted_data");
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.eactive.eai.custom.adapter.http.client.impl.filter;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.http.client.impl.filter.OutCryptoFilter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 토스뱅크 암복호화에 맟추어 커스텀
|
||||||
|
*/
|
||||||
|
public class TossbankEncFieldOutCryptoFilter extends EncFieldOutCryptoFilter {
|
||||||
|
|
||||||
|
protected Properties setProp(Properties p) {
|
||||||
|
p.setProperty(OutCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
|
||||||
|
p.setProperty(OutCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
}
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
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.HttpAdapterServiceKey;
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
||||||
|
import com.eactive.eai.common.security.keyderiv.KeyDerivationStrategy;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 더존 연동용 수신 암복호화 필터.
|
||||||
|
*
|
||||||
|
* {@code HttpAdapterServiceKey.INBOUND_HEADER} 프로퍼티로 전달된 수신 헤더 Map에서
|
||||||
|
* 두 가지 컨텍스트 값을 추출하여 {@link InCryptoFilter}에 위임한다.
|
||||||
|
*
|
||||||
|
* x-emp-nm : GCM AAD 값 ({@code CRYPTO_AAD_HEADER} 프로퍼티에 설정)
|
||||||
|
* x-chnl-nm : DYNAMIC 키 도출 컨텍스트 ({@code contextKey} 프로퍼티에 설정)
|
||||||
|
* → {@code HsmContextSha256KeyDerivationStrategy}가 채널명 기반으로 키를 동적 생성
|
||||||
|
*
|
||||||
|
* 암복호화 필드 경로: {@code /encryptedData}
|
||||||
|
*
|
||||||
|
* 필터 타입 등록 (FQCN):
|
||||||
|
* com.eactive.eai.custom.adapter.http.dynamic.filter.DouzoneEncFieldInCryptoFilter
|
||||||
|
*/
|
||||||
|
public class DouzoneEncFieldInCryptoFilter implements HttpAdapterFilter {
|
||||||
|
|
||||||
|
private final InCryptoFilter filter = new InCryptoFilter();
|
||||||
|
|
||||||
|
protected Properties setProp(Properties p) {
|
||||||
|
p.setProperty(InCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
|
||||||
|
p.setProperty(InCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setContext(Properties tempProp) {
|
||||||
|
Properties inboundHeaders = (Properties) tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
||||||
|
String empNm = inboundHeaders.getProperty("x-emp-nm");
|
||||||
|
tempProp.setProperty(InCryptoFilter.PROP_AAD_HEADER, empNm);
|
||||||
|
|
||||||
|
String chnlNm = inboundHeaders.getProperty("x-chnl-nm");
|
||||||
|
tempProp.setProperty(KeyDerivationStrategy.PARAM_CONTEXT_KEY, chnlNm);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||||
|
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||||
|
setContext(prop);
|
||||||
|
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 {
|
||||||
|
setContext(prop);
|
||||||
|
return filter.doPostFilter(adptGrpName, adptName, resultMessage, setProp(prop), request, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+40
@@ -0,0 +1,40 @@
|
|||||||
|
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* InCryptoFilter를 멤버변수로 관리하는 HttpAdapterFilter 구현체.
|
||||||
|
*
|
||||||
|
* 멤버변수에 세팅된 값을 Properties로 변환하여 {@link InCryptoFilter}에 위임한다.
|
||||||
|
* 값이 blank인 멤버변수는 Properties에 포함하지 않으며, InCryptoFilter의 기본값이 적용된다.
|
||||||
|
*/
|
||||||
|
public class EncFieldInCryptoFilter implements HttpAdapterFilter {
|
||||||
|
|
||||||
|
private final InCryptoFilter filter = new InCryptoFilter();
|
||||||
|
|
||||||
|
@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);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Properties setProp(Properties p) {
|
||||||
|
p.setProperty(InCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
|
||||||
|
p.setProperty(InCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 카카오뱅크 암복호화에 맟추어 커스텀 필요
|
||||||
|
*/
|
||||||
|
public class KakaobankEncFieldInCryptoFilter extends EncFieldInCryptoFilter {
|
||||||
|
|
||||||
|
protected Properties setProp(Properties p) {
|
||||||
|
p.setProperty(InCryptoFilter.PROP_DEC_FROM_PATH, "/encrypted_data");
|
||||||
|
p.setProperty(InCryptoFilter.PROP_ENC_TO_PATH, "/encrypted_data");
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 토스 암복호화에 맟추어 커스텀 필요
|
||||||
|
*/
|
||||||
|
public class TossEncFieldInCryptoFilter extends EncFieldInCryptoFilter {
|
||||||
|
|
||||||
|
protected Properties setProp(Properties p) {
|
||||||
|
p.setProperty(InCryptoFilter.PROP_DEC_FROM_PATH, "/encrypted_data");
|
||||||
|
p.setProperty(InCryptoFilter.PROP_ENC_TO_PATH, "/encrypted_data");
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 토스뱅크 암복호화에 맟추어 커스텀 필요
|
||||||
|
*/
|
||||||
|
public class TossbankEncFieldInCryptoFilter extends EncFieldInCryptoFilter {
|
||||||
|
|
||||||
|
protected Properties setProp(Properties p) {
|
||||||
|
p.setProperty(InCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
|
||||||
|
p.setProperty(InCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
package com.eactive.eai.custom.common.security.keyderiv;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import javax.crypto.SecretKey;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.hsm.HsmCryptoService;
|
||||||
|
import com.eactive.eai.common.security.keyderiv.DerivedKey;
|
||||||
|
import com.eactive.eai.common.security.keyderiv.KeyDerivationStrategy;
|
||||||
|
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HSM 마스터키 + 런타임 컨텍스트값을 연결(concatenate)한 뒤 SHA-256 해싱으로 키를 도출하는 전략.
|
||||||
|
* SHA-256 출력은 항상 32바이트(AES-256)이므로 별도 keyLength 파라미터가 불필요하다.
|
||||||
|
*
|
||||||
|
* key_deriv_params (JSON) 예시:
|
||||||
|
* {
|
||||||
|
* "hsmKeyAlias" : "MASTER_KEY_AES",
|
||||||
|
* "contextKey" : "X-Api-Group-Seq" -- runtimeContext에서 꺼낼 키 이름
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
public class HsmContextSha256KeyDerivationStrategy implements KeyDerivationStrategy {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext) throws Exception {
|
||||||
|
String hsmKeyAlias = required(params, PARAM_HSM_KEY_ALIAS);
|
||||||
|
String contextKey = required(params, PARAM_CONTEXT_KEY);
|
||||||
|
|
||||||
|
SecretKey masterKey = hsmCryptoService().getSecretKey(hsmKeyAlias);
|
||||||
|
byte[] masterKeyBytes = masterKey.getEncoded();
|
||||||
|
byte[] contextBytes = runtimeContext.getOrDefault(contextKey, "")
|
||||||
|
.getBytes(StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
byte[] combined = new byte[masterKeyBytes.length + contextBytes.length];
|
||||||
|
System.arraycopy(masterKeyBytes, 0, combined, 0, masterKeyBytes.length);
|
||||||
|
System.arraycopy(contextBytes, 0, combined, masterKeyBytes.length, contextBytes.length);
|
||||||
|
|
||||||
|
byte[] derived = MessageDigest.getInstance("SHA-256").digest(combined);
|
||||||
|
return new DerivedKey(derived, derived);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String buildCacheKey(String cryptoName, Map<String, String> params, Map<String, String> runtimeContext) {
|
||||||
|
String contextKey = params.getOrDefault(PARAM_CONTEXT_KEY, "");
|
||||||
|
String contextValue = runtimeContext.getOrDefault(contextKey, "");
|
||||||
|
return cryptoName + ":" + contextValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String required(Map<String, String> params, String key) {
|
||||||
|
String value = params.get(key);
|
||||||
|
if (value == null || value.trim().isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("key_deriv_params 필수값 누락: " + key);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HsmCryptoService hsmCryptoService() {
|
||||||
|
return ApplicationContextProvider.getContext().getBean(HsmCryptoService.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
package com.eactive.eai.custom.common.security.keyderiv;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import javax.xml.bind.DatatypeConverter;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.security.keyderiv.DerivedKey;
|
||||||
|
import com.eactive.eai.common.security.keyderiv.strategy.BaseHsmKeyDerivationStrategy;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HSM에서 키와 IV를 각각 가져오는 전략.
|
||||||
|
* IV는 HSM에서 가져온 바이트 배열을 hex 문자열로 변환한 뒤 substring(32, 64)를 적용하여 사용한다.
|
||||||
|
* (32바이트 HSM 키 → 64자 hex → substring(32,64) → 16바이트 IV)
|
||||||
|
*
|
||||||
|
* key_deriv_params (JSON) 예시:
|
||||||
|
* { "hsmKeyAlias" : "MASTER_KEY_AES", "hsmIvAlias" : "MASTER_IV_AES" }
|
||||||
|
*/
|
||||||
|
public class HsmKeyAndIvSliceDerivationStrategy extends BaseHsmKeyDerivationStrategy {
|
||||||
|
|
||||||
|
private static final int IV_HEX_OFFSET = 32;
|
||||||
|
private static final int IV_HEX_END = 64;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext) throws Exception {
|
||||||
|
byte[] keyBytes = super.getHsmKey(params);
|
||||||
|
byte[] rawIv = super.getHsmIv(params);
|
||||||
|
String ivHex = DatatypeConverter.printHexBinary(rawIv);
|
||||||
|
if (ivHex.length() < IV_HEX_END) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"hsmIvAlias hex 길이 부족: 최소 " + IV_HEX_END + "자 필요, 실제=" + ivHex.length()
|
||||||
|
+ " (" + rawIv.length + "바이트)");
|
||||||
|
}
|
||||||
|
byte[] iv = DatatypeConverter.parseHexBinary(ivHex.substring(IV_HEX_OFFSET, IV_HEX_END));
|
||||||
|
return new DerivedKey(keyBytes, keyBytes, iv);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String buildCacheKey(String cryptoName, Map<String, String> params, Map<String, String> runtimeContext) {
|
||||||
|
return cryptoName;
|
||||||
|
}
|
||||||
|
}
|
||||||
+104
@@ -0,0 +1,104 @@
|
|||||||
|
package com.eactive.eai.custom.inbound.action;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||||
|
import com.eactive.eai.adapter.AdapterManager;
|
||||||
|
import com.eactive.eai.adapter.Keys;
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.impl.HttpAdapterServiceRest;
|
||||||
|
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||||
|
import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||||
|
import com.eactive.eai.common.util.MessageKeyExtractor;
|
||||||
|
import com.eactive.eai.inbound.action.ActionException;
|
||||||
|
import com.eactive.eai.inbound.action.RequestActionSupport;
|
||||||
|
|
||||||
|
public class RestAdapterMethodUrlFallbackRequestAction extends RequestActionSupport {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. 기능 : Inbound Adapter를 통해 전달받은 비표준메시지에서 표준메시지를 생성하기 위한 키값을 추출
|
||||||
|
* 2. 처리 개요 :
|
||||||
|
* - TYPE_HTTP_CUSTOM / TYPE_REST: 전체 URI로 키를 먼저 조회하고,
|
||||||
|
* 없으면 뒤 경로를 하나씩 제거하면서 일치하는 키를 탐색한다.
|
||||||
|
* - 그 외: MessageKeyExtractor를 통해 추출
|
||||||
|
*
|
||||||
|
* @param message Object 타입의 요청메시지
|
||||||
|
* @return String 비표준메시지의 메시지키값
|
||||||
|
**/
|
||||||
|
public String[] perform(Object message) throws ActionException {
|
||||||
|
String[] key = null;
|
||||||
|
|
||||||
|
AdapterManager adapterManager = AdapterManager.getInstance();
|
||||||
|
AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(adapterGroupName);
|
||||||
|
String adptGrpName = adptGrpVO.getName();
|
||||||
|
|
||||||
|
if (StringUtils.equals(adptGrpVO.getType(), Keys.TYPE_HTTP_CUSTOM)
|
||||||
|
|| StringUtils.equals(adptGrpVO.getType(), Keys.TYPE_REST)) {
|
||||||
|
try {
|
||||||
|
String requestMethod = prop
|
||||||
|
.getProperty(HttpAdapterServiceRest.PROPERTIES_NAME_HTTP_REQUEST_METHOD);
|
||||||
|
|
||||||
|
// /api/v1/public/getUserInfo.svc
|
||||||
|
String inboundUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
|
||||||
|
String apiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH);
|
||||||
|
|
||||||
|
// /getUserInfo.svc
|
||||||
|
String apiUri = org.apache.commons.lang.StringUtils.removeStart(inboundUri, apiPath);
|
||||||
|
|
||||||
|
Set<String> allKeys = new HashSet<>(Arrays.asList(
|
||||||
|
STDMessageManager.getInstance().getAllSTDMessageKeys()));
|
||||||
|
|
||||||
|
// 전체 URI부터 시작해서 뒤 경로를 하나씩 제거하며 일치하는 키를 탐색
|
||||||
|
String searchUri = apiUri;
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
String candidateKey = adptGrpName + ":" + requestMethod + "|"
|
||||||
|
+ StringUtils.removeStart(searchUri, "/");
|
||||||
|
if (allKeys.contains(candidateKey)) {
|
||||||
|
return new String[] { candidateKey };
|
||||||
|
}
|
||||||
|
String shortened = StringUtils.substringBeforeLast(searchUri, "/");
|
||||||
|
if (StringUtils.isBlank(shortened)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
searchUri = shortened;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 일치하는 키가 없으면 원래 키로 fallback
|
||||||
|
String apiKey = adptGrpName + ":" + requestMethod + "|"
|
||||||
|
+ StringUtils.removeStart(apiUri, "/");
|
||||||
|
return new String[] { apiKey };
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new ActionException(ExceptionUtil.getErrorCode(e, "RECEAIIRA001"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message instanceof byte[]) {
|
||||||
|
try {
|
||||||
|
key = MessageKeyExtractor.getMessageKeyValueForRest(this.adapterGroupName, message, prop, "url", true);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new ActionException(ExceptionUtil.getErrorCode(e, "RECEAIIRA001"));
|
||||||
|
}
|
||||||
|
if (logger.isDebug())
|
||||||
|
logger.debug(adapterName + "] received data >> [" + new String((byte[]) message) + "]");
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
key = MessageKeyExtractor.getMessageKeyValueForRest(this.adapterGroupName, message, prop, "url", true);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new ActionException(ExceptionUtil.getErrorCode(e, "RECEAIIRA001"));
|
||||||
|
}
|
||||||
|
if (logger.isDebug())
|
||||||
|
logger.debug(adapterName + "] received data >> [" + message + "]");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < key.length; i++) {
|
||||||
|
key[i] = adptGrpName.trim() + key[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
package com.eactive.eai.custom.inbound.processor;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
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.DualBucket;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
|
||||||
|
import com.eactive.eai.common.message.EAIMessage;
|
||||||
|
import com.eactive.eai.common.property.PropManager;
|
||||||
|
import com.eactive.eai.common.util.Logger;
|
||||||
|
import com.eactive.eai.custom.inflow.ClientDualBucket;
|
||||||
|
import com.eactive.eai.inbound.processor.ProcessVO;
|
||||||
|
import com.eactive.eai.inbound.processor.RequestProcessor;
|
||||||
|
import com.eactive.eai.message.StandardItem;
|
||||||
|
import com.eactive.eai.message.StandardMessage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 어댑터/인터페이스/클라이언트 유량제어 차단 시 어느 버킷(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 {
|
||||||
|
|
||||||
|
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void afterFoundEaiMessage(EAIMessage eaiMsg, ProcessVO vo, Properties prop) {
|
||||||
|
logger.debug("DJBRequestProcessor interface found.");
|
||||||
|
try {
|
||||||
|
this.resolveStandardHeaderMapping(eaiMsg, prop);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.warn("DJBRequestProcessor header set failed.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void resolveStandardHeaderMapping(EAIMessage eaiMsg, Properties prop) {
|
||||||
|
StandardMessage standardMessage = eaiMsg.getStandardMessage();
|
||||||
|
HashMap<String, String> headerMapping = getPropertyMap("DJB_IN_HTTHEAD_STDHEAD_MAPPING", eaiMsg.getSngSysItfTp());
|
||||||
|
|
||||||
|
for (Entry<String, String> entry : headerMapping.entrySet()) {
|
||||||
|
String stdHeaderPath = entry.getKey();
|
||||||
|
int dotIdx = stdHeaderPath.indexOf('.');
|
||||||
|
if(dotIdx > 0) {
|
||||||
|
String firstPath = stdHeaderPath.substring(0, dotIdx);
|
||||||
|
StandardItem topLevelItem = standardMessage.findItem(firstPath);
|
||||||
|
topLevelItem.setHidden(false);
|
||||||
|
}
|
||||||
|
StandardItem item = standardMessage.findItem(entry.getKey());
|
||||||
|
|
||||||
|
String value = resolveNestedValue(prop, entry.getValue());
|
||||||
|
if (item != null && value != null)
|
||||||
|
item.setValue(value);
|
||||||
|
else
|
||||||
|
logger.debug("header mapping item not found : {} ", entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private HashMap<String, String> getPropertyMap(String propertyGroupName, String prefix) {
|
||||||
|
Properties prop = PropManager.getInstance().getProperties(propertyGroupName);
|
||||||
|
Set<String> keys = prop.stringPropertyNames();
|
||||||
|
HashMap<String, String> tmpToJsonArrayInterface = new HashMap<>();
|
||||||
|
for (String key : keys) {
|
||||||
|
if (StringUtils.startsWith(key, prefix + ".")) {
|
||||||
|
String propValue = prop.getProperty(key);
|
||||||
|
String replacedKey = StringUtils.replace(key, prefix + ".", "");
|
||||||
|
tmpToJsonArrayInterface.put(replacedKey, propValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tmpToJsonArrayInterface;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveNestedValue(Map<?, ?> map, String keyPath) {
|
||||||
|
int dotIdx = keyPath.indexOf('.');
|
||||||
|
if (dotIdx < 0) {
|
||||||
|
Object val = map.get(keyPath);
|
||||||
|
if (val == null)
|
||||||
|
return null;
|
||||||
|
if (val instanceof String)
|
||||||
|
return (String) val;
|
||||||
|
return val.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
String first = keyPath.substring(0, dotIdx);
|
||||||
|
String rest = keyPath.substring(dotIdx + 1);
|
||||||
|
Object val = map.get(first);
|
||||||
|
if (val instanceof Map) {
|
||||||
|
return resolveNestedValue((Map<?, ?>) val, rest);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 폴백: 전체 keyPath를 단일 키로 조회
|
||||||
|
Object direct = map.get(keyPath);
|
||||||
|
if (direct == null)
|
||||||
|
return null;
|
||||||
|
if (direct instanceof String)
|
||||||
|
return (String) direct;
|
||||||
|
return direct.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String checkCustomInflow(Bucket bucket, EAIMessage eaiMsg, Properties prop) {
|
||||||
|
String clientId = eaiMsg.getClientId();
|
||||||
|
if (StringUtils.isBlank(clientId)) return null;
|
||||||
|
if (bucket instanceof ClientDualBucket) {
|
||||||
|
return ((ClientDualBucket) bucket).isClientPassDetail(clientId);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected InflowTargetVO resolveCustomInflowThreshold(Bucket bucket, EAIMessage eaiMsg, Properties prop) {
|
||||||
|
if (bucket instanceof ClientDualBucket) {
|
||||||
|
return ((ClientDualBucket) bucket).getClientInflowThreshold(eaiMsg.getClientId());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String checkAdapterInflow(Bucket bucket, String adapterGroupName) {
|
||||||
|
if (bucket instanceof DualBucket) {
|
||||||
|
return ((DualBucket) bucket).isAdapterPassDetail(adapterGroupName);
|
||||||
|
}
|
||||||
|
return super.checkAdapterInflow(bucket, adapterGroupName);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String checkInterfaceInflow(Bucket bucket, String eaiSvcCd) {
|
||||||
|
if (bucket instanceof DualBucket) {
|
||||||
|
return ((DualBucket) bucket).isInterfacePassDetail(eaiSvcCd);
|
||||||
|
}
|
||||||
|
return super.checkInterfaceInflow(bucket, eaiSvcCd);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 차단 원인에 따라 에러 메시지에 한도 정보를 포함.
|
||||||
|
* <ul>
|
||||||
|
* <li>PER_SECOND: "API 호출 한도 초과 [name: Nreq/sec]"</li>
|
||||||
|
* <li>THRESHOLD: "API 호출 한도 초과 [name: Nreq/UNIT]"</li>
|
||||||
|
* <li>그 외: "API 호출 한도 초과 [name]" (기존 동작)</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
protected String buildInflowTargetErrorMsg(InflowTargetVO inflowTargetVO, String blockedType) {
|
||||||
|
if (DualCustomBucket.RESULT_BLOCKED_PER_SECOND.equals(blockedType)) {
|
||||||
|
return String.format("API 호출 한도 초과 [%s: %dreq/sec]",
|
||||||
|
inflowTargetVO.getName(),
|
||||||
|
inflowTargetVO.getThresholdPerSecond());
|
||||||
|
}
|
||||||
|
if (DualCustomBucket.RESULT_BLOCKED_THRESHOLD.equals(blockedType)) {
|
||||||
|
return String.format("API 호출 한도 초과 [%s: %dreq/%s]",
|
||||||
|
inflowTargetVO.getName(),
|
||||||
|
inflowTargetVO.getThreshold(),
|
||||||
|
inflowTargetVO.getThresholdTimeUnit());
|
||||||
|
}
|
||||||
|
return super.buildInflowTargetErrorMsg(inflowTargetVO, blockedType);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.eactive.eai.custom.inflow;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualBucket;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DualBucket에 클라이언트 유량제어 메서드를 추가한 인터페이스.
|
||||||
|
* {@link ClientDualInflowControlManager}가 구현한다.
|
||||||
|
*/
|
||||||
|
public interface ClientDualBucket extends DualBucket {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 클라이언트 유량제어 체크 — 차단 원인 포함.
|
||||||
|
* @return null이면 통과, "PER_SECOND" 또는 "THRESHOLD"이면 해당 버킷에서 차단
|
||||||
|
*/
|
||||||
|
String isClientPassDetail(String clientId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 클라이언트 유량제어 설정 조회 — 에러 메시지 생성용.
|
||||||
|
* @return 등록된 설정이 없으면 null
|
||||||
|
*/
|
||||||
|
InflowTargetVO getClientInflowThreshold(String clientId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package com.eactive.eai.custom.inflow;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.inflow.Bucket;
|
||||||
|
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||||
|
import com.eactive.eai.common.inflow.InflowType;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||||
|
import com.eactive.eai.common.lifecycle.LifecycleException;
|
||||||
|
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||||
|
import com.eactive.eai.common.util.Logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 어댑터/인터페이스 이중 버킷(DualInflowControlManager)에 클라이언트 유량제어를 추가한 관리자.
|
||||||
|
*
|
||||||
|
* <p>적용 방법: INFLOW.properties에 아래 한 줄 추가.
|
||||||
|
* <pre>inflow.control.bucket.className=com.eactive.eai.common.inflow.dual.ClientDualInflowControlManager</pre>
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class ClientDualInflowControlManager extends DualInflowControlManager implements ClientDualBucket {
|
||||||
|
|
||||||
|
private static final Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||||
|
|
||||||
|
public static synchronized Bucket getBucket() {
|
||||||
|
return ApplicationContextProvider.getContext().getBean(ClientDualInflowControlManager.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
private volatile Map<String, DualCustomBucket> clientBucketMap = new ConcurrentHashMap<>();
|
||||||
|
private final ConcurrentHashMap<String, TargetMetrics> clientMetricsMap = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Lifecycle
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void start() throws LifecycleException {
|
||||||
|
super.start();
|
||||||
|
try {
|
||||||
|
initClients();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new LifecycleException("ClientDualInflowControlManager init failed: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 초기화 / 리로드
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private void initClients() throws Exception {
|
||||||
|
this.clientBucketMap = loadBucketMap(InflowType.CLIENT);
|
||||||
|
if (logger.isInfo()) logger.info("ClientDualInflowControlManager] initClients: " + clientBucketMap.size() + " buckets");
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void reloadClient() throws Exception {
|
||||||
|
initClients();
|
||||||
|
clientMetricsMap.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void reloadClient(String clientId) throws Exception {
|
||||||
|
reloadBucketMap(clientBucketMap, InflowType.CLIENT, clientId);
|
||||||
|
TargetMetrics m = clientMetricsMap.get(clientId);
|
||||||
|
if (m != null) m.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void removeClient(String clientId) {
|
||||||
|
clientBucketMap.remove(clientId);
|
||||||
|
clientMetricsMap.remove(clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 클라이언트 메트릭 접근자
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public TargetMetrics getClientMetrics(String clientId) { return clientMetricsMap.get(clientId); }
|
||||||
|
public Map<String, TargetMetrics> getAllClientMetrics() { return Collections.unmodifiableMap(clientMetricsMap); }
|
||||||
|
public void resetClientMetrics(String clientId) { TargetMetrics m = clientMetricsMap.get(clientId); if (m != null) m.reset(); }
|
||||||
|
public void resetAllClientMetrics() { clientMetricsMap.values().forEach(TargetMetrics::reset); }
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// ClientDualBucket — 클라이언트 유량제어
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String isClientPassDetail(String clientId) {
|
||||||
|
DualCustomBucket b = clientBucketMap.get(clientId);
|
||||||
|
if (b == null) return DualCustomBucket.RESULT_PASS;
|
||||||
|
String result = b.tryConsume();
|
||||||
|
recordMetrics(clientMetricsMap, clientId, result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public InflowTargetVO getClientInflowThreshold(String clientId) {
|
||||||
|
DualCustomBucket b = clientBucketMap.get(clientId);
|
||||||
|
return (b == null) ? null : b.getInflowTargetVo();
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 모니터링용 접근자
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public DualCustomBucket getClientBucket(String clientId) {
|
||||||
|
return clientBucketMap.get(clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, DualCustomBucket> getClientBucketMap() {
|
||||||
|
return clientBucketMap;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.eactive.eai.custom.inflow;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import com.eactive.eai.manage.inflow.TargetBucketStatusDTO;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 클라이언트 버킷 상태 모니터링 API.
|
||||||
|
*
|
||||||
|
* ClientDualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
|
||||||
|
*
|
||||||
|
* GET /manage/inflow/client/bucket-status → 전체 클라이언트 버킷 상태
|
||||||
|
* GET /manage/inflow/client/{clientId}/bucket-status → 특정 클라이언트 버킷 상태
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/manage/inflow")
|
||||||
|
public class ClientInflowTargetBucketController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ClientInflowTargetBucketService bucketService;
|
||||||
|
|
||||||
|
@GetMapping("/client/bucket-status")
|
||||||
|
public ResponseEntity<?> getAllClientBucketStatus() {
|
||||||
|
List<TargetBucketStatusDTO> list = bucketService.getAllClientBucketStatus();
|
||||||
|
return ok(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/client/{clientId}/bucket-status")
|
||||||
|
public ResponseEntity<?> getClientBucketStatus(@PathVariable String clientId) {
|
||||||
|
TargetBucketStatusDTO dto = bucketService.getClientBucketStatus(clientId);
|
||||||
|
return single(dto, "클라이언트를 찾을 수 없습니다: " + clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<?> ok(List<TargetBucketStatusDTO> list) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", list);
|
||||||
|
result.put("count", list.size());
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<?> single(TargetBucketStatusDTO dto, String notFoundMsg) {
|
||||||
|
if (dto == null) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", notFoundMsg);
|
||||||
|
return ResponseEntity.ok(error);
|
||||||
|
}
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", dto);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
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.DualCustomBucket;
|
||||||
|
import com.eactive.eai.manage.inflow.GroupBucketStatusDTO;
|
||||||
|
import com.eactive.eai.manage.inflow.TargetBucketStatusDTO;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 클라이언트 버킷 상태 조회 서비스.
|
||||||
|
*
|
||||||
|
* ClientDualInflowControlManager 가 활성화된 경우에만 동작한다.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class ClientInflowTargetBucketService {
|
||||||
|
|
||||||
|
public TargetBucketStatusDTO getClientBucketStatus(String clientId) {
|
||||||
|
ClientDualInflowControlManager manager = getClientDualManager();
|
||||||
|
if (manager == null) return null;
|
||||||
|
DualCustomBucket bucket = manager.getClientBucket(clientId);
|
||||||
|
if (bucket == null) return null;
|
||||||
|
return toDto(clientId, "CLIENT", bucket);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TargetBucketStatusDTO> getAllClientBucketStatus() {
|
||||||
|
ClientDualInflowControlManager manager = getClientDualManager();
|
||||||
|
if (manager == null) return new ArrayList<>();
|
||||||
|
return toDtoList("CLIENT", manager.getClientBucketMap());
|
||||||
|
}
|
||||||
|
|
||||||
|
protected ClientDualInflowControlManager getClientDualManager() {
|
||||||
|
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
|
||||||
|
return (base instanceof ClientDualInflowControlManager) ? (ClientDualInflowControlManager) base : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private TargetBucketStatusDTO toDto(String targetId, String targetType, DualCustomBucket bucket) {
|
||||||
|
InflowTargetVO vo = bucket.getInflowTargetVo();
|
||||||
|
List<GroupBucketStatusDTO.BucketInfo> buckets = new ArrayList<>();
|
||||||
|
|
||||||
|
if (vo.getThresholdPerSecond() > 0) {
|
||||||
|
long capacity = vo.getThresholdPerSecond();
|
||||||
|
long available = bucket.getPerSecondAvailableTokens();
|
||||||
|
if (available < 0) available = capacity;
|
||||||
|
buckets.add(new GroupBucketStatusDTO.BucketInfo(
|
||||||
|
"perSecond", capacity, Math.min(available, capacity), "SEC"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vo.getThreshold() > 0) {
|
||||||
|
long capacity = vo.getThreshold();
|
||||||
|
long available = bucket.getThresholdAvailableTokens();
|
||||||
|
if (available < 0) available = capacity;
|
||||||
|
buckets.add(new GroupBucketStatusDTO.BucketInfo(
|
||||||
|
"threshold", capacity, Math.min(available, capacity), vo.getThresholdTimeUnit()));
|
||||||
|
}
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = new TargetBucketStatusDTO();
|
||||||
|
dto.setTargetId(targetId);
|
||||||
|
dto.setTargetType(targetType);
|
||||||
|
dto.setActivate(vo.isActivate());
|
||||||
|
dto.setBuckets(buckets);
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<TargetBucketStatusDTO> toDtoList(String targetType, Map<String, DualCustomBucket> bucketMap) {
|
||||||
|
List<TargetBucketStatusDTO> result = new ArrayList<>();
|
||||||
|
for (Map.Entry<String, DualCustomBucket> entry : bucketMap.entrySet()) {
|
||||||
|
result.add(toDto(entry.getKey(), targetType, entry.getValue()));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package com.eactive.eai.custom.inflow;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import com.eactive.eai.manage.inflow.TargetMetricDTO;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 클라이언트 유량제어 메트릭 API.
|
||||||
|
*
|
||||||
|
* ClientDualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
|
||||||
|
*
|
||||||
|
* GET /manage/inflow/client/metric → 전체 클라이언트 메트릭
|
||||||
|
* GET /manage/inflow/client/{clientId}/metric → 특정 클라이언트 메트릭
|
||||||
|
* POST /manage/inflow/client/metric/reset → 전체 클라이언트 메트릭 초기화
|
||||||
|
* POST /manage/inflow/client/{clientId}/metric/reset → 특정 클라이언트 메트릭 초기화
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/manage/inflow")
|
||||||
|
public class ClientInflowTargetMetricController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ClientInflowTargetMetricService metricService;
|
||||||
|
|
||||||
|
@GetMapping("/client/metric")
|
||||||
|
public ResponseEntity<?> getAllClientMetrics() {
|
||||||
|
List<TargetMetricDTO> list = metricService.getAllClientMetrics();
|
||||||
|
return okList(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/client/{clientId}/metric")
|
||||||
|
public ResponseEntity<?> getClientMetric(@PathVariable String clientId) {
|
||||||
|
TargetMetricDTO dto = metricService.getClientMetric(clientId);
|
||||||
|
return okSingle(dto, "클라이언트를 찾을 수 없습니다: " + clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/client/metric/reset")
|
||||||
|
public ResponseEntity<?> resetAllClientMetrics() {
|
||||||
|
metricService.resetAllClientMetrics();
|
||||||
|
return okReset("전체 클라이언트 메트릭 초기화 완료");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/client/{clientId}/metric/reset")
|
||||||
|
public ResponseEntity<?> resetClientMetric(@PathVariable String clientId) {
|
||||||
|
boolean ok = metricService.resetClientMetric(clientId);
|
||||||
|
return okResetSingle(ok, clientId, "클라이언트");
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<?> okList(List<TargetMetricDTO> list) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", list);
|
||||||
|
result.put("count", list.size());
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<?> okSingle(TargetMetricDTO dto, String notFoundMsg) {
|
||||||
|
if (dto == null) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", notFoundMsg);
|
||||||
|
return ResponseEntity.ok(error);
|
||||||
|
}
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", dto);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<?> okReset(String message) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("message", message);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<?> okResetSingle(boolean ok, String targetId, String targetLabel) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", ok);
|
||||||
|
result.put("message", ok
|
||||||
|
? "초기화 완료: " + targetId
|
||||||
|
: targetLabel + "를 찾을 수 없습니다: " + targetId);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
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.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;
|
||||||
|
}
|
||||||
|
}
|
||||||
-123
@@ -1,123 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.TreeMap;
|
|
||||||
import java.util.stream.Stream;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
|
||||||
import com.eactive.eai.common.TransactionContextKeys;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
public class AllHeaderFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String PROPERTIES_GROUP_NAME = "HttpHeaderFilter";
|
|
||||||
public static final String HEADER_KEY_NAMES = "AllHeaderFilter.blackList";
|
|
||||||
|
|
||||||
|
|
||||||
String[] HttpHeaderRelayBlackList = {
|
|
||||||
"Content-Length",
|
|
||||||
"Transfer-Encoding",
|
|
||||||
"Host",
|
|
||||||
"Authorization",
|
|
||||||
"Accept",
|
|
||||||
"Host",
|
|
||||||
"Cookie",
|
|
||||||
"Connection",
|
|
||||||
"Keep-Alive",
|
|
||||||
"Proxy-Authenticate",
|
|
||||||
"Proxy-Authorization",
|
|
||||||
"TE",
|
|
||||||
"Trailer",
|
|
||||||
"Transfer-Encoding",
|
|
||||||
"Upgrade",
|
|
||||||
"Content-Type",
|
|
||||||
"Content-Encoding",
|
|
||||||
"Content-Language",
|
|
||||||
"Content-Location",
|
|
||||||
"Content-MD5",
|
|
||||||
"Expect",
|
|
||||||
};
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
logger.debug("doPreFilter Processing Start.");
|
|
||||||
|
|
||||||
Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
|
|
||||||
if (filterHeaders == null) {
|
|
||||||
filterHeaders = new Properties();
|
|
||||||
tempProp.put("FILTERHEADER", filterHeaders);
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);
|
|
||||||
|
|
||||||
String propValue = PropManager.getInstance().getProperty(PROPERTIES_GROUP_NAME, HEADER_KEY_NAMES, "").trim();
|
|
||||||
|
|
||||||
String[] userSettingBlackList = propValue.split(",");
|
|
||||||
|
|
||||||
if( userSettingBlackList.length > 0 ) {
|
|
||||||
HttpHeaderRelayBlackList = Stream
|
|
||||||
.concat(Arrays.stream(HttpHeaderRelayBlackList), Arrays.stream(userSettingBlackList))
|
|
||||||
.toArray(String[]::new);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
for(String keyName : inboundHeaderMap.keySet() ) {
|
|
||||||
|
|
||||||
if( StringUtils.equalsAnyIgnoreCase( keyName, HttpHeaderRelayBlackList ) ) {
|
|
||||||
logger.debug("Skip Processing Key ["+keyName+"], value ["+inboundHeaderMap.get(keyName)+"] in HttpHeaderRelayBlackList");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
filterHeaders.put(keyName, inboundHeaderMap.get(keyName));
|
|
||||||
logger.debug("Processing Key ["+keyName+"], value ["+inboundHeaderMap.get(keyName)+"]");
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.debug("doPreFilter Processing End.");
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getInboundHeaderProp(Properties prop) {
|
|
||||||
Properties header = new Properties();
|
|
||||||
Map<String, String> inboundHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
|
||||||
try {
|
|
||||||
Object headerObj = prop.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
|
||||||
if (headerObj instanceof Properties) { //tomcat
|
|
||||||
header = (Properties) headerObj;
|
|
||||||
for (String name : header.stringPropertyNames()) {
|
|
||||||
inboundHeaderMap.put(name, header.getProperty(name));
|
|
||||||
}
|
|
||||||
} else if (headerObj instanceof String) { //weblogic
|
|
||||||
String str = (String) headerObj;
|
|
||||||
str = str.substring(1, str.length() - 1);
|
|
||||||
// key=value 쌍 분리
|
|
||||||
String[] entries = str.split(",");
|
|
||||||
for (String entry : entries) {
|
|
||||||
String[] kv = entry.split("=", 2);
|
|
||||||
if (kv.length == 2) {
|
|
||||||
inboundHeaderMap.put(kv[0].trim(), kv[1].trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return inboundHeaderMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-118
@@ -1,118 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.TreeMap;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.common.TransactionContextKeys;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
|
|
||||||
public class AsyncReponseFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String X_TRACE_ID = "partnerTraceId";
|
|
||||||
public static final String TRACE_ID = "traceId";
|
|
||||||
|
|
||||||
public static final String PROPERTIES_GROUP_NAME = "HttpHeaderFilter";
|
|
||||||
public static final String HEADER_KEY_NAMES = "AsyncReponseFilter";
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
logger.debug("AsyncReponseFilter] PreFilter Processing Start!!");
|
|
||||||
String traceId = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID, "");
|
|
||||||
|
|
||||||
Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
|
|
||||||
if (filterHeaders == null) {
|
|
||||||
filterHeaders = new Properties();
|
|
||||||
tempProp.put("FILTERHEADER", filterHeaders);
|
|
||||||
}
|
|
||||||
|
|
||||||
String propValue = PropManager.getInstance().getProperty(PROPERTIES_GROUP_NAME, HEADER_KEY_NAMES, "").trim();
|
|
||||||
|
|
||||||
String[] headerKeyNames = propValue.split(",");
|
|
||||||
|
|
||||||
|
|
||||||
headerKeyNames = Arrays.stream(headerKeyNames)
|
|
||||||
.map(String::trim)
|
|
||||||
.toArray(String[]::new);
|
|
||||||
|
|
||||||
try {
|
|
||||||
Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);
|
|
||||||
|
|
||||||
if (!inboundHeaderMap.isEmpty()) {
|
|
||||||
if (inboundHeaderMap.containsKey(X_TRACE_ID)) {
|
|
||||||
filterHeaders.put(X_TRACE_ID, inboundHeaderMap.get(X_TRACE_ID));
|
|
||||||
logger.debug("AsyncReponseFilter] Processing Key ["+X_TRACE_ID+"], value ["+inboundHeaderMap.get(X_TRACE_ID)+"]");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (inboundHeaderMap.containsKey(TransactionContextKeys.X_LOAN_TOKEN)) {
|
|
||||||
filterHeaders.put(TransactionContextKeys.X_LOAN_TOKEN, inboundHeaderMap.get(TransactionContextKeys.X_LOAN_TOKEN));
|
|
||||||
logger.debug("AsyncReponseFilter] Processing Key ["+TransactionContextKeys.X_LOAN_TOKEN+"], value ["+inboundHeaderMap.get(TransactionContextKeys.X_LOAN_TOKEN)+"]");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
filterHeaders.setProperty(TRACE_ID, traceId);
|
|
||||||
logger.debug("AsyncReponseFilter] Processing Key ["+TRACE_ID+"], value ["+traceId+"]");
|
|
||||||
|
|
||||||
for (String keyName : inboundHeaderMap.keySet()) {
|
|
||||||
|
|
||||||
if (StringUtils.equalsAnyIgnoreCase(keyName, headerKeyNames)) {
|
|
||||||
String value = inboundHeaderMap.get(keyName);
|
|
||||||
filterHeaders.put(keyName, value);
|
|
||||||
logger.debug("AsyncReponseFilter] Processing Key [" + keyName + "], value [" + value + "]");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getInboundHeaderProp(Properties prop) {
|
|
||||||
Properties header = new Properties();
|
|
||||||
Map<String, String> inboundHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
|
||||||
try {
|
|
||||||
Object headerObj = prop.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
|
||||||
if (headerObj instanceof Properties) { //tomcat
|
|
||||||
header = (Properties) headerObj;
|
|
||||||
for (String name : header.stringPropertyNames()) {
|
|
||||||
inboundHeaderMap.put(name, header.getProperty(name));
|
|
||||||
}
|
|
||||||
} else if (headerObj instanceof String) { //weblogic
|
|
||||||
String str = (String) headerObj;
|
|
||||||
str = str.substring(1, str.length() - 1);
|
|
||||||
// key=value 쌍 분리
|
|
||||||
String[] entries = str.split(",");
|
|
||||||
for (String entry : entries) {
|
|
||||||
String[] kv = entry.split("=", 2);
|
|
||||||
if (kv.length == 2) {
|
|
||||||
inboundHeaderMap.put(kv[0].trim(), kv[1].trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return inboundHeaderMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
-115
@@ -1,115 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
public class HttpClient5AdapterFilterFactory {
|
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
static String basePackage = "com.eactive.eai.custom.kjb.adapter.http.client.filter";
|
|
||||||
private static ConcurrentHashMap<String, HttpClientAdapterFilter> h = new ConcurrentHashMap<>();
|
|
||||||
private static ConcurrentHashMap<String, HttpClientAdapterExceptionFilter> eh = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
private HttpClient5AdapterFilterFactory() {
|
|
||||||
throw new IllegalStateException("Utility class");
|
|
||||||
}
|
|
||||||
|
|
||||||
public static HttpClientAdapterFilter createFilter(String type) {
|
|
||||||
if (h.containsKey(type)) {
|
|
||||||
return h.get(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
HttpClientAdapterFilter filter = null;
|
|
||||||
switch (HttpClient5AdapterFilterType.getValue(type)) {
|
|
||||||
case SIMPLEFRAMEWORK:
|
|
||||||
filter = new SimpleFrameworkFilter();
|
|
||||||
break;
|
|
||||||
case SIMPLEFRAMEWORKBODY:
|
|
||||||
filter = new SimpleframeworkBodyFilter();
|
|
||||||
break;
|
|
||||||
case JBOBP:
|
|
||||||
filter = new JBOBPFilter();
|
|
||||||
break;
|
|
||||||
case KFTCFACE:
|
|
||||||
filter = new KFTCFaceFilter();
|
|
||||||
break;
|
|
||||||
case KFTCP2P:
|
|
||||||
filter = new KFTCP2PFilter();
|
|
||||||
break;
|
|
||||||
case KAKAOBANK:
|
|
||||||
filter = new KAKAOBankFilter();
|
|
||||||
break;
|
|
||||||
case NAVERFIN:
|
|
||||||
filter = new NAVERFinFilter();
|
|
||||||
break;
|
|
||||||
case NICECREDIT:
|
|
||||||
filter = new NICECreditFilter();
|
|
||||||
break;
|
|
||||||
case TRACEBODY:
|
|
||||||
filter = new TraceBodyFilter();
|
|
||||||
break;
|
|
||||||
case TOSSBANK:
|
|
||||||
filter = new TOSSBankFilter();
|
|
||||||
break;
|
|
||||||
case ASYNCRESPONSE:
|
|
||||||
filter = new AsyncReponseFilter();
|
|
||||||
break;
|
|
||||||
case ALLHEADER:
|
|
||||||
filter = new AllHeaderFilter();
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
filter = classForName(type);
|
|
||||||
if (filter == null) {
|
|
||||||
filter = classForName(basePackage + "." + type);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (filter != null) {
|
|
||||||
h.put(type, filter);
|
|
||||||
return filter;
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static HttpClientAdapterFilter classForName(String type) {
|
|
||||||
try {
|
|
||||||
Class<?> cl = Class.forName(type);
|
|
||||||
return (HttpClientAdapterFilter) cl.newInstance();
|
|
||||||
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
|
|
||||||
logger.error("Cannot create a HttpClientAdapterFilter. - {}", type);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static HttpClientAdapterExceptionFilter createExceptionFilter(String type) {
|
|
||||||
if (eh.containsKey(type)) {
|
|
||||||
return eh.get(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
HttpClientAdapterExceptionFilter filter = classForExceptionFilterName(type);
|
|
||||||
if (filter == null) {
|
|
||||||
filter = classForExceptionFilterName(basePackage + "." + type);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (filter != null) {
|
|
||||||
eh.put(type, filter);
|
|
||||||
return filter;
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static HttpClientAdapterExceptionFilter classForExceptionFilterName(String type) {
|
|
||||||
try {
|
|
||||||
Class<?> cl = Class.forName(type);
|
|
||||||
return (HttpClientAdapterExceptionFilter) cl.newInstance();
|
|
||||||
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
|
|
||||||
logger.error("Cannot create a HttpClientAdapterExceptionFilter. - {}", type);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
-27
@@ -1,27 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
public enum HttpClient5AdapterFilterType {
|
|
||||||
SIMPLEFRAMEWORK,
|
|
||||||
SIMPLEFRAMEWORKBODY,
|
|
||||||
JBOBP,
|
|
||||||
KFTCFACE,
|
|
||||||
KFTCP2P,
|
|
||||||
KAKAOBANK,
|
|
||||||
NAVERFIN,
|
|
||||||
NICECREDIT,
|
|
||||||
TOSSBANK,
|
|
||||||
TRACEBODY,
|
|
||||||
ASYNCRESPONSE,
|
|
||||||
ALLHEADER,
|
|
||||||
UNKNOWN;
|
|
||||||
|
|
||||||
public static HttpClient5AdapterFilterType getValue(String type) {
|
|
||||||
try {
|
|
||||||
return valueOf(type.toUpperCase());
|
|
||||||
} catch (NullPointerException e) {
|
|
||||||
return UNKNOWN;
|
|
||||||
} catch (Exception e) {
|
|
||||||
return UNKNOWN;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-62
@@ -1,62 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
public abstract class HttpClientAdapterBaseFilter implements HttpClientAdapterFilter {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
protected String filterName = "";
|
|
||||||
protected List<HttpClientAdapterFilter> filters;
|
|
||||||
|
|
||||||
protected HttpClientAdapterBaseFilter(String filterName) {
|
|
||||||
this.filterName = filterName;
|
|
||||||
filters = new ArrayList<>();
|
|
||||||
logger.info("{}] filter created.", filterName);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void addFilter(HttpClientAdapterFilter filter) {
|
|
||||||
filters.add(filter);
|
|
||||||
logger.info("{}] sub filter({}) added. filters= {}", filterName, filter, filters);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
try {
|
|
||||||
Object filteredMessage = message;
|
|
||||||
for(HttpClientAdapterFilter subFilter : filters) {
|
|
||||||
logger.debug("{}] sub filter({}) doPreFilter start.", filterName, subFilter);
|
|
||||||
filteredMessage = subFilter.doPreFilter(adptGrpName, adptName, prop, filteredMessage, tempProp);
|
|
||||||
logger.debug("{}] sub filter({}) doPreFilter end.", filterName, subFilter);
|
|
||||||
}
|
|
||||||
|
|
||||||
return filteredMessage;
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(this.filterName + "] doPreFilter error.", e);
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
try {
|
|
||||||
Object filteredMessage = message;
|
|
||||||
for(HttpClientAdapterFilter subFilter : filters) {
|
|
||||||
logger.debug("{}] sub filter({}) doPostFilter start.", filterName, subFilter);
|
|
||||||
filteredMessage = subFilter.doPostFilter(adptGrpName, adptName, prop, filteredMessage, tempProp);
|
|
||||||
logger.debug("{}] sub filter({}) doPostFilter end.", filterName, subFilter);
|
|
||||||
}
|
|
||||||
return filteredMessage;
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(this.filterName + "] doPostFilter error.", e);
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
-10
@@ -1,10 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
public interface HttpClientAdapterExceptionFilter {
|
|
||||||
|
|
||||||
public Object doExceptionFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp, Exception e) throws Exception;
|
|
||||||
|
|
||||||
}
|
|
||||||
-12
@@ -1,12 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
public interface HttpClientAdapterFilter {
|
|
||||||
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception;
|
|
||||||
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception;
|
|
||||||
}
|
|
||||||
-35
@@ -1,35 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
public class HttpClientAdapterFilterException extends RuntimeException {
|
|
||||||
private static final long serialVersionUID = -1208983360831093751L;
|
|
||||||
@Getter
|
|
||||||
private final String code;
|
|
||||||
@Getter
|
|
||||||
private final Properties prop;
|
|
||||||
@Getter
|
|
||||||
private final Properties tempProp;
|
|
||||||
|
|
||||||
public HttpClientAdapterFilterException(String code, String msg, Properties prop, Properties tmepProp) {
|
|
||||||
super(msg);
|
|
||||||
this.code = code;
|
|
||||||
this.prop = prop;
|
|
||||||
this.tempProp = tmepProp;
|
|
||||||
}
|
|
||||||
|
|
||||||
public HttpClientAdapterFilterException(String code, String msg, Properties prop, Properties tempProp, Throwable cause) {
|
|
||||||
super(msg, cause);
|
|
||||||
this.code = code;
|
|
||||||
this.prop = prop;
|
|
||||||
this.tempProp = tempProp;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return "HttpClientAdapterFilterException [code=" + code + ", prop=" + prop + ", tempProp=" + tempProp + ", parent=" + super.toString() + "]";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.TreeMap;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.common.TransactionContextKeys;
|
|
||||||
import com.eactive.eai.common.property.PropGroupVO;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
|
|
||||||
public class JBOBPFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String KJB_HEADER = "KJB_Header";
|
|
||||||
public static final String X_OBP_PARTNERCODE = "x-obp-partnercode";
|
|
||||||
public static final String X_OBP_TXID = "x-obp-txid";
|
|
||||||
public static final String X_OBP_TRUST_SYSTEM = "x-obp-trust-system";
|
|
||||||
String systemTrustKey = "APIMGW-0001-QVBJTUdXLTAwMDE=";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
logger.debug("JBOBPFilter] PreFilter Processing Start!!");
|
|
||||||
PropGroupVO propGroupVo = PropManager.getInstance().getPropGroupVO(KJB_HEADER);
|
|
||||||
if (propGroupVo != null) systemTrustKey = propGroupVo.getProperty(X_OBP_TRUST_SYSTEM, systemTrustKey);
|
|
||||||
|
|
||||||
Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
|
|
||||||
if (filterHeaders == null) {
|
|
||||||
filterHeaders = new Properties();
|
|
||||||
tempProp.put("FILTERHEADER", filterHeaders);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
String obpPartnerCode = "000000-00";
|
|
||||||
Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);
|
|
||||||
|
|
||||||
if (!inboundHeaderMap.isEmpty()) {
|
|
||||||
if (inboundHeaderMap.containsKey(X_OBP_PARTNERCODE)) {
|
|
||||||
filterHeaders.put(X_OBP_PARTNERCODE, inboundHeaderMap.get(X_OBP_PARTNERCODE));
|
|
||||||
logger.debug("JBOBPFilter] Processing Key ["+X_OBP_PARTNERCODE+"], value ["+inboundHeaderMap.get(X_OBP_PARTNERCODE)+"]");
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_OBP_PARTNERCODE, obpPartnerCode);
|
|
||||||
logger.debug("JBOBPFilter] Processing Key ["+X_OBP_PARTNERCODE+"], value ["+obpPartnerCode+"]");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_OBP_PARTNERCODE, obpPartnerCode);
|
|
||||||
logger.debug("JBOBPFilter] Processing Key ["+X_OBP_PARTNERCODE+"], value ["+obpPartnerCode+"]");
|
|
||||||
}
|
|
||||||
|
|
||||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID, "");
|
|
||||||
if (StringUtils.isNotBlank(uuid)) {
|
|
||||||
filterHeaders.setProperty(X_OBP_TXID, uuid); // JB OBP Framework용
|
|
||||||
logger.debug("JBOBPFilter] Processing Key ["+X_OBP_TXID+"], value ["+uuid+"]");
|
|
||||||
}
|
|
||||||
if (StringUtils.isNotBlank(systemTrustKey)) {
|
|
||||||
filterHeaders.setProperty(X_OBP_TRUST_SYSTEM, systemTrustKey); // JB OBP Framework용
|
|
||||||
logger.debug("JBOBPFilter] Processing Key ["+X_OBP_TRUST_SYSTEM+"], value ["+systemTrustKey+"]");
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getInboundHeaderProp(Properties prop) {
|
|
||||||
Properties header = new Properties();
|
|
||||||
Map<String, String> inboundHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
|
||||||
try {
|
|
||||||
Object headerObj = prop.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
|
||||||
if (headerObj instanceof Properties) { //tomcat
|
|
||||||
header = (Properties) headerObj;
|
|
||||||
for (String name : header.stringPropertyNames()) {
|
|
||||||
inboundHeaderMap.put(name, header.getProperty(name));
|
|
||||||
}
|
|
||||||
} else if (headerObj instanceof String) { //weblogic
|
|
||||||
String str = (String) headerObj;
|
|
||||||
str = str.substring(1, str.length() - 1);
|
|
||||||
// key=value 쌍 분리
|
|
||||||
String[] entries = str.split(",");
|
|
||||||
for (String entry : entries) {
|
|
||||||
String[] kv = entry.split("=", 2);
|
|
||||||
if (kv.length == 2) {
|
|
||||||
inboundHeaderMap.put(kv[0].trim(), kv[1].trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return inboundHeaderMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
-135
@@ -1,135 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.TreeMap;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.common.property.PropGroupVO;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
|
|
||||||
public class KAKAOBankFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String KJB_HEADER = "KJB_Header";
|
|
||||||
public static final String PROP_PREFIX = "kakaobank";
|
|
||||||
public static final String X_KKB_PARTNER_CODE = "X-KKB-PARTNER-CODE";
|
|
||||||
public static final String X_KKB_API_NAME = "X-KKB-API-NAME";
|
|
||||||
public static final String X_KKB_API_TX_ID = "X-KKB-API-TX-ID";
|
|
||||||
public static final String X_KKB_TX_TIME = "X-KKB-TX-TIME";
|
|
||||||
public static final String X_KKB_CMPR_MGMT_NO = "X-KKB-CMPR-MGMT-NO";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
logger.debug("KAKAOBankFilter] PreFilter Processing Start!!");
|
|
||||||
Object returnMessage = message;
|
|
||||||
String partnerCode = "KJB";
|
|
||||||
String apiName = "status_change";
|
|
||||||
String apiTxId = "0";
|
|
||||||
String txTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
|
|
||||||
String cmprMgmtNo = "0";
|
|
||||||
|
|
||||||
PropGroupVO propGroupVo = PropManager.getInstance().getPropGroupVO(KJB_HEADER);
|
|
||||||
if (propGroupVo != null) {
|
|
||||||
partnerCode = propGroupVo.getProperty(PROP_PREFIX + "." + X_KKB_PARTNER_CODE);
|
|
||||||
apiName = propGroupVo.getProperty(PROP_PREFIX + "." + X_KKB_API_NAME);
|
|
||||||
apiTxId = propGroupVo.getProperty(PROP_PREFIX + "." + X_KKB_API_TX_ID);
|
|
||||||
cmprMgmtNo = propGroupVo.getProperty(PROP_PREFIX + "." + X_KKB_CMPR_MGMT_NO);
|
|
||||||
}
|
|
||||||
|
|
||||||
Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
|
|
||||||
if (filterHeaders == null) {
|
|
||||||
filterHeaders = new Properties();
|
|
||||||
tempProp.put("FILTERHEADER", filterHeaders);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);
|
|
||||||
|
|
||||||
if (!inboundHeaderMap.isEmpty()) {
|
|
||||||
if (inboundHeaderMap.containsKey(X_KKB_PARTNER_CODE)) {
|
|
||||||
filterHeaders.put(X_KKB_PARTNER_CODE, inboundHeaderMap.get(X_KKB_PARTNER_CODE));
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_KKB_PARTNER_CODE, partnerCode);
|
|
||||||
}
|
|
||||||
if (inboundHeaderMap.containsKey(X_KKB_API_NAME)) {
|
|
||||||
filterHeaders.put(X_KKB_API_NAME, inboundHeaderMap.get(X_KKB_API_NAME));
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_KKB_API_NAME, apiName);
|
|
||||||
}
|
|
||||||
if (inboundHeaderMap.containsKey(X_KKB_API_TX_ID)) {
|
|
||||||
filterHeaders.put(X_KKB_API_TX_ID, inboundHeaderMap.get(X_KKB_API_TX_ID));
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_KKB_API_TX_ID, apiTxId);
|
|
||||||
}
|
|
||||||
if (inboundHeaderMap.containsKey(X_KKB_TX_TIME)) {
|
|
||||||
filterHeaders.put(X_KKB_TX_TIME, inboundHeaderMap.get(X_KKB_TX_TIME));
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_KKB_TX_TIME, txTime);
|
|
||||||
}
|
|
||||||
if (inboundHeaderMap.containsKey(X_KKB_CMPR_MGMT_NO)) {
|
|
||||||
filterHeaders.put(X_KKB_CMPR_MGMT_NO, inboundHeaderMap.get(X_KKB_CMPR_MGMT_NO));
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_KKB_CMPR_MGMT_NO, cmprMgmtNo);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_KKB_PARTNER_CODE, partnerCode);
|
|
||||||
filterHeaders.put(X_KKB_API_NAME, apiName);
|
|
||||||
filterHeaders.put(X_KKB_API_TX_ID, apiTxId);
|
|
||||||
filterHeaders.put(X_KKB_TX_TIME, txTime);
|
|
||||||
filterHeaders.put(X_KKB_CMPR_MGMT_NO, cmprMgmtNo);
|
|
||||||
}
|
|
||||||
logger.debug("KAKAOBankFilter] Processing Key ["+X_KKB_PARTNER_CODE+"], value ["+filterHeaders.getProperty(X_KKB_PARTNER_CODE)+"]");
|
|
||||||
logger.debug("KAKAOBankFilter] Processing Key ["+X_KKB_API_NAME+"], value ["+filterHeaders.getProperty(X_KKB_API_NAME)+"]");
|
|
||||||
logger.debug("KAKAOBankFilter] Processing Key ["+X_KKB_API_TX_ID+"], value ["+filterHeaders.getProperty(X_KKB_API_TX_ID)+"]");
|
|
||||||
logger.debug("KAKAOBankFilter] Processing Key ["+X_KKB_TX_TIME+"], value ["+filterHeaders.getProperty(X_KKB_TX_TIME)+"]");
|
|
||||||
logger.debug("KAKAOBankFilter] Processing Key ["+X_KKB_CMPR_MGMT_NO+"], value ["+filterHeaders.getProperty(X_KKB_CMPR_MGMT_NO)+"]");
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return returnMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getInboundHeaderProp(Properties prop) {
|
|
||||||
Properties header = new Properties();
|
|
||||||
Map<String, String> inboundHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
|
||||||
try {
|
|
||||||
Object headerObj = prop.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
|
||||||
if (headerObj instanceof Properties) { //tomcat
|
|
||||||
header = (Properties) headerObj;
|
|
||||||
for (String name : header.stringPropertyNames()) {
|
|
||||||
inboundHeaderMap.put(name, header.getProperty(name));
|
|
||||||
}
|
|
||||||
} else if (headerObj instanceof String) { //weblogic
|
|
||||||
String str = (String) headerObj;
|
|
||||||
str = str.substring(1, str.length() - 1);
|
|
||||||
// key=value 쌍 분리
|
|
||||||
String[] entries = str.split(",");
|
|
||||||
for (String entry : entries) {
|
|
||||||
String[] kv = entry.split("=", 2);
|
|
||||||
if (kv.length == 2) {
|
|
||||||
inboundHeaderMap.put(kv[0].trim(), kv[1].trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return inboundHeaderMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
-154
@@ -1,154 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.TreeMap;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.RandomStringUtils;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.json.simple.JSONObject;
|
|
||||||
import org.json.simple.JSONValue;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.common.property.PropGroupVO;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.server.EAIServerManager;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
|
|
||||||
public class KFTCFaceFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String KJB_HEADER = "KJB_Header";
|
|
||||||
public static final String PROP_PREFIX = "kftcface";
|
|
||||||
public static final String H_CLIENT_ID = "Client-Id";
|
|
||||||
public static final String B_ORG_CODE = "org_code";
|
|
||||||
public static final String B_TRANSACTION_ID = "transaction_id";
|
|
||||||
public static final String B_REQUEST_DATETIME = "request_datetime";
|
|
||||||
public static String instId = null;
|
|
||||||
|
|
||||||
static {
|
|
||||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
|
||||||
instId = eaiServerManager.getInstId();
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings({ "unchecked" })
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
logger.debug("KFTCFaceFilter] PreFilter Processing Start!!");
|
|
||||||
JSONObject returnMessage = null;
|
|
||||||
String clientId = "";
|
|
||||||
String orgCode = "034"; // 광주은행 행코드
|
|
||||||
|
|
||||||
PropGroupVO propGroupVo = PropManager.getInstance().getPropGroupVO(KJB_HEADER);
|
|
||||||
if (propGroupVo != null) {
|
|
||||||
if (StringUtils.isEmpty(clientId))
|
|
||||||
clientId = propGroupVo.getProperty(PROP_PREFIX + "." + H_CLIENT_ID);
|
|
||||||
orgCode = propGroupVo.getProperty(PROP_PREFIX + "." + B_ORG_CODE);
|
|
||||||
}
|
|
||||||
|
|
||||||
String request_datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
|
|
||||||
String reqDate = new SimpleDateFormat("yyMMdd").format(new Date());
|
|
||||||
String reqTime = new SimpleDateFormat("HHmmss").format(new Date());
|
|
||||||
// 기관코드(3) + 요청일자(6) -- 금결원 표준화 항목, 고정 9자리.
|
|
||||||
// 요청시간(6) + 인스턴스ID(2) + RandomString(3) -- 기관별 생성 거래고유번호(11자리)
|
|
||||||
// 기관코드(3) + 요청일자(6) + 요청시간(6) + 인스턴스ID(2) + RandomString(3) -- 20자리.
|
|
||||||
String transaction_id = orgCode + reqDate + reqTime + instId + RandomStringUtils.random(3, true, true).toUpperCase();
|
|
||||||
|
|
||||||
Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
|
|
||||||
if (filterHeaders == null) {
|
|
||||||
filterHeaders = new Properties();
|
|
||||||
tempProp.put("FILTERHEADER", filterHeaders);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);
|
|
||||||
|
|
||||||
if (!inboundHeaderMap.isEmpty()) {
|
|
||||||
if (inboundHeaderMap.containsKey(H_CLIENT_ID)) {
|
|
||||||
filterHeaders.put(H_CLIENT_ID, inboundHeaderMap.get(H_CLIENT_ID));
|
|
||||||
logger.debug("KFTCFaceFilter] Processing Key ["+H_CLIENT_ID+"], value ["+inboundHeaderMap.get(H_CLIENT_ID)+"]");
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(H_CLIENT_ID, clientId);
|
|
||||||
logger.debug("KFTCFaceFilter] Processing Key ["+H_CLIENT_ID+"], value ["+clientId+"]");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
filterHeaders.setProperty(H_CLIENT_ID, clientId);
|
|
||||||
logger.debug("KFTCFaceFilter] Processing Key ["+H_CLIENT_ID+"], value ["+clientId+"]");
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
AdapterManager adapterManager = AdapterManager.getInstance();
|
|
||||||
AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(adptGrpName);
|
|
||||||
String encode = adptGrpVO.getMessageEncode();
|
|
||||||
if (message == null) {
|
|
||||||
returnMessage = new JSONObject();
|
|
||||||
} else {
|
|
||||||
if (message instanceof JSONObject) {
|
|
||||||
returnMessage = (JSONObject) message;
|
|
||||||
} else if (message instanceof String) {
|
|
||||||
returnMessage = parseJson((String) message);
|
|
||||||
} else if (message instanceof byte[]) {
|
|
||||||
returnMessage = parseJson(new String((byte[]) message, encode));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
returnMessage.put(B_ORG_CODE, orgCode);
|
|
||||||
returnMessage.put(B_TRANSACTION_ID, transaction_id);
|
|
||||||
returnMessage.put(B_REQUEST_DATETIME, request_datetime);
|
|
||||||
|
|
||||||
return returnMessage.toJSONString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private JSONObject parseJson(String message) throws Exception {
|
|
||||||
if (message == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (JSONObject) JSONValue.parse(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getInboundHeaderProp(Properties prop) {
|
|
||||||
Properties header = new Properties();
|
|
||||||
Map<String, String> inboundHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
|
||||||
try {
|
|
||||||
Object headerObj = prop.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
|
||||||
if (headerObj instanceof Properties) { //tomcat
|
|
||||||
header = (Properties) headerObj;
|
|
||||||
for (String name : header.stringPropertyNames()) {
|
|
||||||
inboundHeaderMap.put(name, header.getProperty(name));
|
|
||||||
}
|
|
||||||
} else if (headerObj instanceof String) { //weblogic
|
|
||||||
String str = (String) headerObj;
|
|
||||||
str = str.substring(1, str.length() - 1);
|
|
||||||
// key=value 쌍 분리
|
|
||||||
String[] entries = str.split(",");
|
|
||||||
for (String entry : entries) {
|
|
||||||
String[] kv = entry.split("=", 2);
|
|
||||||
if (kv.length == 2) {
|
|
||||||
inboundHeaderMap.put(kv[0].trim(), kv[1].trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return inboundHeaderMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
-122
@@ -1,122 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.TreeMap;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.RandomStringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.common.property.PropGroupVO;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.server.EAIServerManager;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
|
|
||||||
public class KFTCP2PFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String KJB_HEADER = "KJB_Header";
|
|
||||||
public static final String PROP_PREFIX = "kftcp2p";
|
|
||||||
public static final String H_ORG_CODE = "org_code";
|
|
||||||
public static final String H_TRX_NO = "api_trx_no";
|
|
||||||
public static final String H_TRX_DTM = "api_trx_dtm";
|
|
||||||
public static String instId = null;
|
|
||||||
|
|
||||||
static {
|
|
||||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
|
||||||
instId = eaiServerManager.getInstId();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
logger.debug("KFTCP2PFilter] PreFilter Processing Start!!");
|
|
||||||
String orgCode = "D210400012"; // 광주은행 개발 기관코드(운영: K210800020)
|
|
||||||
|
|
||||||
PropGroupVO propGroupVo = PropManager.getInstance().getPropGroupVO(KJB_HEADER);
|
|
||||||
if (propGroupVo != null) {
|
|
||||||
orgCode = propGroupVo.getProperty(PROP_PREFIX + "." + H_ORG_CODE);
|
|
||||||
}
|
|
||||||
|
|
||||||
String apiTrxDtm = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
|
|
||||||
String apiTrxTm = new SimpleDateFormat("HHmmss").format(new Date());
|
|
||||||
// 기관코드(10) + 인스턴스ID(2) + 일시(6) + RandomString(2) -- 총 20자리
|
|
||||||
String apiTrxNo = orgCode + instId + apiTrxTm + RandomStringUtils.random(2, true, true).toUpperCase();
|
|
||||||
|
|
||||||
Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
|
|
||||||
if (filterHeaders == null) {
|
|
||||||
filterHeaders = new Properties();
|
|
||||||
tempProp.put("FILTERHEADER", filterHeaders);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);
|
|
||||||
|
|
||||||
if (!inboundHeaderMap.isEmpty()) {
|
|
||||||
if (inboundHeaderMap.containsKey(H_TRX_NO)) {
|
|
||||||
filterHeaders.put(H_TRX_NO, inboundHeaderMap.get(H_TRX_NO));
|
|
||||||
logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_NO+"], value ["+inboundHeaderMap.get(H_TRX_NO)+"]");
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(H_TRX_NO, apiTrxNo);
|
|
||||||
logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_NO+"], value ["+apiTrxNo+"]");
|
|
||||||
}
|
|
||||||
if (inboundHeaderMap.containsKey(H_TRX_DTM)) {
|
|
||||||
filterHeaders.put(H_TRX_DTM, inboundHeaderMap.get(H_TRX_DTM));
|
|
||||||
logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_DTM+"], value ["+inboundHeaderMap.get(H_TRX_DTM)+"]");
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(H_TRX_DTM, apiTrxDtm);
|
|
||||||
logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_DTM+"], value ["+apiTrxDtm+"]");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(H_TRX_NO, apiTrxNo);
|
|
||||||
filterHeaders.put(H_TRX_DTM, apiTrxDtm);
|
|
||||||
}
|
|
||||||
logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_NO+"], value ["+filterHeaders.getProperty(H_TRX_NO)+"]");
|
|
||||||
logger.debug("KFTCP2PFilter] Processing Key ["+H_TRX_DTM+"], value ["+filterHeaders.getProperty(H_TRX_DTM)+"]");
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getInboundHeaderProp(Properties prop) {
|
|
||||||
Properties header = new Properties();
|
|
||||||
Map<String, String> inboundHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
|
||||||
try {
|
|
||||||
Object headerObj = prop.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
|
||||||
if (headerObj instanceof Properties) { //tomcat
|
|
||||||
header = (Properties) headerObj;
|
|
||||||
for (String name : header.stringPropertyNames()) {
|
|
||||||
inboundHeaderMap.put(name, header.getProperty(name));
|
|
||||||
}
|
|
||||||
} else if (headerObj instanceof String) { //weblogic
|
|
||||||
String str = (String) headerObj;
|
|
||||||
str = str.substring(1, str.length() - 1);
|
|
||||||
// key=value 쌍 분리
|
|
||||||
String[] entries = str.split(",");
|
|
||||||
for (String entry : entries) {
|
|
||||||
String[] kv = entry.split("=", 2);
|
|
||||||
if (kv.length == 2) {
|
|
||||||
inboundHeaderMap.put(kv[0].trim(), kv[1].trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return inboundHeaderMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
-107
@@ -1,107 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.TreeMap;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.common.property.PropGroupVO;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
|
|
||||||
public class NAVERFinFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String KJB_HEADER = "KJB_Header";
|
|
||||||
public static final String PROP_PREFIX = "naverfin";
|
|
||||||
public static final String X_PARTNER_ID = "X-Partner-Id";
|
|
||||||
public static final String X_FINTECH_ID = "X-Fintech-Id";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
logger.debug("NAVERFinFilter] PreFilter Processing Start!!");
|
|
||||||
String partnerID = "r0jtqwC9gAW5";
|
|
||||||
String fintechId = "NF";
|
|
||||||
|
|
||||||
PropGroupVO propGroupVo = PropManager.getInstance().getPropGroupVO(KJB_HEADER);
|
|
||||||
if (propGroupVo != null) {
|
|
||||||
partnerID = propGroupVo.getProperty(PROP_PREFIX + "." + X_PARTNER_ID);
|
|
||||||
fintechId = propGroupVo.getProperty(PROP_PREFIX + "." + X_FINTECH_ID);
|
|
||||||
}
|
|
||||||
|
|
||||||
Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
|
|
||||||
if (filterHeaders == null) {
|
|
||||||
filterHeaders = new Properties();
|
|
||||||
tempProp.put("FILTERHEADER", filterHeaders);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);
|
|
||||||
|
|
||||||
if (!inboundHeaderMap.isEmpty()) {
|
|
||||||
if (inboundHeaderMap.containsKey(X_PARTNER_ID)) {
|
|
||||||
filterHeaders.put(X_PARTNER_ID, inboundHeaderMap.get(X_PARTNER_ID));
|
|
||||||
logger.debug("NAVERFinFilter] Processing Key ["+X_PARTNER_ID+"], value ["+inboundHeaderMap.get(X_PARTNER_ID)+"]");
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_PARTNER_ID, partnerID);
|
|
||||||
logger.debug("NAVERFinFilter] Processing Key ["+X_PARTNER_ID+"], value ["+partnerID+"]");
|
|
||||||
}
|
|
||||||
if (inboundHeaderMap.containsKey(X_FINTECH_ID)) {
|
|
||||||
filterHeaders.put(X_FINTECH_ID, inboundHeaderMap.get(X_FINTECH_ID));
|
|
||||||
logger.debug("NAVERFinFilter] Processing Key ["+X_FINTECH_ID+"], value ["+inboundHeaderMap.get(X_FINTECH_ID)+"]");
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_FINTECH_ID, fintechId);
|
|
||||||
logger.debug("NAVERFinFilter] Processing Key ["+X_FINTECH_ID+"], value ["+fintechId+"]");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_PARTNER_ID, partnerID);
|
|
||||||
filterHeaders.put(X_FINTECH_ID, fintechId);
|
|
||||||
}
|
|
||||||
logger.debug("NAVERFinFilter] Processing Key ["+X_PARTNER_ID+"], value ["+filterHeaders.getProperty(X_PARTNER_ID)+"]");
|
|
||||||
logger.debug("NAVERFinFilter] Processing Key ["+X_FINTECH_ID+"], value ["+filterHeaders.getProperty(X_FINTECH_ID)+"]");
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getInboundHeaderProp(Properties prop) {
|
|
||||||
Properties header = new Properties();
|
|
||||||
Map<String, String> inboundHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
|
||||||
try {
|
|
||||||
Object headerObj = prop.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
|
||||||
if (headerObj instanceof Properties) { //tomcat
|
|
||||||
header = (Properties) headerObj;
|
|
||||||
for (String name : header.stringPropertyNames()) {
|
|
||||||
inboundHeaderMap.put(name, header.getProperty(name));
|
|
||||||
}
|
|
||||||
} else if (headerObj instanceof String) { //weblogic
|
|
||||||
String str = (String) headerObj;
|
|
||||||
str = str.substring(1, str.length() - 1);
|
|
||||||
// key=value 쌍 분리
|
|
||||||
String[] entries = str.split(",");
|
|
||||||
for (String entry : entries) {
|
|
||||||
String[] kv = entry.split("=", 2);
|
|
||||||
if (kv.length == 2) {
|
|
||||||
inboundHeaderMap.put(kv[0].trim(), kv[1].trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return inboundHeaderMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
-138
@@ -1,138 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Map.Entry;
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.TreeMap;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.json.simple.JSONObject;
|
|
||||||
import org.json.simple.JSONValue;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.common.property.PropGroupVO;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
|
|
||||||
public class NICECreditFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String KJB_HEADER = "KJB_Header";
|
|
||||||
public static final String PROP_PREFIX = "nicecredit";
|
|
||||||
public static final String H_PRODUCTID = "ProductID";
|
|
||||||
public static final String B_REQ_DTM = "req_dtm";
|
|
||||||
public static final String B_GOODS_CLS = "goods_cls";
|
|
||||||
|
|
||||||
@SuppressWarnings({ "unchecked" })
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
JSONObject returnMessage = null;
|
|
||||||
String productId = "2303102120";
|
|
||||||
String reqDtm = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
|
|
||||||
String goodsCls = "KJBAPI0001";
|
|
||||||
|
|
||||||
PropGroupVO propGroupVo = PropManager.getInstance().getPropGroupVO(KJB_HEADER);
|
|
||||||
if (propGroupVo != null) {
|
|
||||||
productId = propGroupVo.getProperty(PROP_PREFIX + "." + H_PRODUCTID);
|
|
||||||
goodsCls = propGroupVo.getProperty(PROP_PREFIX + "." + B_GOODS_CLS);
|
|
||||||
}
|
|
||||||
|
|
||||||
Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
|
|
||||||
if (filterHeaders == null) {
|
|
||||||
filterHeaders = new Properties();
|
|
||||||
tempProp.put("FILTERHEADER", filterHeaders);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);
|
|
||||||
if (inboundHeaderMap != null && inboundHeaderMap.containsKey(H_PRODUCTID)) {
|
|
||||||
for (Entry<String, String> e : inboundHeaderMap.entrySet()) {
|
|
||||||
String key = (String) e.getKey();
|
|
||||||
String value = (String) e.getValue();
|
|
||||||
|
|
||||||
if (StringUtils.equalsIgnoreCase(key, H_PRODUCTID)) {
|
|
||||||
filterHeaders.setProperty(key, value);
|
|
||||||
}
|
|
||||||
if (logger.isDebugEnabled()) {
|
|
||||||
logger.debug("Request Header :" + key + "=[" + value + "]");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
filterHeaders.setProperty(H_PRODUCTID, productId);
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
AdapterManager adapterManager = AdapterManager.getInstance();
|
|
||||||
AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(adptGrpName);
|
|
||||||
String encode = adptGrpVO.getMessageEncode();
|
|
||||||
if (message == null) {
|
|
||||||
returnMessage = new JSONObject();
|
|
||||||
} else {
|
|
||||||
if (message instanceof JSONObject) {
|
|
||||||
returnMessage = (JSONObject) message;
|
|
||||||
} else if (message instanceof String) {
|
|
||||||
returnMessage = parseJson((String) message);
|
|
||||||
} else if (message instanceof byte[]) {
|
|
||||||
returnMessage = parseJson(new String((byte[]) message, encode));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
returnMessage.put(B_REQ_DTM, reqDtm);
|
|
||||||
returnMessage.put(B_GOODS_CLS, goodsCls);
|
|
||||||
|
|
||||||
return returnMessage.toJSONString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private JSONObject parseJson(String message) throws Exception {
|
|
||||||
if (message == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (JSONObject) JSONValue.parse(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getInboundHeaderProp(Properties prop) {
|
|
||||||
Properties header = new Properties();
|
|
||||||
Map<String, String> inboundHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
|
||||||
try {
|
|
||||||
Object headerObj = prop.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
|
||||||
if (headerObj instanceof Properties) { //tomcat
|
|
||||||
header = (Properties) headerObj;
|
|
||||||
for (String name : header.stringPropertyNames()) {
|
|
||||||
inboundHeaderMap.put(name, header.getProperty(name));
|
|
||||||
}
|
|
||||||
} else if (headerObj instanceof String) { //weblogic
|
|
||||||
String str = (String) headerObj;
|
|
||||||
str = str.substring(1, str.length() - 1);
|
|
||||||
// key=value 쌍 분리
|
|
||||||
String[] entries = str.split(",");
|
|
||||||
for (String entry : entries) {
|
|
||||||
String[] kv = entry.split("=", 2);
|
|
||||||
if (kv.length == 2) {
|
|
||||||
inboundHeaderMap.put(kv[0].trim(), kv[1].trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return inboundHeaderMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
-109
@@ -1,109 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.TreeMap;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
|
||||||
import com.eactive.eai.common.TransactionContextKeys;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
public class SimpleFrameworkFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String CLIENTID = "clientId";
|
|
||||||
public static final String TRACEID = "traceId";
|
|
||||||
public static final String GUID = "guid";
|
|
||||||
public static final String RECEIVEDTIMESTAMP = "receivedTimestamp";
|
|
||||||
public static final String PARTNER_TRACE_ID = "partnerTraceId";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
logger.debug("SimpleFrameworkFilter] PreFilter Processing Start!!");
|
|
||||||
|
|
||||||
Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
|
|
||||||
if (filterHeaders == null) {
|
|
||||||
filterHeaders = new Properties();
|
|
||||||
tempProp.put("FILTERHEADER", filterHeaders);
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);
|
|
||||||
|
|
||||||
try {
|
|
||||||
/* 업체정보 */
|
|
||||||
String clientId = tempProp.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
|
||||||
if (StringUtils.isEmpty(clientId)) clientId = "";
|
|
||||||
filterHeaders.put(CLIENTID, clientId);
|
|
||||||
logger.debug("SimpleFrameworkFilter] Processing Key ["+CLIENTID+"], value ["+clientId+"]");
|
|
||||||
|
|
||||||
/* APIM 거래추적자 */
|
|
||||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID, "");
|
|
||||||
filterHeaders.put(TRACEID, uuid);
|
|
||||||
logger.debug("SimpleFrameworkFilter] Processing Key ["+TRACEID+"], value ["+uuid+"]");
|
|
||||||
|
|
||||||
/* GUID */
|
|
||||||
String guid = tempProp.getProperty(TransactionContextKeys.GUID, "");
|
|
||||||
filterHeaders.put(GUID, guid);
|
|
||||||
logger.debug("SimpleFrameworkFilter] Processing Key ["+GUID+"], value ["+guid+"]");
|
|
||||||
|
|
||||||
/* 최초요청시간 */
|
|
||||||
String receivedTimestamp = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_REQUESTED_TIME, "");
|
|
||||||
filterHeaders.put(RECEIVEDTIMESTAMP, receivedTimestamp);
|
|
||||||
logger.debug("SimpleFrameworkFilter] Processing Key ["+RECEIVEDTIMESTAMP+"], value ["+receivedTimestamp+"]");
|
|
||||||
|
|
||||||
String partnerTraceId = inboundHeaderMap.getOrDefault(PARTNER_TRACE_ID, "");
|
|
||||||
filterHeaders.put(PARTNER_TRACE_ID, partnerTraceId);
|
|
||||||
logger.debug("SimpleFrameworkFilter] Processing Key ["+PARTNER_TRACE_ID+"], value ["+partnerTraceId+"]");
|
|
||||||
|
|
||||||
String x_loan_token = inboundHeaderMap.getOrDefault(TransactionContextKeys.X_LOAN_TOKEN, "");
|
|
||||||
filterHeaders.put(TransactionContextKeys.X_LOAN_TOKEN, x_loan_token);
|
|
||||||
logger.debug("SimpleFrameworkFilter] Processing Key ["+TransactionContextKeys.X_LOAN_TOKEN+"], value ["+x_loan_token+"]");
|
|
||||||
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getInboundHeaderProp(Properties prop) {
|
|
||||||
Properties header = new Properties();
|
|
||||||
Map<String, String> inboundHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
|
||||||
try {
|
|
||||||
Object headerObj = prop.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
|
||||||
if (headerObj instanceof Properties) { //tomcat
|
|
||||||
header = (Properties) headerObj;
|
|
||||||
for (String name : header.stringPropertyNames()) {
|
|
||||||
inboundHeaderMap.put(name, header.getProperty(name));
|
|
||||||
}
|
|
||||||
} else if (headerObj instanceof String) { //weblogic
|
|
||||||
String str = (String) headerObj;
|
|
||||||
str = str.substring(1, str.length() - 1);
|
|
||||||
// key=value 쌍 분리
|
|
||||||
String[] entries = str.split(",");
|
|
||||||
for (String entry : entries) {
|
|
||||||
String[] kv = entry.split("=", 2);
|
|
||||||
if (kv.length == 2) {
|
|
||||||
inboundHeaderMap.put(kv[0].trim(), kv[1].trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return inboundHeaderMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-28
@@ -1,28 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import org.json.simple.JSONObject;
|
|
||||||
import org.json.simple.JSONValue;
|
|
||||||
|
|
||||||
import com.eactive.eai.common.TransactionContextKeys;
|
|
||||||
|
|
||||||
public class SimpleframeworkBodyFilter extends SimpleFrameworkFilter {
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
Object returnMessage = super.doPreFilter(adptGrpName, adptName, prop, message, tempProp);
|
|
||||||
|
|
||||||
JSONObject bizJsonStr = null;
|
|
||||||
|
|
||||||
if ( returnMessage instanceof String ) {
|
|
||||||
bizJsonStr = (JSONObject) JSONValue.parse( (String)returnMessage);
|
|
||||||
if( bizJsonStr != null ) {
|
|
||||||
bizJsonStr.put("GUID", tempProp.getOrDefault(TransactionContextKeys.GUID, "") );
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return bizJsonStr != null ? bizJsonStr.toJSONString() : returnMessage;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-97
@@ -1,97 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.TreeMap;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.common.TransactionContextKeys;
|
|
||||||
import com.eactive.eai.common.property.PropGroupVO;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
|
|
||||||
public class TOSSBankFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String KJB_HEADER = "KJB_Header";
|
|
||||||
public static final String PROP_PREFIX = "tossbank";
|
|
||||||
public static final String X_TOSSBANK_LOAN_TRACE_ID = "X-TOSSBANK-LOAN-TRACE-ID";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
logger.debug("TOSSBankFilter] PreFilter Processing Start!!");
|
|
||||||
String traceId = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID, "");
|
|
||||||
|
|
||||||
PropGroupVO propGroupVo = PropManager.getInstance().getPropGroupVO(KJB_HEADER);
|
|
||||||
if (propGroupVo != null) {
|
|
||||||
}
|
|
||||||
|
|
||||||
Properties filterHeaders = (Properties) tempProp.get("FILTERHEADER");
|
|
||||||
if (filterHeaders == null) {
|
|
||||||
filterHeaders = new Properties();
|
|
||||||
tempProp.put("FILTERHEADER", filterHeaders);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
Map<String, String> inboundHeaderMap = getInboundHeaderProp(tempProp);
|
|
||||||
|
|
||||||
if (!inboundHeaderMap.isEmpty()) {
|
|
||||||
if (inboundHeaderMap.containsKey(X_TOSSBANK_LOAN_TRACE_ID)) {
|
|
||||||
filterHeaders.put(X_TOSSBANK_LOAN_TRACE_ID, inboundHeaderMap.get(X_TOSSBANK_LOAN_TRACE_ID));
|
|
||||||
logger.debug("TOSSBankFilter] Processing Key ["+X_TOSSBANK_LOAN_TRACE_ID+"], value ["+inboundHeaderMap.get(X_TOSSBANK_LOAN_TRACE_ID)+"]");
|
|
||||||
} else {
|
|
||||||
filterHeaders.put(X_TOSSBANK_LOAN_TRACE_ID, traceId);
|
|
||||||
logger.debug("TOSSBankFilter] Processing Key ["+X_TOSSBANK_LOAN_TRACE_ID+"], value ["+traceId+"]");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
/* APIM 거래추적자 */
|
|
||||||
filterHeaders.setProperty(X_TOSSBANK_LOAN_TRACE_ID, traceId);
|
|
||||||
logger.debug("TOSSBankFilter] Processing Key ["+X_TOSSBANK_LOAN_TRACE_ID+"], value ["+traceId+"]");
|
|
||||||
}
|
|
||||||
logger.debug("TOSSBankFilter] Processing Key ["+X_TOSSBANK_LOAN_TRACE_ID+"], value ["+filterHeaders.getProperty(X_TOSSBANK_LOAN_TRACE_ID)+"]");
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<String, String> getInboundHeaderProp(Properties prop) {
|
|
||||||
Properties header = new Properties();
|
|
||||||
Map<String, String> inboundHeaderMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
|
||||||
try {
|
|
||||||
Object headerObj = prop.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
|
||||||
if (headerObj instanceof Properties) { //tomcat
|
|
||||||
header = (Properties) headerObj;
|
|
||||||
for (String name : header.stringPropertyNames()) {
|
|
||||||
inboundHeaderMap.put(name, header.getProperty(name));
|
|
||||||
}
|
|
||||||
} else if (headerObj instanceof String) { //weblogic
|
|
||||||
String str = (String) headerObj;
|
|
||||||
str = str.substring(1, str.length() - 1);
|
|
||||||
// key=value 쌍 분리
|
|
||||||
String[] entries = str.split(",");
|
|
||||||
for (String entry : entries) {
|
|
||||||
String[] kv = entry.split("=", 2);
|
|
||||||
if (kv.length == 2) {
|
|
||||||
inboundHeaderMap.put(kv[0].trim(), kv[1].trim());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
return inboundHeaderMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
-71
@@ -1,71 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.filter;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import org.json.simple.JSONObject;
|
|
||||||
import org.json.simple.JSONValue;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.common.TransactionContextKeys;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.nimbusds.jose.shaded.gson.JsonObject;
|
|
||||||
|
|
||||||
public class TraceBodyFilter implements HttpClientAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String BIZ_HEADER = "header";
|
|
||||||
public static final String GUID = "guid";
|
|
||||||
public static final String TRACEID = "traceId";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
JSONObject bizJsonStr = null;
|
|
||||||
|
|
||||||
if (message instanceof String) {
|
|
||||||
|
|
||||||
bizJsonStr = (JSONObject) JSONValue.parse((String) message);
|
|
||||||
|
|
||||||
if ( bizJsonStr == null ) return message; //json string이 아님.
|
|
||||||
|
|
||||||
if (bizJsonStr.containsKey(BIZ_HEADER)) {
|
|
||||||
JSONObject bizHeader = (JSONObject) bizJsonStr.get(BIZ_HEADER);
|
|
||||||
|
|
||||||
putBizHeaderData(bizHeader, tempProp);
|
|
||||||
|
|
||||||
}else {
|
|
||||||
|
|
||||||
JSONObject bizHeader = new JSONObject();
|
|
||||||
bizJsonStr.put(BIZ_HEADER, bizHeader);
|
|
||||||
putBizHeaderData(bizHeader, tempProp);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return bizJsonStr != null ? bizJsonStr.toJSONString() : message;
|
|
||||||
}
|
|
||||||
|
|
||||||
static private void putBizHeaderData(JSONObject bizHeader, Properties tempProp) {
|
|
||||||
|
|
||||||
String traceId = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID, "");
|
|
||||||
|
|
||||||
String guid = tempProp.getProperty(TransactionContextKeys.GUID, "");
|
|
||||||
|
|
||||||
bizHeader.put(GUID, guid);
|
|
||||||
logger.debug("Processing Key [" + GUID + "], value [" + guid + "]");
|
|
||||||
|
|
||||||
bizHeader.put(TRACEID, traceId);
|
|
||||||
logger.debug("Processing Key [" + TRACEID + "], value [" + traceId + "]");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
// TODO Auto-generated method stub
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-222
@@ -1,222 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.client.impl;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
//import java.util.concurrent.Callable;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.dom4j.Node;
|
|
||||||
import org.json.simple.JSONObject;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
|
||||||
import com.eactive.eai.adapter.http.client.impl.HttpClient5AdapterServiceRest;
|
|
||||||
import com.eactive.eai.custom.kjb.adapter.http.client.filter.HttpClient5AdapterFilterFactory;
|
|
||||||
//import com.eactive.eai.custom.kjb.adapter.http.client.filter.HttpClientAdapterExceptionFilter;
|
|
||||||
import com.eactive.eai.custom.kjb.adapter.http.client.filter.HttpClientAdapterFilter;
|
|
||||||
//import com.eactive.eai.custom.kjb.adapter.http.client.filter.IBKOutCommonFilter;
|
|
||||||
//import com.eactive.eai.custom.kjb.adapter.http.client.filter.IBKOutExceptionFilter;
|
|
||||||
//import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
//import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
//import com.ibk.eai.common.circuitbreaker.url.UrlCircuitBreakerManager;
|
|
||||||
|
|
||||||
//import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 1. 기능 : HttpClient5AdapterServiceRest 호출 전후 Filter 적용할 수 있는 기능을 제공한다.<br>
|
|
||||||
* 2. 처리 개요 : <br>
|
|
||||||
* 3. 주의사항 <br>
|
|
||||||
*
|
|
||||||
* @author :
|
|
||||||
* @version : v 1.0.0
|
|
||||||
* @see : HttpClientAdapterServiceFactory.java,
|
|
||||||
* HttpClientAdapterServiceSupport.java, HttpClient5AdapterServiceRest.java
|
|
||||||
* @since :
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class HttpClient5AdapterServiceRestAddFilter extends HttpClient5AdapterServiceRest
|
|
||||||
implements HttpClientAdapterServiceKey {
|
|
||||||
|
|
||||||
// 요청전 수행할 필터(쉼표(,)로 구분)
|
|
||||||
static final String PRE_FILTERS = "PRE_FILTERS";
|
|
||||||
|
|
||||||
// 요청후 수행할 필터(쉼표(,)로 구분)
|
|
||||||
static final String POST_FILTERS = "POST_FILTERS";
|
|
||||||
|
|
||||||
// // Adapter에서 Exception이 발생한 경우, 처리할 필터
|
|
||||||
// static final String EXCEPTION_FILTER = "EXCEPTION_FILTER";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 1. 기능 : HttpClient 호출 전후 Filter 적용용 2. 처리 개요 : <br>
|
|
||||||
* 3. 주의사항 <br>
|
|
||||||
*
|
|
||||||
* @param prop Http Adapter 속성 정보
|
|
||||||
* @return 반환 된 Object
|
|
||||||
* @exception Exception 수동 시스템 간 통신 중 발생
|
|
||||||
*/
|
|
||||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
|
||||||
|
|
||||||
String adptGrpName = tempProp.getProperty(ADAPTER_GROUP_NAME);
|
|
||||||
String adptName = tempProp.getProperty(ADAPTER_NAME);
|
|
||||||
|
|
||||||
data = doPreFilters(adptGrpName, adptName, prop, data, tempProp);
|
|
||||||
|
|
||||||
Object adapterResponse = super.execute(prop, data, tempProp);
|
|
||||||
|
|
||||||
// //원본 url를 찾아서 있으면, 그것을 사용한다.
|
|
||||||
// String url = tempProp.getProperty("URL_ORG");
|
|
||||||
// if(StringUtils.isEmpty(url))
|
|
||||||
// url = tempProp.getProperty(HttpClientAdapterServiceKey.URL);
|
|
||||||
//
|
|
||||||
// UrlCircuitBreakerManager cManager = UrlCircuitBreakerManager.getInstance();
|
|
||||||
// CircuitBreaker circuitBreaker = cManager.getCircuitBreaker(url);
|
|
||||||
// try {
|
|
||||||
// if (circuitBreaker != null) {
|
|
||||||
// if (logger.isDebugEnabled()) {
|
|
||||||
// // ObjectMapper 인스턴스 생성
|
|
||||||
// ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
// // 서킷 브레이커의 메트릭 정보와 상태 정보를 직접 Node로 변환
|
|
||||||
// ObjectNode combinedNode = objectMapper.createObjectNode();
|
|
||||||
// combinedNode.put("state", circuitBreaker.getState().toString());
|
|
||||||
// combinedNode.set("metrics", objectMapper.valueToTree(circuitBreaker.getMetrics()));
|
|
||||||
// logger.debug("CircuitBreaker state [" + circuitBreaker.getName() + "] - " + combinedNode.toString());
|
|
||||||
// }
|
|
||||||
// adapterResponse = circuitBreaker.executeCallable(new HttpClientAdapterCallable(prop, data, tempProp, this));
|
|
||||||
// } else {
|
|
||||||
// adapterResponse = super.execute(prop, data, tempProp);
|
|
||||||
// }
|
|
||||||
// } catch (Exception e) {
|
|
||||||
// adapterResponse = doExceptionFilters(adptGrpName, adptName, prop, adapterResponse, tempProp, e);
|
|
||||||
//
|
|
||||||
// if (adapterResponse instanceof JSONObject)
|
|
||||||
// adapterResponse = ((JSONObject) adapterResponse).toJSONString();
|
|
||||||
//
|
|
||||||
// if (adapterResponse instanceof Node)
|
|
||||||
// adapterResponse = ((Node) adapterResponse).asXML();
|
|
||||||
//
|
|
||||||
// return adapterResponse;
|
|
||||||
// }
|
|
||||||
|
|
||||||
adapterResponse = doPostFilters(adptGrpName, adptName, prop, adapterResponse, tempProp);
|
|
||||||
if (adapterResponse instanceof JSONObject)
|
|
||||||
adapterResponse = ((JSONObject) adapterResponse).toJSONString();
|
|
||||||
|
|
||||||
if (adapterResponse instanceof Node)
|
|
||||||
adapterResponse = ((Node) adapterResponse).asXML();
|
|
||||||
|
|
||||||
return adapterResponse;
|
|
||||||
}
|
|
||||||
|
|
||||||
// protected Object callSuper(Properties prop, Object data, Properties tempProp) throws Exception {
|
|
||||||
// return super.execute(prop, data, tempProp);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// private class HttpClientAdapterCallable implements Callable<Object> {
|
|
||||||
// Properties prop;
|
|
||||||
// Object data;
|
|
||||||
// Properties tempProp;
|
|
||||||
// HttpClient5AdapterServiceRestAddFilter clientService;
|
|
||||||
//
|
|
||||||
// public HttpClientAdapterCallable(Properties prop, Object data, Properties tempProp,
|
|
||||||
// HttpClient5AdapterServiceRestAddFilter clientService) {
|
|
||||||
// this.prop = prop;
|
|
||||||
// this.data = data;
|
|
||||||
// this.tempProp = tempProp;
|
|
||||||
// this.clientService = clientService;
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// @Override
|
|
||||||
// public Object call() throws Exception {
|
|
||||||
// return clientService.callSuper(prop, data, tempProp);
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// }
|
|
||||||
|
|
||||||
protected Object doPreFilters(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
|
|
||||||
// boolean isSetCommonFilterInAdapterProp = false;
|
|
||||||
// 1. adapter에 설정된 필터 수행
|
|
||||||
String preFiltersStr = prop.getProperty(PRE_FILTERS);
|
|
||||||
if (StringUtils.isNotEmpty(preFiltersStr)) {
|
|
||||||
String[] preFilters = StringUtils.split(preFiltersStr, ",");
|
|
||||||
for (String filterName : preFilters) {
|
|
||||||
if (StringUtils.isBlank(filterName)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.debug("HttpClient5AdapterServiceRestAddFilter] Processing Start [" + filterName + "]");
|
|
||||||
HttpClientAdapterFilter adapterFilter = HttpClient5AdapterFilterFactory.createFilter(filterName.trim());
|
|
||||||
|
|
||||||
if (adapterFilter != null) {
|
|
||||||
// if (adapterFilter instanceof IBKOutCommonFilter)
|
|
||||||
// isSetCommonFilterInAdapterProp = true;
|
|
||||||
|
|
||||||
message = adapterFilter.doPreFilter(adptGrpName, adptName, prop, message, tempProp);
|
|
||||||
} else {
|
|
||||||
throw new Exception("Failed get Filter Class: " + filterName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// // 2. IBKOutCommonFilter 필터 수행(adapter 필터에서 수행하지 않을 때만)
|
|
||||||
// if (!isSetCommonFilterInAdapterProp) {
|
|
||||||
// HttpClientAdapterFilter ibkFilter = HttpClient5AdapterFilterFactory
|
|
||||||
// .createFilter(IBKOutCommonFilter.class.getName());
|
|
||||||
// if (ibkFilter != null) {
|
|
||||||
// message = ibkFilter.doPreFilter(adptGrpName, adptName, prop, message, tempProp);
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// logger.debug("IBKOutCommonFilter isSetCommonFilterInAdapterProp 'POST_FILTERS'. already in adapter filters");
|
|
||||||
// }
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected Object doPostFilters(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
|
|
||||||
// boolean isSetCommonFilterInAdapterProp = false;
|
|
||||||
// 1. adapter에 설정된 필터 수행
|
|
||||||
String postFiltersStr = prop.getProperty(POST_FILTERS);
|
|
||||||
if (StringUtils.isNotEmpty(postFiltersStr)) {
|
|
||||||
String[] postFilters = StringUtils.split(postFiltersStr, ",");
|
|
||||||
for (String filterName : postFilters) {
|
|
||||||
if (StringUtils.isBlank(filterName)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
HttpClientAdapterFilter adapterFilter = HttpClient5AdapterFilterFactory.createFilter(filterName.trim());
|
|
||||||
if (adapterFilter != null) {
|
|
||||||
// if (adapterFilter instanceof IBKOutCommonFilter)
|
|
||||||
// isSetCommonFilterInAdapterProp = true;
|
|
||||||
message = adapterFilter.doPostFilter(adptGrpName, adptName, prop, message, tempProp);
|
|
||||||
} else {
|
|
||||||
throw new Exception("Failed get Filter Class: " + filterName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// // 2. IBKOutCommonFilter 필터 수행
|
|
||||||
// if (!isSetCommonFilterInAdapterProp) {
|
|
||||||
// HttpClientAdapterFilter ibkFilter = HttpClient5AdapterFilterFactory
|
|
||||||
// .createFilter(IBKOutCommonFilter.class.getName());
|
|
||||||
// if (ibkFilter != null) {
|
|
||||||
// message = ibkFilter.doPostFilter(adptGrpName, adptName, prop, message, tempProp);
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// logger.debug("IBKOutCommonFilter isSetCommonFilterInAdapterProp 'PRE_FILTERS'. already in adapter filters");
|
|
||||||
// }
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
// protected Object doExceptionFilters(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
// Properties tempProp, Exception e) throws Exception {
|
|
||||||
// String exceptionFilterName = prop.getProperty(EXCEPTION_FILTER);
|
|
||||||
// if (StringUtils.isEmpty(exceptionFilterName))
|
|
||||||
// exceptionFilterName = IBKOutExceptionFilter.class.getSimpleName();
|
|
||||||
//
|
|
||||||
// HttpClientAdapterExceptionFilter exceptionFilter = HttpClient5AdapterFilterFactory.createExceptionFilter(exceptionFilterName.trim());
|
|
||||||
// return exceptionFilter.doExceptionFilter(adptGrpName, adptName, prop, message, tempProp, e);
|
|
||||||
//
|
|
||||||
// }
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package com.eactive.eai.custom.message;
|
||||||
|
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DJBank(제주은행) 차세대 표준전문 GUID 생성기
|
||||||
|
*
|
||||||
|
* GUID 구성 (40자):
|
||||||
|
* 일자(8) + 시간(6) + 밀리초(3) + 시스템코드(3) + 노드번호(2) + 세션ID(12) + Random(6)
|
||||||
|
* = 8 + 6 + 3 + 3 + 2 + 12 + 6 = 40자
|
||||||
|
*/
|
||||||
|
public final class GUIDGeneratorDJB {
|
||||||
|
|
||||||
|
public static final int GUID_LENGTH = 40;
|
||||||
|
|
||||||
|
private static final DateTimeFormatter FMT_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||||
|
private static final DateTimeFormatter FMT_TIME = DateTimeFormatter.ofPattern("HHmmss");
|
||||||
|
private static final DateTimeFormatter FMT_MILLIS = DateTimeFormatter.ofPattern("SSS");
|
||||||
|
|
||||||
|
private static final AtomicInteger seq = new AtomicInteger(1);
|
||||||
|
private static final SecureRandom rnd = new SecureRandom();
|
||||||
|
|
||||||
|
private static final String NODE_NO;
|
||||||
|
private static final String SESSION_ID_BASE;
|
||||||
|
|
||||||
|
static {
|
||||||
|
// 노드번호(2): 서버명 마지막 2자리, 없으면 "00"
|
||||||
|
String serverName = System.getProperty("server.key", "");
|
||||||
|
if (serverName.length() >= 2) {
|
||||||
|
NODE_NO = serverName.substring(serverName.length() - 2);
|
||||||
|
} else {
|
||||||
|
NODE_NO = "00";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 세션ID 기반(12): 호스트명 앞 12자 (부족 시 '_'로 우측패딩)
|
||||||
|
String hostname;
|
||||||
|
try {
|
||||||
|
hostname = java.net.InetAddress.getLocalHost().getHostName();
|
||||||
|
} catch (Exception e) {
|
||||||
|
hostname = "____________";
|
||||||
|
}
|
||||||
|
if (hostname.length() >= 12) {
|
||||||
|
SESSION_ID_BASE = hostname.substring(0, 12).toUpperCase();
|
||||||
|
} else {
|
||||||
|
SESSION_ID_BASE = String.format("%-12s", hostname).toUpperCase().replace(' ', '_');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private GUIDGeneratorDJB() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param systemCode 시스템구분코드 3자 (예: "EAI", "OPA")
|
||||||
|
*/
|
||||||
|
public static String getGUID(String systemCode) {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
|
||||||
|
String date = now.format(FMT_DATE); // 8자
|
||||||
|
String time = now.format(FMT_TIME); // 6자
|
||||||
|
String millis = now.format(FMT_MILLIS); // 3자
|
||||||
|
|
||||||
|
// 시스템코드 3자 정규화
|
||||||
|
String sysCode = normalizeCode(systemCode, 3);
|
||||||
|
|
||||||
|
// 노드번호 2자
|
||||||
|
String nodeNo = NODE_NO;
|
||||||
|
|
||||||
|
// 세션ID 12자
|
||||||
|
String sessionId = SESSION_ID_BASE;
|
||||||
|
|
||||||
|
// Random 6자 (숫자)
|
||||||
|
int seqVal = seq.getAndUpdate(v -> v >= 999999 ? 1 : v + 1);
|
||||||
|
String random = String.format("%06d", seqVal);
|
||||||
|
|
||||||
|
String guid = date + time + millis + sysCode + nodeNo + sessionId + random;
|
||||||
|
|
||||||
|
if (guid.length() != GUID_LENGTH) {
|
||||||
|
throw new IllegalStateException("GUID length error: " + guid.length() + " [" + guid + "]");
|
||||||
|
}
|
||||||
|
return guid;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String normalizeCode(String code, int len) {
|
||||||
|
if (code == null) code = "";
|
||||||
|
code = code.toUpperCase();
|
||||||
|
if (code.length() >= len) return code.substring(0, len);
|
||||||
|
return String.format("%-" + len + "s", code).replace(' ', '_');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import java.time.ZonedDateTime;
|
|
||||||
import java.time.format.DateTimeFormatter;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.common.server.Keys;
|
|
||||||
import com.eactive.eai.common.util.StringUtil;
|
|
||||||
import com.eactive.eai.common.util.UUID;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 1. 기능 : UUID Generation Class 2. 처리 개요 : * - 3. 주의사항
|
|
||||||
*
|
|
||||||
* @author :
|
|
||||||
* @version : v 1.0.0
|
|
||||||
* @see : 관련 기능을 참조
|
|
||||||
* @since : :
|
|
||||||
*/
|
|
||||||
public final class GUIDGeneratorKAKAOCARD {
|
|
||||||
|
|
||||||
private static final DateTimeFormatter SDF_YYYYMMDDHHMMSSMS = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
|
|
||||||
|
|
||||||
/*
|
|
||||||
* 날짜(17) + "-"(1) + 시스템코드(3) + hostname(6) + 일련번호(5) + "-"(1) + 001(3)
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
public static final int GUID_LENGTH = 33; // seq값 제외부분
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 1. 기능 : Private 생성자 2. 처리 개요 : - 3. 주의사항 - Instance 생성하지 못함
|
|
||||||
**/
|
|
||||||
private GUIDGeneratorKAKAOCARD() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public synchronized static String getGUID(String systemCode) {
|
|
||||||
StringBuilder sb = new StringBuilder();
|
|
||||||
sb.append(SDF_YYYYMMDDHHMMSSMS.format(ZonedDateTime.now()));
|
|
||||||
sb.append("-");
|
|
||||||
sb.append(systemCode);
|
|
||||||
sb.append(UNIQUE_NUM);
|
|
||||||
char[] formatSeq = { '0', '0', '0', '0', '0' };
|
|
||||||
char[] seqCharArray = String.valueOf(seq).toCharArray();
|
|
||||||
int destPos = formatSeq.length - seqCharArray.length;
|
|
||||||
System.arraycopy(seqCharArray, 0, formatSeq, destPos, seqCharArray.length);
|
|
||||||
|
|
||||||
sb.append(formatSeq);
|
|
||||||
seq++;
|
|
||||||
if (seq > 99999) {
|
|
||||||
seq = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return sb.toString() + "-" + "001";
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String UNIQUE_NUM;
|
|
||||||
private static int seq = 1;
|
|
||||||
private static int hostlength = 6;
|
|
||||||
static {
|
|
||||||
String uniqueValue = System.getProperty(Keys.SERVER_KEY);
|
|
||||||
if (StringUtils.isBlank(uniqueValue)) {
|
|
||||||
try {
|
|
||||||
uniqueValue = java.net.InetAddress.getLocalHost().getHostName();
|
|
||||||
} catch (Exception e) {
|
|
||||||
uniqueValue = StringUtil.stringFormat("", false, 'X', hostlength);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (uniqueValue.length() > hostlength) {
|
|
||||||
uniqueValue = uniqueValue.substring(uniqueValue.length() - hostlength, uniqueValue.length());
|
|
||||||
} else if (uniqueValue.length() < hostlength) {
|
|
||||||
uniqueValue = StringUtil.stringFormat(uniqueValue, false, 'X', hostlength);
|
|
||||||
}
|
|
||||||
UNIQUE_NUM = uniqueValue.toUpperCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
String guid = getGUID("FEP");
|
|
||||||
// System.out.println("[" + guid.length() + "]" + guid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import com.eactive.eai.common.server.Keys;
|
|
||||||
import com.eactive.eai.common.util.DatetimeUtil;
|
|
||||||
import com.eactive.eai.common.util.StringUtil;
|
|
||||||
|
|
||||||
public class GUIDGeneratorKBANK {
|
|
||||||
private static String UNIQUE_NUM;
|
|
||||||
private static int seq = 1;
|
|
||||||
|
|
||||||
static {
|
|
||||||
String uniqueValue = System.getProperty(Keys.SERVER_KEY);
|
|
||||||
if(uniqueValue.length() < 8) {
|
|
||||||
uniqueValue = StringUtil.stringFormat(uniqueValue, false, '0', 8);
|
|
||||||
}else if(uniqueValue.length() > 8){
|
|
||||||
uniqueValue = uniqueValue.substring(uniqueValue.length() - 8);
|
|
||||||
}
|
|
||||||
UNIQUE_NUM = uniqueValue.toUpperCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
public synchronized static String makeGUID() {
|
|
||||||
StringBuilder sb = new StringBuilder();
|
|
||||||
sb.append(DatetimeUtil.getCurrentDateTime());
|
|
||||||
sb.append(UNIQUE_NUM);
|
|
||||||
|
|
||||||
char[] formatSeq = {'0','0','0','0','0','0','0','0'};
|
|
||||||
char[] seqCharArray = String.valueOf(seq).toCharArray();
|
|
||||||
int destPos = formatSeq.length - seqCharArray.length;
|
|
||||||
System.arraycopy(seqCharArray, 0, formatSeq, destPos, seqCharArray.length);
|
|
||||||
|
|
||||||
sb.append(formatSeq);
|
|
||||||
|
|
||||||
seq ++;
|
|
||||||
if(seq > 99999999) {
|
|
||||||
seq = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return sb.toString() ;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import java.time.ZonedDateTime;
|
|
||||||
import java.time.format.DateTimeFormatter;
|
|
||||||
|
|
||||||
import com.eactive.eai.common.util.DatetimeUtil;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.common.server.Keys;
|
|
||||||
import com.eactive.eai.common.util.StringUtil;
|
|
||||||
import com.eactive.eai.common.util.UUID;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 1. 기능 : UUID Generation Class 2. 처리 개요 : * - 3. 주의사항
|
|
||||||
*
|
|
||||||
* @author :
|
|
||||||
* @version : v 1.0.0
|
|
||||||
* @see : 관련 기능을 참조
|
|
||||||
* @since : :
|
|
||||||
*/
|
|
||||||
public final class GUIDGeneratorKJB {
|
|
||||||
|
|
||||||
/*
|
|
||||||
* 그룹사코드(3) + 호스트명(8) + 서버구분번호(2) + 일자(8) + 전문생성시간(6) + 일련번호(6) + 시스템경로번호(3, '001')
|
|
||||||
*/
|
|
||||||
|
|
||||||
public static final int GUID_LENGTH = 33; // 시스템경로번호 제외부분
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 1. 기능 : Private 생성자 2. 처리 개요 : - 3. 주의사항 - Instance 생성하지 못함
|
|
||||||
**/
|
|
||||||
private GUIDGeneratorKJB() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public synchronized static String getGUID(String groupCmpCd) {
|
|
||||||
String guid = groupCmpCd + UNIQUE_NUM;
|
|
||||||
guid = guid + DatetimeUtil.getCurrentDateTime();
|
|
||||||
|
|
||||||
if(seq < 10) {
|
|
||||||
guid = guid + "00000" + seq;
|
|
||||||
}
|
|
||||||
else if(seq < 100) {
|
|
||||||
guid = guid + "0000" + seq;
|
|
||||||
}
|
|
||||||
else if(seq < 1000) {
|
|
||||||
guid = guid + "000" + seq;
|
|
||||||
}
|
|
||||||
else if(seq < 10000) {
|
|
||||||
guid = guid + "00" + seq;
|
|
||||||
}
|
|
||||||
else if(seq < 100000) {
|
|
||||||
guid = guid + "0" + seq;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
guid = guid + seq;
|
|
||||||
}
|
|
||||||
|
|
||||||
seq ++;
|
|
||||||
if(seq > 999999) {
|
|
||||||
seq = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return guid + "001";
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String UNIQUE_NUM;
|
|
||||||
private static int seq = 1;
|
|
||||||
static {
|
|
||||||
String hostname = "";
|
|
||||||
try {
|
|
||||||
hostname = java.net.InetAddress.getLocalHost().getHostName();
|
|
||||||
}
|
|
||||||
catch(Exception e) {
|
|
||||||
hostname = "________";
|
|
||||||
}
|
|
||||||
|
|
||||||
if(hostname.getBytes().length != 8) {
|
|
||||||
if(hostname.getBytes().length < 8) {
|
|
||||||
hostname = StringUtils.leftPad(hostname, 8, '_');
|
|
||||||
} else if(hostname.getBytes().length > 8) {
|
|
||||||
hostname = StringUtils.substring(hostname, 0, 8);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String serverName = System.getProperty(Keys.SERVER_KEY);
|
|
||||||
String instid = "00";
|
|
||||||
if(serverName != null && serverName.length() > 2) {
|
|
||||||
instid = serverName.substring(serverName.length()-2, serverName.length());
|
|
||||||
}
|
|
||||||
|
|
||||||
UNIQUE_NUM = hostname.toUpperCase() + instid;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
String guid = getGUID("051");
|
|
||||||
// System.out.println("[" + guid.length() + "]" + guid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
|
|
||||||
import com.eactive.eai.common.server.Keys;
|
|
||||||
import com.eactive.eai.common.util.StringUtil;
|
|
||||||
|
|
||||||
public final class GUIDGeneratorSBI {
|
|
||||||
|
|
||||||
private static final SimpleDateFormat SDF_YYYYMMDDHHMMSSMI = new SimpleDateFormat("yyyyMMddHHmmssSSS");
|
|
||||||
|
|
||||||
private GUIDGeneratorSBI() {
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 시스템일시(17)+시스템환경코드(1)+시스템코드(3)+시스템고유번호(9)+일련번호(2)
|
|
||||||
*
|
|
||||||
* @param envDvcd
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
public synchronized static String getGUID(String envDvcd, String systemType) {
|
|
||||||
String guid = (SDF_YYYYMMDDHHMMSSMI).format(new java.util.Date()) + envDvcd + systemType + UNIQUE_NUM;
|
|
||||||
|
|
||||||
if (seq < 10) {
|
|
||||||
guid = guid + "0" + seq;
|
|
||||||
} else {
|
|
||||||
guid = guid + seq;
|
|
||||||
}
|
|
||||||
|
|
||||||
seq++;
|
|
||||||
if (seq > 99) {
|
|
||||||
seq = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return guid;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String UNIQUE_NUM;
|
|
||||||
private static int seq = 1;
|
|
||||||
static {
|
|
||||||
String hostname = "";
|
|
||||||
try {
|
|
||||||
hostname = java.net.InetAddress.getLocalHost().getHostName();
|
|
||||||
} catch (Exception e) {
|
|
||||||
hostname = "_______";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hostname.getBytes().length != 7) {
|
|
||||||
hostname = StringUtil.stringFormat(hostname, false, '_', 7);
|
|
||||||
}
|
|
||||||
|
|
||||||
String serverName = System.getProperty(Keys.SERVER_KEY); // inst.Name
|
|
||||||
String instid = "11";
|
|
||||||
if (serverName != null && serverName.length() > 2) {
|
|
||||||
instid = serverName.substring(serverName.length() - 2, serverName.length());
|
|
||||||
}
|
|
||||||
|
|
||||||
UNIQUE_NUM = hostname.toUpperCase() + instid;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
package com.eactive.eai.custom.message;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.property.PropManager;
|
||||||
|
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";
|
||||||
|
|
||||||
|
private static String API_ID_PREFIX = StringUtils
|
||||||
|
.defaultString(PropManager.getInstance().getProperty("API_ID_PREFIX"));
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getEaiSvcCode(StandardMessage standardMessage) {
|
||||||
|
if(StringUtils.isNotBlank(standardMessage.getEaiSvcCd()))
|
||||||
|
return standardMessage.getEaiSvcCd();
|
||||||
|
|
||||||
|
// String interfaceId = getInterfaceId(standardMessage);
|
||||||
|
String txId = getServiceId(standardMessage);
|
||||||
|
String sendRecvDvcd = getSendRecvDivision(standardMessage); // S | R
|
||||||
|
String inExDivision = getInExDivision(standardMessage); // 1 | 2
|
||||||
|
|
||||||
|
if(StringUtils.isEmpty(txId))
|
||||||
|
throw new RuntimeException("not found txid");
|
||||||
|
|
||||||
|
return API_ID_PREFIX + txId + 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,202 +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.common.util.StringUtil;
|
|
||||||
import com.eactive.eai.message.StandardMessage;
|
|
||||||
import com.eactive.eai.message.service.DefaultInterfaceMapper;
|
|
||||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
|
||||||
|
|
||||||
@SuppressWarnings("serial")
|
|
||||||
public class InterfaceMapperKAKAOCARD extends DefaultInterfaceMapper {
|
|
||||||
private static String SESSION_ID = "INTERFACE_COMMON.MCI_SESN_ID";
|
|
||||||
private static String INSTANCE_ID = "INTERFACE_COMMON.MCI_INSTNC_ID";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getEaiSvcCode(StandardMessage standardMessage) {
|
|
||||||
String eaiSvcCode = null;
|
|
||||||
String interfaceId = getInterfaceId(standardMessage);
|
|
||||||
String returnType = getSendRecvDivision(standardMessage); // S | R
|
|
||||||
String inExDivision = getInExDivision(standardMessage); // 1 | 2
|
|
||||||
if (interfaceId == null)
|
|
||||||
interfaceId = "";
|
|
||||||
interfaceId = interfaceId.trim();
|
|
||||||
|
|
||||||
// TODO : site에 맞게 조합해야 함.
|
|
||||||
eaiSvcCode = interfaceId + returnType + StringUtils.defaultString(inExDivision);
|
|
||||||
return eaiSvcCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setGuid(StandardMessage standardMessage, String guid) {
|
|
||||||
if (guid == null)
|
|
||||||
throw new RuntimeException("guid is null");
|
|
||||||
if (guid.length() != 36)
|
|
||||||
throw new RuntimeException("The length of guid is not 36");
|
|
||||||
setItemValue(standardMessage, getPath(GUID), guid);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getGuid(StandardMessage standardMessage) {
|
|
||||||
String guid = getItemValue(standardMessage, getPath(GUID));
|
|
||||||
if (guid.length() == 36) {
|
|
||||||
guid = guid.substring(0, 33);
|
|
||||||
}
|
|
||||||
return guid;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getGuidSeq(StandardMessage standardMessage) {
|
|
||||||
String guidseq = null;
|
|
||||||
String guid = getItemValue(standardMessage, getPath(GUID));
|
|
||||||
if (guid.length() == 36) {
|
|
||||||
guidseq = guid.substring(33);
|
|
||||||
} else {
|
|
||||||
guidseq = "000";
|
|
||||||
}
|
|
||||||
return guidseq;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setGuidSeq(StandardMessage standardMessage, String guidSeq) {
|
|
||||||
setItemValue(standardMessage, getPath(GUID), getGuid(standardMessage) + guidSeq);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getOrgGuid(StandardMessage standardMessage) {
|
|
||||||
String orgGuid = getItemValue(standardMessage, getPath(GUID_ORG));
|
|
||||||
if (orgGuid.length() == 36) {
|
|
||||||
orgGuid = orgGuid.substring(0, 33);
|
|
||||||
}
|
|
||||||
return orgGuid;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setOrgGuid(StandardMessage standardMessage, String orgGuid) {
|
|
||||||
if (orgGuid.length() == 36) {
|
|
||||||
orgGuid = orgGuid.substring(0, 33);
|
|
||||||
}
|
|
||||||
setItemValue(standardMessage, getPath(GUID_ORG), orgGuid);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String nextGuidSeq(StandardMessage standardMessage) {
|
|
||||||
String guidSeq = getGuidSeq(standardMessage);
|
|
||||||
if (guidSeq == null)
|
|
||||||
return "";
|
|
||||||
int seq = 0;
|
|
||||||
try {
|
|
||||||
seq = Integer.parseInt(guidSeq) + 1;
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
seq = 1;
|
|
||||||
}
|
|
||||||
guidSeq = StringUtil.stringFormat(Integer.toString(seq), true, '0', 3);
|
|
||||||
setGuidSeq(standardMessage, guidSeq);
|
|
||||||
return guidSeq;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 표준전문의 복원은 COMMON.ORTR_RESTR_YN 의 value는 (Y/N) 엔진에서 복원여부 의 value는 (1/0)
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public String getRecoverYn(StandardMessage standardMessage) {
|
|
||||||
String data = getItemValue(standardMessage, getPath(RECOVER_YN));
|
|
||||||
if ("Y".equals(data)) {
|
|
||||||
return "1";
|
|
||||||
} else {
|
|
||||||
return "0";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setRecoverYn(StandardMessage standardMessage, String recoverYn) {
|
|
||||||
if ("1".equals(recoverYn)) {
|
|
||||||
setItemValue(standardMessage, getPath(RECOVER_YN), "Y");
|
|
||||||
} else {
|
|
||||||
setItemValue(standardMessage, getPath(RECOVER_YN), "N");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getInstCode(StandardMessage standardMessage) {
|
|
||||||
EAIServerManager server = EAIServerManager.getInstance();
|
|
||||||
if (server != null && server.isMCI()) {
|
|
||||||
return getItemValue(standardMessage, INSTANCE_ID);
|
|
||||||
} else {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setInstCode(StandardMessage standardMessage, String instCode) {
|
|
||||||
EAIServerManager server = EAIServerManager.getInstance();
|
|
||||||
if (server != null && server.isMCI()) {
|
|
||||||
setItemValue(standardMessage, INSTANCE_ID, instCode);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getSessionId(StandardMessage standardMessage) {
|
|
||||||
EAIServerManager server = EAIServerManager.getInstance();
|
|
||||||
if (server != null && server.isMCI()) {
|
|
||||||
return getItemValue(standardMessage, SESSION_ID);
|
|
||||||
} else {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setSessionId(StandardMessage standardMessage, String sessionId) {
|
|
||||||
EAIServerManager server = EAIServerManager.getInstance();
|
|
||||||
if (server != null && server.isMCI()) {
|
|
||||||
setItemValue(standardMessage, SESSION_ID, sessionId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
|
||||||
* 엔진 에서는 public static final String RESPONSE_TYPE_CODE_N = "0";//정상(normal)
|
|
||||||
* public static final String RESPONSE_TYPE_CODE_E = "1";//오류(error)
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void setResponseType(StandardMessage standardMessage, String responseType) {
|
|
||||||
if (responseType != null && (STDMessageKeys.RESPONSE_TYPE_CODE_N.equals(responseType)
|
|
||||||
|| STDMessageKeys.RESPONSE_TYPE_CODE_E.equals(responseType))) {
|
|
||||||
if (STDMessageKeys.RESPONSE_TYPE_CODE_N.equals(responseType)) {
|
|
||||||
setItemValue(standardMessage, getPath(RESPONSE_TYPE), "NR");
|
|
||||||
} else {
|
|
||||||
setItemValue(standardMessage, getPath(RESPONSE_TYPE), "ER");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setItemValue(standardMessage, getPath(RESPONSE_TYPE), responseType);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getInterfaceId(StandardMessage standardMessage) {
|
|
||||||
String interfaceId = getItemValue(standardMessage, getPath(INTERFACE_ID));
|
|
||||||
if (interfaceId == null)
|
|
||||||
return "";
|
|
||||||
interfaceId = interfaceId.trim();
|
|
||||||
return interfaceId;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getReqSysCode(StandardMessage standardMessage) {
|
|
||||||
// apiPath의 값에서 추출할 예정 : serviceId = api_path
|
|
||||||
String apiPath = getItemValue(standardMessage, getPath(SERVICE_ID));
|
|
||||||
if (apiPath != null) {
|
|
||||||
String[] split = apiPath.split("/");
|
|
||||||
if (split.length > 2) {
|
|
||||||
String route = split[1].toUpperCase();
|
|
||||||
if (route.length() > 3) {
|
|
||||||
route = route.substring(0, 3);
|
|
||||||
}
|
|
||||||
return route;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.message.StandardMessage;
|
|
||||||
import com.eactive.eai.message.service.DefaultInterfaceMapper;
|
|
||||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
|
||||||
|
|
||||||
public class InterfaceMapperKBANK extends DefaultInterfaceMapper {
|
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
//전문작성일시
|
|
||||||
String ITEM_TLGR_WRTN_DT = "header_part.tlgrWrtnDt";
|
|
||||||
//전문생성시스템
|
|
||||||
String ITEM_TLGR_CRTN_SYS_NM = "header_part.tlgrCrtnSysNm";
|
|
||||||
//전문일련번호
|
|
||||||
String ITEM_TLGR_SRL_NO = "header_part.tlgrSrlNo";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getInExDivision(StandardMessage standardMessage) {
|
|
||||||
return "2";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setGuid(StandardMessage standardMessage, String guid) {
|
|
||||||
String tlgrWrtnDt = StringUtils.substring(guid, 0, 14);
|
|
||||||
String tlgrCrtnSysNm = StringUtils.substring(guid, 14, 22);
|
|
||||||
String tlgrSrlNo = StringUtils.substring(guid, 22, 30);
|
|
||||||
setItemValue(standardMessage, ITEM_TLGR_WRTN_DT, tlgrWrtnDt);
|
|
||||||
setItemValue(standardMessage, ITEM_TLGR_CRTN_SYS_NM, tlgrCrtnSysNm);
|
|
||||||
setItemValue(standardMessage, ITEM_TLGR_SRL_NO, tlgrSrlNo);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setGuidSeq(StandardMessage standardMessage, String guidSeq) {
|
|
||||||
if(guidSeq.length() == 1) {
|
|
||||||
guidSeq = "0"+guidSeq;
|
|
||||||
}
|
|
||||||
super.setGuidSeq(standardMessage, guidSeq);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getGuid(StandardMessage standardMessage) {
|
|
||||||
String tlgrWrtnDt = getItemValue(standardMessage, ITEM_TLGR_WRTN_DT);
|
|
||||||
String tlgrCrtnSysNm = getItemValue(standardMessage, ITEM_TLGR_CRTN_SYS_NM);
|
|
||||||
String tlgrSrlNo = getItemValue(standardMessage, ITEM_TLGR_SRL_NO);
|
|
||||||
return tlgrWrtnDt+tlgrCrtnSysNm+tlgrSrlNo;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,202 +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.common.util.StringUtil;
|
|
||||||
import com.eactive.eai.message.StandardMessage;
|
|
||||||
import com.eactive.eai.message.service.DefaultInterfaceMapper;
|
|
||||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
|
||||||
|
|
||||||
@SuppressWarnings("serial")
|
|
||||||
public class InterfaceMapperKJB extends DefaultInterfaceMapper {
|
|
||||||
private static String SESSION_ID = "INTERFACE_COMMON.MCI_SESN_ID";
|
|
||||||
private static String INSTANCE_ID = "INTERFACE_COMMON.MCI_INSTNC_ID";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getEaiSvcCode(StandardMessage standardMessage) {
|
|
||||||
String eaiSvcCode = null;
|
|
||||||
String interfaceId = getInterfaceId(standardMessage);
|
|
||||||
String returnType = getSendRecvDivision(standardMessage); // S | R
|
|
||||||
String inExDivision = getInExDivision(standardMessage); // 1 | 2
|
|
||||||
if (interfaceId == null)
|
|
||||||
interfaceId = "";
|
|
||||||
interfaceId = interfaceId.trim();
|
|
||||||
|
|
||||||
// TODO : site에 맞게 조합해야 함.
|
|
||||||
eaiSvcCode = interfaceId + returnType + StringUtils.defaultString(inExDivision);
|
|
||||||
return eaiSvcCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setGuid(StandardMessage standardMessage, String guid) {
|
|
||||||
if (guid == null)
|
|
||||||
throw new RuntimeException("guid is null");
|
|
||||||
if (guid.length() != 36)
|
|
||||||
throw new RuntimeException("The length of guid is not 36");
|
|
||||||
setItemValue(standardMessage, getPath(GUID), guid);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getGuid(StandardMessage standardMessage) {
|
|
||||||
String guid = getItemValue(standardMessage, getPath(GUID));
|
|
||||||
if (guid.length() == 36) {
|
|
||||||
guid = guid.substring(0, 33);
|
|
||||||
}
|
|
||||||
return guid;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getGuidSeq(StandardMessage standardMessage) {
|
|
||||||
String guidseq = null;
|
|
||||||
String guid = getItemValue(standardMessage, getPath(GUID));
|
|
||||||
if (guid.length() == 36) {
|
|
||||||
guidseq = guid.substring(33);
|
|
||||||
} else {
|
|
||||||
guidseq = "000";
|
|
||||||
}
|
|
||||||
return guidseq;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setGuidSeq(StandardMessage standardMessage, String guidSeq) {
|
|
||||||
setItemValue(standardMessage, getPath(GUID), getGuid(standardMessage) + guidSeq);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getOrgGuid(StandardMessage standardMessage) {
|
|
||||||
String orgGuid = getItemValue(standardMessage, getPath(GUID));
|
|
||||||
if (orgGuid.length() == 36) {
|
|
||||||
orgGuid = orgGuid.substring(0, 33);
|
|
||||||
}
|
|
||||||
return orgGuid;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setOrgGuid(StandardMessage standardMessage, String orgGuid) {
|
|
||||||
if (orgGuid.length() == 36) {
|
|
||||||
orgGuid = orgGuid.substring(0, 33);
|
|
||||||
}
|
|
||||||
setItemValue(standardMessage, getPath(GUID_ORG), orgGuid);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String nextGuidSeq(StandardMessage standardMessage) {
|
|
||||||
String guidSeq = getGuidSeq(standardMessage);
|
|
||||||
if (guidSeq == null)
|
|
||||||
return "";
|
|
||||||
int seq = 0;
|
|
||||||
try {
|
|
||||||
seq = Integer.parseInt(guidSeq) + 1;
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
seq = 1;
|
|
||||||
}
|
|
||||||
guidSeq = StringUtil.stringFormat(Integer.toString(seq), true, '0', 3);
|
|
||||||
setGuidSeq(standardMessage, guidSeq);
|
|
||||||
return guidSeq;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 표준전문의 복원은 COMMON.ORTR_RESTR_YN 의 value는 (Y/N) 엔진에서 복원여부 의 value는 (1/0)
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public String getRecoverYn(StandardMessage standardMessage) {
|
|
||||||
String data = getItemValue(standardMessage, getPath(RECOVER_YN));
|
|
||||||
if ("Y".equals(data)) {
|
|
||||||
return "1";
|
|
||||||
} else {
|
|
||||||
return "0";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setRecoverYn(StandardMessage standardMessage, String recoverYn) {
|
|
||||||
if ("1".equals(recoverYn)) {
|
|
||||||
setItemValue(standardMessage, getPath(RECOVER_YN), "Y");
|
|
||||||
} else {
|
|
||||||
setItemValue(standardMessage, getPath(RECOVER_YN), "N");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getInstCode(StandardMessage standardMessage) {
|
|
||||||
EAIServerManager server = EAIServerManager.getInstance();
|
|
||||||
if (server != null && server.isMCI()) {
|
|
||||||
return getItemValue(standardMessage, INSTANCE_ID);
|
|
||||||
} else {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setInstCode(StandardMessage standardMessage, String instCode) {
|
|
||||||
EAIServerManager server = EAIServerManager.getInstance();
|
|
||||||
if (server != null && server.isMCI()) {
|
|
||||||
setItemValue(standardMessage, INSTANCE_ID, instCode);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getSessionId(StandardMessage standardMessage) {
|
|
||||||
EAIServerManager server = EAIServerManager.getInstance();
|
|
||||||
if (server != null && server.isMCI()) {
|
|
||||||
return getItemValue(standardMessage, SESSION_ID);
|
|
||||||
} else {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setSessionId(StandardMessage standardMessage, String sessionId) {
|
|
||||||
EAIServerManager server = EAIServerManager.getInstance();
|
|
||||||
if (server != null && server.isMCI()) {
|
|
||||||
setItemValue(standardMessage, SESSION_ID, sessionId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
|
||||||
* 엔진 에서는 public static final String RESPONSE_TYPE_CODE_N = "0";//정상(normal)
|
|
||||||
* public static final String RESPONSE_TYPE_CODE_E = "1";//오류(error)
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void setResponseType(StandardMessage standardMessage, String responseType) {
|
|
||||||
if (responseType != null && (STDMessageKeys.RESPONSE_TYPE_CODE_N.equals(responseType)
|
|
||||||
|| STDMessageKeys.RESPONSE_TYPE_CODE_E.equals(responseType))) {
|
|
||||||
if (STDMessageKeys.RESPONSE_TYPE_CODE_N.equals(responseType)) {
|
|
||||||
setItemValue(standardMessage, getPath(RESPONSE_TYPE), "NR");
|
|
||||||
} else {
|
|
||||||
setItemValue(standardMessage, getPath(RESPONSE_TYPE), "ER");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setItemValue(standardMessage, getPath(RESPONSE_TYPE), responseType);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getInterfaceId(StandardMessage standardMessage) {
|
|
||||||
String interfaceId = getItemValue(standardMessage, getPath(INTERFACE_ID));
|
|
||||||
if (interfaceId == null)
|
|
||||||
return "";
|
|
||||||
interfaceId = interfaceId.trim();
|
|
||||||
return interfaceId;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getReqSysCode(StandardMessage standardMessage) {
|
|
||||||
// apiPath의 값에서 추출할 예정 : serviceId = api_path
|
|
||||||
String apiPath = getItemValue(standardMessage, getPath(SERVICE_ID));
|
|
||||||
if (apiPath != null) {
|
|
||||||
String[] split = apiPath.split("/");
|
|
||||||
if (split.length > 2) {
|
|
||||||
String route = split[1].toUpperCase();
|
|
||||||
if (route.length() > 3) {
|
|
||||||
route = route.substring(0, 3);
|
|
||||||
}
|
|
||||||
return route;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.message.StandardMessage;
|
|
||||||
import com.eactive.eai.message.service.DefaultInterfaceMapper;
|
|
||||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
|
||||||
|
|
||||||
@SuppressWarnings("serial")
|
|
||||||
public class InterfaceMapperSBI extends DefaultInterfaceMapper {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getSendRecvDivision(StandardMessage standardMessage) {
|
|
||||||
String sendRecvDivision = super.getSendRecvDivision(standardMessage);
|
|
||||||
if (StringUtils.equals(sendRecvDivision, "Q")) {
|
|
||||||
return STDMessageKeys.SEND_RECV_CD_SEND;
|
|
||||||
} else {
|
|
||||||
return sendRecvDivision;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,401 @@
|
|||||||
|
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.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
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.StandardType;
|
||||||
|
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");
|
||||||
|
|
||||||
|
// ${callProp.key} 또는 ${callProp.key:기본값} 패턴
|
||||||
|
private static final Pattern CALL_PROP_PATTERN =
|
||||||
|
Pattern.compile("\\$\\{callProp\\.([^}:]+)(?::([^}]*))?\\}");
|
||||||
|
|
||||||
|
// 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";
|
||||||
|
|
||||||
|
private String[] netInfo;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void coordinateAfterParsing(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
||||||
|
// TODO 표준전문을 수신할 경우, 전문의 interface id로 가져온 eaiSvcCd가 다른 값으로 치환되어야 할 수도 있다.
|
||||||
|
// 수신한 if_id를 기준으로 api gw의 eaiSvcCd를 매핑하는 프러퍼티가 있어야 한다.
|
||||||
|
// PropGroup : DJB_IN_STDHEAD_IFID_MAPPING, DJB_IN_HTTHEAD_STDHEAD_MAPPING
|
||||||
|
// standardMessage.setEaiSvcCd(mappedIfId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void coordinateAfterCreateMessageByRule(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
||||||
|
StandardMessageManager manager = StandardMessageManager.getInstance();
|
||||||
|
InterfaceMapper mapper = manager.getMapper();
|
||||||
|
|
||||||
|
// GUID 생성 (40자) 및 설정
|
||||||
|
String guid = GUIDGeneratorDJB.getGUID("OPA");
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// refValue="${callProp.키}" 필드에 Properties 값 주입
|
||||||
|
resolveCallPropRefValues(standardMessage, prop);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 void resolveCallPropRefValues(StandardMessage standardMessage, Properties prop) {
|
||||||
|
if (prop == null) return;
|
||||||
|
resolveCallPropInChilds(standardMessage.getChilds(), prop);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void resolveCallPropInChilds(LinkedHashMap<String, StandardItem> childs, Properties prop) {
|
||||||
|
if (childs == null) return;
|
||||||
|
for (StandardItem item : childs.values()) {
|
||||||
|
int type = item.getType();
|
||||||
|
if (type == StandardType.FIELD) {
|
||||||
|
String refValue = item.getRefValue();
|
||||||
|
if (refValue == null) continue;
|
||||||
|
Matcher m = CALL_PROP_PATTERN.matcher(refValue);
|
||||||
|
if (m.matches()) {
|
||||||
|
String key = m.group(1);
|
||||||
|
String defaultVal = m.group(2) != null ? m.group(2) : "";
|
||||||
|
String resolved = resolveCallPropValue(prop, key);
|
||||||
|
item.setValue(resolved != null ? resolved : defaultVal);
|
||||||
|
}
|
||||||
|
} else if (type == StandardType.GROUP) {
|
||||||
|
resolveCallPropInChilds(item.getChilds(), prop);
|
||||||
|
}
|
||||||
|
// GRID, FARRAY, BIZDATA: 배열/업무데이터 영역은 건너뜀
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Properties/Map 중첩 구조에서 점(.) 구분 keyPath로 값을 탐색한다.
|
||||||
|
* Properties는 Map을 구현하므로 Map<?,?> 단일 메서드로 통일한다.
|
||||||
|
* - "aaa.bbb" : map.get("aaa")가 Map(Properties 포함)이면 그 안에서 "bbb" 재귀 조회
|
||||||
|
* - 중간 값이 Map이 아니면 전체 keyPath로 폴백 조회
|
||||||
|
* - 값을 찾지 못하면 null 반환
|
||||||
|
*/
|
||||||
|
private String resolveCallPropValue(Properties props, String keyPath) {
|
||||||
|
return resolveNestedValue(props, keyPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private String resolveNestedValue(Map<?, ?> map, String keyPath) {
|
||||||
|
int dotIdx = keyPath.indexOf('.');
|
||||||
|
if (dotIdx < 0) {
|
||||||
|
Object val = map.get(keyPath);
|
||||||
|
if (val == null) return null;
|
||||||
|
if (val instanceof String) return (String) val;
|
||||||
|
return val.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
String first = keyPath.substring(0, dotIdx);
|
||||||
|
String rest = keyPath.substring(dotIdx + 1);
|
||||||
|
Object val = map.get(first);
|
||||||
|
if (val instanceof Map) {
|
||||||
|
return resolveNestedValue((Map<?, ?>) val, rest);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 폴백: 전체 keyPath를 단일 키로 조회
|
||||||
|
Object direct = map.get(keyPath);
|
||||||
|
if (direct == null) return null;
|
||||||
|
if (direct instanceof String) return (String) direct;
|
||||||
|
return direct.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getSysEnvDvcd(EAIServerManager server) {
|
||||||
|
if (server.isPEAIServer()) return "P"; // 운영
|
||||||
|
if (server.isSEAIServer()) return "T"; // 검증/테스트
|
||||||
|
return "D"; // 개발
|
||||||
|
}
|
||||||
|
|
||||||
|
private String[] collectNetworkInfo() {
|
||||||
|
if(this.netInfo != null)
|
||||||
|
return this.netInfo;
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
this.netInfo = new String[]{ipv4, mac};
|
||||||
|
return this.netInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
-419
@@ -1,419 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
|
||||||
import com.eactive.eai.common.message.EAIMessage;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.server.EAIServerManager;
|
|
||||||
import com.eactive.eai.common.util.DatetimeUtil;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.eactive.eai.common.util.MessageUtil;
|
|
||||||
import com.eactive.eai.custom.stderrorcode.ChannelErrorCodeManager;
|
|
||||||
import com.eactive.eai.custom.stderrorcode.ChannelErrorCodeVO;
|
|
||||||
import com.eactive.eai.custom.stderrorcode.StdErrorCodeManager;
|
|
||||||
import com.eactive.eai.custom.stderrorcode.StdErrorCodeVO;
|
|
||||||
import com.eactive.eai.inbound.error.InboundErrorKeys;
|
|
||||||
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.STDMessageErrorKeys;
|
|
||||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
|
||||||
|
|
||||||
public class StandardMessageCoordinatorKAKAOCARD extends DefaultStandardMessageCoordinator {
|
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
|
||||||
//private static int defaultTimeout = 30;
|
|
||||||
private static String GW_SESSION_ID = "INTERFACE_COMMON.GTWY_SESN_ID";
|
|
||||||
private static String GW_INSTANCE_ID = "INTERFACE_COMMON.GTWY_INSTNC_ID";
|
|
||||||
private static String MESSAGE_OUT_ATRB_CD = "MESSAGE.OUT_ATRB_CD";//출력속성코드
|
|
||||||
private static String MESSAGE_OUT_MSG_DESC = "MESSAGE.OUT_MSG_DESC";//출력메시지설명
|
|
||||||
private static String COMMON_OUT_FMSG_DSTCD = "COMMON.OUT_FMSG_DSTCD";//출력전문구별코드
|
|
||||||
private static String MESSAGE = "MESSAGE";//메시지부
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void coordinateAfterParsing(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
|
||||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
|
||||||
InterfaceMapper mapper = standardManager.getMapper();
|
|
||||||
//표준에서 들어올때 표준전문의 값을 header에 셋팅
|
|
||||||
//표준전문 to prop
|
|
||||||
if (EAIServerManager.getInstance().isFEP()) {
|
|
||||||
StandardItem gwSesnId = standardMessage.findItem(GW_SESSION_ID);//transactionId
|
|
||||||
StandardItem gwNodeNo = standardMessage.findItem(GW_INSTANCE_ID);//instanceId
|
|
||||||
if (gwSesnId != null && gwNodeNo != null && StringUtils.isNotBlank(gwSesnId.getValue()) && StringUtils.isNotBlank(gwNodeNo.getValue())) {
|
|
||||||
prop.put(HttpClientAdapterServiceKey.TRANSACTION_ID, gwSesnId.getValue());
|
|
||||||
prop.put(HttpClientAdapterServiceKey.INSTANCE_ID, gwNodeNo.getValue());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// REST용 전달값 중 api_path 이후의 값을 표준전문 API_PATH에 셋팅
|
|
||||||
String adapterApiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH);
|
|
||||||
if (StringUtils.isNotBlank(adapterApiPath)) {
|
|
||||||
String adapterExtUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
|
|
||||||
/*
|
|
||||||
* apiPath 나머지를 추출하기 위해서
|
|
||||||
* 예) 어댑터에 설정되어 있는 API_PATH = /api/cts
|
|
||||||
* 어댑터에 들어온 INBOUND_EXTURI = /api/cts/cmb/api/user/custom
|
|
||||||
* 표준전문에 셋팅하고 싶은값 /cmb/api/user/custom
|
|
||||||
*/
|
|
||||||
String standardApiPath = adapterExtUri.replaceAll(adapterApiPath, "");
|
|
||||||
if (!standardApiPath.startsWith("/")) {
|
|
||||||
standardApiPath = standardApiPath + "/";
|
|
||||||
}
|
|
||||||
if (standardApiPath.length() > 1) {
|
|
||||||
mapper.setServiceId(standardMessage,standardApiPath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//아래로직은 표준전문에서 요청일때 MESSAGE부가 안보이고 응답일때 MESSAGE부 보이게 설정
|
|
||||||
String sendRecvDivision = mapper.getSendRecvDivision(standardMessage);
|
|
||||||
StandardItem msg = standardMessage.findItem(MESSAGE);
|
|
||||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_SEND)) {
|
|
||||||
msg.setHidden(true);
|
|
||||||
}
|
|
||||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
|
||||||
msg.setHidden(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
//mci이고 요청 거래시에 설정 인스턴스ID설정
|
|
||||||
EAIServerManager server = EAIServerManager.getInstance();
|
|
||||||
if (server != null && server.isMCI() && (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_SEND))) {
|
|
||||||
//인스턴스ID설정
|
|
||||||
String instCode = mapper.getInstCode(standardMessage);
|
|
||||||
String localServer = server.getLocalServerName();
|
|
||||||
if (instCode != null && localServer != null) {
|
|
||||||
mapper.setInstCode(standardMessage, localServer);
|
|
||||||
}
|
|
||||||
//타임아웃값이 없을경우 default값 설정
|
|
||||||
String timeout = mapper.getTimeout(standardMessage);
|
|
||||||
|
|
||||||
int defaultTimeout = getDefaultTimeout();
|
|
||||||
if (StringUtils.isBlank(timeout)) {
|
|
||||||
mapper.setTimeout(standardMessage, Integer.toString(defaultTimeout));
|
|
||||||
}else {
|
|
||||||
try {
|
|
||||||
Integer.parseInt(timeout);
|
|
||||||
}catch(Exception e) {
|
|
||||||
mapper.setTimeout(standardMessage, Integer.toString(defaultTimeout));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//TODO 표준전문 메시지 설정해야됨
|
|
||||||
//표준전문에 메시지 부에 값이 있을경우 처리
|
|
||||||
if (!msg.isHidden()) {
|
|
||||||
String errmsg = mapper.getErrorMsg(standardMessage);
|
|
||||||
if (StringUtils.isBlank(errmsg)) {
|
|
||||||
String errCode = mapper.getErrorCode(standardMessage);
|
|
||||||
if (StringUtils.isNotBlank(errCode)) {
|
|
||||||
StdErrorCodeManager manager = StdErrorCodeManager.getInstance();
|
|
||||||
StdErrorCodeVO vo = manager.getSTDErrorCode(errCode);
|
|
||||||
if (vo != null) {
|
|
||||||
mapper.setErrorMsg(standardMessage, vo.getErrMsg());
|
|
||||||
if (server != null && server.isMCI()) {
|
|
||||||
String type = mapper.getChannelDetailCd(standardMessage);
|
|
||||||
//채널오류코드 셋팅
|
|
||||||
ChannelErrorCodeManager cmanager = ChannelErrorCodeManager.getInstance();
|
|
||||||
ChannelErrorCodeVO cvo = cmanager.getChannelErrorCode(errCode+"_"+type);
|
|
||||||
if (cvo != null) {
|
|
||||||
mapper.setErrorMsg(standardMessage, cvo.getErrMsg());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
//비표준처리
|
|
||||||
public void coordinateAfterCreateMessageByRule(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
|
||||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
|
||||||
InterfaceMapper mapper = standardManager.getMapper();
|
|
||||||
//비표준에서 들어올때 header값을 표준전문에 셋팅
|
|
||||||
//prop to 표준전문
|
|
||||||
if (EAIServerManager.getInstance().isFEP()) {
|
|
||||||
String trandactionId = prop.getProperty(HttpClientAdapterServiceKey.TRANSACTION_ID);
|
|
||||||
String instanceId = prop.getProperty(HttpClientAdapterServiceKey.INSTANCE_ID);
|
|
||||||
if (StringUtils.isNotBlank(trandactionId) && StringUtils.isNotBlank(instanceId)) {
|
|
||||||
StandardItem gwSesnId = standardMessage.findItem(GW_SESSION_ID);//transactionId
|
|
||||||
if (gwSesnId != null) {
|
|
||||||
gwSesnId.setValue(trandactionId);
|
|
||||||
}
|
|
||||||
StandardItem gwNodeNo = standardMessage.findItem(GW_INSTANCE_ID);//instanceId
|
|
||||||
if (gwNodeNo != null) {
|
|
||||||
gwNodeNo.setValue(instanceId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
|
||||||
//HEADER.GUID설정
|
|
||||||
mapper.setGuid(standardMessage,GUIDGeneratorKAKAOCARD.getGUID(eaiServerManager.getSystemType()));
|
|
||||||
//HEADER.FMSG_REQ_RES_DSTCD 전문요청응답구별코드 : 표준전문값
|
|
||||||
|
|
||||||
//HEADER.FRST_TRNM_IPAD 최초전송IP주소
|
|
||||||
mapper.setFirstReqIp(standardMessage, "0.0.0.0");
|
|
||||||
//HEADER.GNRZ_TMOT_TM 총괄타임아웃시간
|
|
||||||
mapper.setTimeout(standardMessage, "180");
|
|
||||||
// HEADER.SYS_ENV_DSTCD 시스템운영환경구분코드
|
|
||||||
String operationEnv = mapper.getOperationEnv(standardMessage);
|
|
||||||
if (operationEnv != null && StringUtils.isBlank(operationEnv)) {
|
|
||||||
mapper.setOperationEnv(standardMessage, getSysOprtEnvDvcd(eaiServerManager));
|
|
||||||
}
|
|
||||||
// HEADER.CARD_TX_TYP_DSTCD 거래유형구별코드
|
|
||||||
StandardItem cardTxTypDstcd = standardMessage.findItem("HEADER.CARD_TX_TYP_DSTCD");
|
|
||||||
if (cardTxTypDstcd != null ) {
|
|
||||||
cardTxTypDstcd.setValue("O");
|
|
||||||
}
|
|
||||||
//COMMON.GROUP_CMP_CD 그룹회사코드
|
|
||||||
StandardItem groupCmpCd = standardMessage.findItem("COMMON.GROUP_CMP_CD");
|
|
||||||
if (groupCmpCd != null ) {
|
|
||||||
groupCmpCd.setValue("090");
|
|
||||||
}
|
|
||||||
//COMMON.TX_BRCD 거래부점코드
|
|
||||||
StandardItem txBrcd = standardMessage.findItem("COMMON.TX_BRCD");
|
|
||||||
if (txBrcd != null ) {
|
|
||||||
txBrcd.setValue("0000");
|
|
||||||
}
|
|
||||||
//COMMON.RLTR_BRCD 실거래부점코드
|
|
||||||
StandardItem rltrBrcd = standardMessage.findItem("COMMON.RLTR_BRCD");
|
|
||||||
if (rltrBrcd != null ) {
|
|
||||||
rltrBrcd.setValue("0000");
|
|
||||||
}
|
|
||||||
//COMMON.TLRNO 텔러번호
|
|
||||||
StandardItem tlrno = standardMessage.findItem("COMMON.TLRNO");
|
|
||||||
if (tlrno != null ) {
|
|
||||||
tlrno.setValue("000000");
|
|
||||||
}
|
|
||||||
//COMMON.TX_DT 거래일자
|
|
||||||
StandardItem txDt = standardMessage.findItem("COMMON.TX_DT");
|
|
||||||
if (txDt != null ) {
|
|
||||||
txDt.setValue(DatetimeUtil.getFormattedDate("yyyyMMdd"));
|
|
||||||
}
|
|
||||||
//COMMON.TX_TM 거래시간
|
|
||||||
StandardItem txTm = standardMessage.findItem("COMMON.TX_TM");
|
|
||||||
if (txTm != null ) {
|
|
||||||
txTm.setValue(DatetimeUtil.getFormattedDate("HHmmssSSS"));
|
|
||||||
}
|
|
||||||
|
|
||||||
//아래로직은 표준전문에서 요청일때 MESSAGE부가 안보이고 응답일때 MESSAGE부 보이게 설정
|
|
||||||
String sendRecvDivision = mapper.getSendRecvDivision(standardMessage);
|
|
||||||
StandardItem msg = standardMessage.findItem(MESSAGE);
|
|
||||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_SEND)) {
|
|
||||||
msg.setHidden(true);
|
|
||||||
}
|
|
||||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
|
||||||
msg.setHidden(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
//TODO 표준전문 메시지 설정해야됨
|
|
||||||
//응답일경우 MESSAGE부에 정상 메시지 헤더를 설정하기 위해서
|
|
||||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
|
||||||
StandardItem outputAtrbCd = standardMessage.findItem(MESSAGE_OUT_ATRB_CD);//출력속성코드
|
|
||||||
outputAtrbCd.setValue("1");
|
|
||||||
|
|
||||||
mapper.setErrorCode(standardMessage, STDMessageErrorKeys.SUCCESS_CODE_VALUE);
|
|
||||||
mapper.setErrorMsg(standardMessage, STDMessageErrorKeys.SUCCESS_MSG_VALUE);
|
|
||||||
mapper.setResponseType(standardMessage, STDMessageKeys.RESPONSE_TYPE_CODE_N);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public void coordinateInReturnObject(StandardMessage standardMessage) {
|
|
||||||
//아래로직은 표준전문에서 응답일때 MESSAGE부가 보이게 하기위해서
|
|
||||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
|
||||||
InterfaceMapper mapper = standardManager.getMapper();
|
|
||||||
mapper.setSendRecvDivision(standardMessage, STDMessageKeys.SEND_RECV_CD_RECV);
|
|
||||||
StandardItem msg = standardMessage.findItem(MESSAGE);
|
|
||||||
msg.setHidden(false);
|
|
||||||
}
|
|
||||||
public String getSysOprtEnvDvcd(EAIServerManager eaiServerManager) {
|
|
||||||
String result = "";
|
|
||||||
if (eaiServerManager.isPEAIServer()) { // 운영
|
|
||||||
result = "R";
|
|
||||||
} else if (eaiServerManager.isDEAIServer()) { // 개발
|
|
||||||
result = "D";
|
|
||||||
} else if (eaiServerManager.isSEAIServer()) { // 테스트/검증
|
|
||||||
result = "T";
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void coordinateBeforeInboundErrorResponse(StandardMessage standardMessage) {
|
|
||||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
|
||||||
InterfaceMapper mapper = standardManager.getMapper();
|
|
||||||
mapper.setSendRecvDivision(standardMessage, STDMessageKeys.SEND_RECV_CD_RECV);
|
|
||||||
StandardItem msg = standardMessage.findItem(MESSAGE);
|
|
||||||
msg.setHidden(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean coordinateSetStandardMessageError(StandardMessage standardMessage, InterfaceMapper mapper,
|
|
||||||
String errCode, String errMsg) {
|
|
||||||
String siteErrCode = null;
|
|
||||||
String siteErrMessage = null;
|
|
||||||
if(errCode != null) {
|
|
||||||
siteErrCode = MessageUtil.getTobeCode(errCode);
|
|
||||||
siteErrMessage = MessageUtil.getTobeMessage(errCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
String sendRecvDivision = mapper.getSendRecvDivision(standardMessage);
|
|
||||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
|
||||||
StandardItem msg = standardMessage.findItem(MESSAGE);
|
|
||||||
msg.setHidden(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
StandardItem outputAtrbCd = standardMessage.findItem(MESSAGE_OUT_ATRB_CD);//출력속성코드
|
|
||||||
outputAtrbCd.setValue("1");
|
|
||||||
|
|
||||||
if (siteErrCode != null) {
|
|
||||||
mapper.setErrorCode(standardMessage, siteErrCode);
|
|
||||||
}else if (errCode != null) {
|
|
||||||
mapper.setErrorCode(standardMessage, errCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (siteErrMessage != null) {
|
|
||||||
mapper.setErrorMsg(standardMessage, siteErrMessage);
|
|
||||||
}else if (errMsg != null){
|
|
||||||
mapper.setErrorMsg(standardMessage, errMsg);
|
|
||||||
}
|
|
||||||
|
|
||||||
StandardItem outputMsgDesc = standardMessage.findItem(MESSAGE_OUT_MSG_DESC);//출력메시지설명
|
|
||||||
if (errMsg != null){
|
|
||||||
outputMsgDesc.setValue(errMsg);
|
|
||||||
}
|
|
||||||
mapper.setResponseType(standardMessage, STDMessageKeys.RESPONSE_TYPE_CODE_E);
|
|
||||||
|
|
||||||
return false;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
//복원시
|
|
||||||
public void coordinateAfterRestored(StandardMessage dbMessage, StandardMessage responseMessage) {
|
|
||||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
|
||||||
InterfaceMapper mapper = standardManager.getMapper();
|
|
||||||
String interfaceId = mapper.getInterfaceId(responseMessage);
|
|
||||||
mapper.setInterfaceId(dbMessage, interfaceId);
|
|
||||||
|
|
||||||
String sendRecvDivision = mapper.getSendRecvDivision(responseMessage);
|
|
||||||
mapper.setSendRecvDivision(dbMessage, sendRecvDivision);
|
|
||||||
|
|
||||||
String inExDivision = mapper.getInExDivision(responseMessage);
|
|
||||||
mapper.setInExDivision(dbMessage, inExDivision);
|
|
||||||
|
|
||||||
String recoverYn = mapper.getRecoverYn(responseMessage);
|
|
||||||
mapper.setRecoverYn(dbMessage, recoverYn);
|
|
||||||
|
|
||||||
//복원시 처리결과수신 서비스코드를 서비스코드에 셋팅한다.
|
|
||||||
//처리결과수신값이 없을경우 원거래 서비스ID를 셋팅한다.
|
|
||||||
String returnServiceId = mapper.getReturnServiceId(dbMessage);
|
|
||||||
if (StringUtils.isBlank(returnServiceId)){
|
|
||||||
returnServiceId = mapper.getServiceId(dbMessage);
|
|
||||||
}
|
|
||||||
mapper.setServiceId(dbMessage, returnServiceId);
|
|
||||||
|
|
||||||
//표준전문 메시지 관련 설정
|
|
||||||
String dbSendRecvDivision = mapper.getSendRecvDivision(dbMessage);
|
|
||||||
StandardItem msg = dbMessage.findItem(MESSAGE);
|
|
||||||
if ( StringUtils.equals(dbSendRecvDivision, STDMessageKeys.SEND_RECV_CD_SEND)) {
|
|
||||||
msg.setHidden(true);
|
|
||||||
}
|
|
||||||
if (StringUtils.equals(dbSendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
|
||||||
msg.setHidden(false);
|
|
||||||
}
|
|
||||||
//응답일경우 MESSAGE부 정상설정
|
|
||||||
if (StringUtils.equals(dbSendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
|
||||||
StandardItem outputAtrbCd = dbMessage.findItem(MESSAGE_OUT_ATRB_CD);//출력속성코드
|
|
||||||
outputAtrbCd.setValue("1");
|
|
||||||
|
|
||||||
mapper.setErrorCode(dbMessage, STDMessageErrorKeys.SUCCESS_CODE_VALUE);//출력메시지코드
|
|
||||||
mapper.setErrorMsg(dbMessage, STDMessageErrorKeys.SUCCESS_MSG_VALUE);//출력메시지내용
|
|
||||||
mapper.setResponseType(dbMessage, STDMessageKeys.RESPONSE_TYPE_CODE_N);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public boolean coordinateIsWaitCheckForSync(StandardMessage responseMessage) {
|
|
||||||
StandardItem outputMesgTycd = responseMessage.findItem(COMMON_OUT_FMSG_DSTCD);
|
|
||||||
if (outputMesgTycd != null && StringUtils.equals(outputMesgTycd.getValue(), "9")) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public int coordinateForTimeoutCodeToValue(EAIMessage eaiMessage) {
|
|
||||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
|
||||||
InterfaceMapper mapper = standardManager.getMapper();
|
|
||||||
EAIServerManager server = EAIServerManager.getInstance();
|
|
||||||
if (server != null && server.isMCI()) { //MCI 일경우 처리
|
|
||||||
StandardMessage standardMessage = eaiMessage.getStandardMessage();
|
|
||||||
String timeout = mapper.getTimeout(standardMessage);
|
|
||||||
int defaultTimeout = getDefaultTimeout();
|
|
||||||
|
|
||||||
if (StringUtils.isBlank(timeout)) {
|
|
||||||
return defaultTimeout;
|
|
||||||
}else {
|
|
||||||
try {
|
|
||||||
return Integer.parseInt(timeout);
|
|
||||||
}catch(Exception e) {
|
|
||||||
return defaultTimeout;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}else { //MCI 이외일 경우 처리 (인터페이스에 있는 타임아웃기준)
|
|
||||||
return eaiMessage.getCurrentSvcMsg().getTmoVl();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private int getDefaultTimeout() {
|
|
||||||
PropManager manager = PropManager.getInstance();
|
|
||||||
int defaultTimeout = 30;
|
|
||||||
try {
|
|
||||||
String sdefaultTimeout = manager.getProperty("KAKAO_CARD", "DEFAULT_TIMEOUT", Integer.toString(defaultTimeout));
|
|
||||||
defaultTimeout = Integer.parseInt(sdefaultTimeout);
|
|
||||||
}catch(Exception e) {
|
|
||||||
|
|
||||||
}
|
|
||||||
return defaultTimeout;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean coordinateValidation(StandardMessage standardMessage, ProcessVO vo) {
|
|
||||||
// RECEAIIRP110 인터페이스 ({1}) 에 표준전문 항목 ({2}) 의 값이 없습니다.
|
|
||||||
// RECEAIIRP120 인터페이스 ({1}) 에 표준전문 항목 ({2}) 의 값을 확인하세요.
|
|
||||||
|
|
||||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
|
||||||
InterfaceMapper mapper = standardManager.getMapper();
|
|
||||||
String interfaceId = mapper.getInterfaceId(standardMessage);
|
|
||||||
|
|
||||||
String guid = mapper.getGuid(standardMessage);
|
|
||||||
if (StringUtils.isBlank(guid)) {
|
|
||||||
vo.setRspErrorCode("RECEAIIRP110");
|
|
||||||
vo.setRspErrorMsg(ExceptionUtil.make(vo.getRspErrorCode(), new String[] { interfaceId, "GUID" }));
|
|
||||||
vo.setErrTypeCode(InboundErrorKeys.IN_ERROR);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
String guidSeq = mapper.getGuidSeq(standardMessage);
|
|
||||||
if (StringUtils.isBlank(guidSeq)) {
|
|
||||||
vo.setRspErrorCode("RECEAIIRP110");
|
|
||||||
vo.setRspErrorMsg(ExceptionUtil.make(vo.getRspErrorCode(), new String[] { interfaceId, "GUID" }));
|
|
||||||
vo.setErrTypeCode(InboundErrorKeys.IN_ERROR);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (guid.length() + guidSeq.length() != 36) {
|
|
||||||
vo.setRspErrorCode("RECEAIIRP120");
|
|
||||||
vo.setRspErrorMsg(ExceptionUtil.make(vo.getRspErrorCode(), new String[] { interfaceId, "GUID" }));
|
|
||||||
vo.setErrTypeCode(InboundErrorKeys.IN_ERROR);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import com.eactive.eai.common.server.EAIServerManager;
|
|
||||||
import com.eactive.eai.common.server.Keys;
|
|
||||||
import com.eactive.eai.common.util.DatetimeUtil;
|
|
||||||
import com.eactive.eai.common.util.MessageUtil;
|
|
||||||
import com.eactive.eai.common.util.StringUtil;
|
|
||||||
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;
|
|
||||||
|
|
||||||
public class StandardMessageCoordinatorKBANK extends DefaultStandardMessageCoordinator {
|
|
||||||
|
|
||||||
private static final String MESSAGE_PART_SUB_MSG_GOUP = "message_part.subMsgGoup";
|
|
||||||
private static final String MESSAGE_PART_MSG_TYPE = "message_part.msgType";
|
|
||||||
private static final String MESSAGE_PART = "message_part";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void coordinateAfterParsing(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void coordinateAfterCreateMessageByRule(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
|
||||||
// guid 설정
|
|
||||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
|
||||||
InterfaceMapper mapper = standardManager.getMapper();
|
|
||||||
|
|
||||||
String guid = GUIDGeneratorKBANK.makeGUID();
|
|
||||||
|
|
||||||
mapper.setGuid(standardMessage, guid);
|
|
||||||
|
|
||||||
String orgGuid = guid + mapper.getGuidSeq(standardMessage);
|
|
||||||
|
|
||||||
mapper.setOrgGuid(standardMessage, orgGuid);
|
|
||||||
|
|
||||||
mapper.setOperationEnv(standardMessage, System.getProperty(Keys.EAI_SYSTEMMODE));
|
|
||||||
|
|
||||||
mapper.setFirstReqIp(standardMessage, EAIServerManager.getInstance().getServerIp());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean coordinateSetStandardMessageError(StandardMessage standardMessage, InterfaceMapper mapper,
|
|
||||||
String errCode, String errMsg) {
|
|
||||||
|
|
||||||
mapper.setResponseType(standardMessage, STDMessageKeys.RESPONSE_TYPE_CODE_E);
|
|
||||||
|
|
||||||
StandardItem messagePart = standardMessage.findItem(MESSAGE_PART);
|
|
||||||
messagePart.setHidden(false);
|
|
||||||
messagePart.setSize(1);
|
|
||||||
StandardItem messageType = standardMessage.findItem(MESSAGE_PART_MSG_TYPE);
|
|
||||||
messageType.setValue("99");
|
|
||||||
StandardItem subMsgGoup = standardMessage.findItem(MESSAGE_PART_SUB_MSG_GOUP);
|
|
||||||
subMsgGoup.getList().clear();
|
|
||||||
subMsgGoup.setRefValue("0");
|
|
||||||
|
|
||||||
if(errCode != null) {
|
|
||||||
String siteErrCode = MessageUtil.getTobeCode(errCode);
|
|
||||||
String siteErrMessage;
|
|
||||||
switch(errCode) {
|
|
||||||
case("RECEAIIRP070"):
|
|
||||||
siteErrMessage = "거래 통제 되었습니다.";
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
siteErrMessage = MessageUtil.getTobeMessage(errCode); break;
|
|
||||||
}
|
|
||||||
|
|
||||||
mapper.setErrorCode(standardMessage, siteErrCode);
|
|
||||||
mapper.setErrorMsg(standardMessage, siteErrMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void coordinateAfterRecvNonStdSyncResponse(StandardMessage responseMessage) {
|
|
||||||
StandardItem messagePart = responseMessage.findItem(MESSAGE_PART);
|
|
||||||
messagePart.setHidden(false);
|
|
||||||
messagePart.setSize(1);
|
|
||||||
StandardItem subMsgGoup = responseMessage.findItem(MESSAGE_PART_SUB_MSG_GOUP);
|
|
||||||
subMsgGoup.getList().clear();
|
|
||||||
subMsgGoup.setRefValue("0");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,198 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
|
||||||
import com.eactive.eai.common.dao.Keys;
|
|
||||||
import com.eactive.eai.common.server.EAIServerManager;
|
|
||||||
import com.eactive.eai.common.util.DatetimeUtil;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.eactive.eai.common.util.MessageUtil;
|
|
||||||
import com.eactive.eai.common.util.StringUtil;
|
|
||||||
import com.eactive.eai.inbound.processor.ProcessVO;
|
|
||||||
import com.eactive.eai.inbound.processor.Processor;
|
|
||||||
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;
|
|
||||||
import org.apache.commons.lang.StringUtils;
|
|
||||||
|
|
||||||
import java.net.UnknownHostException;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
public class StandardMessageCoordinatorKJB extends DefaultStandardMessageCoordinator {
|
|
||||||
private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
|
||||||
|
|
||||||
private static final String MESSAGE_PART = "Message";
|
|
||||||
private static final String MESSAGE_PART_HEADER_PART = "Message.Msg_Header";
|
|
||||||
private static final String MESSAGE_PART_MSG_HEDR_KNCD = "Message.Msg_Header.MSG_HEDR_KNCD";
|
|
||||||
private static final String MESSAGE_PART_MSG_HEDR_LEN = "Message.Msg_Header.MSG_HEDR_LEN";
|
|
||||||
private static final String MESSAGE_PART_BODY_PART = "Message.Msg_Body";
|
|
||||||
private static final String MESSAGE_PART_OUTPUT_MSG_CD = "Message.Msg_Body.OUTPUT_MSG_CD";
|
|
||||||
private static final String MESSAGE_PART_OUTPUT_MSG_CTNT = "Message.Msg_Body.OUTPUT_MSG_CTNT";
|
|
||||||
private static final String MESSAGE_PART_OUTPUT_MSG_GRID = "Message.Msg_Body.Output_Msg_Grid";
|
|
||||||
private static final String COMMON_PART_GROUP_CMD_CD = "Common.Service_info.GROUP_CMP_CD";
|
|
||||||
private static final String COMMON_PART_OTSD_CHNL_INST_CD = "Common.Service_info.OTSD_CHNL_INST_CD";
|
|
||||||
private static final String DATA_HEADER_DATA_HEDR_LEN = "Data_Part.Data_Header.DATA_HEDR_LEN";
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void coordinateAfterParsing(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void coordinateBeforeStandardMessageSend(StandardMessage standardMessage, String msgType, String charset) {
|
|
||||||
makeupDataHeaderLength(standardMessage, charset);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void coordinateBeforeResponse(StandardMessage standardMessage, ProcessVO processVO, Properties prop, String charset) {
|
|
||||||
makeupDataHeaderLength(standardMessage, charset);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void coordinateAfterCreateMessageByRule(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
|
||||||
// guid 설정
|
|
||||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
|
||||||
InterfaceMapper mapper = standardManager.getMapper();
|
|
||||||
|
|
||||||
//GUID 설정
|
|
||||||
String groupCmdCd = standardMessage.findItemValue(COMMON_PART_GROUP_CMD_CD);
|
|
||||||
|
|
||||||
String guid = GUIDGeneratorKJB.getGUID(groupCmdCd);
|
|
||||||
|
|
||||||
mapper.setGuid(standardMessage, guid);
|
|
||||||
|
|
||||||
StandardItem dataHeaderEtc = standardMessage.findItem("Data_Part.Data_Header_Etc");
|
|
||||||
dataHeaderEtc.setHidden(true);
|
|
||||||
|
|
||||||
//기관코드, 텔러번호 설정
|
|
||||||
//Adapter에 셋팅된 기관코드를 셋팅한다.
|
|
||||||
String adapterGroupName = prop.getProperty(Processor.ADAPTER_GROUP_NAME);
|
|
||||||
AdapterManager adapterManager = AdapterManager.getInstance();
|
|
||||||
AdapterGroupVO adptGrpVO = adapterManager.getAdapterGroupVO(adapterGroupName);
|
|
||||||
|
|
||||||
// Adapter의 기관코드를 얻어온다.
|
|
||||||
//TODO: 기관코드의 경우 현재 EAPIM 시스템에 컬럼은 있으나 설정을 사용하지 않고있으므로 불필요 할 경우 사용하지 않는다, 필요 할 경우 추가한다.
|
|
||||||
String inAdapterOsidInstiNo = adptGrpVO.getOsidInstiNo();
|
|
||||||
if(inAdapterOsidInstiNo != null && inAdapterOsidInstiNo.trim().length() > 0) {
|
|
||||||
standardMessage.setData(COMMON_PART_OTSD_CHNL_INST_CD, inAdapterOsidInstiNo);
|
|
||||||
if (logger.isDebug()) {
|
|
||||||
logger.debug("FIELD SET " + COMMON_PART_OTSD_CHNL_INST_CD + " << "+inAdapterOsidInstiNo);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//2012-12-17 나영채 차장 타발요청에만 셋팅해달라고 요청
|
|
||||||
//전문요청일자
|
|
||||||
standardMessage.setData("Common.BizProc_Info.MESG_DMAN_DT", DatetimeUtil.getCurrentDate());
|
|
||||||
//전문요청시간
|
|
||||||
standardMessage.setData("Common.BizProc_Info.MESG_DMAN_TKTM", DatetimeUtil.getFormattedDate("HHmmssSSS"));
|
|
||||||
|
|
||||||
|
|
||||||
//2012-07-24 임의 로 영업일자에 system시간 설정
|
|
||||||
standardMessage.setData("Common.BizProc_Info.BZOP_DT", DatetimeUtil.getCurrentDate());
|
|
||||||
|
|
||||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
|
||||||
//비표준일경우 시스템 운영환경 구분코드를 셋팅한다.
|
|
||||||
standardMessage.setData("Common.Service_info.SYS_OPRT_ENV_DVCD", getSysOprtEnvDvcd(eaiServerManager));
|
|
||||||
|
|
||||||
//헤더부 최초전송IP주소 FRST_TRNM_IPAD
|
|
||||||
try {
|
|
||||||
standardMessage.setData("Header.Src_System.FRST_TRNM_IPAD", java.net.InetAddress.getLocalHost().getHostAddress());
|
|
||||||
} catch (UnknownHostException e) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean coordinateSetStandardMessageError(StandardMessage standardMessage, InterfaceMapper mapper,
|
|
||||||
String errCode, String errMsg) {
|
|
||||||
|
|
||||||
mapper.setResponseType(standardMessage, STDMessageKeys.RESPONSE_TYPE_CODE_E);
|
|
||||||
mapper.setSendRecvDivision(standardMessage, STDMessageKeys.SEND_RECV_CD_RECV);
|
|
||||||
|
|
||||||
StandardItem messagePart = standardMessage.findItem(MESSAGE_PART);
|
|
||||||
messagePart.setHidden(false);
|
|
||||||
messagePart.setSize(1);
|
|
||||||
|
|
||||||
StandardItem messageHeaderPart = standardMessage.findItem(MESSAGE_PART_HEADER_PART);
|
|
||||||
messageHeaderPart.setSize(1);
|
|
||||||
StandardItem messageBodyPart = standardMessage.findItem(MESSAGE_PART_BODY_PART);
|
|
||||||
messageBodyPart.setSize(1);
|
|
||||||
|
|
||||||
errCode = StringUtils.defaultString(errCode);
|
|
||||||
String siteErrCode = MessageUtil.getTobeCode(errCode);
|
|
||||||
String siteErrMessage;
|
|
||||||
switch(errCode) {
|
|
||||||
case("RECEAIIRP070"):
|
|
||||||
siteErrMessage = "거래 통제 되었습니다.";
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
siteErrMessage = MessageUtil.getTobeMessage(errCode);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
mapper.setErrorCode(standardMessage, siteErrCode);
|
|
||||||
|
|
||||||
standardMessage.setData(MESSAGE_PART_MSG_HEDR_KNCD, "EM");
|
|
||||||
standardMessage.setData(MESSAGE_PART_OUTPUT_MSG_CD, siteErrCode);
|
|
||||||
StandardItem msgGrid = standardMessage.findItem(MESSAGE_PART_OUTPUT_MSG_GRID);
|
|
||||||
LinkedHashMap<String, StandardItem> msgGridFirstChilds = msgGrid.getArrayChilds(0, true);
|
|
||||||
msgGridFirstChilds.get("OUTPUT_MSG_CD").setValue(siteErrCode);
|
|
||||||
msgGridFirstChilds.get("OUTPUT_MSG_CTNT").setValue(siteErrMessage);
|
|
||||||
//Message.Msg_Body.OUTPUT_MSG_CTNT
|
|
||||||
mapper.setErrorMsg(standardMessage, siteErrMessage);
|
|
||||||
int len = standardMessage.getBytesDataLengthForPath(MESSAGE_PART_BODY_PART);
|
|
||||||
String lenStr = StringUtils.leftPad(String.valueOf(len), 8, '0');
|
|
||||||
standardMessage.setData(MESSAGE_PART_MSG_HEDR_LEN, lenStr);
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void coordinateAfterRecvNonStdSyncResponse(StandardMessage responseMessage) {
|
|
||||||
StandardItem messagePart = responseMessage.findItem(MESSAGE_PART);
|
|
||||||
messagePart.setHidden(false);
|
|
||||||
messagePart.setSize(1);
|
|
||||||
|
|
||||||
StandardItem messageHeaderPart = responseMessage.findItem(MESSAGE_PART_HEADER_PART);
|
|
||||||
messageHeaderPart.setSize(1);
|
|
||||||
StandardItem messageBodyPart = responseMessage.findItem(MESSAGE_PART_BODY_PART);
|
|
||||||
messageBodyPart.setSize(1);
|
|
||||||
|
|
||||||
responseMessage.setData(MESSAGE_PART_MSG_HEDR_KNCD, "NM");
|
|
||||||
responseMessage.setData(MESSAGE_PART_OUTPUT_MSG_CD, "100000 ");
|
|
||||||
responseMessage.setData(MESSAGE_PART_OUTPUT_MSG_CTNT, "정상처리");
|
|
||||||
StandardItem msgGrid = responseMessage.findItem(MESSAGE_PART_OUTPUT_MSG_GRID);
|
|
||||||
LinkedHashMap<String, StandardItem> msgGridFirstChilds = msgGrid.getArrayChilds(0, true);
|
|
||||||
msgGridFirstChilds.get("OUTPUT_MSG_CD").setValue("100000 ");
|
|
||||||
msgGridFirstChilds.get("OUTPUT_MSG_CTNT").setValue("정상처리");
|
|
||||||
int len = responseMessage.getBytesDataLengthForPath(MESSAGE_PART_BODY_PART);
|
|
||||||
String lenStr = StringUtils.leftPad(String.valueOf(len), 8, '0');
|
|
||||||
responseMessage.setData(MESSAGE_PART_MSG_HEDR_LEN, lenStr);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSysOprtEnvDvcd(EAIServerManager eaiServerManager) {
|
|
||||||
String result = "";
|
|
||||||
if (eaiServerManager.isPEAIServer()){ //운영
|
|
||||||
result = STDMessageKeys.SYS_OPRT_ENV_DVCD_ONLINE;
|
|
||||||
}else if (eaiServerManager.isDEAIServer()){ //개발
|
|
||||||
result = STDMessageKeys.SYS_OPRT_ENV_DVCD_DEV;
|
|
||||||
}else if (eaiServerManager.isSEAIServer()){ //테스트/검증
|
|
||||||
result = STDMessageKeys.SYS_OPRT_ENV_DVCD_TESTSTAGE;
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void makeupDataHeaderLength(StandardMessage standardMessage, String charset) {
|
|
||||||
String dataBytesLengthStr = null;
|
|
||||||
try {
|
|
||||||
dataBytesLengthStr = String.valueOf(standardMessage.getBizDataBytes(charset).length);
|
|
||||||
String dataHeaderLength = StringUtils.leftPad(dataBytesLengthStr, 8, '0');
|
|
||||||
standardMessage.setData(DATA_HEADER_DATA_HEDR_LEN, dataHeaderLength);
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import java.net.InetAddress;
|
|
||||||
import java.net.UnknownHostException;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.common.server.EAIServerManager;
|
|
||||||
import com.eactive.eai.common.util.DatetimeUtil;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
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.eactive.eai.message.service.StandardMessageCoordinator;
|
|
||||||
|
|
||||||
public class StandardMessageCoordinatorSBI extends DefaultStandardMessageCoordinator {
|
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void coordinateAfterCreateMessageByRule(StandardMessage message, Object paramObject, Properties prop) {
|
|
||||||
// STD_HEADER.mesgDvcd 설정
|
|
||||||
StandardItem mesgDvcdItem = message.findItem("STD_HEADER.mesgDvcd");
|
|
||||||
if (mesgDvcdItem != null && StringUtils.equals(mesgDvcdItem.getValue(), "S")) {
|
|
||||||
mesgDvcdItem.setValue("Q");
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.mesgKind 설정
|
|
||||||
StandardItem mesgKindItem = message.findItem("STD_HEADER.mesgKind");
|
|
||||||
if (mesgKindItem != null && StringUtils.isBlank(mesgKindItem.getValue())) {
|
|
||||||
mesgKindItem.setValue("3"); // 3:데이터 4:시스템
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.envDvcd 설정
|
|
||||||
StandardItem envDvcdItem = message.findItem("STD_HEADER.envDvcd");
|
|
||||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
|
||||||
if (envDvcdItem != null && StringUtils.isBlank(envDvcdItem.getValue())) {
|
|
||||||
envDvcdItem.setValue(getSysOprtEnvDvcd(eaiServerManager));
|
|
||||||
}
|
|
||||||
|
|
||||||
// guid 설정
|
|
||||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
|
||||||
InterfaceMapper mapper = standardManager.getMapper();
|
|
||||||
mapper.setGuid(message,
|
|
||||||
GUIDGeneratorSBI.getGUID(getSysOprtEnvDvcd(eaiServerManager), eaiServerManager.getSystemType()));
|
|
||||||
|
|
||||||
// STD_HEADER.frstTrnmChnlCd 설정
|
|
||||||
StandardItem frstTrnmChnlCdItem = message.findItem("STD_HEADER.frstTrnmChnlCd");
|
|
||||||
if (frstTrnmChnlCdItem != null && StringUtils.isBlank(frstTrnmChnlCdItem.getValue())) {
|
|
||||||
frstTrnmChnlCdItem.setValue(eaiServerManager.getSystemType());
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.trnmChnlCd 설정
|
|
||||||
StandardItem trnmChnlCdItem = message.findItem("STD_HEADER.trnmChnlCd");
|
|
||||||
if (trnmChnlCdItem != null && StringUtils.isBlank(trnmChnlCdItem.getValue())) {
|
|
||||||
trnmChnlCdItem.setValue(eaiServerManager.getSystemType());
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.userNo 설정
|
|
||||||
StandardItem userNoItem = message.findItem("STD_HEADER.userNo");
|
|
||||||
if (userNoItem != null && StringUtils.isBlank(userNoItem.getValue())) {
|
|
||||||
ProcessVO processVo = (ProcessVO) paramObject;
|
|
||||||
if (StringUtils.isNotBlank(processVo.getInAdapterUserEmpid())) {
|
|
||||||
userNoItem.setValue(eaiServerManager.getSystemType());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.mesgDmndDttm 설정
|
|
||||||
StandardItem mesgDmndDttmItem = message.findItem("STD_HEADER.mesgDmndDttm");
|
|
||||||
if (mesgDmndDttmItem != null && StringUtils.isBlank(mesgDmndDttmItem.getValue())) {
|
|
||||||
mesgDmndDttmItem.setValue(DatetimeUtil.getCurrentTimeMillis());
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.ipAd 설정
|
|
||||||
StandardItem ipAdItem = message.findItem("STD_HEADER.ipAd");
|
|
||||||
if (ipAdItem != null && StringUtils.isBlank(ipAdItem.getValue())) {
|
|
||||||
try {
|
|
||||||
ipAdItem.setValue(InetAddress.getLocalHost().getHostAddress());
|
|
||||||
} catch (UnknownHostException e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.mesgTycd 설정
|
|
||||||
StandardItem mesgTycdItem = message.findItem("STD_HEADER.mesgTycd");
|
|
||||||
if (mesgTycdItem != null && StringUtils.isBlank(mesgTycdItem.getValue())) {
|
|
||||||
mesgTycdItem.setValue("1");
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.mesgCntySrno 설정
|
|
||||||
StandardItem mesgCntySrnoItem = message.findItem("STD_HEADER.mesgCntySrno");
|
|
||||||
if (mesgCntySrnoItem != null && StringUtils.isBlank(mesgCntySrnoItem.getValue())) {
|
|
||||||
mesgCntySrnoItem.setValue("00");
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.bfrDtLoinYn 설정
|
|
||||||
StandardItem bfrDtLoinYnItem = message.findItem("STD_HEADER.bfrDtLoinYn");
|
|
||||||
if (bfrDtLoinYnItem != null && StringUtils.isBlank(bfrDtLoinYnItem.getValue())) {
|
|
||||||
bfrDtLoinYnItem.setValue("N");
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.canCrctDvcd 설정
|
|
||||||
StandardItem canCrctDvcdItem = message.findItem("STD_HEADER.canCrctDvcd");
|
|
||||||
if (canCrctDvcdItem != null && StringUtils.isBlank(canCrctDvcdItem.getValue())) {
|
|
||||||
canCrctDvcdItem.setValue("0");
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.cmpgRelmUseDvcd 설정
|
|
||||||
StandardItem cmpgRelmUseDvcdItem = message.findItem("STD_HEADER.cmpgRelmUseDvcd");
|
|
||||||
if (cmpgRelmUseDvcdItem != null && StringUtils.isBlank(cmpgRelmUseDvcdItem.getValue())) {
|
|
||||||
cmpgRelmUseDvcdItem.setValue("0");
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.bzwrSvrCd 설정
|
|
||||||
StandardItem bzwrSvrCdItem = message.findItem("STD_HEADER.bzwrSvrCd");
|
|
||||||
if (bzwrSvrCdItem != null && StringUtils.isBlank(bzwrSvrCdItem.getValue())) {
|
|
||||||
String serverName = eaiServerManager.getLocalServerName();
|
|
||||||
if (StringUtils.isNotBlank(serverName)) {
|
|
||||||
String instanceid1 = serverName.substring(0, 2);
|
|
||||||
String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
|
||||||
bzwrSvrCdItem.setValue(StringUtils.upperCase(instanceid1 + instanceid2));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getSysOprtEnvDvcd(EAIServerManager eaiServerManager) {
|
|
||||||
String result = "";
|
|
||||||
if (eaiServerManager.isPEAIServer()) { // 운영
|
|
||||||
result = "R";
|
|
||||||
} else if (eaiServerManager.isDEAIServer()) { // 개발
|
|
||||||
result = "D";
|
|
||||||
} else if (eaiServerManager.isSEAIServer()) { // 테스트/검증
|
|
||||||
result = "T";
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -63,10 +63,11 @@ public class HourStatsAggregator {
|
|||||||
|
|
||||||
// 로그 시퀀스 100: 총 건수만 증가 (첫 호출)
|
// 로그 시퀀스 100: 총 건수만 증가 (첫 호출)
|
||||||
if (logSeq == 100) {
|
if (logSeq == 100) {
|
||||||
totalCnt.incrementAndGet();
|
// totalCnt.incrementAndGet();
|
||||||
}
|
}
|
||||||
// 로그 시퀀스 400: 응답시간 및 에러 타입 기록
|
// 로그 시퀀스 400: 응답시간 및 에러 타입 기록
|
||||||
else if (logSeq == 400) {
|
else if (logSeq == 400) {
|
||||||
|
totalCnt.incrementAndGet();
|
||||||
// 성공 여부 카운트
|
// 성공 여부 카운트
|
||||||
if (event.isSuccess()) {
|
if (event.isSuccess()) {
|
||||||
successCnt.incrementAndGet();
|
successCnt.incrementAndGet();
|
||||||
|
|||||||
+2
-1
@@ -63,10 +63,11 @@ public class MinuteStatsAggregator {
|
|||||||
|
|
||||||
// 로그 시퀀스 100: 총 건수만 증가 (첫 호출)
|
// 로그 시퀀스 100: 총 건수만 증가 (첫 호출)
|
||||||
if (logSeq == 100) {
|
if (logSeq == 100) {
|
||||||
totalCnt.incrementAndGet();
|
// totalCnt.incrementAndGet();
|
||||||
}
|
}
|
||||||
// 로그 시퀀스 400: 응답시간 및 에러 타입 기록
|
// 로그 시퀀스 400: 응답시간 및 에러 타입 기록
|
||||||
else if (logSeq == 400) {
|
else if (logSeq == 400) {
|
||||||
|
totalCnt.incrementAndGet();
|
||||||
// 성공 여부 카운트
|
// 성공 여부 카운트
|
||||||
if (event.isSuccess()) {
|
if (event.isSuccess()) {
|
||||||
successCnt.incrementAndGet();
|
successCnt.incrementAndGet();
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ public class ApiStatsConfig {
|
|||||||
/** 기본값 상수 */
|
/** 기본값 상수 */
|
||||||
private static final boolean DEFAULT_ENABLED = true;
|
private static final boolean DEFAULT_ENABLED = true;
|
||||||
private static final boolean DEFAULT_MINUTE_ENABLED = true;
|
private static final boolean DEFAULT_MINUTE_ENABLED = true;
|
||||||
private static final boolean DEFAULT_HOUR_ENABLED = true;
|
private static final boolean DEFAULT_HOUR_ENABLED = false;
|
||||||
|
|
||||||
private final PropManager propManager;
|
private final PropManager propManager;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.eactive.eai.custom.transformer.function;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Stack;
|
||||||
|
|
||||||
|
import org.nfunk.jep.ParseException;
|
||||||
|
import org.nfunk.jep.function.PostfixMathCommand;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.security.CryptoModuleService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JEP 트랜스포머 함수 — DJB ERP 연동 복호화.
|
||||||
|
*
|
||||||
|
* 사용법: DJBErpDecryt(encBase64, moduleName)
|
||||||
|
*
|
||||||
|
* 파라미터:
|
||||||
|
* encBase64 : Base64 인코딩된 암호문
|
||||||
|
* moduleName : DB에 등록된 암호화 모듈명
|
||||||
|
*
|
||||||
|
* 반환값: 복호화된 평문 (String)
|
||||||
|
*/
|
||||||
|
public class DJBDecrypt extends PostfixMathCommand {
|
||||||
|
|
||||||
|
public DJBDecrypt() {
|
||||||
|
numberOfParameters = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||||
|
public void run(Stack inStack) throws ParseException {
|
||||||
|
checkStack(inStack);
|
||||||
|
|
||||||
|
if (curNumberOfParameters != 2) {
|
||||||
|
throw new ParseException("DJBErpDecryt: 파라미터는 2개개여야 합니다 (encBase64, moduleName");
|
||||||
|
}
|
||||||
|
|
||||||
|
String moduleName = inStack.pop().toString();
|
||||||
|
String encBase64 = inStack.pop().toString();
|
||||||
|
|
||||||
|
try {
|
||||||
|
byte[] cipherBytes = Base64.getDecoder().decode(encBase64.trim());
|
||||||
|
byte[] plainBytes = CryptoModuleService.getInstance().decrypt(moduleName, new HashMap<>(), null, cipherBytes);
|
||||||
|
inStack.push(new String(plainBytes, StandardCharsets.UTF_8));
|
||||||
|
} catch (ParseException e) {
|
||||||
|
throw e;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new ParseException("DJBErpDecryt 복호화 실패: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.eactive.eai.custom.transformer.function;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Stack;
|
||||||
|
|
||||||
|
import org.nfunk.jep.ParseException;
|
||||||
|
import org.nfunk.jep.function.PostfixMathCommand;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.security.CryptoModuleService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JEP 트랜스포머 함수 — DJB ERP 연동 암호화.
|
||||||
|
*
|
||||||
|
* 사용법: DJBErpEncryt(plainText, moduleName) DJBErpEncryt(plainText, moduleName,
|
||||||
|
* groupSeq)
|
||||||
|
*
|
||||||
|
* 파라미터: plainText : 암호화할 평문 (String) moduleName : DB에 등록된 암호화 모듈명 (String)
|
||||||
|
* groupSeq : 키 도출용 그룹 시퀀스 (String, 선택). 미전달 시 빈 context로 호출.
|
||||||
|
*
|
||||||
|
* 반환값: Base64 인코딩된 암호문 (String)
|
||||||
|
*/
|
||||||
|
public class DJBEncrypt extends PostfixMathCommand {
|
||||||
|
|
||||||
|
public DJBEncrypt() {
|
||||||
|
numberOfParameters = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||||
|
public void run(Stack inStack) throws ParseException {
|
||||||
|
checkStack(inStack);
|
||||||
|
|
||||||
|
if (curNumberOfParameters != 2) {
|
||||||
|
throw new ParseException("DJBErpEncryt: 파라미터는 2개여야 합니다 (plainText, moduleName)");
|
||||||
|
}
|
||||||
|
|
||||||
|
String moduleName = inStack.pop().toString();
|
||||||
|
String plainText = inStack.pop().toString();
|
||||||
|
|
||||||
|
try {
|
||||||
|
byte[] cipherBytes = CryptoModuleService.getInstance().encrypt(moduleName, new HashMap<>(), null,
|
||||||
|
plainText.getBytes(StandardCharsets.UTF_8));
|
||||||
|
inStack.push(Base64.getEncoder().encodeToString(cipherBytes));
|
||||||
|
} catch (ParseException e) {
|
||||||
|
throw e;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new ParseException("DJBErpEncryt 암호화 실패: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
public class GroupMetricDTO {
|
||||||
|
private String groupId;
|
||||||
|
private String groupName;
|
||||||
|
private boolean activate;
|
||||||
|
private long allowed;
|
||||||
|
private long rejectedPerSecond;
|
||||||
|
private long rejectedThreshold;
|
||||||
|
private long totalRequests;
|
||||||
|
private double rejectRatio;
|
||||||
|
private long lastResetTime;
|
||||||
|
|
||||||
|
public String getGroupId() { return groupId; }
|
||||||
|
public void setGroupId(String groupId) { this.groupId = groupId; }
|
||||||
|
|
||||||
|
public String getGroupName() { return groupName; }
|
||||||
|
public void setGroupName(String groupName) { this.groupName = groupName; }
|
||||||
|
|
||||||
|
public boolean isActivate() { return activate; }
|
||||||
|
public void setActivate(boolean activate) { this.activate = activate; }
|
||||||
|
|
||||||
|
public long getAllowed() { return allowed; }
|
||||||
|
public void setAllowed(long allowed) { this.allowed = allowed; }
|
||||||
|
|
||||||
|
public long getRejectedPerSecond() { return rejectedPerSecond; }
|
||||||
|
public void setRejectedPerSecond(long rejectedPerSecond) { this.rejectedPerSecond = rejectedPerSecond; }
|
||||||
|
|
||||||
|
public long getRejectedThreshold() { return rejectedThreshold; }
|
||||||
|
public void setRejectedThreshold(long rejectedThreshold) { this.rejectedThreshold = rejectedThreshold; }
|
||||||
|
|
||||||
|
public long getTotalRequests() { return totalRequests; }
|
||||||
|
public void setTotalRequests(long totalRequests) { this.totalRequests = totalRequests; }
|
||||||
|
|
||||||
|
public double getRejectRatio() { return rejectRatio; }
|
||||||
|
public void setRejectRatio(double rejectRatio) { this.rejectRatio = rejectRatio; }
|
||||||
|
|
||||||
|
public long getLastResetTime() { return lastResetTime; }
|
||||||
|
public void setLastResetTime(long lastResetTime) { this.lastResetTime = lastResetTime; }
|
||||||
|
}
|
||||||
@@ -1,21 +1,20 @@
|
|||||||
package com.eactive.eai.manage.inflow;
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Service;
|
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.CustomGroupBucket;
|
||||||
import com.eactive.eai.common.inflow.InflowControlManager;
|
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||||
import com.eactive.eai.common.inflow.InflowGroupVO;
|
import com.eactive.eai.common.inflow.InflowGroupVO;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class InflowGroupBucketService {
|
public class InflowGroupBucketService {
|
||||||
|
|
||||||
public GroupBucketStatusDTO getGroupBucketStatus(String groupId) {
|
public GroupBucketStatusDTO getGroupBucketStatus(String groupId) {
|
||||||
InflowControlManager manager = InflowControlManager.getInstance();
|
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
|
||||||
|
|
||||||
InflowGroupVO groupVo = manager.getGroupInflowThreshold(groupId);
|
InflowGroupVO groupVo = manager.getGroupInflowThreshold(groupId);
|
||||||
if (groupVo == null) {
|
if (groupVo == null) {
|
||||||
@@ -72,25 +71,12 @@ public class InflowGroupBucketService {
|
|||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 그룹 버킷 조회 (리플렉션 사용)
|
|
||||||
*/
|
|
||||||
public CustomGroupBucket getCustomGroupBucket(String groupId) {
|
public CustomGroupBucket getCustomGroupBucket(String groupId) {
|
||||||
try {
|
return InflowControlUtil.getInflowControlManager().getGroupBucket(groupId);
|
||||||
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() {
|
public List<GroupBucketStatusDTO> getAllGroupBucketStatus() {
|
||||||
InflowControlManager manager = InflowControlManager.getInstance();
|
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
|
||||||
String[] groupIds = manager.getGroupAllKeys();
|
String[] groupIds = manager.getGroupAllKeys();
|
||||||
|
|
||||||
List<GroupBucketStatusDTO> result = new ArrayList<>();
|
List<GroupBucketStatusDTO> result = new ArrayList<>();
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/manage/inflow/group")
|
||||||
|
public class InflowGroupMetricController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private InflowGroupMetricService metricService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 특정 그룹의 메트릭 조회
|
||||||
|
* GET /manage/inflow/group/{groupId}/metric
|
||||||
|
*/
|
||||||
|
@GetMapping("/{groupId}/metric")
|
||||||
|
public ResponseEntity<?> getGroupMetric(@PathVariable String groupId) {
|
||||||
|
GroupMetricDTO metric = metricService.getGroupMetric(groupId);
|
||||||
|
|
||||||
|
if (metric == null) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "그룹을 찾을 수 없습니다: " + groupId);
|
||||||
|
return ResponseEntity.ok(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", metric);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모든 그룹의 메트릭 조회
|
||||||
|
* GET /manage/inflow/group/metric
|
||||||
|
*/
|
||||||
|
@GetMapping("/metric")
|
||||||
|
public ResponseEntity<?> getAllGroupMetrics() {
|
||||||
|
List<GroupMetricDTO> list = metricService.getAllGroupMetrics();
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", list);
|
||||||
|
result.put("count", list.size());
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 특정 그룹의 메트릭 초기화
|
||||||
|
* POST /manage/inflow/group/{groupId}/metric/reset
|
||||||
|
*/
|
||||||
|
@PostMapping("/{groupId}/metric/reset")
|
||||||
|
public ResponseEntity<?> resetGroupMetric(@PathVariable String groupId) {
|
||||||
|
boolean ok = metricService.resetGroupMetric(groupId);
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", ok);
|
||||||
|
result.put("message", ok ? "초기화 완료: " + groupId : "그룹을 찾을 수 없습니다: " + groupId);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 전체 그룹 메트릭 초기화
|
||||||
|
* POST /manage/inflow/group/metric/reset
|
||||||
|
*/
|
||||||
|
@PostMapping("/metric/reset")
|
||||||
|
public ResponseEntity<?> resetAllGroupMetrics() {
|
||||||
|
metricService.resetAllGroupMetrics();
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("message", "전체 그룹 메트릭 초기화 완료");
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.inflow.Bucket;
|
||||||
|
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||||
|
import com.eactive.eai.common.inflow.InflowGroupVO;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class InflowGroupMetricService {
|
||||||
|
|
||||||
|
public GroupMetricDTO getGroupMetric(String groupId) {
|
||||||
|
DualInflowControlManager manager = getManager();
|
||||||
|
if (manager == null) return null;
|
||||||
|
|
||||||
|
InflowGroupVO groupVo = manager.getGroupInflowThreshold(groupId);
|
||||||
|
if (groupVo == null) return null;
|
||||||
|
|
||||||
|
return buildDTO(groupId, groupVo, manager.getGroupMetrics(groupId));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<GroupMetricDTO> getAllGroupMetrics() {
|
||||||
|
DualInflowControlManager manager = getManager();
|
||||||
|
if (manager == null) return new ArrayList<>();
|
||||||
|
|
||||||
|
List<GroupMetricDTO> result = new ArrayList<>();
|
||||||
|
for (String groupId : manager.getGroupAllKeys()) {
|
||||||
|
GroupMetricDTO dto = getGroupMetric(groupId);
|
||||||
|
if (dto != null) result.add(dto);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean resetGroupMetric(String groupId) {
|
||||||
|
DualInflowControlManager manager = getManager();
|
||||||
|
if (manager == null) return false;
|
||||||
|
if (manager.getGroupInflowThreshold(groupId) == null) return false;
|
||||||
|
manager.resetGroupMetrics(groupId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void resetAllGroupMetrics() {
|
||||||
|
DualInflowControlManager manager = getManager();
|
||||||
|
if (manager != null) manager.resetAllGroupMetrics();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected DualInflowControlManager getManager() {
|
||||||
|
Bucket bucket = InflowControlUtil.getBucket();
|
||||||
|
return (bucket instanceof DualInflowControlManager)
|
||||||
|
? (DualInflowControlManager) bucket
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private GroupMetricDTO buildDTO(String groupId, InflowGroupVO groupVo,
|
||||||
|
DualInflowControlManager.TargetMetrics m) {
|
||||||
|
GroupMetricDTO dto = new GroupMetricDTO();
|
||||||
|
dto.setGroupId(groupId);
|
||||||
|
dto.setGroupName(groupVo.getGroupName());
|
||||||
|
dto.setActivate(groupVo.isActivate());
|
||||||
|
|
||||||
|
if (m != null) {
|
||||||
|
long allowed = m.allowed.get();
|
||||||
|
long rejPs = m.rejectedPerSecond.get();
|
||||||
|
long rejTh = m.rejectedThreshold.get();
|
||||||
|
long total = allowed + rejPs + rejTh;
|
||||||
|
dto.setAllowed(allowed);
|
||||||
|
dto.setRejectedPerSecond(rejPs);
|
||||||
|
dto.setRejectedThreshold(rejTh);
|
||||||
|
dto.setTotalRequests(total);
|
||||||
|
dto.setRejectRatio(total > 0
|
||||||
|
? Math.round((double)(rejPs + rejTh) / total * 10000) / 100.0
|
||||||
|
: 0.0);
|
||||||
|
dto.setLastResetTime(m.lastResetTime);
|
||||||
|
}
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 어댑터/인터페이스/클라이언트 버킷 상태 모니터링 API.
|
||||||
|
*
|
||||||
|
* DualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
|
||||||
|
* 비활성화 환경에서는 success=false 또는 빈 목록을 반환한다.
|
||||||
|
*
|
||||||
|
* GET /manage/inflow/adapter/bucket-status → 전체 어댑터 버킷 상태
|
||||||
|
* GET /manage/inflow/adapter/{adapterId}/bucket-status → 특정 어댑터 버킷 상태
|
||||||
|
* GET /manage/inflow/interface/bucket-status → 전체 인터페이스 버킷 상태
|
||||||
|
* GET /manage/inflow/interface/{interfaceId}/bucket-status → 특정 인터페이스 버킷 상태
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/manage/inflow")
|
||||||
|
public class InflowTargetBucketController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private InflowTargetBucketService bucketService;
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 어댑터
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@GetMapping("/adapter/bucket-status")
|
||||||
|
public ResponseEntity<?> getAllAdapterBucketStatus() {
|
||||||
|
List<TargetBucketStatusDTO> list = bucketService.getAllAdapterBucketStatus();
|
||||||
|
return ok(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/adapter/{adapterId}/bucket-status")
|
||||||
|
public ResponseEntity<?> getAdapterBucketStatus(@PathVariable String adapterId) {
|
||||||
|
TargetBucketStatusDTO dto = bucketService.getAdapterBucketStatus(adapterId);
|
||||||
|
return single(dto, "어댑터를 찾을 수 없습니다: " + adapterId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 인터페이스
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@GetMapping("/interface/bucket-status")
|
||||||
|
public ResponseEntity<?> getAllInterfaceBucketStatus() {
|
||||||
|
List<TargetBucketStatusDTO> list = bucketService.getAllInterfaceBucketStatus();
|
||||||
|
return ok(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/interface/{interfaceId}/bucket-status")
|
||||||
|
public ResponseEntity<?> getInterfaceBucketStatus(@PathVariable String interfaceId) {
|
||||||
|
TargetBucketStatusDTO dto = bucketService.getInterfaceBucketStatus(interfaceId);
|
||||||
|
return single(dto, "인터페이스를 찾을 수 없습니다: " + interfaceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Helpers
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
private ResponseEntity<?> ok(List<TargetBucketStatusDTO> list) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", list);
|
||||||
|
result.put("count", list.size());
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<?> single(TargetBucketStatusDTO dto, String notFoundMsg) {
|
||||||
|
if (dto == null) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", notFoundMsg);
|
||||||
|
return ResponseEntity.ok(error);
|
||||||
|
}
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", dto);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
|
||||||
|
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||||
|
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 어댑터/인터페이스/클라이언트 버킷 상태 조회 서비스.
|
||||||
|
*
|
||||||
|
* DualInflowControlManager 가 활성화된 경우에만 동작한다.
|
||||||
|
* InflowControlManager 가 기본 구현체인 경우 빈 목록 또는 null 을 반환한다.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class InflowTargetBucketService {
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 어댑터
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public TargetBucketStatusDTO getAdapterBucketStatus(String adapterId) {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return null;
|
||||||
|
DualCustomBucket bucket = manager.getAdapterBucket(adapterId);
|
||||||
|
if (bucket == null) return null;
|
||||||
|
return toDto(adapterId, "ADAPTER", bucket);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TargetBucketStatusDTO> getAllAdapterBucketStatus() {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return new ArrayList<>();
|
||||||
|
return toDtoList("ADAPTER", manager.getAdapterBucketMap());
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 인터페이스
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public TargetBucketStatusDTO getInterfaceBucketStatus(String interfaceId) {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return null;
|
||||||
|
DualCustomBucket bucket = manager.getInterfaceBucket(interfaceId);
|
||||||
|
if (bucket == null) return null;
|
||||||
|
return toDto(interfaceId, "INTERFACE", bucket);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TargetBucketStatusDTO> getAllInterfaceBucketStatus() {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return new ArrayList<>();
|
||||||
|
return toDtoList("INTERFACE", manager.getInterfaceBucketMap());
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Private helpers
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
protected DualInflowControlManager getDualManager() {
|
||||||
|
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
|
||||||
|
return (base instanceof DualInflowControlManager) ? (DualInflowControlManager) base : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private TargetBucketStatusDTO toDto(String targetId, String targetType, DualCustomBucket bucket) {
|
||||||
|
InflowTargetVO vo = bucket.getInflowTargetVo();
|
||||||
|
List<GroupBucketStatusDTO.BucketInfo> buckets = new ArrayList<>();
|
||||||
|
|
||||||
|
if (vo.getThresholdPerSecond() > 0) {
|
||||||
|
long capacity = vo.getThresholdPerSecond();
|
||||||
|
long available = bucket.getPerSecondAvailableTokens();
|
||||||
|
if (available < 0) available = capacity;
|
||||||
|
buckets.add(new GroupBucketStatusDTO.BucketInfo(
|
||||||
|
"perSecond", capacity, Math.min(available, capacity), "SEC"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vo.getThreshold() > 0) {
|
||||||
|
long capacity = vo.getThreshold();
|
||||||
|
long available = bucket.getThresholdAvailableTokens();
|
||||||
|
if (available < 0) available = capacity;
|
||||||
|
buckets.add(new GroupBucketStatusDTO.BucketInfo(
|
||||||
|
"threshold", capacity, Math.min(available, capacity), vo.getThresholdTimeUnit()));
|
||||||
|
}
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = new TargetBucketStatusDTO();
|
||||||
|
dto.setTargetId(targetId);
|
||||||
|
dto.setTargetType(targetType);
|
||||||
|
dto.setActivate(vo.isActivate());
|
||||||
|
dto.setBuckets(buckets);
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<TargetBucketStatusDTO> toDtoList(String targetType, Map<String, DualCustomBucket> bucketMap) {
|
||||||
|
List<TargetBucketStatusDTO> result = new ArrayList<>();
|
||||||
|
for (Map.Entry<String, DualCustomBucket> entry : bucketMap.entrySet()) {
|
||||||
|
result.add(toDto(entry.getKey(), targetType, entry.getValue()));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user