Compare commits

..

30 Commits

Author SHA1 Message Date
curry772 46aaaf1059 elink-online-common 서브모듈 업데이트
- 토큰 현황 목록 조회에 최근 발급 이력 1건 포함
2026-09-11 17:35:56 +09:00
curry772 6bbddb4794 elink-online-common 서브모듈 업데이트
- OAuth 토큰 발급 이력 조회 기능
- 거래 중 토큰 재발급을 분산락 경로로 통합
- 토큰 만료 전 선제 갱신
- 클러스터 중복 발급 수정 (near 캐시 우회 조회)
2026-09-11 15:05:33 +09:00
curry772 b414561b47 elink-online-common 서브모듈 업데이트
- 아웃바운드 OAuth 토큰 TLS 인증서 검증 옵션
- 설정 기반 범용 OAuth 토큰 발급 구현체 추가
- 아웃바운드 OAuth 토큰 현황 조회 API 추가
- 빈 토큰이 캐시에 고착되는 문제 수정
2026-09-11 10:40:55 +09:00
curry772 b6c64983ee 보안성심의 오픈소스 조치 2026-09-07 16:08:56 +09:00
curry772 831dc9fc48 EZDATA 없는데, Ref필드에는 'ERP'로 되어 있는 경우, flat 전문 파싱 오류 처리 2026-09-07 14:39:47 +09:00
curry772 ad7ff7276f Merge branch 'feature/std-msg-explicit-success-value'
정상 응답 MSG 코드/메시지를 레이아웃 기본값 대신 coordinateBeforeResponse 에서
명시적으로 설정한다. 운영 반영에는 DB 표준전문 정의의 기본값 제거가 함께 필요하다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UnybKuxcuPafGhVGh4wqkZ
2026-09-03 10:20:23 +09:00
curry772 ec6b51f2a8 정상 응답 MSG 코드/메시지를 레이아웃 기본값 대신 명시적으로 설정
outp_msg_cd(NCMM00001) / outp_msg_ctnt(정상처리되었습니다.) 가 표준전문 레이아웃의
기본값으로 붙어 있어서, "아무도 채우지 않은 상태" 와 "정상이라고 판정한 상태" 가
값만으로 구분되지 않았다. 2026-09 사고에서 MSG 부 파싱이 통째로 스킵됐는데도
오류가 "정상처리되었습니다." 로 보고된 것이 이 때문이다.

레이아웃 기본값을 없애고, StandardMessageCoordinatorDJB.coordinateBeforeResponse 에서
정상 응답일 때만 채운다. 이 메서드는 모든 동기 응답이 거치는 마지막 관문이라
(RequestProcessor 에서 호출) 경로를 빠짐없이 덮는다.

두 조건을 함께 본다.
 - 정상 응답(procs_rslt_dvcd=S) 일 때만. 오류 응답에 정상 메시지를 채우면 사고 재현이다.
 - 값이 비어 있을 때만(setIfBlank). 대외계가 표준응답으로 보낸 MSG 가 우선이며
   덮어쓰면 JsonReader 의 MSG 부 보존 수정이 무의미해진다.

테스트: 기존 3건이 coordinateAfterRecvNonStdSyncResponse 직후에 단정하고 있었으나
값은 이제 마지막 관문에서 채워지므로, 실제 흐름대로 coordinateBeforeResponse 까지
거치도록 고치고 단정도 "공백 아님" 에서 상수 일치로 강화했다.
설계 조건을 지키는 회귀 테스트 2건을 추가했다.
 - 오류응답에는_정상메시지가_채워지지_않는다
 - 대외계가_보낸_MSG_값은_덮어쓰지_않는다

주의: 이 CSV 는 layout.file.type=CSV 인 테스트 설정에서만 쓰인다. 운영은 DB 레이아웃을
읽으므로 DB 의 두 항목 기본값도 함께 비워야 실제 효과가 있다. 비우기 전까지는
setIfBlank 가 아무것도 하지 않아 기존과 동일하게 동작한다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UnybKuxcuPafGhVGh4wqkZ
2026-09-03 10:20:13 +09:00
curry772 2153ed51a8 Merge branch 'feature/msg-block-parse-skip'
- 표준 레이아웃 DATA 를 GRID 로 정정
- MSG부 파싱 회귀 테스트 추가

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UnybKuxcuPafGhVGh4wqkZ
2026-09-03 08:58:31 +09:00
curry772 64d94a1fdc 표준 레이아웃 DATA 를 GRID 로 정정 + MSG부 파싱 회귀 테스트 추가
standard-layout-djb.csv 의 DATA 가 GROUP(3)으로 선언돼 있어, 매핑설정의
BIZ_DATA=DATA[0].BIZ_DATA 인덱스 접근이 실패했다. getBizDataBytes() 가 null 을
반환하고 makeupDataScopLen 이 이를 그대로 역참조해 NPE 가 나면서
coordinateBeforeRequest/Response 가 통째로 실패, 관련 테스트 9건이 깨져 있었다.
운영 레이아웃(DB)대로 GRID(4)로 정정한다. 이 CSV 는 layout.file.type=CSV 인
테스트 설정에서만 사용된다.

- DATA 픽스처를 실제 전문과 같은 배열 형태로 변경
- GRID 는 인덱스 없는 경로가 직렬화에 쓰이지 않는 템플릿을 가리키므로, 조회/단정
  경로를 운영과 같은 DATA[0] 형태로 변경
- 상대 헤더가 표준을 어긴 오류응답(dman_rspn_dvcd=S) 회귀 테스트 2건 추가.
  같은 전문에 있던 선행 0 숫자(00001)와 이스케이프되지 않은 개행/탭도 픽스처에 포함

알려진 별건: DATA 가 GRID 이므로 StandardMessageCoordinatorDJB.DATA_SCOP_LEN
("DATA.data_scop_len") 이 행이 아닌 템플릿에 기록되어 data_scop_len 이 재계산되지
않고 수신값이 그대로 나간다. JSON 경로에서는 영향이 없어 별도 건으로 둔다.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UnybKuxcuPafGhVGh4wqkZ
2026-09-02 17:25:16 +09:00
curry772 50c08d7813 KakaopayAdapterErrorMsgHandler: 제어문자 정규화 후 파싱
상대 응답에 이스케이프되지 않은 제어문자가 섞여 오면
"Illegal unquoted character ((CTRL-CHAR, code 10))" 로 실패한다.
readTree() 전에 JacksonUtil.escapeControlChars() 로 표준 JSON 으로 맞춘다.

검증: gradlew compileJava BUILD SUCCESSFUL
2026-08-28 14:28:12 +09:00
curry772 c5bf45cad9 custom 어댑터/변환함수의 Jackson mapper 를 number-safe 로 통일
기본 ObjectMapper 는 JSON 숫자 왕복에서 값을 변형한다
(100000000.00 -> 1.0E8, 0.00000012 -> 1.2E-7). payload 를 다루는
지점을 JacksonUtil.newNumberSafeMapper() 로 맞춘다.

- KakaopayAdapterErrorMsgHandler: 응답 JSON 파싱/왕복 지점 전환
- HttpClient5AdapterServiceBigTechAddFilter: JsonNode 직렬화 지점 전환
- KakaopayFilter: JacksonUtil.readTree(message, OBJECT_MAPPER) 로 plain mapper 를
  넘기고 있어 유틸을 써도 파싱이 깨졌다. 인자 1개 오버로드(number-safe 싱글턴)를
  쓰도록 바꾸고 plain 필드 제거
- JsonPathExtractRequestMessage: 미사용으로 보였던 objectMapper 필드는 사실
  연결이 빠진 것이었다. JsonPath 의 기본 JacksonJsonNodeJsonProvider() 가 내부적으로
  plain ObjectMapper 를 쓰기 때문에 JSON 실수가 DoubleNode 로 파싱되어
  resultNode.asText() 가 "1.0E8" 을 반환했다. 프로바이더에 number-safe mapper 를
  주입해 해결
- NaverpayAdapterErrorMsgHandler: Kakaopay 판을 복사하며 딸려온 미사용 필드/import 제거.
  이 핸들러는 JSON 을 파싱하지 않고 StandardMessage 로만 응답을 만든다

검증: gradlew compileJava BUILD SUCCESSFUL
2026-08-28 09:26:43 +09:00
curry772 76a3b705c0 Jackson Mapper 생성을 newNumberSafeMapper 이용으로 통일 2026-08-27 16:57:05 +09:00
curry772 57f4847e21 어댑터 에러 핸들러 orgRspErrCd 설정 추가
-현재까지 미사용
2026-08-26 16:34:49 +09:00
curry772 a6e41150cd 거래로그의 오류 출력 부분 수정
- 오류 발생 시 AdapterErrorMessageHandler가 처리하여도 400 오류로 출력되도록 수정
- 업무 오류 발생 시 AdapterErrorMessageHandler가 처리하여도 에러 RECEAIINA001 출력
2026-08-26 09:47:33 +09:00
curry772 79c8aa6151 weblogic에서 ApiRequestBodyFilter를 사용 부분 주석 처리 2026-08-25 15:04:44 +09:00
curry772 ed17053cf1 weblogic 환경에서 /manage url에 대해 FrontFilter가 수행되도록 수정 2026-08-25 14:37:13 +09:00
curry772 af7673ea2c oAuth token 발급 시 client id를 전송하지 않을 경우, 발생하는 오류 처리
- 파라미터로 넘어올 때만, prop에 설정되도록 수정
- 응답에 광주은행 문구 제거
2026-08-25 14:00:31 +09:00
curry772 f0a36a5365 보안성 소스코드 점검 조치 2026-08-20 10:40:50 +09:00
curry772 30dbe31f17 chore fix update 2026-08-15 11:23:16 +09:00
curry772 0263e97640 주석 변경 2026-08-13 10:36:59 +09:00
curry772 26ebad85a7 비동기 로그 배치 커밋 적용 2026-08-12 13:15:21 +09:00
curry772 2c82573a50 파라미터, path variable 처리 수정 2026-08-12 09:42:13 +09:00
curry772 540ebdaf1f 어댑터 에러 핸들러 추가 2026-08-12 09:41:52 +09:00
curry772 e9261c55ad headerGroupName null 체크 추가 2026-08-07 15:14:26 +09:00
curry772 777b1c477c 운영환경 properties 설정 2026-08-07 14:21:11 +09:00
curry772 464ed59a3d 주석 변경 2026-08-06 16:46:01 +09:00
curry772 5486489985 HttpAdapterServiceVirtualAccount online -> common 이동 2026-08-06 14:23:35 +09:00
curry772 2bbd3824ed Merge branch 'master' of https://git.eactive.synology.me:8090/eapim/djbank/eapim-online.git 2026-08-05 13:05:42 +09:00
curry772 4ff3589557 서브모듈 인덱스 업데이트 2026-08-05 13:05:30 +09:00
Rinjae db2b34a355 "SBOM 생성 및 변환 추가 - CycloneDX -> Excel(xlsx) 지원 - Jenkins 단계에 SBOM 빌드 및 아티팩트 보관 연결" 2026-07-31 17:31:45 +09:00
33 changed files with 2177 additions and 1077 deletions
Vendored
+15
View File
@@ -73,6 +73,21 @@ pipeline {
}
}
}
// SBOM(CycloneDX) -> xlsx. 산출물 eapim-online-sbom.xlsx 를 아티팩트로 보관.
// 실패해도 배포는 진행하도록 UNSTABLE 로만 표시한다.
stage('SBOM') {
steps {
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
sh 'gradle sbomXlsx --no-daemon -Pprofile=weblogic'
}
}
post {
always {
archiveArtifacts allowEmptyArchive: true, artifacts: 'build/reports/sbom/*.xlsx', fingerprint: true
}
}
}
}
}
@@ -66,6 +66,10 @@
<prop key="hibernate.dialect">${hibernate.dialect:org.hibernate.dialect.Oracle12cDialect}</prop>
<prop key="hibernate.jdbc.batch_size">100</prop>
<prop key="hibernate.jdbc.fetch_size">100</prop>
<!-- 배치 로그 적재 시 같은 테이블 INSERT끼리 묶이도록 정렬한다.
미설정 시 엔티티 종류가 섞이면 배치가 잘게 쪼개진다. -->
<prop key="hibernate.order_inserts">true</prop>
<prop key="hibernate.order_updates">true</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
@@ -9,6 +9,12 @@ hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
# eLink default functions
inst.Name=agwSvr11
eai.jdbc.Name=jdbc/dsOBP_AGW
eai.rmiport=39111
eai.rmiserviceport=39112
eai.systemmode=P
# EAI FEP MCI GW ...
eai.systemtype=API
eai.server.extractor=[0,2],[0,2],[-2]
eai.tableowner=AGWAPP
eai.server.extractor=[0,2],[0,2],[-2]
@@ -1,10 +1,13 @@
# transaction logging
logger.async.active=true
logger.async.pool.initonstartup=true
logger.async.pool.intsize=8
logger.async.pool.initsize=8
logger.async.pool.maxsize=10
logger.async.queue.size=1024
logger.async.worker.size=16
# worker.size=1 batch, 2~ 1Commit
logger.async.worker.size=1
# batch max sizeˆ˜
logger.async.batch.size=100
# cloud option
scalable=false
+3 -2
View File
@@ -19,10 +19,11 @@
<url-pattern>/agent/*</url-pattern>
<url-pattern>/common/*</url-pattern>
<url-pattern>/management/*</url-pattern>
<url-pattern>/manage/*</url-pattern>
<url-pattern>/mgr/*</url-pattern>
</filter-mapping>
<filter>
<!-- <filter>
<filter-name>ApiRequestBodyFilter</filter-name>
<filter-class>com.eactive.eai.adapter.controller.ApiRequestBodyFilter</filter-class>
</filter>
@@ -30,7 +31,7 @@
<filter-name>ApiRequestBodyFilter</filter-name>
<url-pattern>/api/*</url-pattern>
<url-pattern>/mapi/*</url-pattern>
</filter-mapping>
</filter-mapping> -->
<context-param>
<param-name>logbackDisableServletContainerInitializer</param-name>
+31 -1
View File
@@ -5,6 +5,7 @@ plugins {
id 'groovy'
id 'war'
id 'com.diffplug.eclipse.apt' version '3.41.1'
id 'org.cyclonedx.bom' version '3.2.4'
}
group 'com.eactvie'
@@ -109,7 +110,11 @@ dependencies {
implementation "org.springframework:spring-webmvc:${springVersion}"
implementation "org.springframework.security:spring-security-jwt:1.1.1.RELEASE"
// bcpkix/bcprov-jdk15on:1.64 전이 차단 — BouncyCastle 은 elink-online-common 이
// 제공하는 jdk18on 라인만 사용한다(구버전 클래스 중복 방지).
implementation ("org.springframework.security:spring-security-jwt:1.1.1.RELEASE") {
exclude group: 'org.bouncycastle'
}
//implementation "com.eactive:ojdbc8:1.0"
//implementation "org.postgresql:postgresql:42.2.23"
@@ -156,6 +161,28 @@ test {
configurations.all {
exclude group: 'log4j', module: 'log4j'
exclude group: 'org.codehaus.jackson'
// commons-fileupload: elink-online-common 이 api 로 선언(build.gradle:85)하지만,
// 사용처는 HttpAdapterServiceRest / HttpAdapterServiceVirtualAccount 두 클래스뿐이다.
// 두 클래스는 정적 참조가 없고 HttpAdapterServiceFactory 의
// Class.forName(DB 설정 클래스명) 으로만 로드되는데, DJB 는 자체 DJBApiAdapterService 를
// 사용하므로 이 어댑터 서비스가 기동되지 않는다(= 런타임 미사용).
// 공유 모듈인 elink-online-common 에서 의존성을 지우면 타 사이트가 깨지므로,
// 루트에서만 배제해 배포 WAR(WEB-INF/lib)에서 제외한다.
// ※ 운영 DB 어댑터 설정에 위 두 클래스가 등록되면 NoClassDefFoundError 가 발생하므로,
// 해당 어댑터를 사용하게 되는 시점에 이 exclude 를 반드시 제거할 것.
exclude group: 'commons-fileupload'
// BouncyCastle jdk15on 라인 최종 차단.
// jdk15on 과 jdk18on 은 artifactId 가 달라 Gradle 이 같은 라이브러리로 보지 않는다.
// 어느 경로로든 유입되면 org.bouncycastle.* 가 WEB-INF/lib 에 중복 적재되므로
// 배포 WAR 기준으로 한 번 더 배제한다(사용 버전: bcprov/bcpkix-jdk18on 1.78.1).
exclude group: 'org.bouncycastle', module: 'bcprov-jdk15on'
exclude group: 'org.bouncycastle', module: 'bcpkix-jdk15on'
// 구 groupId 의 dom4j(=1.6.1) 최종 차단. org.dom4j:dom4j:2.1.3 만 사용한다.
// (groupId 가 달라 Gradle 이 버전 충돌로 인식하지 못하므로 명시적으로 배제)
exclude group: 'dom4j', module: 'dom4j'
}
task settingEclipseEncoding {
@@ -249,3 +276,6 @@ eclipse {
}
}
// CycloneDX SBOM -> xlsx 변환 (gradle sbomXlsx)
apply from: "$projectDir/gradle/sbom-xlsx.gradle"
+326
View File
@@ -0,0 +1,326 @@
/*
* CycloneDX SBOM(bom.json) -> Excel(xlsx) 변환 태스크.
*
* gradle sbomXlsx # cyclonedxBom 실행 후 변환
* gradle sbomXlsx -PsbomJson=path.json # 기존 bom.json 사용(cyclonedxBom 생략)
* gradle sbomXlsx -PsbomOut=out.xlsx # 출력 경로 지정
*
* buildscript 블록이 이 스크립트에만 적용되므로 POI 의존성이 메인 빌드
* classpath 나 WAR 산출물에는 포함되지 않는다.
*
* 시트: 요약 / WAR 기준
* 산출 기준은 war 태스크의 classpath(= runtimeClasspath) 이므로
* test·annotationProcessor·developmentOnly·compileOnly 의존은 모두 제외된다.
* bom.json 은 라이선스/해시/설명/직접-전이 판별을 위한 메타 소스로만 쓴다.
*/
buildscript {
repositories {
maven {
url "https://nexus.eactive.synology.me:8090/repository/maven-public/"
allowInsecureProtocol = true
}
mavenCentral()
}
dependencies {
classpath 'org.apache.poi:poi-ooxml:3.17'
}
}
import groovy.json.JsonSlurper
import org.apache.poi.ss.usermodel.BorderStyle
import org.apache.poi.ss.usermodel.FillPatternType
import org.apache.poi.ss.usermodel.HorizontalAlignment
import org.apache.poi.ss.usermodel.IndexedColors
import org.apache.poi.ss.usermodel.VerticalAlignment
import org.apache.poi.ss.util.CellRangeAddress
import org.apache.poi.xssf.usermodel.XSSFWorkbook
// 엑셀 셀 문자열 상한(32767)보다 여유를 둔 절단 길이
ext.SBOM_CELL_LIMIT = 32000
task sbomXlsx {
group = 'sbom'
description = 'CycloneDX bom.json 을 WAR 수록 기준 xlsx 로 변환한다'
// -PsbomJson 으로 기존 산출물을 지정하면 재생성하지 않는다
if (!project.hasProperty('sbomJson')) {
dependsOn 'cyclonedxBom'
}
doLast {
File src = resolveBomJson(project)
File out = project.hasProperty('sbomOut')
? project.file(project.property('sbomOut'))
: new File(project.buildDir, "reports/sbom/${sbomFileName(project)}")
out.parentFile.mkdirs()
def bom = new JsonSlurper().parse(src, 'UTF-8')
def deploy = collectDeployJars(project)
def warRows = joinWarRows(deploy.jars, indexComponents(bom))
def wb = new XSSFWorkbook()
def st = createStyles(wb)
writeSummarySheet(wb, st, bom, warRows, src, deploy.label)
writeWarSheet(wb, st, warRows)
out.withOutputStream { os -> wb.write(os) }
wb.close()
int unmatched = warRows.count { it.matched == 'N' }
logger.lifecycle("SBOM xlsx 생성: ${out.absolutePath} " +
"(배포 수록 ${warRows.size()}개, SBOM 미매칭 ${unmatched}개, 원본 ${src.name})")
}
}
/** 산출 파일명: 배포 패키지명 기준 (war 있으면 war 파일명, 없으면 project 이름[-버전]) */
String sbomFileName(Project p) {
def warTask = p.tasks.findByName('war')
if (warTask != null) {
String archive = warTask.archiveFileName.get()
return archive.replaceAll(/\.(war|jar|ear)$/, '') + '-sbom.xlsx'
}
String ver = (p.version == null || p.version.toString() in ['', 'unspecified']) ? '' : "-${p.version}"
return "${p.name}${ver}-sbom.xlsx"
}
/** bom.json 위치 결정: -PsbomJson > cyclonedxBom 산출 경로 후보 */
File resolveBomJson(Project p) {
if (p.hasProperty('sbomJson')) {
File f = p.file(p.property('sbomJson'))
if (!f.exists()) {
throw new GradleException("bom.json 없음: ${f.absolutePath}")
}
return f
}
def candidates = [
new File(p.buildDir, 'reports/cyclonedx/bom.json'),
new File(p.buildDir, 'reports/bom.json'),
]
File found = candidates.find { it.exists() }
if (found == null) {
throw new GradleException(
"bom.json 을 찾지 못했다. 확인한 경로: " + candidates*.absolutePath.join(', ') +
"\n'gradle cyclonedxBom' 실행 후 재시도하거나 -PsbomJson=<경로> 로 지정한다.")
}
return found
}
/**
* 실제 배포물에 packaging 되는 jar 목록.
* war 프로젝트는 war 태스크 classpath(= runtimeClasspath), 그 외는 runtimeClasspath 를
* 기준으로 하므로 test/annotationProcessor/developmentOnly/compileOnly 는 자동으로 빠진다.
*
* @return [label: 기준 설명, jars: 행 목록]
*/
Map collectDeployJars(Project p) {
def cfg = p.configurations.findByName('runtimeClasspath')
if (cfg == null) {
p.logger.warn("[${p.name}] runtimeClasspath 가 없어 배포 기준 시트를 비운다")
return [label: '(없음)', jars: []]
}
def warTask = p.tasks.findByName('war')
def files
String label
if (warTask != null) {
files = warTask.classpath.files
label = 'WAR WEB-INF/lib (war 태스크 classpath)'
} else {
files = cfg.files
label = 'runtimeClasspath (war 태스크 없음)'
}
def coordByFile = [:]
cfg.resolvedConfiguration.resolvedArtifacts.each { a ->
def id = a.moduleVersion.id
coordByFile[a.file] = [group: id.group, name: id.name, version: id.version]
}
def jars = files.findAll { it.name.endsWith('.jar') }.collect { f ->
def c = coordByFile[f]
[
file : f.name,
group : c?.group ?: '',
name : c?.name ?: f.name.replaceAll(/\.jar$/, ''),
version: c?.version ?: '',
coord : c ? "${c.group}:${c.name}:${c.version}".toString() : '',
]
}.sort { it.file }
return [label: label, jars: jars]
}
/** bom.json 컴포넌트를 'group:name:version' 키로 색인 (라이선스/해시/설명/직접-전이) */
Map indexComponents(bom) {
String rootRef = bom.metadata?.component?.'bom-ref'
Set directRefs = (bom.dependencies?.find { it.ref == rootRef }?.dependsOn ?: []) as Set
def index = [:]
bom.components?.each { c ->
def hashes = [:]
c.hashes?.each { h -> hashes[h.alg] = h.content }
def licenses = (c.licenses ?: []).collect { l ->
l.license?.id ?: l.license?.name ?: l.expression ?: ''
}.findAll { it }
index["${c.group ?: ''}:${c.name ?: ''}:${c.version ?: ''}".toString()] = [
direct : directRefs.contains(c.'bom-ref') ? '직접' : '전이',
licenses : licenses.join('; '),
licenseList: licenses.isEmpty() ? ['(미상)'] : licenses,
purl : c.purl ?: '',
sha256 : hashes['SHA-256'] ?: '',
sha1 : hashes['SHA-1'] ?: '',
description: c.description ?: '',
]
}
return index
}
/** WAR jar 목록에 SBOM 메타를 좌표로 결합 */
List joinWarRows(List warJars, Map index) {
def result = []
warJars.eachWithIndex { j, i ->
def m = j.coord ? index[j.coord] : null
result << [
no : i + 1,
file : j.file,
group : j.group,
name : j.name,
version : j.version,
direct : m?.direct ?: '',
licenses : m?.licenses ?: '',
licenseList: m?.licenseList ?: ['(미상)'],
purl : m?.purl ?: '',
sha256 : m?.sha256 ?: '',
sha1 : m?.sha1 ?: '',
matched : (m != null) ? 'Y' : 'N',
description: m?.description ?: '',
]
}
return result
}
Map createStyles(wb) {
def headFont = wb.createFont()
headFont.setBold(true)
headFont.setColor(IndexedColors.WHITE.getIndex())
def head = wb.createCellStyle()
head.setFont(headFont)
head.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex())
head.setFillPattern(FillPatternType.SOLID_FOREGROUND)
head.setAlignment(HorizontalAlignment.CENTER)
head.setVerticalAlignment(VerticalAlignment.CENTER)
head.setBorderBottom(BorderStyle.THIN)
def body = wb.createCellStyle()
body.setVerticalAlignment(VerticalAlignment.TOP)
def wrap = wb.createCellStyle()
wrap.setVerticalAlignment(VerticalAlignment.TOP)
wrap.setWrapText(true)
def labelFont = wb.createFont()
labelFont.setBold(true)
def label = wb.createCellStyle()
label.setFont(labelFont)
return [head: head, body: body, wrap: wrap, label: label]
}
/** 헤더 행 생성 + 폭 지정 + 틀고정 */
def writeHeader(sheet, style, List<String> headers, List<Integer> widths) {
def row = sheet.createRow(0)
row.setHeightInPoints(20f)
headers.eachWithIndex { h, i ->
def cell = row.createCell(i)
cell.setCellValue(h)
cell.setCellStyle(style)
sheet.setColumnWidth(i, widths[i] * 256)
}
sheet.createFreezePane(0, 1)
}
def cellOf(row, int idx, value, style) {
def cell = row.createCell(idx)
String s = (value == null) ? '' : value.toString()
if (s.length() > SBOM_CELL_LIMIT) {
s = s.substring(0, SBOM_CELL_LIMIT) + '…(생략)'
}
cell.setCellValue(s)
cell.setCellStyle(style)
return cell
}
def writeSummarySheet(wb, st, bom, List warRows, File src, String basisLabel) {
def sheet = wb.createSheet('요약')
def comp = bom.metadata?.component ?: [:]
def tool = bom.metadata?.tools?.components?.getAt(0)
Set licenseKinds = warRows.collectMany { it.licenseList } as Set
def items = [
['대상 프로젝트', "${comp.group ?: ''}:${comp.name ?: ''}:${comp.version ?: ''}"],
['산출 기준', "${basisLabel} — test/annotationProcessor/compileOnly 제외"],
['BOM 포맷', "${bom.bomFormat ?: ''} ${bom.specVersion ?: ''}"],
['serialNumber', bom.serialNumber ?: ''],
['생성 시각', bom.metadata?.timestamp ?: ''],
['생성 도구', tool ? "${tool.name} ${tool.version}" : ''],
['원본 파일', src.absolutePath],
['배포 수록 jar', warRows.size()],
[' └ 직접 의존', warRows.count { it.direct == '직접' }],
[' └ 전이 의존', warRows.count { it.direct == '전이' }],
[' └ SBOM 미매칭', warRows.count { it.matched == 'N' }],
['라이선스 종류', licenseKinds.size()],
['라이선스 미상', warRows.count { it.licenses.isEmpty() }],
]
writeHeader(sheet, st.head, ['항목', '값'], [30, 90])
items.eachWithIndex { item, i ->
def row = sheet.createRow(i + 1)
cellOf(row, 0, item[0], st.label)
cellOf(row, 1, item[1], st.body)
}
// 라이선스 분포 (요약 하단)
def byLicense = [:].withDefault { 0 }
warRows.each { r -> r.licenseList.each { lic -> byLicense[lic] = byLicense[lic] + 1 } }
def sorted = byLicense.entrySet().sort { a, b -> (b.value <=> a.value) ?: (a.key <=> b.key) }
int base = items.size() + 2
def hdr = sheet.createRow(base)
cellOf(hdr, 0, '라이선스', st.head)
cellOf(hdr, 1, 'jar 수', st.head)
sorted.eachWithIndex { e, i ->
def row = sheet.createRow(base + 1 + i)
cellOf(row, 0, e.key, st.body)
cellOf(row, 1, e.value, st.body)
}
}
/** 실제 배포물(WAR WEB-INF/lib) 기준 시트 */
def writeWarSheet(wb, st, List warRows) {
def sheet = wb.createSheet('WAR 기준')
def headers = ['No', 'jar 파일명', 'Group', 'Name', 'Version', '구분',
'License', 'purl', 'SHA-256', 'SHA-1', 'SBOM매칭', 'Description']
def widths = [6, 46, 32, 34, 16, 7, 30, 60, 40, 30, 10, 60]
writeHeader(sheet, st.head, headers, widths)
warRows.eachWithIndex { r, i ->
def row = sheet.createRow(i + 1)
cellOf(row, 0, r.no, st.body)
cellOf(row, 1, r.file, st.body)
cellOf(row, 2, r.group, st.body)
cellOf(row, 3, r.name, st.body)
cellOf(row, 4, r.version, st.body)
cellOf(row, 5, r.direct, st.body)
cellOf(row, 6, r.licenses, st.body)
cellOf(row, 7, r.purl, st.body)
cellOf(row, 8, r.sha256, st.body)
cellOf(row, 9, r.sha1, st.body)
cellOf(row, 10, r.matched, st.body)
cellOf(row, 11, r.description, st.wrap)
}
if (!warRows.isEmpty()) {
sheet.setAutoFilter(new CellRangeAddress(0, warRows.size(), 0, headers.size() - 1))
}
}
@@ -2,7 +2,9 @@ package com.eactive.eai.adapter.service;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
@@ -10,6 +12,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import javax.servlet.ServletInputStream;
@@ -18,6 +21,7 @@ import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.hc.core5.http.ContentType;
import org.apache.mina.common.ByteBuffer;
import org.dom4j.Document;
import org.dom4j.DocumentException;
@@ -28,7 +32,7 @@ import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.json.simple.JSONValue;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
@@ -40,10 +44,13 @@ 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.dynamic.filter.FilterException;
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
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.stdmessage.STDMessageManager;
import com.eactive.eai.common.util.CommonLib;
import com.eactive.eai.common.util.JacksonUtil;
import com.eactive.eai.common.util.Logger;
@@ -52,8 +59,9 @@ 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.eactive.eai.util.JsonPathUtil;
import com.eactive.eai.message.StandardMessage;
import com.eactive.eai.message.manager.StandardMessageManager;
import com.eactive.eai.util.QueryStringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -61,8 +69,16 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
@Service
public class DJBApiAdapterService extends HttpAdapterServiceSupport {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static final String STD_MESSAGE_KEY = "STD_MESSAGE_KEY";
public static final String FINAL_STD_MESSAGE_KEY = "FINAL_STD_MESSAGE_KEY";
public static final String API_SERVICE_CODE = "API_SERVICE_CODE";
// 응답은 헤더그룹 처리를 위해 readTree() 로 파싱한 뒤 writeValueAsString() 으로 다시
// 문자열이 되므로, 이 왕복에서 숫자 자릿수가 유실되지 않는 mapper 를 써야 한다.
// 기본 ObjectMapper 는 100000000.00 을 1.0E8 로 바꿔버린다.
private static final ObjectMapper OBJECT_MAPPER = JacksonUtil.newNumberSafeMapper();
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
static Logger siftLogger = Logger.getLogger(Logger.LOGGER_SIFT);
@@ -74,7 +90,7 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id"; // jwhong
private ObjectMapper mapper = new ObjectMapper();
private ObjectMapper mapper = JacksonUtil.newNumberSafeMapper();
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp,
AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
@@ -90,7 +106,6 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
String relayRequestHeaderKeys = httpProp.getProperty(HEADER_KEYS);
String headerGroupName = httpProp.getProperty(HEADER_GROUP);
boolean isParameterType = false;
String message = null;
String paramValue = null;
@@ -126,12 +141,6 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
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
@@ -170,74 +179,8 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
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) {
String recvBody = "";
if (request.getContentLength() > 0) {
ServletInputStream sis = request.getInputStream();
ByteBuffer bb = ByteBuffer.allocate(1024).setAutoExpand(true);
int i = 0;
@@ -257,43 +200,68 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
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();
try {
MediaType mediaType = MediaType.parseMediaType(contentTypeHeader);
if (mediaType.getCharset() != null) {
bodyEncode = mediaType.getCharset().name();
}
} catch (Exception ignored) {
}
} catch (Exception ignored) {}
}
paramValue = new String(data, bodyEncode);
recvBody = new String(data, bodyEncode);
if (traceLevel >= 3) {
HttpMemoryLogger.txlog(adptGrpName + adptName,
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(data));
"RECV " + "[" + recvBody + "]" + CommonLib.getDumpMessage(data));
}
if (logger.isDebug()) {
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + recvBody + "]\n"
+ CommonLib.getDumpMessage(data));
}
}
}
// 순수한 Body값을 저장을 위해 위치 변경.
transactionProp.put(INBOUND_REQUEST_MESSAGE, recvBody);
// 요청 URL 에서 서비스키(STD_MESSAGE_KEY/FINAL_STD_MESSAGE_KEY/API_SERVICE_CODE)를 확정한다.
assignApiKeys(adptGrpName, adptName, transactionProp.get(INBOUND_REQUEST_MESSAGE), transactionProp);
// 확정된 서비스키로 PathVariable 을 추출한다. djerp bypass 의 Outbound URL 치환에도 사용된다.
Map<String, String> pathVariables = extractPathVariables(transactionProp.getProperty(STD_MESSAGE_KEY),
transactionProp.getProperty(FINAL_STD_MESSAGE_KEY));
transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
boolean isParameterType = isParameterType(HttpMethodType.getValue(request.getMethod()),
request.getContentType());
if (isParameterType) {
Map<String, String[]> paramMap = assignParameterMap(request, adptGrpName, adptName, recvBody,
transactionProp, urlDecodeYn, pathVariables);
boolean bUrlDecode = "Y".equals(urlDecodeYn);
paramValue = QueryStringUtils.makeJson(paramMap, bUrlDecode);
if (logger.isDebug()) {
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]");
}
} else {
Map<String, String[]> paramMap = convertArrayStringValue(pathVariables);
boolean bUrlDecode = "Y".equals(urlDecodeYn);
paramValue = mergeParamsToJsonBody(recvBody, paramMap, bUrlDecode);
}
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 {
// if ("Y".equals(urlDecodeYn) && isParameterType) {
// message = URLDecoder.decode(paramValue);
// } else {
message = paramValue;
}
// }
TxFileLogger.logTxFile(transactionProp, message, "[IN_RECV]");
@@ -314,9 +282,6 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
// transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
ApiKeyExtractFilter apiKeyExtractor = new ApiKeyExtractFilter();
apiKeyExtractor.doPreFilter(adptGrpName, adptName, transactionProp.get(INBOUND_REQUEST_MESSAGE), transactionProp, request, response);
Object result = service(adptGrpName, adptName, reqObject, transactionProp, request, response);
// bypass만 필요
@@ -612,71 +577,231 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
return (String)resultMessage;
}
public static boolean isParameterType(HttpMethodType method, String contentType) {
boolean isParameterType = true;
switch (method) {
case GET:
case DELETE:
isParameterType = true;
break;
case POST:
case PUT:
case PATCH:
if (StringUtils.contains(contentType, "application/x-www-form-urlencoded")) {
isParameterType = true;
} else {
isParameterType = false;
}
break;
default:
break;
}
return isParameterType;
}
private Map<String, String[]> assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName,
Object reqMessage, Properties prop, String urlDecode, Map<String, String> variablesMap) throws UnsupportedEncodingException {
Map<String, String[]> pathMap = convertArrayStringValue(variablesMap);
// param encoding 추가
String encoding = null;
String reqContentType = request.getContentType();
try {
ContentType oContentType = ContentType.parse(reqContentType);
if (oContentType != null && oContentType.getCharset() != null)
encoding = oContentType.getCharset().displayName();
} catch (Exception e) {
// 지원하지 않는 charset(UnsupportedCharsetException)이 헤더로 들어와도 500 이 나가지 않도록 한다.
logger.warn("HttpAdapterServiceRest] invalid Content-Type charset. [" + reqContentType + "]");
}
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];
boolean bUrlDecode = StringUtils.equalsIgnoreCase(urlDecode, "Y");
if (encoding == null) {
// Content-Type 에 charset 이 없을 때(GET 등)의 기본값은 처리 경로에 따라 다르다.
// - %인코딩 복원(URLDecoder) : HTML5/WHATWG 표준이 UTF-8 이므로 UTF-8.
// ISO-8859-1 로 복원하면 %ED%95%9C%EA%B8%80 이 '한글' 로 깨진다.
// - 그 외 : 컨테이너가 디코딩한 문자열의 원본 바이트를 되찾는 용도(byte latch)이므로
// 기존 동작인 ISO-8859-1 을 유지한다.
encoding = bUrlDecode ? StandardCharsets.UTF_8.name() : "ISO-8859-1";
}
// 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) });
}
// POST 방식의 form data
if (reqMessage instanceof String) {
String formData = (String) reqMessage;
Map<String, String[]> formDataParamMap = QueryStringUtils.parseQueryString(formData, encoding, bUrlDecode);
pathMap.putAll(formDataParamMap);
}
return returnMap;
}
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
// GET 방식의 query string
String queryString = request.getQueryString();
Map<String, String[]> paramMap = QueryStringUtils.parseQueryString(queryString, encoding, bUrlDecode);
pathMap.putAll(paramMap);
return request.getParameterMap();
}
return pathMap;
}
private Map<String, String[]> convertArrayStringValue(Map<String, String> variablesMap) {
Map<String, String[]> pathMap = new HashMap<>();
for (String key : variablesMap.keySet()) {
if (StringUtils.equalsIgnoreCase(key, "method")) {
continue;
}
pathMap.put(key, new String[] { variablesMap.get(key) });
}
return pathMap;
}
/**
* JSON Body 요청에 PathVariable(및 추가 파라미터)을 병합한다.
*
* <ul>
* <li>추가할 파라미터가 없으면 Body 를 그대로 반환한다.</li>
* <li>Body 가 비어있으면 파라미터만으로 JSON 오브젝트를 만든다.</li>
* <li>Body 가 JSON 오브젝트({...})면 항목을 추가한다. 빈 오브젝트({})도 유효한 JSON 으로 병합한다.</li>
* <li>XML / JSON 배열 등 오브젝트가 아닌 Body 는 훼손하지 않고 그대로 반환한다.
* (PathVariable 은 INBOUND_PATH_VARIABLES 로 Outbound 에 전달된다)</li>
* </ul>
*/
private String mergeParamsToJsonBody(String body, Map<String, String[]> paramMap, boolean bUrlDecode)
throws UnsupportedEncodingException {
if (paramMap == null || paramMap.isEmpty()) {
return body;
}
StringBuilder addJson = new StringBuilder();
for (Entry<String, String[]> entry : paramMap.entrySet()) {
if (addJson.length() > 0)
addJson.append(",");
addJson.append("\"").append(JSONValue.escape(entry.getKey())).append("\":");
String[] values = entry.getValue();
if (values.length > 1) {
addJson.append("[");
for (int j = 0; j < values.length; j++) {
if (j > 0) {
addJson.append(",");
}
addJson.append("\"").append(JSONValue.escape(decodeParamValue(values[j], bUrlDecode))).append("\"");
}
addJson.append("]");
} else {
addJson.append("\"").append(JSONValue.escape(decodeParamValue(values[0], bUrlDecode))).append("\"");
}
}
String trimmedBody = StringUtils.trimToEmpty(body);
if (trimmedBody.isEmpty()) {
return "{" + addJson + "}";
}
if (!StringUtils.startsWith(trimmedBody, "{") || !StringUtils.endsWith(trimmedBody, "}")) {
// JSON 오브젝트가 아니면 Body 를 덮어쓰지 않는다.
logger.warn("HttpAdapterServiceRest] body is not a JSON object. skip pathVariable merge.");
return body;
}
String innerBody = StringUtils.substring(trimmedBody, 1, trimmedBody.length() - 1);
String mergedJson;
if (StringUtils.isBlank(innerBody)) {
mergedJson = "{" + addJson + "}";
} else {
mergedJson = "{" + innerBody + "," + addJson + "}";
}
logger.debug("HttpAdapterServiceRest] add pathVariable : JSON =[" + mergedJson + "] ");
return mergedJson;
}
private String decodeParamValue(String value, boolean bUrlDecode) throws UnsupportedEncodingException {
return bUrlDecode ? URLDecoder.decode(value, StandardCharsets.UTF_8.name()) : value;
}
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];
/**
* 요청 URL 로부터 서비스키를 확정해 tx prop 에 세팅한다.
* (기존 {@link ApiKeyExtractFilter#doPreFilter} 가 하던 일)
*
* <ul>
* <li>{@code STD_MESSAGE_KEY} : Action 이 만들어낸 요청 경로 (ex. {@code GET/api/v1/users/123})</li>
* <li>{@code FINAL_STD_MESSAGE_KEY} : 등록된 서비스키 (ex. {@code GET/api/v1/users/{userId}})</li>
* <li>{@code API_SERVICE_CODE} : 서비스키에 매핑된 EAI 서비스 코드</li>
* </ul>
*
* <p>기존에는 이 필터와 PathVariable 추출이 각각 Action 을 생성해 {@code perform()} 을 호출하고
* 서비스키 매칭까지 중복 수행했다. Action 호출은 요청 1건당 한 번이면 충분하므로 여기서만 수행하고,
* PathVariable 추출은 여기서 확정한 서비스키를 {@link #extractPathVariables(String, String)} 에
* 넘겨 처리한다.
*/
private void assignApiKeys(String adptGrpName, String adptName, Object reqMessage, Properties prop)
throws Exception {
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
RequestAction action = ActionFactory.createAction(actionName);
action.setAdapterInfo(adptGrpName, adptName, prop);
String[] keys = action.perform(reqMessage);
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());
}
prop.setProperty(STD_MESSAGE_KEY, requestPath); // action class 통해서 생성
// PathVariable 지원 추가
// ex) /api/bank/account/12345 --> /api/bank/account/{accountNo}
String ruledPath = ApiKeyExtractFilter.getMatchedKey(requestPath);
if (StringUtils.isBlank(ruledPath)) {
throw new FilterException("path not found - " + requestPath, HttpAdapterFilter.ERROR_PRE_FAIL,
HttpStatus.FORBIDDEN.value());
}
prop.setProperty(FINAL_STD_MESSAGE_KEY, ruledPath);
String apiSvcCode = getEaiSvcCode(ruledPath);
if (StringUtils.isBlank(apiSvcCode)) {
// Properties 는 null 값을 허용하지 않아 그대로 put 하면 NPE 로 500 이 나간다.
logger.warn("HttpAdapterServiceRest] eaiSvcCode not found. apiId=[" + ruledPath + "]");
}
prop.put(API_SERVICE_CODE, StringUtils.defaultString(apiSvcCode));
}
private String getEaiSvcCode(String apiId) {
StandardMessage standardMessage = STDMessageManager.getInstance().getSTDMessage(apiId);
return StandardMessageManager.getInstance().getMapper().getEaiSvcCode(standardMessage);
}
/**
* 요청 경로와 매칭된 서비스키를 비교해 PathVariable 을 추출한다.
* ex) {@code GET/api/v1/users/123} + {@code GET/api/v1/users/{userId}} → {@code {userId=123}}
*
* <p>QueryString 유무와 무관하게 추출한다. Outbound(HttpClient5AdapterServiceRest/Bypass)의
* URL 치환에 사용되므로 QueryString 이 있다고 건너뛰면 치환이 불가하거나 NPE 가 발생한다.
*
* @param requestPath 실제 요청 경로 ({@code STD_MESSAGE_KEY})
* @param ruledPath 매칭된 서비스키 ({@code FINAL_STD_MESSAGE_KEY})
* @return PathVariable Map. 없으면 빈 Map (null 아님)
*/
private Map<String, String> extractPathVariables(String requestPath, String ruledPath) {
Map<String, String> pathMap = new HashMap<>();
if (StringUtils.equals(requestPath, ruledPath) || !StringUtils.contains(ruledPath, "{")) {
return pathMap;
}
return variablesMap;
Map<String, String> variablesMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath, requestPath);
if (variablesMap == null) {
return pathMap;
}
for (Entry<String, String> entry : variablesMap.entrySet()) {
// {method} 는 서비스키를 구성하는 요소일 뿐 업무 파라미터가 아니다.
if (StringUtils.equalsIgnoreCase(entry.getKey(), "method")) {
continue;
}
pathMap.put(entry.getKey(), entry.getValue());
}
return pathMap;
}
private Properties getHeaders(HttpServletRequest request) {
@@ -746,34 +871,4 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
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;
}
}
@@ -62,7 +62,7 @@ public class WebMvcConfig {
request.setAttribute("_authServerStatusCode", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
String detailMessage = ex.getMessage();
if ( StringUtils.isBlank(detailMessage) ) {
detailMessage = "광주은행 관리자에게 문의하세요.";
detailMessage = "API 관리자에게 문의하세요.";
}
request.setAttribute("errorMessage", detailMessage);
return "forward:/error.jsp";
@@ -163,7 +163,9 @@ public class DJBOAuth2Controller {
logTokenIssuance(false, false, e.getMessage(), null);
Properties logProp = new Properties();
logProp.put("clientId", clientId);
if(StringUtils.isNotEmpty(clientId))
logProp.put("clientId", clientId);
UnknownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
@@ -178,7 +180,9 @@ public class DJBOAuth2Controller {
logTokenIssuance(false, false, e.getMessage(), null);
Properties logProp = new Properties();
logProp.put("clientId", clientId);
if(StringUtils.isNotEmpty(clientId))
logProp.put("clientId", clientId);
UnknownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
@@ -0,0 +1,101 @@
package com.eactive.eai.custom.adapter.handler;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import com.eactive.eai.adapter.handler.TemplateCodeConvertAdapterErrorMsgHandler;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.custom.message.StandardMessageCoordinatorDJB;
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.InterfaceMapper;
import com.eactive.eai.util.JsonPathUtil;
import com.fasterxml.jackson.databind.JsonNode;
public class DJbCommonAdapterErrorMsgHandler extends TemplateCodeConvertAdapterErrorMsgHandler {
/**
* 표준 -> 비표준 거래 아웃바운드 어댑터에서 Exception이 발생했을 때, Outbound Process 응답 메시지 생성
*/
@Override
public Object generateOutboundErrorResponseMessage(String outboundadapterGroupName, String outboundadapterName,
Properties callProp, Object outboundRequestData, EAIMessage resEaiMsg) throws Exception {
StandardMessage standardMessage = resEaiMsg.getStandardMessage();
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) callProp.get(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP);
Object responseMessage = map.get(HttpAdapterServiceKey.OUTBOUND_RESPONSE_MESSAGE);
String rspErrCd = resEaiMsg.getRspErrCd();
String errorCode = StringUtils.defaultString(MessageUtil.getTobeCode(rspErrCd));
String errorMsg = StringUtils.defaultString(MessageUtil.getTobeMessage(rspErrCd));
String errorDesc = StringUtils.defaultString(MessageUtil.getTobeDesc(rspErrCd));
String errorLoc = StringUtils.substring(resEaiMsg.getRspErrMsg(), 0, 200);
JsonNode jsonNode = JsonPathUtil.toTree(responseMessage);
if (jsonNode != null) {
if(jsonNode.has("rspCode"))
errorCode = jsonNode.get("rspCode").asText();
if(jsonNode.has("rspMsg"))
errorMsg = jsonNode.get("rspMsg").asText();
if(jsonNode.has("outpMsgDesc"))
errorDesc = jsonNode.get("outpMsgDesc").asText();
}
// msg_dvcd = EM (에러메시지)
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_DVCD, "EM");
// 출력속성코드 = 1(팝업)
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_OUTP_ATRB_CD, "1");
StandardMessageManager manager = StandardMessageManager.getInstance();
InterfaceMapper mapper = manager.getMapper();
// mapper 에러코드 설정
mapper.setErrorCode(standardMessage, errorCode);
mapper.setErrorMsg(standardMessage, errorMsg);
// MSG_LIST 1건 구성
StandardItem msgList = standardMessage.findItem(StandardMessageCoordinatorDJB.MSG_LIST);
if(msgList == null) {
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_LIST_ROWCNT, "1");
msgList = standardMessage.findItem(StandardMessageCoordinatorDJB.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(errorCode);
if (row.containsKey("outp_msg_ctnt"))
row.get("outp_msg_ctnt").setValue(errorMsg);
if (row.containsKey("outp_msg_desc"))
row.get("outp_msg_desc").setValue(errorDesc);
if (row.containsKey("err_occu_loct"))
row.get("err_occu_loct").setValue(errorLoc);
}
}
// 성공 처리 처럼 진행한다.
// 단, 거래로그/에러로그는 원본 에러코드 기준으로 남겨야 하므로 별도로 보관한다.
resEaiMsg.setOrgRspErrCd(resEaiMsg.getRspErrCd());
resEaiMsg.setRspErrCd(EAIMessageKeys.EAI_SUCCESS_CODE, false);
// 응답 메시지 리턴
return "";
}
}
@@ -2,47 +2,52 @@ package com.eactive.eai.custom.adapter.handler;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import com.eactive.eai.adapter.handler.TemplateCodeConvertAdapterErrorMsgHandler;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.util.Logger;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.custom.message.StandardMessageCoordinatorDJB;
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.InterfaceMapper;
public class ErpAdapterErrorMsgHandler extends TemplateCodeConvertAdapterErrorMsgHandler {
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* 표준 -> 비표준 거래
* 아웃바운드 어댑터에서 Exception이 발생했을 때, Outbound Process 응답 메시지 생성
*/
@Override
public Object generateNonStandardErrorResponseMessage(String inboundAdapterGroupName, String inboundAdapterName,
Properties callProp, Object outboundRequestData, EAIMessage resEaiMsg) throws Exception {
public Object generateOutboundErrorResponseMessage(String outboundadapterGroupName,
String outboundadapterName, Properties callProp, Object outboundRequestData, EAIMessage resEaiMsg)
throws Exception {
StandardMessage standardMessage = resEaiMsg.getStandardMessage();
// msg_dvcd = EM (에러메시지)
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_DVCD, "NM");
Object responseMsessage = super.generateNonStandardErrorResponseMessage(inboundAdapterGroupName,
inboundAdapterName, callProp, outboundRequestData, resEaiMsg);
// 출력속성코드 = 1(팝업)
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_OUTP_ATRB_CD, "1");
logger.debug("generateNonStandardErrorResponseMessage - {}", responseMsessage);
// MSG_LIST 1건 구성
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_LIST_ROWCNT, "0");
StandardItem msgPart = standardMessage.findItem("MSG");
msgPart.getChilds().remove("MSG_LIST");
if (!(responseMsessage instanceof String)) {
return responseMsessage;
}
StandardMessageManager manager = StandardMessageManager.getInstance();
InterfaceMapper mapper = manager.getMapper();
// mapper 에러코드 설정
mapper.setErrorCode(standardMessage, "");
mapper.setErrorMsg(standardMessage, "처리오류");
String jsonStr = (String) responseMsessage;
if (StringUtils.isBlank(jsonStr)) {
return responseMsessage;
}
// 성공 처리 처럼 진행한다.
// 단, 거래로그/에러로그는 원본 에러코드 기준으로 남겨야 하므로 별도로 보관한다.
resEaiMsg.setOrgRspErrCd(resEaiMsg.getRspErrCd());
resEaiMsg.setRspErrCd(EAIMessageKeys.EAI_SUCCESS_CODE, false);
return null;
JsonNode rootNode = OBJECT_MAPPER.readTree(jsonStr);
boolean modified = false;
if (modified) {
responseMsessage = OBJECT_MAPPER.writeValueAsString(rootNode);
}
return responseMsessage;
}
}
@@ -10,6 +10,7 @@ import com.eactive.eai.adapter.handler.TemplateCodeConvertAdapterErrorMsgHandler
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.util.JacksonUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.custom.message.StandardMessageCoordinatorDJB;
import com.eactive.eai.message.StandardItem;
@@ -23,7 +24,8 @@ public class KakaopayAdapterErrorMsgHandler extends TemplateCodeConvertAdapterEr
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
// 기본 ObjectMapper 는 응답 JSON 왕복에서 100000000.00 을 1.0E8 로 바꿔버린다.
private static final ObjectMapper OBJECT_MAPPER = JacksonUtil.newNumberSafeMapper();
@Override
public Object generateNonStandardErrorResponseMessage(String inboundAdapterGroupName, String inboundAdapterName,
@@ -43,7 +45,8 @@ public class KakaopayAdapterErrorMsgHandler extends TemplateCodeConvertAdapterEr
return responseMsessage;
}
JsonNode rootNode = OBJECT_MAPPER.readTree(jsonStr);
// 제어문자를 이스케이프하지 않고 보내는 상대 시스템 대응 (JacksonUtil.escapeControlChars 주석 참조)
JsonNode rootNode = OBJECT_MAPPER.readTree(JacksonUtil.escapeControlChars(jsonStr));
boolean modified = false;
@@ -72,7 +75,7 @@ public class KakaopayAdapterErrorMsgHandler extends TemplateCodeConvertAdapterEr
if (responseBody instanceof String) {
String jsonStr = (String) responseBody;
if (!StringUtils.isBlank(jsonStr)) {
JsonNode rootNode = OBJECT_MAPPER.readTree(jsonStr);
JsonNode rootNode = OBJECT_MAPPER.readTree(JacksonUtil.escapeControlChars(jsonStr));
StringBuffer sb = new StringBuffer();
JsonNode errorCode = rootNode.get("error_code");
if(errorCode != null)
@@ -113,6 +116,8 @@ public class KakaopayAdapterErrorMsgHandler extends TemplateCodeConvertAdapterEr
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_OUTP_MSG_DESC, msgDesc);
// 성공 처리 처럼 진행한다.
// 단, 거래로그/에러로그는 원본 에러코드 기준으로 남겨야 하므로 별도로 보관한다.
resEaiMsg.setOrgRspErrCd(resEaiMsg.getRspErrCd());
resEaiMsg.setRspErrCd(EAIMessageKeys.EAI_SUCCESS_CODE, false);
return null;
@@ -15,15 +15,11 @@ 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.InterfaceMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class NaverpayAdapterErrorMsgHandler extends TemplateAdapterErrorMsgHandler {
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* 표준 -> 비표준 거래
* 아웃바운드 어댑터에서 Exception이 발생했을 때, Outbound Process 응답 메시지 생성
@@ -53,6 +49,8 @@ public class NaverpayAdapterErrorMsgHandler extends TemplateAdapterErrorMsgHandl
mapper.setErrorMsg(standardMessage, "처리오류");
// 성공 처리 처럼 진행한다.
// 단, 거래로그/에러로그는 원본 에러코드 기준으로 남겨야 하므로 별도로 보관한다.
resEaiMsg.setOrgRspErrCd(resEaiMsg.getRspErrCd());
resEaiMsg.setRspErrCd(EAIMessageKeys.EAI_SUCCESS_CODE, false);
return null;
@@ -9,6 +9,7 @@ import org.json.simple.JSONObject;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.client.impl.filter.HttpClient5AdapterFilterFactory;
import com.eactive.eai.adapter.http.client.impl.filter.HttpClientAdapterFilter;
import com.eactive.eai.common.util.JacksonUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -36,7 +37,8 @@ public class HttpClient5AdapterServiceBigTechAddFilter extends HttpClient5Adapte
// // Adapter에서 Exception이 발생한 경우, 처리할 필터
// static final String EXCEPTION_FILTER = "EXCEPTION_FILTER";
private ObjectMapper mapper = new ObjectMapper();
// 기본 ObjectMapper 는 JsonNode 직렬화 시 작은 소수를 1.2E-7 로 바꿔버린다.
private ObjectMapper mapper = JacksonUtil.newNumberSafeMapper();
/**
* 1. 기능 : HttpClient 호출 전후 Filter 적용용 2. 처리 개요 : <br>
@@ -6,6 +6,7 @@ import com.eactive.eai.adapter.http.client.impl.HttpClient5AdapterServiceRest;
import com.eactive.eai.adapter.http.client.impl.filter.OutCryptoFilter;
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
import com.eactive.eai.common.util.JacksonUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.util.JsonPathUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -15,6 +16,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
*/
public class DouzoneEncFieldOutCryptoFilter extends EncFieldOutCryptoFilter {
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
private final OutCryptoFilter filter = new OutCryptoFilter();
protected Properties setProp(Properties tempProp) {
@@ -28,26 +31,46 @@ public class DouzoneEncFieldOutCryptoFilter extends EncFieldOutCryptoFilter {
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
throws Exception {
String headerGroupName = prop.getProperty(HttpClient5AdapterServiceRest.HEADER_GROUP);
JsonNode root = JacksonUtil.readTree(message);
ObjectNode rootObjectNode = (ObjectNode) root;
JsonNode header = rootObjectNode.get(headerGroupName);
JsonNode header = (headerGroupName == null) ? null : rootObjectNode.get(headerGroupName);
// 더존은 헤더의 x-emp-nm(AAD), x-chnl-nm(DYNAMIC 키 도출 컨텍스트)이 있어야 암호화가 가능하다.
// 값이 없으면 잘못된 컨텍스트로 암호화되지 않도록 암호화를 스킵하고 원본을 그대로 전달한다.
String xEmpNm = getHeaderText(header, "x-emp-nm");
String xChnlNm = getHeaderText(header, "x-chnl-nm");
if (xEmpNm == null || xChnlNm == null) {
logger.warn("더존 암호화 컨텍스트 헤더 없음, 암호화 스킵. adptGrpName={}, adptName={}, headerGroup={}",
adptGrpName, adptName, headerGroupName);
return message;
}
rootObjectNode.remove(headerGroupName);
String xEmpNm = header.get("x-emp-nm").asText();
tempProp.setProperty("x-emp-nm", xEmpNm);
tempProp.setProperty(InCryptoFilter.PROP_AAD_HEADER, xEmpNm);
String xChnlNm = header.get("x-chnl-nm").asText();
tempProp.setProperty("x-chnl-nm", xChnlNm);
Object enc = filter.doPreFilter(adptGrpName, adptName, prop, rootObjectNode, setProp(tempProp));
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
encJson.set(headerGroupName, header);
return encJson;
}
/**
* 헤더 그룹에서 지정한 헤더 값을 조회한다. 헤더 그룹 또는 해당 항목이 없으면 null을 반환한다.
*/
private String getHeaderText(JsonNode header, String name) {
if (header == null) {
return null;
}
JsonNode node = header.get(name);
return (node == null) ? null : node.asText();
}
@Override
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
Properties tempProp) throws Exception {
@@ -26,17 +26,21 @@ public class EncFieldOutCryptoFilter implements HttpClientAdapterFilter {
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
throws Exception {
String headerGroupName = prop.getProperty(HttpClient5AdapterServiceRest.HEADER_GROUP);
JsonNode root = JacksonUtil.readTree(message);
ObjectNode rootObjectNode = (ObjectNode) root;
JsonNode header = rootObjectNode.get(headerGroupName);
rootObjectNode.remove(headerGroupName);
JsonNode header = null;
if (headerGroupName != null) {
header = rootObjectNode.get(headerGroupName);
rootObjectNode.remove(headerGroupName);
}
Object enc = filter.doPreFilter(adptGrpName, adptName, prop, rootObjectNode, setProp(tempProp));
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
encJson.set(headerGroupName, header);
if (header != null)
encJson.set(headerGroupName, header);
return encJson;
}
@@ -9,20 +9,18 @@ import com.eactive.eai.adapter.http.dynamic.filter.FilterException;
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
import com.eactive.eai.common.util.JacksonUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* 카카오뱅크 암복호화에 맟추어 커스텀 필요
*/
public class KakaopayFilter implements HttpAdapterFilter {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Override
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
HttpServletRequest request, HttpServletResponse response) throws Exception {
JsonNode rootNode = JacksonUtil.readTree(message, OBJECT_MAPPER);
// 인자 1개 오버로드는 JacksonUtil 내부의 number-safe 싱글턴 mapper 를 쓴다.
JsonNode rootNode = JacksonUtil.readTree(message);
// term_agreements[0].is_agreed 값이 true 인지 확인
boolean firstAgreed = JacksonUtil.getBoolean(rootNode, "term_agreements[0].is_agreed", false);
@@ -1,766 +0,0 @@
package com.eactive.eai.custom.adapter.http.dynamic.impl;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.mina.common.ByteBuffer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.AdapterPropManager;
import com.eactive.eai.adapter.AdapterVO;
import com.eactive.eai.adapter.Keys;
import com.eactive.eai.adapter.http.HttpMemoryLogger;
import com.eactive.eai.adapter.http.HttpMethodType;
import com.eactive.eai.adapter.http.HttpStatusException;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
import com.eactive.eai.common.TransactionContextKeys;
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.HttpAdapterExtraLogUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.env.ElinkConfig;
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;
/*
* Kbank 가상계좌 INBOUND
* @see com.eactive.eai.custom.adapter.http.dynamic.filter.VirtualAccountCryptoFilter
* @Deprecated
*/
// FIXME : kbank - kbank에서는 Controller 방식을 사용하므로, 이 어댑터는 사용되지 않음 (VirtualAccountCryptoFilter 로 대체)
public class HttpAdapterServiceVirtualAccount extends HttpAdapterServiceSupport {
public static final String HEADER_GROUP = "HEADER_GROUP";
// HEADER_GROUP JSON에 추가할 항목 정의, 없으면 전체 header 추가
public static final String HEADER_KEYS = "HEADER_KEYS";
public static final String HTTP_STATUS = "HTTP_STATUS";
public static final String PROPERTIES_NAME_HTTP_REQUEST_METHOD = "httpRequestMethod";
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
private String logPrefix = "HttpAdapterServiceRest] ";
private static final String JSON_CONTENT_TYPE = "application/json";
private static final String JSON_FIELD_NAME = "json-body";
private static final String FILE_GROUP_NAME = "image-file";
private static final String UPLOAD_ROOT_PATH = "UPLOAD_ROOT_PATH";
private Properties addCryptoFilter(Properties prop) {
String cryptoFilterName = "com.eactive.eai.custom.adapter.http.dynamic.filter.VirtualAccountCryptoFilter";
String addedPreFilter = prop.getProperty(PRE_FILTERS);
String addedPostFilter = prop.getProperty(POST_FILTERS);
if(StringUtils.isBlank(addedPreFilter)) {
addedPreFilter = cryptoFilterName;
}
else {
addedPreFilter = addedPreFilter + "," +cryptoFilterName;
}
if(StringUtils.isBlank(addedPostFilter)) {
addedPostFilter = cryptoFilterName;
}
else {
addedPostFilter = cryptoFilterName + "," +addedPostFilter;
}
prop.setProperty(PRE_FILTERS, addedPreFilter);
prop.setProperty(POST_FILTERS, addedPostFilter);
return prop;
}
private String readMultipartBody(HttpServletRequest request) throws Exception {
String jsonString = null;
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set the maximum size of the files to be uploaded
factory.setSizeThreshold(1024 * 1024);
// Set the temporary directory to store uploaded files
File tempDir = (File) request.getSession().getServletContext().getAttribute("javax.servlet.context.tempdir");
factory.setRepository(tempDir);
ServletFileUpload upload = new ServletFileUpload(factory);
Map<String, String> fileMap = new HashMap<>();
InputStream fin = null;
try {
byte[] buffer = new byte[1024];
int read = 0;
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
// file
String fieldName = item.getFieldName();
String fileName = item.getName();
fin = item.getInputStream();
ByteArrayOutputStream fo = new ByteArrayOutputStream();
while ((read = fin.read(buffer)) > 0) {
fo.write(buffer, 0, read);
}
int fileSize = fo.size();
byte[] fileBytes = fo.toByteArray();
String fileContents = new String(fileBytes);
if (logger.isInfo()) {
logger.info("[FILE]-------------------------------------------------->");
logger.info("Field name = " + fieldName);
logger.info("File name = " + fileName + " contents length = " + fileSize);
logger.info("File Contents [" + fileContents + "]");
logger.info("[FILE]<--------------------------------------------------");
}
fileMap.put(fileName, fileContents);
fin.close();
} else {
// regular form field
String fieldName = item.getFieldName();
String fieldValue = item.getString();
if (logger.isInfo()) {
logger.info("[FIELD] " + fieldName + " [" + fieldValue + "]");
}
if (JSON_CONTENT_TYPE.equalsIgnoreCase(item.getContentType())
|| JSON_FIELD_NAME.equals(fieldName)) {
jsonString = fieldValue;
}
}
}
if (logger.isInfo()) {
logger.info("Json body [" + jsonString + "]");
}
if (jsonString == null) {
jsonString = "{}";
} else {
// parsing json & add file contents
JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString);
if (jsonObject == null) {
jsonString = "{}";
} else {
JSONObject fileGroup = new JSONObject();
for (Map.Entry<String, String> entry : fileMap.entrySet()) {
fileGroup.put("fileName", entry.getKey());
fileGroup.put("fileContents", entry.getValue());
}
jsonObject.put(FILE_GROUP_NAME, fileGroup);
jsonString = jsonObject.toJSONString();
}
}
if (logger.isInfo()) {
logger.info("Json with file [" + jsonString + "]");
}
return jsonString;
} catch (Exception e) {
logger.error("Read multipart body error.", e);
throw e;
} finally {
if (fin != null) {
try {
fin.close();
} catch (Exception ex) {
// empty
}
}
}
}
private String checkRootPath(String path) {
if (StringUtils.isEmpty(path)) {
logger.info("upload dir not set(UPLOAD_ROOT_PATH), use system temp " + path);
return System.getProperty("java.io.tmpdir");
}
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
return path;
}
private String uploadMultipartBody(HttpServletRequest request, String uploadRootPath) throws Exception {
String jsonString = null;
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set the maximum size of the files to be uploaded
factory.setSizeThreshold(1024 * 1024);
// Set the temporary directory to store uploaded files
File tempDir = (File) request.getSession().getServletContext().getAttribute("javax.servlet.context.tempdir");
factory.setRepository(tempDir);
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// if not exist, create folders
String uploadDir = checkRootPath(uploadRootPath);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
// file
String fieldName = item.getFieldName();
String fileName = item.getName();
String uploadFilePath = uploadDir + File.separator + fileName;
File uploadFile = new File(uploadFilePath);
item.write(uploadFile);
if (logger.isInfo()) {
logger.info("[FILE]-------------------------------------------------->");
logger.info("Field name = " + fieldName);
logger.info("File name = " + fileName + " path = " + uploadFile.getAbsolutePath());
logger.info("[FILE]<--------------------------------------------------");
}
} else {
// regular form field
String fieldName = item.getFieldName();
String fieldValue = item.getString();
if (logger.isInfo()) {
logger.info("[FIELD] " + fieldName + " [" + fieldValue + "]");
}
if (JSON_CONTENT_TYPE.equalsIgnoreCase(item.getContentType())
|| JSON_FIELD_NAME.equals(fieldName)) {
jsonString = fieldValue;
}
}
}
if (logger.isInfo()) {
logger.info("Json body [" + jsonString + "]");
}
return jsonString;
} catch (Exception e) {
logger.error("Read multipart body error.", e);
throw e;
}
}
@SuppressWarnings({ "unchecked", "deprecation" })
public void service(String adptGrpName, String adptName, HttpServletRequest request, HttpServletResponse response) {
int traceLevel = 0;
AdapterVO adptVO = null;
AdapterPropManager manager = null;
Properties httpProp = null;
String responseType = null;
String urlDecodeYn = null;
String encode = null;
String traceLevelTemp = null;
String relayRequestHeaderKeys = null;
String headerGroupName = null;
boolean isParameterType = false;
String message = null;
StopWatch stopWatch = null;
Properties prop = null;
String paramValue = null;
String adptMsgType = null;
String errorResponseFormat = null;
String uploadRootPath = null;
try {
AdapterManager adapterManager = AdapterManager.getInstance();
adptVO = adapterManager.getAdapterVO(adptGrpName, adptName);
if (adptVO == null) {
throw new Exception("Adapter not found error");
}
manager = AdapterPropManager.getInstance();
httpProp = manager.getProperties(adptVO.getPropGroupName());
responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
urlDecodeYn = httpProp.getProperty(URL_DECODE_YN, "N");
// encode = httpProp.getProperty(ENCODE, "UTF-8");
encode = StringUtils.defaultIfBlank(adapterManager.getAdapterGroupVO(adptGrpName).getMessageEncode(),
"UTF-8");
traceLevelTemp = httpProp.getProperty(TRACE_LEVEL, "0");
relayRequestHeaderKeys = httpProp.getProperty(HEADER_KEYS);
headerGroupName = httpProp.getProperty(HEADER_GROUP);
errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
uploadRootPath = httpProp.getProperty(UPLOAD_ROOT_PATH);
prop = new Properties();
prop.put(INBOUND_METHOD, request.getMethod());
prop.put(INBOUND_URI, request.getRequestURI());
prop.put(INBOUND_HEADER, getHeaders(request));
prop.put(INBOUND_EXTPARAMS, StringUtils.defaultString(request.getQueryString()));
if (StringUtils.equals(adptVO.getAdapterGroupVO().getType(), Keys.TYPE_REST)
|| StringUtils.equals(adptVO.getAdapterGroupVO().getType(), Keys.TYPE_HTTP_CUSTOM)) {
// /api/v1/public/getUserInfo.svc
String extUrl = StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
prop.put(INBOUND_EXTURI, extUrl);
} else {
prop.put(INBOUND_EXTURI, getExtUri(request));
}
prop.put(Processor.REQUEST_ACTION, adptVO.getAdapterGroupVO().getRefClass());
prop.put(API_PATH, httpProp.getProperty(API_PATH, ""));
prop.put(PRE_FILTERS, httpProp.getProperty(PRE_FILTERS, ""));
prop.put(POST_FILTERS, httpProp.getProperty(POST_FILTERS, ""));
prop.put(PROPERTIES_NAME_HTTP_REQUEST_METHOD, request.getMethod());
prop.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
isParameterType = false;
try {
traceLevel = Integer.parseInt(traceLevelTemp);
} catch (Exception e) {
traceLevel = 0;
}
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 {
isParameterType = false;
}
break;
default:
break;
}
if (isParameterType) {
paramValue = request.getQueryString();
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, prop);
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();
} else {
if (ServletFileUpload.isMultipartContent(request)) {
// TODO : 아래의 로직은 업무에 맞게 수정이 필요함.
// 불필요할 경우 제거
// if(StringUtils.isEmpty(uploadRootPath)) {
// uploadRootPath = System.getProperty("java.io.tmpdir");
// }
// 임시로직 : UPLOAD_ROOT_PATH 가 없는 경우에는 JSON에 추가
if (StringUtils.isEmpty(uploadRootPath)) {
paramValue = readMultipartBody(request);
} else {
paramValue = uploadMultipartBody(request, uploadRootPath);
}
// TEST : 테스트용 임시코드
// response.setCharacterEncoding(encode);
// response.getWriter().print(paramValue);
// return;
} else {
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);
paramValue = new String(data, encode);
if (traceLevel >= 3) {
HttpMemoryLogger.txlog(adptGrpName + adptName,
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(paramValue));
}
}
}
if (paramValue == null) { // parameter가 없는 경우때문에 처리
paramValue = "";
}
if (logger.isDebug()) {
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
+ CommonLib.getDumpMessage(paramValue));
}
if ("Y".equals(urlDecodeYn) && isParameterType) {
message = URLDecoder.decode(paramValue);
} else {
message = paramValue;
}
if (logger.isDebug()) {
String[] msgArgs = new String[2];
msgArgs[0] = adptGrpName;
msgArgs[1] = message;
String resMsg = ExceptionUtil.make("RICEAIAHA005", msgArgs);
logger.debug(logPrefix + resMsg);
}
adptMsgType = adptVO.getAdapterGroupVO().getMessageType();
if (StringUtils.equals(adptMsgType, MessageType.JSON)) {
response.setContentType(JSON_CONTENT_TYPE+"; charset="+encode);
}
// HEADER_GROUP 셋팅
if (MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)
&& StringUtils.isNotBlank(relayRequestHeaderKeys)) {
JSONObject jsonMessage = (JSONObject) JSONValue.parse(message);
JSONObject headerJson = new JSONObject();
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
String key = e.nextElement();
headerJson.put(key, request.getHeader(key));
}
} else {
String[] relayKeyArr = org.springframework.util.StringUtils
.tokenizeToStringArray(relayRequestHeaderKeys, ",");
for (String key : relayKeyArr) {
String headerValue = request.getHeader(key);
if (StringUtils.isNotBlank(headerValue)) {
headerJson.put(key, headerValue);
}
}
}
if (headerJson.size() > 0) {
jsonMessage.put(headerGroupName, headerJson);
message = jsonMessage.toJSONString();
}
}
if (message == null) {
message = "";
}
// com.eactive.eai.custom.adapter.http.dynamic.filter.VirtualAccountCryptoFilter
prop = addCryptoFilter(prop);
// 로컬 서비스 호출 ,encoding 처리 추가
String result = (String) service(adptGrpName, adptName, message, prop, request, response);
if (logger.isDebug()) {
logger.debug("HttpAdapterServiceRest] result " + encode + " (" + adptGrpName + ") = [" + result + "]");
}
stopWatch.stop();
String responseData = "";
if (RESPONSE_TYPE_ASYNC.equals(responseType)) {
if (stopWatch.getTime() > slowTranTime && (logger.isInfo())) {
logger.info("HttpAdapterServiceRest] dummy response time = " + stopWatch.toString() + ", message = "
+ message);
}
if (result == null) {
responseData = ElinkConfig.getAsyncDummyDataForAdapterGroup(adptGrpName);
}
response.setCharacterEncoding(encode);
response.getWriter().print(responseData);
if (traceLevel >= 3) {
HttpMemoryLogger.txlog(adptGrpName + adptName,
"SEND " + "[" + responseData + "]" + CommonLib.getDumpMessage(responseData));
}
} else {
responseData = result;
logger.info("종료 >> encode = [" + encode + "]");
JSONObject dataObject = null;
if (MessageType.JSON.equals(adptMsgType)) {
dataObject = (JSONObject) JSONValue.parse(responseData);
}
// HEADER_GROUP 하위 필드를 response Header에 세팅한다.
HashMap<String, String> header = new HashMap<>();
boolean redirect = assignHttpHeaders(header, dataObject, headerGroupName);
if (logger.isDebug()) {
logger.debug("HttpAdapterServiceRest] response header field (" + adptGrpName + ") = ["
+ header.toString() + "]");
}
if (redirect) {
response.setStatus(302);
logger.debug("HttpAdapterServiceRest] set response status_code: 302");
} else {
String httpStatus = header.get(HTTP_STATUS);
if (httpStatus != null && !"".equals(httpStatus))
response.setStatus(Integer.parseInt(httpStatus));
header.remove(HTTP_STATUS);
}
// response header 셋팅
for (Map.Entry<String, String> entry : header.entrySet()) {
response.setHeader(entry.getKey(), entry.getValue());
}
if (dataObject != null) {
responseData = dataObject.toJSONString();
}
// UI와 통신시(UTF-8) 변환오류로 ENCODE 제거
response.setCharacterEncoding(encode);
response.getWriter().print(responseData);
if (logger.isDebug()) {
logger.debug("HttpAdapterServiceRest] SEND (" + adptGrpName + ") = [" + responseData + "]");
logger.debug("HttpAdapterServiceRest] SEND (" + adptGrpName + ") = "
+ CommonLib.getDumpMessage(responseData));
}
if (traceLevel >= 3) {
HttpMemoryLogger.txlog(adptGrpName + adptName,
"SEND " + "[" + responseData + "]" + CommonLib.getDumpMessage(responseData));
}
}
} catch (HttpStatusException e) {
if (traceLevel >= 3) {
HttpMemoryLogger.error(adptGrpName + adptName, e.toString(), e);
}
logger.warn("HttpAdapter] " + adptGrpName + "-" + adptName + ">>" + e.getMessage());
response.setStatus(e.getStatus());
try {
String errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode, e.getCode(),
e.getMessage(), errorResponseFormat);
response.getWriter().println(errorMsg);
} catch (Exception ex) {
// IGNORE
}
} catch (JwtAuthException e) {
if (traceLevel >= 3) {
HttpMemoryLogger.error(adptGrpName + adptName, e.toString(), e);
}
logger.error(logPrefix + adptGrpName + "-" + adptName + ">>" + e.getMessage(), e);
response.setStatus(HttpStatus.UNAUTHORIZED.value());
try {
String errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode, e.getCode(),
e.getMessage(), errorResponseFormat);
response.getWriter().println(errorMsg);
} catch (Exception ex) {
// IGNORE
}
} catch (Exception e) {
if (traceLevel >= 3) {
HttpMemoryLogger.error(adptGrpName + adptName, e.toString(), e);
}
logger.error(logPrefix + adptGrpName + "-" + adptName + ">>" + e.getMessage(), e);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
try {
response.getWriter().println(e.getMessage());
String errCode = ExceptionUtil.getErrorCode(e, "RECEAIAHA003");
throw new Exception(errCode);
} catch (Exception ex) {
// IGNORE
logger.warn(logPrefix + adptGrpName + "-" + adptName + ">>" + e.getMessage(), e);
}
} finally {
String uuid = prop.getProperty(TransactionContextKeys.TRANSACTION_UUID);
String url = prop.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
String method = prop.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
String adapterGroupName = prop.getProperty(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME);
String adapterName = prop.getProperty(HttpClientAdapterServiceKey.ADAPTER_NAME);
int httpStatusCode = response.getStatus();
HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName, adapterName, new HashMap<>(), url, method, httpStatusCode);
}
}
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 void validateServiceAndAdapter(String adptGrpName, String adptName, byte[] requestBytes, Properties prop)
throws JwtAuthException {
}
/**
* request header 를 hashmap으로 조립
*
* @param request
* @return
*/
private Properties getHeaders(HttpServletRequest request) {
Properties prop = new Properties();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = headerNames.nextElement();
String value = request.getHeader(key);
prop.setProperty(key, value);
}
return prop;
}
/**
* adapter property의 HEADER_GROUP으로 정의된 (MFE_HEADER) 그룹의 하위 필드를 http Header에
* 세팅한다.
*
* @param header
* @param object
*/
private boolean assignHttpHeaders(HashMap<String, String> header, Object msg, String headerGroupName) {
boolean redirect = false;
if (msg == null || StringUtils.isBlank(headerGroupName)) {
return false;
}
if (msg instanceof JSONObject) {
JSONObject headerObject = (JSONObject) ((JSONObject) msg).get(headerGroupName);
if (headerObject == null) {
return false;
}
// List<String> headerKeys = new ArrayList<>();
for (Object key : headerObject.keySet()) {
Object obj = headerObject.get(key);
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
continue;
}
header.put((String) key, (String) obj);
if (StringUtils.equalsIgnoreCase((String) key, "Location")) {
redirect = true;
}
}
((JSONObject) msg).remove(headerGroupName);
}
return redirect;
}
/**
* 어댑터 명 이후의 URI값을 가져온다.
*
* @param request
* @return
*/
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(), "/");
}
// public static void main(String[] args) throws Exception {
// String orgUri = "/HTT/CbsInNetSys/abcd/123456";
// String result = "";
// result = getExtUri(orgUri, 3);
// System.out.println(result);
// }
}
@@ -77,7 +77,15 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
// DATA 영역 경로
public static final String DATA_SCOP_LEN = "DATA.data_scop_len";
// 정상 응답 메시지.
// 예전에는 표준전문 레이아웃의 기본값으로 붙였으나, 그렇게 두면 "아무도 채우지 않은 상태" 와
// "정상이라고 판정한 상태" 가 구분되지 않는다. 실제로 2026-09 사고에서 MSG 부 파싱이 통째로
// 스킵됐는데도 오류가 "정상처리되었습니다." 로 보고됐다.
// 이제 레이아웃 기본값을 없애고, 정상이라고 판정한 지점에서만 명시적으로 설정한다.
public static final String NORMAL_OUTP_MSG_CD = "NCMM00001";
public static final String NORMAL_OUTP_MSG_CTNT = "정상처리되었습니다.";
private String[] netInfo;
@Override
@@ -156,7 +164,21 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
standardMessage.setData(HEAD_MESG_RSPN_DT, now.format(FMT_DATE));
standardMessage.setData(HEAD_MESG_RSPN_TIME, now.format(FMT_TIME_MILLIS));
// 정상 응답의 MSG 코드/메시지를 여기서 채운다. 레이아웃 기본값을 없앴으므로
// 이 지점이 정상 응답 메시지의 유일한 출처다.
// coordinateBeforeResponse 는 모든 동기 응답이 거치는 마지막 관문이라
// (RequestProcessor 에서 호출) 경로를 빠짐없이 덮는다.
//
// 반드시 두 조건을 함께 본다.
// 1) 정상 응답일 때만. 오류 응답에 "정상처리되었습니다." 를 채우면 2026-09 사고
// (MSG 부가 버려졌는데 오류가 정상으로 보고됨)를 코드로 재현하는 셈이다.
// 2) 값이 비어 있을 때만. 대외계가 표준응답으로 MSG 를 채워 보낸 경우 그 값이
// 우선이며 덮어쓰면 안 된다.
if (STDMessageKeys.RESPONSE_TYPE_CODE_N.equals(mapper.getResponseType(standardMessage))) {
setIfBlank(standardMessage, MSG_OUTP_MSG_CD, NORMAL_OUTP_MSG_CD);
setIfBlank(standardMessage, MSG_OUTP_MSG_CTNT, NORMAL_OUTP_MSG_CTNT);
}
StandardItem msgListRowCnt = standardMessage.findItem(StandardMessageCoordinatorDJB.MSG_LIST_ROWCNT);
if (msgListRowCnt == null || "0".equals(msgListRowCnt.getValue()) || "".equals(msgListRowCnt.getValue())) {
StandardItem msgPart = standardMessage.findItem("MSG");
@@ -209,10 +231,10 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
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(siteErrDesc);
if (row.containsKey("err_occu_loct")) row.get("err_occu_loct").setValue(errCode);
setIfPresent(row, "outp_msg_cd", siteErrCode);
setIfPresent(row, "outp_msg_ctnt", siteErrMsg);
setIfPresent(row, "outp_msg_desc", siteErrDesc);
setIfPresent(row, "err_occu_loct", errCode);
}
}
@@ -249,8 +271,9 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
mainMsgItem.setSize(1);
}
// msg_dvcd=NM, outp_atrb_cd=0, outp_msg_cd, outp_msg_ctnt, msg_list_rowcnt=0
// → 모두 CSV 기본값 사용
// msg_dvcd=NM, outp_atrb_cd=0, msg_list_rowcnt=0 → 레이아웃 기본값 사용
// outp_msg_cd, outp_msg_ctnt → 레이아웃 기본값을 없앴으므로 여기서는 비워 두고,
// 모든 동기 응답이 거치는 coordinateBeforeResponse 에서 정상 응답일 때만 채운다.
makeMsgScopLen(responseMessage);
}
@@ -259,6 +282,28 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
// private helpers
// ----------------------------------------------------------------
/**
* row 에 해당 키의 StandardItem 이 존재할 때만 값을 설정한다.
* containsKey + get 이중 조회를 제거하고 널 역참조 가능성을 차단한다.
*/
private void setIfPresent(LinkedHashMap<String, StandardItem> row, String key, String value) {
StandardItem item = row.get(key);
if (item != null) {
item.setValue(value);
}
}
/**
* 항목이 존재하고 값이 비어 있을 때만 설정한다.
* 이미 채워진 값(대외계가 보낸 MSG, 오류 경로가 설정한 값 등)은 그대로 보존한다.
*/
private void setIfBlank(StandardMessage standardMessage, String path, String value) {
StandardItem item = standardMessage.findItem(path);
if (item != null && StringUtils.isBlank(item.getValue())) {
item.setValue(value);
}
}
private void resolveCallPropRefValues(StandardMessage standardMessage, Properties prop) {
if (prop == null) return;
resolveCallPropInChilds(standardMessage.getChilds(), prop);
@@ -275,7 +320,8 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
if (m.matches()) {
String key = m.group(1);
String defaultVal = m.group(2) != null ? m.group(2) : "";
String resolved = resolveCallPropValue(prop, key);
// 패턴상 group(1)은 필수 캡처 그룹이나, 널 역참조 정적분석 지적 대응으로 방어코드 추가
String resolved = (key != null) ? resolveCallPropValue(prop, key) : null;
item.setValue(resolved != null ? resolved : defaultVal);
}
} else if (type == StandardType.GROUP) {
@@ -385,18 +431,10 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
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;
// 판정 기준은 StandardItem.matchRefCondition 하나로 통일한다.
// (FlatReader 파싱 / FLAT 직렬화와 같은 기준이어야 블록 유무 판단이 어긋나지 않음)
return StandardItem.matchRefCondition(refValue,
StringUtils.trimToEmpty(standardMessage.findItemValue(refPath)));
}
private void makeupDataScopLen(StandardMessage standardMessage, String charset) {
@@ -81,7 +81,8 @@ public class MinuteStatsAggregator {
systemErrCnt.incrementAndGet();
break;
case BUSINESS_ERROR:
bizErrCnt.incrementAndGet();
systemErrCnt.incrementAndGet();
//bizErrCnt.incrementAndGet();
break;
}
}
@@ -11,9 +11,9 @@ import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.common.security.CryptoModuleService;
/**
* JEP 트랜스포머 함수 — DJB ERP 연동 복호화.
* JEP 트랜스포머 함수 — DJB 연동 복호화.
*
* 사용법: DJBErpDecryt(encBase64, moduleName)
* 사용법: djbdecryt(encBase64, moduleName)
*
* 파라미터:
* encBase64 : Base64 인코딩된 암호문
@@ -33,7 +33,7 @@ public class DJBDecrypt extends PostfixMathCommand {
checkStack(inStack);
if (curNumberOfParameters != 2) {
throw new ParseException("DJBErpDecryt: 파라미터는 2개개여야 합니다 (encBase64, moduleName");
throw new ParseException("DJBDecrypt: 파라미터는 2개개여야 합니다 (encBase64, moduleName");
}
String moduleName = inStack.pop().toString();
@@ -46,7 +46,7 @@ public class DJBDecrypt extends PostfixMathCommand {
} catch (ParseException e) {
throw e;
} catch (Exception e) {
throw new ParseException("DJBErpDecryt 복호화 실패: " + e.getMessage());
throw new ParseException("DJBDecrypt 복호화 실패: " + e.getMessage());
}
}
}
@@ -11,13 +11,11 @@ import org.nfunk.jep.function.PostfixMathCommand;
import com.eactive.eai.common.security.CryptoModuleService;
/**
* JEP 트랜스포머 함수 — DJB ERP 연동 암호화.
* JEP 트랜스포머 함수 — DJB 연동 암호화.
*
* 사용법: DJBErpEncryt(plainText, moduleName) DJBErpEncryt(plainText, moduleName,
* groupSeq)
* 사용법: djbencrypt(plainText, moduleName)
*
* 파라미터: plainText : 암호화할 평문 (String) moduleName : DB에 등록된 암호화 모듈명 (String)
* groupSeq : 키 도출용 그룹 시퀀스 (String, 선택). 미전달 시 빈 context로 호출.
* 파라미터: plainText : 암호화할 평문 (String), moduleName : DB에 등록된 암호화 모듈명 (String)
*
* 반환값: Base64 인코딩된 암호문 (String)
*/
@@ -33,7 +31,7 @@ public class DJBEncrypt extends PostfixMathCommand {
checkStack(inStack);
if (curNumberOfParameters != 2) {
throw new ParseException("DJBErpEncryt: 파라미터는 2개여야 합니다 (plainText, moduleName)");
throw new ParseException("DJBEncrypt: 파라미터는 2개여야 합니다 (plainText, moduleName)");
}
String moduleName = inStack.pop().toString();
@@ -46,7 +44,7 @@ public class DJBEncrypt extends PostfixMathCommand {
} catch (ParseException e) {
throw e;
} catch (Exception e) {
throw new ParseException("DJBErpEncryt 암호화 실패: " + e.getMessage());
throw new ParseException("DJBEncrypt 암호화 실패: " + e.getMessage());
}
}
}
@@ -1,12 +1,12 @@
package com.eactive.eai.custom.transformer.function.userdefined;
import com.eactive.eai.common.context.ElinkTransactionContext;
import com.eactive.eai.common.util.JacksonUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;
@@ -14,7 +14,9 @@ import java.util.Stack;
public class JsonPathExtractRequestMessage extends PostfixMathCommand {
private static final ObjectMapper objectMapper = new ObjectMapper();
// JsonPath 의 기본 Jackson 프로바이더는 기본 ObjectMapper 를 쓴다. 그러면 JSON 실수가
// DoubleNode 로 파싱되어, 아래 asText() 결과가 100000000.00 -> "1.0E8" 로 깨진다.
private static final ObjectMapper objectMapper = JacksonUtil.newNumberSafeMapper();
public JsonPathExtractRequestMessage() {
numberOfParameters = -1;
@@ -33,7 +35,7 @@ public class JsonPathExtractRequestMessage extends PostfixMathCommand {
try {
// Jackson을 JsonPath의 JSON 프로바이더로 설정
Configuration config = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.jsonProvider(new JacksonJsonNodeJsonProvider(objectMapper))
.build();
JsonNode resultNode = JsonPath.using(config).parse(bizData).read(path);
+3 -3
View File
@@ -151,8 +151,8 @@ msg_dvcd,2,2,0,1,2,1,,,NM
msg_scop_len,2,2,0,1,8,2,,,
MAIN_MSG,2,3,0,1,0,1,,,
outp_atrb_cd,3,2,1,1,1,1,,,0
outp_msg_cd,3,2,1,1,12,1,,,NCMM00001
outp_msg_ctnt,3,2,1,1,200,1,,,정상처리되었습니다.
outp_msg_cd,3,2,1,1,12,1,,,
outp_msg_ctnt,3,2,1,1,200,1,,,
outp_msg_desc,3,2,1,1,300,1,,,
mngm_msg_cd,3,2,1,1,12,1,,,
msg_list_rowcnt,3,2,0,1,5,2,,,0
@@ -168,7 +168,7 @@ err_chrg_cnpl_no,3,2,0,1,20,1,,,
# ============================================================
# DATA - 데이터부
# ============================================================
DATA,1,3,1,1,0,1,,,
DATA,1,4,1,1,0,1,,,
data_dvcd,2,2,1,1,2,1,,,IO
data_scop_len,2,2,1,1,8,2,,,
BIZ_DATA,2,9,1,1,0,1,,,
1 #-----------------------------------------------------------------------------
151 msg_scop_len,2,2,0,1,8,2,,,
152 MAIN_MSG,2,3,0,1,0,1,,,
153 outp_atrb_cd,3,2,1,1,1,1,,,0
154 outp_msg_cd,3,2,1,1,12,1,,,NCMM00001 outp_msg_cd,3,2,1,1,12,1,,,
155 outp_msg_ctnt,3,2,1,1,200,1,,,정상처리되었습니다. outp_msg_ctnt,3,2,1,1,200,1,,,
156 outp_msg_desc,3,2,1,1,300,1,,,
157 mngm_msg_cd,3,2,1,1,12,1,,,
158 msg_list_rowcnt,3,2,0,1,5,2,,,0
168 # ============================================================
169 # DATA - 데이터부
170 # ============================================================
171 DATA,1,3,1,1,0,1,,, DATA,1,4,1,1,0,1,,,
172 data_dvcd,2,2,1,1,2,1,,,IO
173 data_scop_len,2,2,1,1,8,2,,,
174 BIZ_DATA,2,9,1,1,0,1,,,
@@ -0,0 +1,694 @@
package com.eactive.eai.adapter.service;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.mockito.Mockito;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
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.HttpMethodType;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.adapter.http.dynamic.filter.FilterException;
import com.eactive.eai.common.errorcode.ErrorCodeManager;
import com.eactive.eai.common.message.MessageType;
import com.eactive.eai.common.stdmessage.STDMessageManager;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.inbound.action.ActionException;
import com.eactive.eai.inbound.action.RequestAction;
import com.eactive.eai.inbound.processor.Processor;
import com.eactive.eai.message.StandardMessage;
import com.eactive.eai.message.manager.StandardMessageManager;
import com.eactive.eai.message.service.InterfaceMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* DJBApiAdapterService : Parameter(QueryString/FormData) + PathVariable 동시 처리 검증
*
* <p>검증 대상 (2026-08 수정분)
* <ul>
* <li>{@code isParameterType(HttpMethodType, String)} : 파라미터형 요청 판정</li>
* <li>{@code assignParameterMap(...)} : PathVariable + FormData + QueryString 병합</li>
* <li>{@code assignApiKeys(...)} : 서비스키 확정 (Action 1회 수행)</li>
* <li>{@code extractPathVariables(...)} : 확정된 서비스키로 PathVariable 추출</li>
* <li>{@code callApi(...)} : JSON Body 요청에 PathVariable 을 병합해 만드는 최종 전문</li>
* </ul>
*
* <p>STDMessageManager / StandardMessageManager 는 실제 DB 로딩 대신 Mock 으로 대체하고,
* 게이트웨이 본 처리({@code service(...)})는 테스트 서브클래스에서 가로채 전달 전문만 캡처한다.
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class DJBApiAdapterServiceTest {
/** StandardMessageUtil.REST_URL_ACTION2 - PathVariable 매칭이 허용되는 action */
private static final String ACTION = "com.eactive.eai.inbound.action.RestUrlParseRequestAction";
private static final String GRP = "TESTGRP";
private static final String ADP = "TESTADP";
/** STDMessageManager 에 등록되어 있다고 가정하는 서비스 키 목록 */
private static final String[] STD_KEYS = {
"GET/api/v1/users/{userId}",
"DELETE/api/v1/users/{userId}",
"POST/api/v1/users/{userId}/orders/{orderId}",
"PUT/api/v1/users/{userId}",
"PATCH/api/v1/users/{userId}",
"POST/api/v1/plain",
"{method}/api/v2/users/{userId}"
};
private final ObjectMapper json = new ObjectMapper();
// ================================================================
// 공통 setup
// ================================================================
@BeforeAll
void setUpAll() throws Exception {
STDMessageManager stdManager = Mockito.mock(STDMessageManager.class);
Mockito.when(stdManager.getAllSTDMessageKeys()).thenReturn(STD_KEYS);
Mockito.when(stdManager.getMatchedPathVariable(anyString())).thenAnswer(inv -> {
String key = inv.getArgument(0);
AntPathMatcher matcher = new AntPathMatcher();
for (String candidate : STD_KEYS) {
if (matcher.match(candidate, key)) {
return candidate;
}
}
return null;
});
Mockito.when(stdManager.getSTDMessage(anyString())).thenReturn(Mockito.mock(StandardMessage.class));
// logger.isDebug() 경로에서 호출되는 ExceptionUtil.make() 대응
ErrorCodeManager errorCodeManager = Mockito.mock(ErrorCodeManager.class);
Mockito.when(errorCodeManager.getMessage(anyString())).thenReturn("[{1}] [{2}]");
ApplicationContext ctx = Mockito.mock(ApplicationContext.class);
Mockito.when(ctx.getBean(STDMessageManager.class)).thenReturn(stdManager);
Mockito.when(ctx.getBean(ErrorCodeManager.class)).thenReturn(errorCodeManager);
Field ctxField = ApplicationContextProvider.class.getDeclaredField("context");
ctxField.setAccessible(true);
ctxField.set(null, ctx);
// ApiKeyExtractFilter.getEaiSvcCode() 대응
InterfaceMapper mapper = Mockito.mock(InterfaceMapper.class);
Mockito.when(mapper.getEaiSvcCode(any())).thenReturn("TESTSVC");
StandardMessageManager.getInstance().setMapper(mapper);
}
// ================================================================
// 1. isParameterType : 파라미터형 요청 판정
// ================================================================
@Test
@DisplayName("GET/DELETE 는 Content-Type 과 무관하게 파라미터형")
void isParameterType_GET_DELETE() {
assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.GET, null));
assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.GET, "application/json"));
assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.DELETE, "application/json"));
}
@Test
@DisplayName("POST/PUT/PATCH + form-urlencoded 는 파라미터형")
void isParameterType_form() {
String form = "application/x-www-form-urlencoded;charset=UTF-8";
assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.POST, form));
assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.PUT, form));
assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.PATCH, form));
}
@Test
@DisplayName("POST/PUT/PATCH + JSON 은 Body 형(=파라미터형 아님)")
void isParameterType_json() {
String ct = "application/json;charset=UTF-8";
assertFalse(DJBApiAdapterService.isParameterType(HttpMethodType.POST, ct));
assertFalse(DJBApiAdapterService.isParameterType(HttpMethodType.PUT, ct));
assertFalse(DJBApiAdapterService.isParameterType(HttpMethodType.PATCH, ct));
// Content-Type 미지정 POST 도 Body 형으로 취급
assertFalse(DJBApiAdapterService.isParameterType(HttpMethodType.POST, null));
}
@Test
@DisplayName("정의되지 않은 메서드(HEAD/OPTIONS 등)는 파라미터형으로 취급된다")
void isParameterType_unknown() {
// 수정 전에는 지역변수 초기값이 false 라 Body 형이었으나, 현재는 true 로 바뀌었다.
assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.getValue("OPTIONS"), null));
assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.UNKNOWN, "application/json"));
}
// ================================================================
// 2. assignParameterMap : PathVariable + FormData + QueryString 병합
// ================================================================
@Test
@DisplayName("GET : QueryString 과 PathVariable 이 동시에 병합된다")
void assignParameterMap_query_and_pathVariable() throws Exception {
MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123");
req.setQueryString("page=2&size=10");
Properties prop = newProp("GET", "/api/v1/users/123");
Map<String, String[]> map = assignParameterMap(req, "", prop, "N");
assertEquals("123", single(map, "userId"), "PathVariable 이 누락됨");
assertEquals("2", single(map, "page"));
assertEquals("10", single(map, "size"));
assertEquals(3, map.size());
}
@Test
@DisplayName("GET : QueryString 이 없어도 PathVariable 은 추출된다")
void assignParameterMap_pathVariable_only() throws Exception {
MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123");
Properties prop = newProp("GET", "/api/v1/users/123");
Map<String, String[]> map = assignParameterMap(req, "", prop, "N");
assertEquals(1, map.size());
assertEquals("123", single(map, "userId"));
}
@Test
@DisplayName("이름이 겹치면 QueryString 값이 PathVariable 을 덮어쓴다")
void assignParameterMap_query_overrides_pathVariable() throws Exception {
MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123");
req.setQueryString("userId=999");
Properties prop = newProp("GET", "/api/v1/users/123");
Map<String, String[]> map = assignParameterMap(req, "", prop, "N");
assertEquals("999", single(map, "userId"));
}
@Test
@DisplayName("동일 파라미터 다중 값은 배열로 유지된다")
void assignParameterMap_multiValue() throws Exception {
MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123");
req.setQueryString("code=A&code=B");
Properties prop = newProp("GET", "/api/v1/users/123");
Map<String, String[]> map = assignParameterMap(req, "", prop, "N");
assertEquals(2, map.get("code").length);
assertEquals("A", map.get("code")[0]);
assertEquals("B", map.get("code")[1]);
}
@Test
@DisplayName("POST form-urlencoded : Body(form) + QueryString + PathVariable 이 모두 병합된다")
void assignParameterMap_formData() throws Exception {
MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9");
req.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
req.setQueryString("trace=on");
Properties prop = newProp("POST", "/api/v1/users/123/orders/9");
Map<String, String[]> map = assignParameterMap(req, "amount=1000&memo=hello", prop, "N");
assertEquals("123", single(map, "userId"));
assertEquals("9", single(map, "orderId"));
assertEquals("1000", single(map, "amount"));
assertEquals("hello", single(map, "memo"));
assertEquals("on", single(map, "trace"));
}
@Test
@DisplayName("Content-Type 이 없어도(GET 등) 예외 없이 처리된다")
void assignParameterMap_nullContentType() throws Exception {
MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123");
req.setQueryString("page=1");
req.setContentType(null);
Properties prop = newProp("GET", "/api/v1/users/123");
Map<String, String[]> map = assertDoesNotThrow(() -> assignParameterMap(req, "", prop, "N"));
assertEquals("1", single(map, "page"));
}
@Test
@DisplayName("잘못된 charset 이 담긴 Content-Type 도 예외로 전파되지 않는다")
void assignParameterMap_invalidCharset() throws Exception {
MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9");
req.setContentType("application/x-www-form-urlencoded;charset=NO_SUCH_CHARSET");
Properties prop = newProp("POST", "/api/v1/users/123/orders/9");
Map<String, String[]> map = assertDoesNotThrow(() -> assignParameterMap(req, "amount=1000", prop, "N"));
assertEquals("1000", single(map, "amount"));
assertEquals("123", single(map, "userId"));
}
@Test
@DisplayName("URL_DECODE_YN=Y : %인코딩된 한글 파라미터가 UTF-8 로 복원된다")
void assignParameterMap_urlDecode_hangul() throws Exception {
MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123");
// "한글" == %ED%95%9C%EA%B8%80 (UTF-8)
req.setQueryString("name=%ED%95%9C%EA%B8%80");
Properties prop = newProp("GET", "/api/v1/users/123");
Map<String, String[]> map = assignParameterMap(req, "", prop, "Y");
assertEquals("한글", single(map, "name"), "%인코딩 복원 기본 charset 이 UTF-8 이 아니면 깨진다");
}
@Test
@DisplayName("URL_DECODE_YN=Y : Content-Type 의 charset 이 %인코딩 복원에 우선한다")
void assignParameterMap_urlDecode_contentTypeCharset() throws Exception {
MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9");
req.setContentType("application/x-www-form-urlencoded;charset=EUC-KR");
Properties prop = newProp("POST", "/api/v1/users/123/orders/9");
// "한글" == %C7%D1%B1%DB (EUC-KR)
Map<String, String[]> map = assignParameterMap(req, "name=%C7%D1%B1%DB", prop, "Y");
assertEquals("한글", single(map, "name"));
}
@Test
@DisplayName("URL_DECODE_YN=N : 기존 ISO-8859-1 byte latch 동작을 유지한다")
void assignParameterMap_noUrlDecode_keepsLatin1Latch() throws Exception {
MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123");
// 컨테이너가 URIEncoding=ISO-8859-1 로 디코딩해 넘겨준 상태를 재현한다.
String latin1Decoded = new String("한글".getBytes("UTF-8"), "ISO-8859-1");
req.setQueryString("name=" + latin1Decoded);
Properties prop = newProp("GET", "/api/v1/users/123");
Map<String, String[]> map = assignParameterMap(req, "", prop, "N");
// ISO-8859-1 로 원본 바이트를 되찾은 뒤 플랫폼 기본 charset 으로 디코딩하는 기존 동작.
String expected = new String("한글".getBytes("UTF-8"));
assertEquals(expected, single(map, "name"), "URL_DECODE_YN=N 경로의 기존 동작이 변경됨");
}
// ================================================================
// 3-1. assignApiKeys : 서비스키 확정 (기존 ApiKeyExtractFilter.doPreFilter)
// ================================================================
@Test
@DisplayName("서비스키 3종(STD/FINAL/API_SERVICE_CODE)을 tx prop 에 세팅한다")
void assignApiKeys_setsServiceKeys() throws Exception {
Properties prop = newProp("GET", "/api/v1/users/123");
assignApiKeys("", prop);
assertEquals("GET/api/v1/users/123", prop.getProperty(DJBApiAdapterService.STD_MESSAGE_KEY));
assertEquals("GET/api/v1/users/{userId}", prop.getProperty(DJBApiAdapterService.FINAL_STD_MESSAGE_KEY));
assertEquals("TESTSVC", prop.getProperty(DJBApiAdapterService.API_SERVICE_CODE));
}
@Test
@DisplayName("PathVariable 없이 정확히 일치하는 서비스키도 세팅된다")
void assignApiKeys_exactKey() throws Exception {
Properties prop = newProp("POST", "/api/v1/plain");
assignApiKeys("", prop);
assertEquals("POST/api/v1/plain", prop.getProperty(DJBApiAdapterService.STD_MESSAGE_KEY));
assertEquals("POST/api/v1/plain", prop.getProperty(DJBApiAdapterService.FINAL_STD_MESSAGE_KEY));
}
@Test
@DisplayName("등록되지 않은 경로는 403 FilterException 으로 차단한다")
void assignApiKeys_unknownPath() throws Exception {
Properties prop = newProp("GET", "/api/v1/unknown/path");
FilterException e = assertThrows(FilterException.class, () -> assignApiKeys("", prop));
assertEquals(HttpStatus.FORBIDDEN.value(), e.getStatus());
}
@Test
@DisplayName("Action 생성 실패는 예외로 전파된다")
void assignApiKeys_actionFailure() throws Exception {
Properties prop = newProp("GET", "/api/v1/users/123");
prop.setProperty(Processor.REQUEST_ACTION, "com.eactive.eai.NoSuchAction");
assertThrows(ActionException.class, () -> assignApiKeys("", prop));
}
@Test
@DisplayName("요청 1건당 Action 은 한 번만 생성/수행된다 (중복 제거 검증)")
void assignApiKeys_actionPerformedOnce() throws Exception {
CapturingAdapterService svc = new CapturingAdapterService();
MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123");
req.setQueryString("page=2");
CountingRequestAction.COUNT.set(0);
callApi(svc, req, CountingRequestAction.class.getName());
assertEquals(1, CountingRequestAction.COUNT.get(),
"서비스키 확정과 PathVariable 추출이 각각 Action 을 호출하면 2 가 된다");
}
// ================================================================
// 3-2. extractPathVariables : 서비스키 대비 PathVariable 추출 (순수 함수)
// ================================================================
@Test
@DisplayName("PathVariable 이 없는 서비스키는 빈 Map 을 반환한다(null 아님)")
void extractPathVariables_noTemplate() throws Exception {
Map<String, String> map = extractPathVariables("POST/api/v1/plain", "POST/api/v1/plain");
assertNotNull(map);
assertTrue(map.isEmpty());
}
@Test
@DisplayName("서비스키 템플릿에서 PathVariable 을 추출한다")
void extractPathVariables_extract() throws Exception {
Map<String, String> map = extractPathVariables("POST/api/v1/users/123/orders/9",
"POST/api/v1/users/{userId}/orders/{orderId}");
assertEquals("123", map.get("userId"));
assertEquals("9", map.get("orderId"));
assertEquals(2, map.size());
}
@Test
@DisplayName("{method} 는 파라미터로 포함하지 않는다")
void extractPathVariables_skipMethod() throws Exception {
Map<String, String> map = extractPathVariables("GET/api/v2/users/777", "{method}/api/v2/users/{userId}");
assertFalse(map.containsKey("method"), "{method} 는 제외되어야 함");
assertEquals("777", map.get("userId"));
assertEquals(1, map.size());
}
@Test
@DisplayName("QueryString 유무는 PathVariable 추출에 영향을 주지 않는다")
void extractPathVariables_independentOfQueryString() throws Exception {
// 서비스키는 QueryString 을 포함하지 않으므로 동일 입력 → 동일 결과여야 한다.
Map<String, String> map = extractPathVariables("GET/api/v1/users/123", "GET/api/v1/users/{userId}");
assertEquals("123", map.get("userId"), "QueryString 존재 시 PathVariable 추출이 생략되면 안 됨");
}
// ================================================================
// 4. callApi : JSON Body + PathVariable 병합 (end-to-end)
// ================================================================
@Test
@DisplayName("POST JSON : Body 에 PathVariable 이 추가된다")
void callApi_jsonBody_with_pathVariables() throws Exception {
CapturingAdapterService svc = new CapturingAdapterService();
MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9");
req.setContentType("application/json;charset=UTF-8");
req.setContent("{\"amount\":\"1000\"}".getBytes("UTF-8"));
callApi(svc, req);
JsonNode node = json.readTree((String) svc.captured);
assertEquals("1000", node.path("amount").asText());
assertEquals("123", node.path("userId").asText(), "PathVariable userId 누락");
assertEquals("9", node.path("orderId").asText(), "PathVariable orderId 누락");
}
@Test
@DisplayName("POST JSON : PathVariable 이 없으면 Body 를 그대로 전달한다")
void callApi_jsonBody_without_pathVariables() throws Exception {
CapturingAdapterService svc = new CapturingAdapterService();
MockHttpServletRequest req = newRequest("POST", "/api/v1/plain");
req.setContentType("application/json;charset=UTF-8");
req.setContent("{\"amount\":\"1000\"}".getBytes("UTF-8"));
callApi(svc, req);
assertEquals("{\"amount\":\"1000\"}", svc.captured);
}
@Test
@DisplayName("POST JSON : 빈 오브젝트 Body({}) 에 PathVariable 을 넣어도 유효한 JSON")
void callApi_emptyJsonBody() throws Exception {
CapturingAdapterService svc = new CapturingAdapterService();
MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9");
req.setContentType("application/json;charset=UTF-8");
req.setContent("{}".getBytes("UTF-8"));
callApi(svc, req);
JsonNode node = json.readTree((String) svc.captured); // {,"userId":..} 이면 파싱 실패
assertEquals("123", node.path("userId").asText());
assertEquals("9", node.path("orderId").asText());
}
@Test
@DisplayName("POST JSON : Body 가 없으면 PathVariable 만으로 JSON 을 만든다")
void callApi_noBody() throws Exception {
CapturingAdapterService svc = new CapturingAdapterService();
MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9");
req.setContentType("application/json;charset=UTF-8");
callApi(svc, req);
JsonNode node = json.readTree((String) svc.captured);
assertEquals("123", node.path("userId").asText());
assertEquals("9", node.path("orderId").asText());
}
@Test
@DisplayName("POST JSON : Body 끝에 개행/공백이 있어도 Body 가 유실되지 않는다")
void callApi_jsonBody_trailingNewline() throws Exception {
CapturingAdapterService svc = new CapturingAdapterService();
MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9");
req.setContentType("application/json;charset=UTF-8");
req.setContent("{\"amount\":\"1000\"}\n".getBytes("UTF-8"));
callApi(svc, req);
JsonNode node = json.readTree((String) svc.captured);
assertEquals("1000", node.path("amount").asText(), "Body 가 PathVariable 로 덮어써짐");
assertEquals("123", node.path("userId").asText());
}
@Test
@DisplayName("POST XML : JSON 이 아닌 Body 는 PathVariable 병합으로 유실되면 안 된다")
void callApi_xmlBody_must_not_be_dropped() throws Exception {
CapturingAdapterService svc = new CapturingAdapterService();
MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9");
req.setContentType("application/xml;charset=UTF-8");
req.setContent("<root><amount>1000</amount></root>".getBytes("UTF-8"));
callApi(svc, req);
assertTrue(((String) svc.captured).contains("<amount>1000</amount>"),
"XML Body 가 PathVariable JSON 으로 덮어써짐 : " + svc.captured);
}
@Test
@DisplayName("PathVariable 값에 특수문자가 있어도 JSON 이 깨지지 않는다")
void callApi_pathVariable_escaping() throws Exception {
CapturingAdapterService svc = new CapturingAdapterService();
MockHttpServletRequest req = newRequest("POST", "/api/v1/users/a\"b/orders/9");
req.setContentType("application/json;charset=UTF-8");
req.setContent("{\"amount\":\"1000\"}".getBytes("UTF-8"));
callApi(svc, req);
JsonNode node = json.readTree((String) svc.captured); // escape 누락이면 파싱 실패
assertEquals("a\"b", node.path("userId").asText());
}
@Test
@DisplayName("GET : QueryString + PathVariable 이 하나의 JSON 전문으로 전달된다")
void callApi_get_query_and_pathVariable() throws Exception {
CapturingAdapterService svc = new CapturingAdapterService();
MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123");
req.setQueryString("page=2&size=10");
callApi(svc, req);
JsonNode node = json.readTree((String) svc.captured);
assertEquals("123", node.path("userId").asText());
assertEquals("2", node.path("page").asText());
assertEquals("10", node.path("size").asText());
}
@Test
@DisplayName("QueryString 이 있어도 INBOUND_PATH_VARIABLES 가 채워진다(Outbound URL 치환용)")
void callApi_inboundPathVariables_with_queryString() throws Exception {
CapturingAdapterService svc = new CapturingAdapterService();
MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123");
req.setQueryString("page=2");
callApi(svc, req);
@SuppressWarnings("unchecked")
Map<String, String> pathVariables = (Map<String, String>) svc.capturedProp
.get(HttpAdapterServiceKey.INBOUND_PATH_VARIABLES);
assertNotNull(pathVariables, "QueryString 존재 시 INBOUND_PATH_VARIABLES 미설정 → Outbound 치환 불가/NPE");
assertEquals("123", pathVariables.get("userId"));
}
@Test
@DisplayName("[현재 동작] POST JSON + QueryString : QueryString 은 전문에 병합되지 않는다")
void callApi_jsonBody_with_queryString_currentBehavior() throws Exception {
CapturingAdapterService svc = new CapturingAdapterService();
MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9");
req.setContentType("application/json;charset=UTF-8");
req.setQueryString("trace=on");
req.setContent("{\"amount\":\"1000\"}".getBytes("UTF-8"));
callApi(svc, req);
JsonNode node = json.readTree((String) svc.captured);
assertEquals("1000", node.path("amount").asText());
assertEquals("123", node.path("userId").asText());
assertTrue(node.path("trace").isMissingNode(),
"현재 사양: JSON Body 요청의 QueryString 은 전문에 포함되지 않음");
// QueryString 자체는 필터 검증용으로 보존된다.
assertEquals("trace=on", svc.capturedProp.getProperty(HttpAdapterServiceKey.INBOUND_QUERY_STRING));
}
// ================================================================
// helper
// ================================================================
/** 게이트웨이 본 처리를 가로채 전달 전문/컨텍스트만 캡처하는 테스트용 서브클래스 */
static class CapturingAdapterService extends DJBApiAdapterService {
Object captured;
Properties capturedProp;
@Override
public Object service(String adptGrpName, String adptName, Object message, Properties prop,
HttpServletRequest request, HttpServletResponse response) {
this.captured = message;
this.capturedProp = prop;
return "{\"result\":\"ok\"}";
}
}
private MockHttpServletRequest newRequest(String method, String uri) {
MockHttpServletRequest req = new MockHttpServletRequest(method, uri);
req.setContextPath("");
return req;
}
/** RestUrlParseRequestAction 이 서비스키를 만들기 위해 필요한 최소 컨텍스트 */
private Properties newProp(String method, String extUri) {
Properties prop = new Properties();
prop.setProperty(Processor.REQUEST_ACTION, ACTION);
prop.setProperty(DJBApiAdapterService.PROPERTIES_NAME_HTTP_REQUEST_METHOD, method);
prop.setProperty(HttpAdapterServiceKey.INBOUND_EXTURI, extUri);
return prop;
}
private String callApi(CapturingAdapterService svc, MockHttpServletRequest req) throws Exception {
return callApi(svc, req, ACTION);
}
private String callApi(CapturingAdapterService svc, MockHttpServletRequest req, String actionName)
throws Exception {
AdapterGroupVO group = new AdapterGroupVO();
group.setName(GRP);
group.setType(Keys.TYPE_REST);
group.setMessageType(MessageType.JSON);
group.setMessageEncode("UTF-8");
group.setRefClass(actionName);
AdapterVO adapter = new AdapterVO();
adapter.setName(ADP);
adapter.setAdapterGroupVO(group);
Properties httpProp = new Properties();
httpProp.setProperty(HttpAdapterServiceKey.URL_DECODE_YN, "N");
httpProp.setProperty(DJBApiAdapterService.HEADER_GROUP, "");
httpProp.setProperty(DJBApiAdapterService.HEADER_KEYS, "");
return svc.callApi(req, new MockHttpServletResponse(), httpProp, group, adapter, new Properties());
}
/** 운영 흐름(callApi)과 동일하게 assignApiKeys → extractPathVariables 결과를 넘겨 호출한다. */
@SuppressWarnings("unchecked")
private Map<String, String[]> assignParameterMap(HttpServletRequest req, Object reqMessage, Properties prop,
String urlDecode) throws Exception {
assignApiKeys(reqMessage, prop);
Map<String, String> variablesMap = extractPathVariables(
prop.getProperty(DJBApiAdapterService.STD_MESSAGE_KEY),
prop.getProperty(DJBApiAdapterService.FINAL_STD_MESSAGE_KEY));
Method m = DJBApiAdapterService.class.getDeclaredMethod("assignParameterMap", HttpServletRequest.class,
String.class, String.class, Object.class, Properties.class, String.class, Map.class);
m.setAccessible(true);
try {
return (Map<String, String[]>) m.invoke(new DJBApiAdapterService(), req, GRP, ADP, reqMessage, prop,
urlDecode, variablesMap);
} catch (java.lang.reflect.InvocationTargetException e) {
throw (Exception) e.getCause();
}
}
private void assignApiKeys(Object reqMessage, Properties prop) throws Exception {
Method m = DJBApiAdapterService.class.getDeclaredMethod("assignApiKeys", String.class, String.class,
Object.class, Properties.class);
m.setAccessible(true);
try {
m.invoke(new DJBApiAdapterService(), GRP, ADP, reqMessage, prop);
} catch (java.lang.reflect.InvocationTargetException e) {
throw (Exception) e.getCause();
}
}
@SuppressWarnings("unchecked")
private Map<String, String> extractPathVariables(String requestPath, String ruledPath) throws Exception {
Method m = DJBApiAdapterService.class.getDeclaredMethod("extractPathVariables", String.class, String.class);
m.setAccessible(true);
try {
return (Map<String, String>) m.invoke(new DJBApiAdapterService(), requestPath, ruledPath);
} catch (java.lang.reflect.InvocationTargetException e) {
throw (Exception) e.getCause();
}
}
/** Action 이 요청당 몇 번 수행되는지 세기 위한 테스트용 RequestAction */
public static class CountingRequestAction implements RequestAction {
static final AtomicInteger COUNT = new AtomicInteger();
private Properties prop;
@Override
public void setAdapterInfo(String adapterGroupName, String adapterName, Properties prop) {
this.prop = prop;
}
@Override
public String[] perform(Object message) {
COUNT.incrementAndGet();
String method = prop.getProperty(DJBApiAdapterService.PROPERTIES_NAME_HTTP_REQUEST_METHOD);
String extUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
return new String[] { method + "/" + StringUtils.removeStart(extUri, "/") };
}
@Override
public String getDescription() {
return "counting test action";
}
}
private String single(Map<String, String[]> map, String key) {
String[] values = map.get(key);
assertNotNull(values, "key 없음 : " + key);
assertEquals(1, values.length, "단일 값이 아님 : " + key);
return values[0];
}
}
@@ -324,20 +324,59 @@ class StandardMessageCoordinatorDJBTest {
"정상 수신 시 msg_dvcd는 NM이어야 함");
}
// outp_msg_cd / outp_msg_ctnt 는 레이아웃 기본값을 없앴으므로 이 시점에는 비어 있고,
// 실제 흐름대로 coordinateBeforeResponse 까지 거쳐야 채워진다.
@Test
void 정상수신시_outp_msg_cd_설정됨() {
void 정상수신시_outp_msg_cd_는_응답조정후_설정됨() {
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
assertTrue(isBlankValue(message.findItemValue("MSG.MAIN_MSG.outp_msg_cd")),
"수신 조정 단계에서는 아직 비어 있어야 함 (레이아웃 기본값이 없어야 한다)");
String msgCd = message.findItemValue("MSG.MAIN_MSG.outp_msg_cd");
assertFalse(msgCd == null || msgCd.trim().isEmpty(), "outp_msg_cd가 설정되어야 함");
coordinator.coordinateBeforeResponse(message, null, null, "utf-8");
assertEquals(StandardMessageCoordinatorDJB.NORMAL_OUTP_MSG_CD,
message.findItemValue("MSG.MAIN_MSG.outp_msg_cd"),
"정상 응답의 outp_msg_cd 가 설정되어야 함");
}
@Test
void 정상수신시_outp_msg_ctnt_설정됨() {
void 정상수신시_outp_msg_ctnt_는_응답조정후_설정됨() {
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
assertTrue(isBlankValue(message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt")),
"수신 조정 단계에서는 아직 비어 있어야 함 (레이아웃 기본값이 없어야 한다)");
String ctnt = message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt");
assertFalse(ctnt == null || ctnt.trim().isEmpty(), "outp_msg_ctnt가 설정되어야 함");
coordinator.coordinateBeforeResponse(message, null, null, "utf-8");
assertEquals(StandardMessageCoordinatorDJB.NORMAL_OUTP_MSG_CTNT,
message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt"),
"정상 응답의 outp_msg_ctnt 가 설정되어야 함");
}
@Test
void 오류응답에는_정상메시지가_채워지지_않는다() {
coordinator.coordinateSetStandardMessageError(message, mapper, "RECEAIINA001", "테스트오류");
coordinator.coordinateBeforeResponse(message, null, null, "utf-8");
assertNotEquals(StandardMessageCoordinatorDJB.NORMAL_OUTP_MSG_CD,
message.findItemValue("MSG.MAIN_MSG.outp_msg_cd"),
"오류 응답에 정상코드가 채워지면 안 됨");
assertNotEquals(StandardMessageCoordinatorDJB.NORMAL_OUTP_MSG_CTNT,
message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt"),
"오류 응답에 '정상처리되었습니다.' 가 채워지면 안 됨 — 2026-09 사고의 재현");
}
@Test
void 대외계가_보낸_MSG_값은_덮어쓰지_않는다() {
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
message.setData("MSG.MAIN_MSG.outp_msg_cd", "ABC00001");
message.setData("MSG.MAIN_MSG.outp_msg_ctnt", "상대가 보낸 메시지");
coordinator.coordinateBeforeResponse(message, null, null, "utf-8");
assertEquals("ABC00001", message.findItemValue("MSG.MAIN_MSG.outp_msg_cd"),
"이미 채워진 outp_msg_cd 를 덮어쓰면 안 됨");
assertEquals("상대가 보낸 메시지", message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt"),
"이미 채워진 outp_msg_ctnt 를 덮어쓰면 안 됨");
}
@Test
@@ -496,4 +535,8 @@ class StandardMessageCoordinatorDJBTest {
f.setAccessible(true);
f.set(item, refValue);
}
private static boolean isBlankValue(String value) {
return value == null || value.trim().isEmpty();
}
}
@@ -32,19 +32,20 @@ import static org.mockito.ArgumentMatchers.anyString;
* 검증 시나리오:
* 1. FlatReader 등록 확인
* 2. 비ERP 요청 FLAT 왕복 — HEAD 보존, EZDATA/MSG 바이트 미포함
* 2-1. ERP 요청인데 JSON 에 EZDATA 가 없는 경우 — EZDATA 바이트 포함
* 3. ERP 요청 FLAT 왕복 — EZDATA 포함 보존
* 4. 오류 응답 FLAT 왕복 — MSG EM 포함 보존
* 5. 정상 응답 FLAT 왕복 — MSG NM 포함 보존
* 6. 거래로그 시나리오 — FLAT 바이트 길이 검증 (조건부 블록 포함 여부)
*
* 핵심 버그 (EZDATA FLAT 오류):
* JSON 파싱 시 JSON에 없는 조건부 블록(EZDATA, MSG)은 isHidden=false 로 남는다.
* toByteArray() GROUP 케이스에서 size=0 이면서 refPath/refValue 가 있는 경우
* isHidden 체크만으로는 불충분 → FLAT에 비활성 블록 바이트가 잘못 포함된다.
* 핵심: FLAT 은 위치 기반이라 블록의 존재 여부를 전문에서 알 수 없고 ref 조건으로만 판단한다.
* 따라서 직렬화와 파싱이 같은 기준을 써야 한다.
*
* 수정: toByteArray() / getBytesDataLength() GROUP 케이스를
* toJson() 과 동일하게 size==0 이면 무조건 skip 으로 변경
* (StandardItem.java 두 곳)
* 기준: 조건부 블록(refPath/refValue)은 ref 조건 성립 여부로 FLAT 포함 여부를 정한다.
* - 조건 불성립 → JSON 에 블록이 있어도 FLAT 미포함
* - 조건 성립 → JSON 에 블록이 없어도(size=0) 레이아웃 기본값으로 FLAT 포함
* (StandardItem.isFlatGroupActive / FlatReader.traverse 가 공유하는
* StandardItem.matchRefCondition 로 판정)
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class StandardMessageFlatFlowTest {
@@ -127,6 +128,42 @@ class StandardMessageFlatFlowTest {
+ "}"
+ "}";
/**
* ERP 요청인데 EZDATA 블록을 보내지 않은 JSON.
* corp_tlwn_virt_brcd=ERP 이므로 레이아웃상 EZDATA 는 "있어야 하는" 블록이지만
* 수신 JSON 에 없어 size=0 으로 남는다. 실제 거래로그에서 확인된 케이스다.
*/
private static final String ERP_REQ_NO_EZDATA_JSON =
"{"
+ "\"HEAD\":{"
+ "\"nxgn_stnd_idfr\":\"JERA\","
+ "\"guid\":\"" + TEST_GUID + "\","
+ "\"guid_prgs_no\":\"1\","
+ "\"stnd_mesg_ver\":\"R10\","
+ "\"ortr_guid\":\"" + TEST_GUID + "\","
+ "\"dman_rspn_dvcd\":\"S\","
+ "\"if_id\":\"" + TEST_IF_ID + "\","
+ "\"procs_rslt_dvcd\":\"S\","
+ "\"tx_id\":\"" + TEST_TX_ID + "\","
+ "\"chnl_tycd\":\"EAI\","
+ "\"hmab_dvcd\":\"1\","
+ "\"corp_tlwn_virt_brcd\":\"ERP\","
+ "\"trnm_sys_dvcd\":\"OPA\","
+ "\"frst_trnm_sys_dvcd\":\"OPA\","
+ "\"sys_env_dvcd\":\"D\","
+ "\"frst_mesg_dman_dt\":\"20260420\","
+ "\"frst_mesg_dman_time\":\"120000000\""
+ "},"
+ "\"DATA\":{"
+ "\"data_dvcd\":\"IO\","
+ "\"data_scop_len\":\"00000037\","
+ "\"BIZ_DATA\":{\"acct_no\":\"987654321\",\"amt\":\"500000\"}"
+ "}"
+ "}";
/** EZDATA 블록 선언 길이 (standard-layout-djb.csv 기준) */
private static final int EZDATA_BLOCK_SIZE = 1500;
private StandardMessageManager manager;
private InterfaceMapper mapper;
private StandardReader flatReader;
@@ -253,6 +290,78 @@ class StandardMessageFlatFlowTest {
"비ERP FLAT 왕복 후 EZDATA 블록이 활성 상태이면 안 됨");
}
// ================================================================
// 2-1. ERP 요청인데 JSON 에 EZDATA 가 없는 경우
//
// [버그] corp_tlwn_virt_brcd=ERP 라 FlatReader 는 EZDATA(1500B)가 있다고 보고 읽는데,
// 직렬화는 size==0 이라 건너뛰어 헤더가 678B 로 기록된다.
// → cut() underflow → 거래로그 화면에서 헤더 파싱 실패(원문 노출)
// [수정] ref 조건이 성립하면 size==0 이어도 레이아웃 기본값으로 FLAT 출력
// (StandardItem.isFlatGroupActive)
// ================================================================
@Test
void ERP요청_EZDATA미포함_FLAT_파싱_예외없음() throws Exception {
StandardMessage src = parseJson(ERP_REQ_NO_EZDATA_JSON);
String flatStr = src.toFixedString(false, FLAT_CHARSET);
StandardMessage dst = manager.getStandardMessage();
assertDoesNotThrow(() -> flatReader.parse(dst, flatStr),
"ERP 요청(EZDATA 미포함) FLAT 파싱 중 예외 발생 — "
+ "corp_tlwn_virt_brcd=ERP 이면 EZDATA 바이트가 FLAT 에 포함되어야 함");
}
@Test
void ERP요청_EZDATA미포함_FLAT에_EZDATA_바이트_포함() throws Exception {
byte[] nonErpBytes = parseJson(NON_ERP_REQ_JSON)
.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
byte[] erpNoEzBytes = parseJson(ERP_REQ_NO_EZDATA_JSON)
.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
assertEquals(nonErpBytes.length + EZDATA_BLOCK_SIZE, erpNoEzBytes.length,
String.format("ERP 요청(EZDATA 미포함) FLAT 길이(%d)는 "
+ "비ERP FLAT 길이(%d) + EZDATA(%d) 여야 함",
erpNoEzBytes.length, nonErpBytes.length, EZDATA_BLOCK_SIZE));
}
@Test
void ERP요청_EZDATA_포함여부와_무관하게_FLAT_길이_동일() throws Exception {
byte[] withEzBytes = parseJson(ERP_REQ_JSON)
.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
byte[] noEzBytes = parseJson(ERP_REQ_NO_EZDATA_JSON)
.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
// 블록 유무는 JSON 수신 여부가 아니라 ref 조건(corp_tlwn_virt_brcd=ERP)이 정한다
assertEquals(withEzBytes.length, noEzBytes.length,
String.format("EZDATA 포함 JSON(%d)과 미포함 JSON(%d)의 FLAT 길이가 달라짐",
withEzBytes.length, noEzBytes.length));
}
@Test
void ERP요청_EZDATA미포함_FLAT_왕복_HEAD_corp_tlwn_virt_brcd_ERP() throws Exception {
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_NO_EZDATA_JSON));
assertEquals("ERP", dst.findItemValue("HEAD.corp_tlwn_virt_brcd").trim(),
"ERP 요청(EZDATA 미포함) FLAT 왕복 후 HEAD.corp_tlwn_virt_brcd 불일치");
}
@Test
void ERP요청_EZDATA미포함_FLAT_왕복_HEAD_if_id_보존() throws Exception {
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_NO_EZDATA_JSON));
assertEquals(TEST_IF_ID, dst.findItemValue("HEAD.if_id").trim(),
"ERP 요청(EZDATA 미포함) FLAT 왕복 후 HEAD.if_id 불일치");
}
@Test
void ERP요청_EZDATA미포함_FLAT_왕복_DATA_data_dvcd_IO() throws Exception {
// 거래로그 화면에서 깨졌던 지점: EZDATA 를 건너뛰면 DATA 부 오프셋이 어긋난다
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_NO_EZDATA_JSON));
assertEquals("IO", dst.findItemValue("DATA.data_dvcd").trim(),
"ERP 요청(EZDATA 미포함) FLAT 왕복 후 DATA.data_dvcd 불일치 — EZDATA 오프셋 어긋남");
}
// ================================================================
// 3. ERP 요청 FLAT 왕복 — EZDATA 포함
// ================================================================
@@ -40,6 +40,7 @@ import static org.mockito.ArgumentMatchers.anyString;
* 5. 비표준 수신 → 정상 응답 표준 생성 (coordinateAfterRecvNonStdSyncResponse → JSON)
* 6. 오류 응답 표준 생성 (coordinateSetStandardMessageError → JSON)
* 7. JSON 왕복(parse → serialize) 일관성
* 8. 상대 헤더가 표준을 어긴 응답 파싱 (2026-09 사고 회귀 방지)
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class StandardMessageJsonFlowTest {
@@ -80,11 +81,11 @@ class StandardMessageJsonFlowTest {
+ "\"frst_mesg_dman_dt\":\"20260420\","
+ "\"frst_mesg_dman_time\":\"120000000\""
+ "},"
+ "\"DATA\":{"
+ "\"DATA\":[{"
+ "\"data_dvcd\":\"IO\","
+ "\"data_scop_len\":\"37\","
+ "\"BIZ_DATA\":{\"acct_no\":\"123456789\",\"amt\":\"100000\"}"
+ "}"
+ "}]"
+ "}";
/**
@@ -121,10 +122,58 @@ class StandardMessageJsonFlowTest {
+ "\"msg_list_rowcnt\":\"1\""
+ "}"
+ "},"
+ "\"DATA\":{"
+ "\"DATA\":[{"
+ "\"data_dvcd\":\"IO\","
+ "\"data_scop_len\":\"37\","
+ "\"BIZ_DATA\":{\"acct_no\":\"123456789\",\"bal\":\"900000\"}"
+ "}]"
+ "}";
/**
* 상대 헤더가 표준을 어긴 오류응답 JSON (2026-09 실제 사고 전문 형태)
*
* 표준은 응답 시 dman_rspn_dvcd=R 이어야 하는데, 상대가 요청값 S 를 그대로 에코백하면서
* procs_rslt_dvcd 만 F(오류)로 보냈다. MSG 블록의 레이아웃 조건이 !S 라 예전에는
* MSG 이하가 통째로 버려졌고, MAIN_MSG 가 레이아웃 기본값으로 남아 오류가
* "정상처리되었습니다." 로 보고되고 거래로그에서도 MSG 부가 누락됐다.
*
* 같은 전문에 들어있던 다른 비표준 요소도 함께 담아 둔다.
* - msg_list_rowcnt 가 따옴표 없는 선행 0 숫자(00001)
* - outp_msg_desc 안에 이스케이프되지 않은 개행/탭
*/
private static final String RSP_JSON_BAD_HEADER =
"{"
+ "\"HEAD\":{"
+ "\"nxgn_stnd_idfr\":\"JERA\","
+ "\"guid\":\"" + TEST_GUID + "\","
+ "\"guid_prgs_no\":\"2\","
+ "\"stnd_mesg_ver\":\"R10\","
+ "\"ortr_guid\":\"" + TEST_GUID + "\","
+ "\"dman_rspn_dvcd\":\"S\"," // 표준 위반: 응답인데 R 이 아님
+ "\"if_id\":\"" + TEST_IF_ID + "\","
+ "\"procs_rslt_dvcd\":\"F\","
+ "\"tx_id\":\"" + TEST_TX_ID + "\","
+ "\"chnl_tycd\":\"EAI\","
+ "\"hmab_dvcd\":\"1\","
+ "\"trnm_sys_dvcd\":\"EAI\","
+ "\"sys_env_dvcd\":\"D\","
+ "\"frst_mesg_dman_dt\":\"20260420\","
+ "\"frst_mesg_dman_time\":\"120000000\","
+ "\"mesg_rspn_dt\":\"20260420\","
+ "\"mesg_rspn_time\":\"120100000\","
+ "\"rprs_msg_cd\":\"900400\""
+ "},"
+ "\"MSG\":{"
+ "\"msg_dvcd\":\"EM\","
+ "\"msg_scop_len\":1437,"
+ "\"MAIN_MSG\":{"
+ "\"outp_atrb_cd\":\"0\","
+ "\"outp_msg_cd\":\"900400\","
+ "\"outp_msg_ctnt\":\"\","
+ "\"outp_msg_desc\":\"[ErrorCode:S9OWP0011].WTC.Adapter.\n\t호출 오류\","
+ "\"mngm_msg_cd\":\"\","
+ "\"msg_list_rowcnt\":00001"
+ "}"
+ "}"
+ "}";
@@ -208,7 +257,11 @@ class StandardMessageJsonFlowTest {
void 요청JSON_파싱_DATA_BIZ_DATA_JSON_오브젝트_저장() throws Exception {
StandardMessage msg = parseReq();
String bizData = msg.findItemValue("DATA.BIZ_DATA");
// DATA는 GRID(반복부)라 값은 행(row 0)에 들어간다. 인덱스 없는 "DATA.BIZ_DATA"는
// 직렬화에 쓰이지 않는 템플릿 항목을 가리키므로 빈 값이 나온다.
// 운영 경로도 인덱스 형태를 쓴다 — standard-message-mapping-config-djb.properties:27
// BIZ_DATA=DATA[0].BIZ_DATA
String bizData = msg.findItemValue("DATA[0].BIZ_DATA");
assertNotNull(bizData, "BIZ_DATA가 null");
assertFalse(bizData.trim().isEmpty(), "BIZ_DATA가 공백");
// JSON 오브젝트로 파싱 가능한지 검증
@@ -344,9 +397,11 @@ class StandardMessageJsonFlowTest {
String json = msg.getDataString(MessageType.JSON, "utf-8");
JsonNode root = jacksonMapper.readTree(json);
// DATA는 GRID(반복부)이므로 직렬화하면 JSON 배열이다. 표준 레이아웃상 1건 고정.
// BIZ_DATA는 JSON 문자열 또는 JSON 오브젝트로 들어갈 수 있음
assertNotNull(root.path("DATA").get("BIZ_DATA"),
"직렬화 JSON에 DATA.BIZ_DATA 없음");
assertTrue(root.path("DATA").isArray(), "직렬화 JSON의 DATA가 배열이 아님");
assertNotNull(root.path("DATA").path(0).get("BIZ_DATA"),
"직렬화 JSON에 DATA[0].BIZ_DATA 없음");
}
// ================================================================
@@ -388,11 +443,15 @@ class StandardMessageJsonFlowTest {
void 비표준수신_정상응답_JSON_직렬화_outp_msg_ctnt_설정됨() throws Exception {
StandardMessage msg = manager.getStandardMessage();
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
// outp_msg_cd/ctnt 는 레이아웃 기본값이 없으므로, 실제 흐름대로 응답 직전 조정까지
// 거쳐야 채워진다 (StandardMessageCoordinatorDJB.coordinateBeforeResponse)
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
String json = msg.getDataString(MessageType.JSON, "utf-8");
JsonNode root = jacksonMapper.readTree(json);
String ctnt = root.path("MSG").path("MAIN_MSG").path("outp_msg_ctnt").asText();
assertFalse(ctnt.isEmpty(), "정상응답 JSON의 outp_msg_ctnt가 설정되어야 함");
assertEquals(StandardMessageCoordinatorDJB.NORMAL_OUTP_MSG_CTNT, ctnt,
"정상응답 JSON의 outp_msg_ctnt가 설정되어야 함");
}
// ================================================================
@@ -490,6 +549,40 @@ class StandardMessageJsonFlowTest {
"응답 JSON 왕복 후 msg_dvcd 불일치");
}
// ================================================================
// 8. 상대 헤더가 표준을 어긴 응답 파싱 (2026-09 사고 회귀 방지)
// ================================================================
@Test
void 상대헤더오류_dman_rspn_dvcd가_S여도_MSG부가_파싱됨() throws Exception {
StandardMessage msg = parseRspBadHeader();
assertEquals("F", msg.findItemValue("HEAD.procs_rslt_dvcd"),
"HEAD가 파싱되지 않음 — 전제 조건 실패");
assertEquals("EM", msg.findItemValue("MSG.msg_dvcd"),
"MSG.msg_dvcd 미반영 — MSG 블록이 버려졌다");
assertEquals("900400", msg.findItemValue("MSG.MAIN_MSG.outp_msg_cd"),
"outp_msg_cd가 레이아웃 기본값(NCMM00001) 그대로 — MSG부가 버려졌다");
assertNotEquals("정상처리되었습니다.", msg.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt"),
"오류응답인데 레이아웃 기본값 '정상처리되었습니다.'가 그대로 남음");
assertNotNull(msg.findItemValue("MSG.MAIN_MSG.outp_msg_desc"),
"outp_msg_desc가 null — 개행/탭이 섞인 값이 파싱되지 않았다");
}
@Test
void 상대헤더오류_재직렬화시_MSG부_보존() throws Exception {
StandardMessage msg = parseRspBadHeader();
// 거래로그(EAILogDAO)는 수신 원문이 아니라 StandardMessage 재직렬화본을 저장한다.
// MSG가 hidden 이면 로그에서도 MSG부 이후가 통째로 누락된다.
String json = msg.getDataString(MessageType.JSON, "utf-8");
JsonNode root = jacksonMapper.readTree(json);
assertTrue(root.has("MSG"), "재직렬화 결과에 MSG 블록 없음 — 거래로그에 MSG부 누락");
assertEquals("900400", root.path("MSG").path("MAIN_MSG").path("outp_msg_cd").asText(),
"재직렬화 결과의 outp_msg_cd 불일치");
}
// ================================================================
// helper
// ================================================================
@@ -505,4 +598,10 @@ class StandardMessageJsonFlowTest {
jsonReader.parse(msg, RSP_JSON_OK);
return msg;
}
private StandardMessage parseRspBadHeader() throws Exception {
StandardMessage msg = manager.getStandardMessage();
jsonReader.parse(msg, RSP_JSON_BAD_HEADER);
return msg;
}
}
@@ -0,0 +1,262 @@
package com.eactive.eai.message;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
import com.eactive.eai.message.parser.FlatReader;
/**
* 조건부 GROUP 블록의 FLAT 직렬화 판정 단위 테스트
*
* 검증 대상:
* - {@link StandardItem#matchRefCondition(String, String)} : ref 조건 판정 규칙
* - {@link StandardItem#isFlatGroupActive(StandardMessage, boolean)} : GROUP 의 FLAT 출력 여부
* (관측 가능한 계약인 toByteArray() / getBytesDataLength() 결과로 검증)
*
* 핵심 계약:
* FLAT 은 위치 기반이라 전문만 보고 블록 존재 여부를 알 수 없고 ref 조건으로만 판단한다.
* 따라서 직렬화(StandardItem)와 파싱(FlatReader)이 반드시 같은 기준을 써야 하며,
* 조건이 성립하면 수신 전문에 블록이 없어(size=0) 도 레이아웃 기본값으로 출력해야 한다.
* 출력하지 않으면 파서는 블록이 있다고 보고 읽어 오프셋이 어긋난다.
*/
class StandardItemFlatGroupTest {
private static final String CHARSET = "euc-kr";
// 테스트 레이아웃 블록별 선언 길이
private static final int HEAD_LEN = 3; // mode(3)
private static final int COND_SUB_LEN = 4; // SUB.s1(4)
private static final int COND_LEN = 5 + COND_SUB_LEN; // c1(5) + SUB
private static final int TAIL_LEN = 2; // t1(2)
private static final int LEN_WITH_COND = HEAD_LEN + COND_LEN + TAIL_LEN; // 14
private static final int LEN_WITHOUT_COND = HEAD_LEN + TAIL_LEN; // 5
// ================================================================
// 1. matchRefCondition — ref 조건 판정 규칙
// ================================================================
@Test
void matchRefCondition_단일값_일치() {
assertTrue(StandardItem.matchRefCondition("ERP", "ERP"));
}
@Test
void matchRefCondition_단일값_불일치() {
assertFalse(StandardItem.matchRefCondition("ERP", "XXX"));
}
@Test
void matchRefCondition_실제값_공백패딩_무시() {
// FLAT 필드는 스페이스로 우측 패딩되므로 trim 후 비교해야 한다
assertTrue(StandardItem.matchRefCondition("ERP", "ERP "));
assertTrue(StandardItem.matchRefCondition("ERP", " ERP "));
}
@Test
void matchRefCondition_실제값_null이면_불일치() {
assertFalse(StandardItem.matchRefCondition("ERP", null));
}
@Test
void matchRefCondition_refValue_null이면_불일치() {
assertFalse(StandardItem.matchRefCondition(null, "ERP"));
}
@Test
void matchRefCondition_OR조건() {
assertTrue(StandardItem.matchRefCondition("NM|EM", "NM"));
assertTrue(StandardItem.matchRefCondition("NM|EM", "EM"));
assertFalse(StandardItem.matchRefCondition("NM|EM", "XX"));
}
@Test
void matchRefCondition_NOT조건() {
assertFalse(StandardItem.matchRefCondition("!S", "S"));
assertTrue(StandardItem.matchRefCondition("!S", "R"));
// 응답구분이 비어 있으면 S 가 아니므로 조건 성립
assertTrue(StandardItem.matchRefCondition("!S", " "));
}
@Test
void matchRefCondition_NOT와_OR_조합() {
assertFalse(StandardItem.matchRefCondition("!NM|EM", "NM"));
assertFalse(StandardItem.matchRefCondition("!NM|EM", "EM"));
assertTrue(StandardItem.matchRefCondition("!NM|EM", "XX"));
}
// ================================================================
// 2. 조건부 GROUP 의 FLAT 출력 여부
// ================================================================
@Test
void 조건성립이면_size0이어도_FLAT에_포함() throws Exception {
// 수신 전문에 COND 블록이 없어 size=0 이지만 조건(mode=ERP)이 성립하는 상황
StandardMessage msg = newMessage("ERP");
assertEquals(0, msg.findItem("COND").getSize(), "전제조건: COND 는 미활성(size=0) 이어야 함");
assertEquals(LEN_WITH_COND, msg.toByteArray(false, CHARSET).length,
"조건 성립 시 COND 블록이 레이아웃 기본값으로 FLAT 에 포함되어야 함");
}
@Test
void 조건불성립이면_FLAT에_미포함() throws Exception {
StandardMessage msg = newMessage("XXX");
assertEquals(LEN_WITHOUT_COND, msg.toByteArray(false, CHARSET).length,
"조건 불성립 시 COND 블록은 FLAT 에서 제외되어야 함");
}
@Test
void 조건성립으로_활성화된_블록의_하위_무조건GROUP도_포함() throws Exception {
StandardMessage msg = newMessage("ERP");
assertEquals(0, msg.findItem("COND.SUB").getSize(), "전제조건: SUB 도 미활성(size=0) 이어야 함");
// SUB(4바이트)가 빠지면 FlatReader 가 SUB 를 읽을 때 오프셋이 어긋난다
int len = msg.toByteArray(false, CHARSET).length;
assertEquals(LEN_WITH_COND, len,
String.format("활성화된 COND 하위의 무조건 GROUP(SUB %d바이트)도 함께 출력되어야 함. 실제=%d",
COND_SUB_LEN, len));
}
@Test
void hidden블록은_조건성립이어도_미포함() throws Exception {
StandardMessage msg = newMessage("ERP");
msg.findItem("COND").setHidden(true);
assertEquals(LEN_WITHOUT_COND, msg.toByteArray(false, CHARSET).length,
"isHidden=true 인 블록은 조건이 성립해도 출력하지 않아야 함");
}
@Test
void 명시적으로_활성화된_블록은_조건불성립이어도_포함() throws Exception {
// 코디네이터가 setSize(1) 로 직접 활성화한 블록(오류응답 MSG 등)의 기존 동작 보존
StandardMessage msg = newMessage("XXX");
msg.findItem("COND").setSize(1);
assertEquals(LEN_WITH_COND, msg.toByteArray(false, CHARSET).length,
"size>0 으로 명시 활성화된 블록은 조건과 무관하게 출력되어야 함");
}
// ================================================================
// 3. 길이 계산(getBytesDataLength)과 직렬화(toByteArray)의 일관성
// FlatMessageFilter 가 전문길이 필드를 이 값으로 채우므로 어긋나면 안 된다
// ================================================================
@Test
void 조건성립_길이계산과_직렬화결과_일치() throws Exception {
StandardMessage msg = newMessage("ERP");
assertEquals(msg.toByteArray(false, CHARSET).length, msg.getBytesDataLength(CHARSET),
"조건 성립 시 getBytesDataLength 와 toByteArray 길이가 달라짐");
}
@Test
void 조건불성립_길이계산과_직렬화결과_일치() throws Exception {
StandardMessage msg = newMessage("XXX");
assertEquals(msg.toByteArray(false, CHARSET).length, msg.getBytesDataLength(CHARSET),
"조건 불성립 시 getBytesDataLength 와 toByteArray 길이가 달라짐");
}
// ================================================================
// 4. 기존 시그니처 호환 — root 없이 호출하면 종전 규칙(size==0 skip) 유지
// ================================================================
@Test
void root없이_호출하면_조건평가없이_size규칙_적용() throws Exception {
StandardMessage msg = newMessage("ERP");
StandardItem cond = msg.findItem("COND");
// 조건을 평가할 root 가 없으므로 size==0 인 블록은 출력하지 않는다
assertEquals(0, cond.toByteArray(false, CHARSET).length,
"root 미전달 시에는 기존 규칙(size==0 → skip)이 유지되어야 함");
assertEquals(0, cond.getBytesDataLength(CHARSET),
"root 미전달 시에는 기존 규칙(size==0 → skip)이 유지되어야 함");
}
// ================================================================
// 5. 직렬화 ↔ 파싱 대칭성 (FlatReader 와 같은 기준인지)
// ================================================================
@Test
void 조건성립_FLAT_왕복_남는바이트없이_파싱() throws Exception {
String flat = newMessage("ERP").toFixedString(false, CHARSET);
StandardMessage dst = newMessage("");
// FlatReader 는 다 읽고 남은 바이트가 있으면 예외를 던진다(overflow),
// 블록이 모자라면 cut() 에서 underflow 예외를 던진다
assertDoesNotThrow(() -> new FlatReader().parse(dst, flat),
"조건 성립 FLAT 파싱 중 예외 발생 — 직렬화와 파싱 기준 불일치");
assertEquals("ERP", dst.findItemValue("HEAD.mode").trim(), "왕복 후 HEAD.mode 불일치");
assertEquals("IO", dst.findItemValue("TAIL.t1").trim(),
"왕복 후 TAIL.t1 불일치 — COND 블록 오프셋이 어긋남");
}
@Test
void 조건불성립_FLAT_왕복_남는바이트없이_파싱() throws Exception {
String flat = newMessage("XXX").toFixedString(false, CHARSET);
StandardMessage dst = newMessage("");
assertDoesNotThrow(() -> new FlatReader().parse(dst, flat),
"조건 불성립 FLAT 파싱 중 예외 발생 — 직렬화와 파싱 기준 불일치");
assertEquals("XXX", dst.findItemValue("HEAD.mode").trim(), "왕복 후 HEAD.mode 불일치");
assertEquals("IO", dst.findItemValue("TAIL.t1").trim(), "왕복 후 TAIL.t1 불일치");
}
@Test
void 조건성립_FLAT_왕복후_COND블록_기본값_보존() throws Exception {
StandardMessage src = newMessage("ERP");
String flat = src.toFixedString(false, CHARSET);
StandardMessage dst = newMessage("");
new FlatReader().parse(dst, flat);
assertEquals("C1", dst.findItemValue("COND.c1").trim(),
"왕복 후 COND.c1 레이아웃 기본값 불일치");
assertEquals("S1", dst.findItemValue("COND.SUB.s1").trim(),
"왕복 후 COND.SUB.s1 레이아웃 기본값 불일치");
}
// ================================================================
// helpers
// ================================================================
/**
* 테스트용 최소 레이아웃 (DJBank 표준전문의 HEAD / EZDATA / DATA 구조를 축약)
*
* <pre>
* HEAD GROUP size=1
* mode (3) 조건 판정 필드
* COND GROUP size=0, 조건 HEAD.mode=ERP
* c1 (5)
* SUB GROUP size=0, 조건 없음 (상위 활성화 전파 검증용)
* s1 (4)
* TAIL GROUP size=1
* t1 (2)
* </pre>
*/
private StandardMessage newMessage(String modeValue) throws Exception {
return StandardMessageUtil.generate(layout(
"HEAD,1,3,1,1,0,1,,,",
"mode,2,2,1,1,3,1,,," + modeValue,
"COND,1,3,0,1,0,1,HEAD.mode,ERP,",
"c1,2,2,1,1,5,1,,,C1",
"SUB,2,3,0,1,0,1,,,",
"s1,3,2,1,1,4,1,,,S1",
"TAIL,1,3,1,1,0,1,,,",
"t1,2,2,1,1,2,1,,,IO"));
}
/** CsvFileReader 와 동일한 방식으로 레이아웃 행을 StandardItem 으로 만든다 */
private ArrayList<StandardItem> layout(String... rows) throws Exception {
ArrayList<StandardItem> list = new ArrayList<StandardItem>();
for (String row : rows) {
list.add(new StandardItem(row.split(",", StandardItem.ITEM_COUNT)));
}
return list;
}
}