Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2153ed51a8 | |||
| 64d94a1fdc | |||
| 50c08d7813 | |||
| c5bf45cad9 | |||
| 76a3b705c0 | |||
| 57f4847e21 | |||
| a6e41150cd | |||
| 79c8aa6151 | |||
| ed17053cf1 | |||
| af7673ea2c | |||
| f0a36a5365 | |||
| 30dbe31f17 | |||
| 0263e97640 | |||
| 26ebad85a7 | |||
| 2c82573a50 | |||
| 540ebdaf1f | |||
| e9261c55ad | |||
| 777b1c477c | |||
| 464ed59a3d | |||
| 5486489985 | |||
| 2bbd3824ed | |||
| 4ff3589557 | |||
| db2b34a355 |
Vendored
+15
@@ -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.dialect">${hibernate.dialect:org.hibernate.dialect.Oracle12cDialect}</prop>
|
||||||
<prop key="hibernate.jdbc.batch_size">100</prop>
|
<prop key="hibernate.jdbc.batch_size">100</prop>
|
||||||
<prop key="hibernate.jdbc.fetch_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_second_level_cache">false</prop>
|
||||||
<prop key="hibernate.cache.use_query_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>
|
<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
|
# 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.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
|
# transaction logging
|
||||||
logger.async.active=true
|
logger.async.active=true
|
||||||
logger.async.pool.initonstartup=true
|
logger.async.pool.initonstartup=true
|
||||||
logger.async.pool.intsize=8
|
logger.async.pool.initsize=8
|
||||||
logger.async.pool.maxsize=10
|
logger.async.pool.maxsize=10
|
||||||
logger.async.queue.size=1024
|
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
|
# cloud option
|
||||||
scalable=false
|
scalable=false
|
||||||
|
|||||||
@@ -19,10 +19,11 @@
|
|||||||
<url-pattern>/agent/*</url-pattern>
|
<url-pattern>/agent/*</url-pattern>
|
||||||
<url-pattern>/common/*</url-pattern>
|
<url-pattern>/common/*</url-pattern>
|
||||||
<url-pattern>/management/*</url-pattern>
|
<url-pattern>/management/*</url-pattern>
|
||||||
|
<url-pattern>/manage/*</url-pattern>
|
||||||
<url-pattern>/mgr/*</url-pattern>
|
<url-pattern>/mgr/*</url-pattern>
|
||||||
</filter-mapping>
|
</filter-mapping>
|
||||||
|
|
||||||
<filter>
|
<!-- <filter>
|
||||||
<filter-name>ApiRequestBodyFilter</filter-name>
|
<filter-name>ApiRequestBodyFilter</filter-name>
|
||||||
<filter-class>com.eactive.eai.adapter.controller.ApiRequestBodyFilter</filter-class>
|
<filter-class>com.eactive.eai.adapter.controller.ApiRequestBodyFilter</filter-class>
|
||||||
</filter>
|
</filter>
|
||||||
@@ -30,7 +31,7 @@
|
|||||||
<filter-name>ApiRequestBodyFilter</filter-name>
|
<filter-name>ApiRequestBodyFilter</filter-name>
|
||||||
<url-pattern>/api/*</url-pattern>
|
<url-pattern>/api/*</url-pattern>
|
||||||
<url-pattern>/mapi/*</url-pattern>
|
<url-pattern>/mapi/*</url-pattern>
|
||||||
</filter-mapping>
|
</filter-mapping> -->
|
||||||
|
|
||||||
<context-param>
|
<context-param>
|
||||||
<param-name>logbackDisableServletContainerInitializer</param-name>
|
<param-name>logbackDisableServletContainerInitializer</param-name>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ plugins {
|
|||||||
id 'groovy'
|
id 'groovy'
|
||||||
id 'war'
|
id 'war'
|
||||||
id 'com.diffplug.eclipse.apt' version '3.41.1'
|
id 'com.diffplug.eclipse.apt' version '3.41.1'
|
||||||
|
id 'org.cyclonedx.bom' version '3.2.4'
|
||||||
}
|
}
|
||||||
|
|
||||||
group 'com.eactvie'
|
group 'com.eactvie'
|
||||||
@@ -249,3 +250,6 @@ eclipse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// CycloneDX SBOM -> xlsx 변환 (gradle sbomXlsx)
|
||||||
|
apply from: "$projectDir/gradle/sbom-xlsx.gradle"
|
||||||
|
|||||||
+1
-1
Submodule elink-online-common updated: 44093681b7...e9fbffa87e
+1
-1
Submodule elink-online-core-jpa updated: 138621f2d0...62291c9e57
+1
-1
Submodule elink-online-transformer updated: 229156d51d...09ac7f4ca5
@@ -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.IOException;
|
||||||
import java.io.StringWriter;
|
import java.io.StringWriter;
|
||||||
|
import java.io.UnsupportedEncodingException;
|
||||||
import java.net.URLDecoder;
|
import java.net.URLDecoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.Enumeration;
|
import java.util.Enumeration;
|
||||||
@@ -10,6 +12,7 @@ import java.util.HashMap;
|
|||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import javax.servlet.ServletInputStream;
|
import javax.servlet.ServletInputStream;
|
||||||
@@ -18,6 +21,7 @@ import javax.servlet.http.HttpServletResponse;
|
|||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.apache.commons.lang3.time.StopWatch;
|
import org.apache.commons.lang3.time.StopWatch;
|
||||||
|
import org.apache.hc.core5.http.ContentType;
|
||||||
import org.apache.mina.common.ByteBuffer;
|
import org.apache.mina.common.ByteBuffer;
|
||||||
import org.dom4j.Document;
|
import org.dom4j.Document;
|
||||||
import org.dom4j.DocumentException;
|
import org.dom4j.DocumentException;
|
||||||
@@ -28,7 +32,7 @@ import org.dom4j.io.OutputFormat;
|
|||||||
import org.dom4j.io.XMLWriter;
|
import org.dom4j.io.XMLWriter;
|
||||||
import org.json.simple.JSONValue;
|
import org.json.simple.JSONValue;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.util.AntPathMatcher;
|
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.HttpMethodType;
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
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.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.adapter.http.filter.AbstractCryptoFilter;
|
||||||
import com.eactive.eai.common.context.ElinkTransactionContext;
|
import com.eactive.eai.common.context.ElinkTransactionContext;
|
||||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||||
import com.eactive.eai.common.message.MessageType;
|
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.CommonLib;
|
||||||
import com.eactive.eai.common.util.JacksonUtil;
|
import com.eactive.eai.common.util.JacksonUtil;
|
||||||
import com.eactive.eai.common.util.Logger;
|
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.ActionFactory;
|
||||||
import com.eactive.eai.inbound.action.RequestAction;
|
import com.eactive.eai.inbound.action.RequestAction;
|
||||||
import com.eactive.eai.inbound.processor.Processor;
|
import com.eactive.eai.inbound.processor.Processor;
|
||||||
import com.eactive.eai.message.StandardMessageUtil;
|
import com.eactive.eai.message.StandardMessage;
|
||||||
import com.eactive.eai.util.JsonPathUtil;
|
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||||
|
import com.eactive.eai.util.QueryStringUtils;
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
@@ -61,8 +69,16 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
|||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
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 logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||||
static Logger siftLogger = Logger.getLogger(Logger.LOGGER_SIFT);
|
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
|
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,
|
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp,
|
||||||
AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
|
AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
|
||||||
@@ -90,7 +106,6 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
String relayRequestHeaderKeys = httpProp.getProperty(HEADER_KEYS);
|
String relayRequestHeaderKeys = httpProp.getProperty(HEADER_KEYS);
|
||||||
String headerGroupName = httpProp.getProperty(HEADER_GROUP);
|
String headerGroupName = httpProp.getProperty(HEADER_GROUP);
|
||||||
|
|
||||||
boolean isParameterType = false;
|
|
||||||
String message = null;
|
String message = null;
|
||||||
|
|
||||||
String paramValue = null;
|
String paramValue = null;
|
||||||
@@ -126,12 +141,6 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
transactionProp.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
|
transactionProp.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
|
||||||
transactionProp.put("BLOCK_IP", httpProp.getProperty("BLOCK_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(ENC_PATHS, httpProp.getProperty(ENC_PATHS, ""));
|
||||||
|
|
||||||
transactionProp.put(ENCRYPT_ALGORITHM, httpProp.getProperty(ENCRYPT_ALGORITHM, "")); //jwhong
|
transactionProp.put(ENCRYPT_ALGORITHM, httpProp.getProperty(ENCRYPT_ALGORITHM, "")); //jwhong
|
||||||
@@ -170,74 +179,8 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
stopWatch.start();
|
stopWatch.start();
|
||||||
|
|
||||||
logger.debug("시작 >> encode = [" + encode + "]");
|
logger.debug("시작 >> encode = [" + encode + "]");
|
||||||
|
String recvBody = "";
|
||||||
switch (HttpMethodType.getValue(request.getMethod())) {
|
if (request.getContentLength() > 0) {
|
||||||
case GET:
|
|
||||||
case DELETE:
|
|
||||||
isParameterType = true;
|
|
||||||
break;
|
|
||||||
case POST:
|
|
||||||
case PUT:
|
|
||||||
if (StringUtils.contains(request.getContentType(), "application/x-www-form-urlencoded")) {
|
|
||||||
isParameterType = true;
|
|
||||||
} else if ( StringUtils.isNoneBlank(request.getQueryString()) ) { // jwhong
|
|
||||||
isParameterType = true;
|
|
||||||
} else {
|
|
||||||
isParameterType = false;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isParameterType) {
|
|
||||||
paramValue = request.getQueryString();
|
|
||||||
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(paramValue)); // Filter에서 QueryString 검증을 위해 저장
|
|
||||||
if (paramValue == null)
|
|
||||||
paramValue = "";
|
|
||||||
if (traceLevel >= 3) {
|
|
||||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
|
||||||
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(paramValue));
|
|
||||||
}
|
|
||||||
|
|
||||||
// json으로 변환
|
|
||||||
StringBuilder sb = new StringBuilder();
|
|
||||||
sb.append("{");
|
|
||||||
Map<String, String[]> paramMap = assignParameterMap(request, adptGrpName, adptName, null, transactionProp);
|
|
||||||
int i = 0;
|
|
||||||
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
|
|
||||||
if (i > 0) {
|
|
||||||
sb.append(",");
|
|
||||||
}
|
|
||||||
sb.append("\"").append(entry.getKey()).append("\":");
|
|
||||||
String[] values = entry.getValue();
|
|
||||||
if (values.length > 1) {
|
|
||||||
// ["111", "222"]
|
|
||||||
sb.append("[");
|
|
||||||
for (int j = 0; j < values.length; j++) {
|
|
||||||
if (j > 0) {
|
|
||||||
sb.append(",");
|
|
||||||
}
|
|
||||||
sb.append("\"").append(JSONValue.escape(values[j])).append("\"");
|
|
||||||
}
|
|
||||||
sb.append("]");
|
|
||||||
} else {
|
|
||||||
sb.append("\"").append(JSONValue.escape(values[0])).append("\"");
|
|
||||||
}
|
|
||||||
|
|
||||||
i++;
|
|
||||||
}
|
|
||||||
|
|
||||||
sb.append("}");
|
|
||||||
|
|
||||||
paramValue = sb.toString();
|
|
||||||
|
|
||||||
if (logger.isDebug()) {
|
|
||||||
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
|
||||||
+ CommonLib.getDumpMessage(paramValue.getBytes(encode)));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (request.getContentLength() > 0) {
|
|
||||||
ServletInputStream sis = request.getInputStream();
|
ServletInputStream sis = request.getInputStream();
|
||||||
ByteBuffer bb = ByteBuffer.allocate(1024).setAutoExpand(true);
|
ByteBuffer bb = ByteBuffer.allocate(1024).setAutoExpand(true);
|
||||||
int i = 0;
|
int i = 0;
|
||||||
@@ -257,43 +200,68 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
String bodyEncode = encode;
|
String bodyEncode = encode;
|
||||||
String contentTypeHeader = request.getContentType();
|
String contentTypeHeader = request.getContentType();
|
||||||
if (StringUtils.isNotBlank(contentTypeHeader)) {
|
if (StringUtils.isNotBlank(contentTypeHeader)) {
|
||||||
try {
|
try {
|
||||||
MediaType mediaType = MediaType.parseMediaType(contentTypeHeader);
|
MediaType mediaType = MediaType.parseMediaType(contentTypeHeader);
|
||||||
if (mediaType.getCharset() != null) {
|
if (mediaType.getCharset() != null) {
|
||||||
bodyEncode = mediaType.getCharset().name();
|
bodyEncode = mediaType.getCharset().name();
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
}
|
}
|
||||||
} catch (Exception ignored) {}
|
|
||||||
}
|
}
|
||||||
paramValue = new String(data, bodyEncode);
|
recvBody = new String(data, bodyEncode);
|
||||||
|
|
||||||
if (traceLevel >= 3) {
|
if (traceLevel >= 3) {
|
||||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||||
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(data));
|
"RECV " + "[" + recvBody + "]" + CommonLib.getDumpMessage(data));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (logger.isDebug()) {
|
if (logger.isDebug()) {
|
||||||
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + recvBody + "]\n"
|
||||||
+ CommonLib.getDumpMessage(data));
|
+ 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가 없는 경우때문에 처리
|
if (paramValue == null) { // parameter가 없는 경우때문에 처리
|
||||||
paramValue = "";
|
paramValue = "";
|
||||||
}
|
}
|
||||||
// 순수한 Body값을 저장을 위해 위치 변경.
|
|
||||||
transactionProp.put(INBOUND_REQUEST_MESSAGE, paramValue);
|
|
||||||
|
|
||||||
// paramValue가 null이 아닌 빈문자열(""," ")인 경우에 대비하여 조건 수정.
|
// paramValue가 null이 아닌 빈문자열(""," ")인 경우에 대비하여 조건 수정.
|
||||||
// if (StringUtils.isNotBlank(paramValue)) { // jwhong decrypt
|
// if (StringUtils.isNotBlank(paramValue)) { // jwhong decrypt
|
||||||
// paramValue = doPreDecryption(paramValue, transactionProp, request);
|
// paramValue = doPreDecryption(paramValue, transactionProp, request);
|
||||||
// }
|
// }
|
||||||
|
|
||||||
if ("Y".equals(urlDecodeYn) && isParameterType) {
|
// if ("Y".equals(urlDecodeYn) && isParameterType) {
|
||||||
message = URLDecoder.decode(paramValue);
|
// message = URLDecoder.decode(paramValue);
|
||||||
} else {
|
// } else {
|
||||||
message = paramValue;
|
message = paramValue;
|
||||||
}
|
// }
|
||||||
|
|
||||||
TxFileLogger.logTxFile(transactionProp, message, "[IN_RECV]");
|
TxFileLogger.logTxFile(transactionProp, message, "[IN_RECV]");
|
||||||
|
|
||||||
@@ -314,9 +282,6 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
|
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
|
||||||
// transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
|
// 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);
|
Object result = service(adptGrpName, adptName, reqObject, transactionProp, request, response);
|
||||||
|
|
||||||
// bypass만 필요
|
// bypass만 필요
|
||||||
@@ -612,71 +577,231 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
|
|
||||||
return (String)resultMessage;
|
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,
|
boolean bUrlDecode = StringUtils.equalsIgnoreCase(urlDecode, "Y");
|
||||||
Object requestBytes, Properties prop) {
|
if (encoding == null) {
|
||||||
// PathVariable 체크
|
// Content-Type 에 charset 이 없을 때(GET 등)의 기본값은 처리 경로에 따라 다르다.
|
||||||
if (StringUtils.equalsAnyIgnoreCase(request.getMethod(), HttpMethod.GET.name(), HttpMethod.DELETE.name())
|
// - %인코딩 복원(URLDecoder) : HTML5/WHATWG 표준이 UTF-8 이므로 UTF-8.
|
||||||
&& StringUtils.isBlank(request.getQueryString())) {
|
// ISO-8859-1 로 복원하면 %ED%95%9C%EA%B8%80 이 '한글' 로 깨진다.
|
||||||
try {
|
// - 그 외 : 컨테이너가 디코딩한 문자열의 원본 바이트를 되찾는 용도(byte latch)이므로
|
||||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
// 기존 동작인 ISO-8859-1 을 유지한다.
|
||||||
RequestAction action = ActionFactory.createAction(actionName);
|
encoding = bUrlDecode ? StandardCharsets.UTF_8.name() : "ISO-8859-1";
|
||||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
}
|
||||||
String[] keys = action.perform(requestBytes);
|
|
||||||
String requestPath = keys[0];
|
|
||||||
|
|
||||||
// PathVariable 지원 추가
|
// POST 방식의 form data
|
||||||
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
if (reqMessage instanceof String) {
|
||||||
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
String formData = (String) reqMessage;
|
||||||
Map<String, String> paramMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath,
|
Map<String, String[]> formDataParamMap = QueryStringUtils.parseQueryString(formData, encoding, bUrlDecode);
|
||||||
requestPath);
|
pathMap.putAll(formDataParamMap);
|
||||||
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;
|
// GET 방식의 query string
|
||||||
}
|
String queryString = request.getQueryString();
|
||||||
}
|
Map<String, String[]> paramMap = QueryStringUtils.parseQueryString(queryString, encoding, bUrlDecode);
|
||||||
} catch (Exception e) {
|
pathMap.putAll(paramMap);
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
private String getRewritePath(String extUri, String basePath) {
|
||||||
return StringUtils.removeStart(extUri, StringUtils.removeEnd(basePath, "/"));
|
return StringUtils.removeStart(extUri, StringUtils.removeEnd(basePath, "/"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<String, String> assignPathVariables(HttpServletRequest request, String adptGrpName, String adptName,
|
/**
|
||||||
Object requestBytes, Properties prop) {
|
* 요청 URL 로부터 서비스키를 확정해 tx prop 에 세팅한다.
|
||||||
Map<String, String> variablesMap = null;
|
* (기존 {@link ApiKeyExtractFilter#doPreFilter} 가 하던 일)
|
||||||
// QueryString 있을때는 체크(X)
|
*
|
||||||
if (StringUtils.isBlank(request.getQueryString())) {
|
* <ul>
|
||||||
try {
|
* <li>{@code STD_MESSAGE_KEY} : Action 이 만들어낸 요청 경로 (ex. {@code GET/api/v1/users/123})</li>
|
||||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
* <li>{@code FINAL_STD_MESSAGE_KEY} : 등록된 서비스키 (ex. {@code GET/api/v1/users/{userId}})</li>
|
||||||
RequestAction action = ActionFactory.createAction(actionName);
|
* <li>{@code API_SERVICE_CODE} : 서비스키에 매핑된 EAI 서비스 코드</li>
|
||||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
* </ul>
|
||||||
String[] keys = action.perform(requestBytes);
|
*
|
||||||
String requestPath = keys[0];
|
* <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 지원 추가
|
prop.setProperty(STD_MESSAGE_KEY, requestPath); // action class 통해서 생성
|
||||||
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
|
||||||
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
// PathVariable 지원 추가
|
||||||
variablesMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath, requestPath);
|
// ex) /api/bank/account/12345 --> /api/bank/account/{accountNo}
|
||||||
}
|
String ruledPath = ApiKeyExtractFilter.getMatchedKey(requestPath);
|
||||||
} catch (Exception e) {
|
if (StringUtils.isBlank(ruledPath)) {
|
||||||
logger.error(e.getMessage());
|
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) {
|
private Properties getHeaders(HttpServletRequest request) {
|
||||||
@@ -746,34 +871,4 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
return ipAddress;
|
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);
|
request.setAttribute("_authServerStatusCode", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
|
||||||
String detailMessage = ex.getMessage();
|
String detailMessage = ex.getMessage();
|
||||||
if ( StringUtils.isBlank(detailMessage) ) {
|
if ( StringUtils.isBlank(detailMessage) ) {
|
||||||
detailMessage = "광주은행 관리자에게 문의하세요.";
|
detailMessage = "API 관리자에게 문의하세요.";
|
||||||
}
|
}
|
||||||
request.setAttribute("errorMessage", detailMessage);
|
request.setAttribute("errorMessage", detailMessage);
|
||||||
return "forward:/error.jsp";
|
return "forward:/error.jsp";
|
||||||
|
|||||||
@@ -163,7 +163,9 @@ public class DJBOAuth2Controller {
|
|||||||
logTokenIssuance(false, false, e.getMessage(), null);
|
logTokenIssuance(false, false, e.getMessage(), null);
|
||||||
|
|
||||||
Properties logProp = new Properties();
|
Properties logProp = new Properties();
|
||||||
logProp.put("clientId", clientId);
|
if(StringUtils.isNotEmpty(clientId))
|
||||||
|
logProp.put("clientId", clientId);
|
||||||
|
|
||||||
UnknownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
|
UnknownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
|
||||||
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
|
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
|
||||||
|
|
||||||
@@ -178,7 +180,9 @@ public class DJBOAuth2Controller {
|
|||||||
logTokenIssuance(false, false, e.getMessage(), null);
|
logTokenIssuance(false, false, e.getMessage(), null);
|
||||||
|
|
||||||
Properties logProp = new Properties();
|
Properties logProp = new Properties();
|
||||||
logProp.put("clientId", clientId);
|
if(StringUtils.isNotEmpty(clientId))
|
||||||
|
logProp.put("clientId", clientId);
|
||||||
|
|
||||||
UnknownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
|
UnknownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
|
||||||
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
|
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
|
||||||
|
|
||||||
|
|||||||
+101
@@ -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 "";
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+35
-30
@@ -2,47 +2,52 @@ package com.eactive.eai.custom.adapter.handler;
|
|||||||
|
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.handler.TemplateCodeConvertAdapterErrorMsgHandler;
|
import com.eactive.eai.adapter.handler.TemplateCodeConvertAdapterErrorMsgHandler;
|
||||||
import com.eactive.eai.common.message.EAIMessage;
|
import com.eactive.eai.common.message.EAIMessage;
|
||||||
import com.eactive.eai.common.util.Logger;
|
import com.eactive.eai.common.message.EAIMessageKeys;
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.eactive.eai.custom.message.StandardMessageCoordinatorDJB;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
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 {
|
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
|
@Override
|
||||||
public Object generateNonStandardErrorResponseMessage(String inboundAdapterGroupName, String inboundAdapterName,
|
public Object generateOutboundErrorResponseMessage(String outboundadapterGroupName,
|
||||||
Properties callProp, Object outboundRequestData, EAIMessage resEaiMsg) throws Exception {
|
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,
|
// 출력속성코드 = 1(팝업)
|
||||||
inboundAdapterName, callProp, outboundRequestData, resEaiMsg);
|
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)) {
|
StandardMessageManager manager = StandardMessageManager.getInstance();
|
||||||
return responseMsessage;
|
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-3
@@ -10,6 +10,7 @@ import com.eactive.eai.adapter.handler.TemplateCodeConvertAdapterErrorMsgHandler
|
|||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||||
import com.eactive.eai.common.message.EAIMessage;
|
import com.eactive.eai.common.message.EAIMessage;
|
||||||
import com.eactive.eai.common.message.EAIMessageKeys;
|
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.common.util.Logger;
|
||||||
import com.eactive.eai.custom.message.StandardMessageCoordinatorDJB;
|
import com.eactive.eai.custom.message.StandardMessageCoordinatorDJB;
|
||||||
import com.eactive.eai.message.StandardItem;
|
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 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
|
@Override
|
||||||
public Object generateNonStandardErrorResponseMessage(String inboundAdapterGroupName, String inboundAdapterName,
|
public Object generateNonStandardErrorResponseMessage(String inboundAdapterGroupName, String inboundAdapterName,
|
||||||
@@ -43,7 +45,8 @@ public class KakaopayAdapterErrorMsgHandler extends TemplateCodeConvertAdapterEr
|
|||||||
return responseMsessage;
|
return responseMsessage;
|
||||||
}
|
}
|
||||||
|
|
||||||
JsonNode rootNode = OBJECT_MAPPER.readTree(jsonStr);
|
// 제어문자를 이스케이프하지 않고 보내는 상대 시스템 대응 (JacksonUtil.escapeControlChars 주석 참조)
|
||||||
|
JsonNode rootNode = OBJECT_MAPPER.readTree(JacksonUtil.escapeControlChars(jsonStr));
|
||||||
|
|
||||||
boolean modified = false;
|
boolean modified = false;
|
||||||
|
|
||||||
@@ -72,7 +75,7 @@ public class KakaopayAdapterErrorMsgHandler extends TemplateCodeConvertAdapterEr
|
|||||||
if (responseBody instanceof String) {
|
if (responseBody instanceof String) {
|
||||||
String jsonStr = (String) responseBody;
|
String jsonStr = (String) responseBody;
|
||||||
if (!StringUtils.isBlank(jsonStr)) {
|
if (!StringUtils.isBlank(jsonStr)) {
|
||||||
JsonNode rootNode = OBJECT_MAPPER.readTree(jsonStr);
|
JsonNode rootNode = OBJECT_MAPPER.readTree(JacksonUtil.escapeControlChars(jsonStr));
|
||||||
StringBuffer sb = new StringBuffer();
|
StringBuffer sb = new StringBuffer();
|
||||||
JsonNode errorCode = rootNode.get("error_code");
|
JsonNode errorCode = rootNode.get("error_code");
|
||||||
if(errorCode != null)
|
if(errorCode != null)
|
||||||
@@ -113,6 +116,8 @@ public class KakaopayAdapterErrorMsgHandler extends TemplateCodeConvertAdapterEr
|
|||||||
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_OUTP_MSG_DESC, msgDesc);
|
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_OUTP_MSG_DESC, msgDesc);
|
||||||
|
|
||||||
// 성공 처리 처럼 진행한다.
|
// 성공 처리 처럼 진행한다.
|
||||||
|
// 단, 거래로그/에러로그는 원본 에러코드 기준으로 남겨야 하므로 별도로 보관한다.
|
||||||
|
resEaiMsg.setOrgRspErrCd(resEaiMsg.getRspErrCd());
|
||||||
resEaiMsg.setRspErrCd(EAIMessageKeys.EAI_SUCCESS_CODE, false);
|
resEaiMsg.setRspErrCd(EAIMessageKeys.EAI_SUCCESS_CODE, false);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
+2
-4
@@ -15,15 +15,11 @@ import com.eactive.eai.message.StandardItem;
|
|||||||
import com.eactive.eai.message.StandardMessage;
|
import com.eactive.eai.message.StandardMessage;
|
||||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||||
import com.eactive.eai.message.service.InterfaceMapper;
|
import com.eactive.eai.message.service.InterfaceMapper;
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
|
|
||||||
public class NaverpayAdapterErrorMsgHandler extends TemplateAdapterErrorMsgHandler {
|
public class NaverpayAdapterErrorMsgHandler extends TemplateAdapterErrorMsgHandler {
|
||||||
|
|
||||||
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||||
|
|
||||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 표준 -> 비표준 거래
|
* 표준 -> 비표준 거래
|
||||||
* 아웃바운드 어댑터에서 Exception이 발생했을 때, Outbound Process 응답 메시지 생성
|
* 아웃바운드 어댑터에서 Exception이 발생했을 때, Outbound Process 응답 메시지 생성
|
||||||
@@ -53,6 +49,8 @@ public class NaverpayAdapterErrorMsgHandler extends TemplateAdapterErrorMsgHandl
|
|||||||
mapper.setErrorMsg(standardMessage, "처리오류");
|
mapper.setErrorMsg(standardMessage, "처리오류");
|
||||||
|
|
||||||
// 성공 처리 처럼 진행한다.
|
// 성공 처리 처럼 진행한다.
|
||||||
|
// 단, 거래로그/에러로그는 원본 에러코드 기준으로 남겨야 하므로 별도로 보관한다.
|
||||||
|
resEaiMsg.setOrgRspErrCd(resEaiMsg.getRspErrCd());
|
||||||
resEaiMsg.setRspErrCd(EAIMessageKeys.EAI_SUCCESS_CODE, false);
|
resEaiMsg.setRspErrCd(EAIMessageKeys.EAI_SUCCESS_CODE, false);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
+3
-1
@@ -9,6 +9,7 @@ import org.json.simple.JSONObject;
|
|||||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
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.HttpClient5AdapterFilterFactory;
|
||||||
import com.eactive.eai.adapter.http.client.impl.filter.HttpClientAdapterFilter;
|
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.ObjectMapper;
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
|
||||||
@@ -36,7 +37,8 @@ public class HttpClient5AdapterServiceBigTechAddFilter extends HttpClient5Adapte
|
|||||||
// // Adapter에서 Exception이 발생한 경우, 처리할 필터
|
// // Adapter에서 Exception이 발생한 경우, 처리할 필터
|
||||||
// static final String EXCEPTION_FILTER = "EXCEPTION_FILTER";
|
// 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>
|
* 1. 기능 : HttpClient 호출 전후 Filter 적용용 2. 처리 개요 : <br>
|
||||||
|
|||||||
+31
-8
@@ -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.client.impl.filter.OutCryptoFilter;
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
||||||
import com.eactive.eai.common.util.JacksonUtil;
|
import com.eactive.eai.common.util.JacksonUtil;
|
||||||
|
import com.eactive.eai.common.util.Logger;
|
||||||
import com.eactive.eai.util.JsonPathUtil;
|
import com.eactive.eai.util.JsonPathUtil;
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
@@ -15,6 +16,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
|||||||
*/
|
*/
|
||||||
public class DouzoneEncFieldOutCryptoFilter extends EncFieldOutCryptoFilter {
|
public class DouzoneEncFieldOutCryptoFilter extends EncFieldOutCryptoFilter {
|
||||||
|
|
||||||
|
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||||
|
|
||||||
private final OutCryptoFilter filter = new OutCryptoFilter();
|
private final OutCryptoFilter filter = new OutCryptoFilter();
|
||||||
|
|
||||||
protected Properties setProp(Properties tempProp) {
|
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)
|
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
||||||
throws Exception {
|
throws Exception {
|
||||||
String headerGroupName = prop.getProperty(HttpClient5AdapterServiceRest.HEADER_GROUP);
|
String headerGroupName = prop.getProperty(HttpClient5AdapterServiceRest.HEADER_GROUP);
|
||||||
|
|
||||||
JsonNode root = JacksonUtil.readTree(message);
|
JsonNode root = JacksonUtil.readTree(message);
|
||||||
ObjectNode rootObjectNode = (ObjectNode) root;
|
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);
|
rootObjectNode.remove(headerGroupName);
|
||||||
|
|
||||||
String xEmpNm = header.get("x-emp-nm").asText();
|
|
||||||
tempProp.setProperty("x-emp-nm", xEmpNm);
|
tempProp.setProperty("x-emp-nm", xEmpNm);
|
||||||
tempProp.setProperty(InCryptoFilter.PROP_AAD_HEADER, xEmpNm);
|
tempProp.setProperty(InCryptoFilter.PROP_AAD_HEADER, xEmpNm);
|
||||||
String xChnlNm = header.get("x-chnl-nm").asText();
|
|
||||||
tempProp.setProperty("x-chnl-nm", xChnlNm);
|
tempProp.setProperty("x-chnl-nm", xChnlNm);
|
||||||
|
|
||||||
Object enc = filter.doPreFilter(adptGrpName, adptName, prop, rootObjectNode, setProp(tempProp));
|
Object enc = filter.doPreFilter(adptGrpName, adptName, prop, rootObjectNode, setProp(tempProp));
|
||||||
|
|
||||||
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
|
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
|
||||||
encJson.set(headerGroupName, header);
|
encJson.set(headerGroupName, header);
|
||||||
|
|
||||||
return encJson;
|
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
|
@Override
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
||||||
Properties tempProp) throws Exception {
|
Properties tempProp) throws Exception {
|
||||||
|
|||||||
+11
-7
@@ -26,17 +26,21 @@ public class EncFieldOutCryptoFilter implements HttpClientAdapterFilter {
|
|||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
||||||
throws Exception {
|
throws Exception {
|
||||||
String headerGroupName = prop.getProperty(HttpClient5AdapterServiceRest.HEADER_GROUP);
|
String headerGroupName = prop.getProperty(HttpClient5AdapterServiceRest.HEADER_GROUP);
|
||||||
|
|
||||||
JsonNode root = JacksonUtil.readTree(message);
|
JsonNode root = JacksonUtil.readTree(message);
|
||||||
ObjectNode rootObjectNode = (ObjectNode) root;
|
ObjectNode rootObjectNode = (ObjectNode) root;
|
||||||
JsonNode header = rootObjectNode.get(headerGroupName);
|
JsonNode header = null;
|
||||||
rootObjectNode.remove(headerGroupName);
|
if (headerGroupName != null) {
|
||||||
|
header = rootObjectNode.get(headerGroupName);
|
||||||
|
rootObjectNode.remove(headerGroupName);
|
||||||
|
}
|
||||||
|
|
||||||
Object enc = filter.doPreFilter(adptGrpName, adptName, prop, rootObjectNode, setProp(tempProp));
|
Object enc = filter.doPreFilter(adptGrpName, adptName, prop, rootObjectNode, setProp(tempProp));
|
||||||
|
|
||||||
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
|
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
|
||||||
encJson.set(headerGroupName, header);
|
if (header != null)
|
||||||
|
encJson.set(headerGroupName, header);
|
||||||
|
|
||||||
return encJson;
|
return encJson;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-4
@@ -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.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||||
import com.eactive.eai.common.util.JacksonUtil;
|
import com.eactive.eai.common.util.JacksonUtil;
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 카카오뱅크 암복호화에 맟추어 커스텀 필요
|
* 카카오뱅크 암복호화에 맟추어 커스텀 필요
|
||||||
*/
|
*/
|
||||||
public class KakaopayFilter implements HttpAdapterFilter {
|
public class KakaopayFilter implements HttpAdapterFilter {
|
||||||
|
|
||||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
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 인지 확인
|
// term_agreements[0].is_agreed 값이 true 인지 확인
|
||||||
boolean firstAgreed = JacksonUtil.getBoolean(rootNode, "term_agreements[0].is_agreed", false);
|
boolean firstAgreed = JacksonUtil.getBoolean(rootNode, "term_agreements[0].is_agreed", false);
|
||||||
|
|||||||
-766
@@ -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);
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
@@ -209,10 +209,10 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
|
|||||||
msgList.setSize(1);
|
msgList.setSize(1);
|
||||||
LinkedHashMap<String, StandardItem> row = msgList.getArrayChilds(0, true);
|
LinkedHashMap<String, StandardItem> row = msgList.getArrayChilds(0, true);
|
||||||
if (row != null) {
|
if (row != null) {
|
||||||
if (row.containsKey("outp_msg_cd")) row.get("outp_msg_cd").setValue(siteErrCode);
|
setIfPresent(row, "outp_msg_cd", siteErrCode);
|
||||||
if (row.containsKey("outp_msg_ctnt")) row.get("outp_msg_ctnt").setValue(siteErrMsg);
|
setIfPresent(row, "outp_msg_ctnt", siteErrMsg);
|
||||||
if (row.containsKey("outp_msg_desc")) row.get("outp_msg_desc").setValue(siteErrDesc);
|
setIfPresent(row, "outp_msg_desc", siteErrDesc);
|
||||||
if (row.containsKey("err_occu_loct")) row.get("err_occu_loct").setValue(errCode);
|
setIfPresent(row, "err_occu_loct", errCode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -259,6 +259,17 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
|
|||||||
// private helpers
|
// 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void resolveCallPropRefValues(StandardMessage standardMessage, Properties prop) {
|
private void resolveCallPropRefValues(StandardMessage standardMessage, Properties prop) {
|
||||||
if (prop == null) return;
|
if (prop == null) return;
|
||||||
resolveCallPropInChilds(standardMessage.getChilds(), prop);
|
resolveCallPropInChilds(standardMessage.getChilds(), prop);
|
||||||
@@ -275,7 +286,8 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
|
|||||||
if (m.matches()) {
|
if (m.matches()) {
|
||||||
String key = m.group(1);
|
String key = m.group(1);
|
||||||
String defaultVal = m.group(2) != null ? m.group(2) : "";
|
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);
|
item.setValue(resolved != null ? resolved : defaultVal);
|
||||||
}
|
}
|
||||||
} else if (type == StandardType.GROUP) {
|
} else if (type == StandardType.GROUP) {
|
||||||
|
|||||||
+2
-1
@@ -81,7 +81,8 @@ public class MinuteStatsAggregator {
|
|||||||
systemErrCnt.incrementAndGet();
|
systemErrCnt.incrementAndGet();
|
||||||
break;
|
break;
|
||||||
case BUSINESS_ERROR:
|
case BUSINESS_ERROR:
|
||||||
bizErrCnt.incrementAndGet();
|
systemErrCnt.incrementAndGet();
|
||||||
|
//bizErrCnt.incrementAndGet();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ import org.nfunk.jep.function.PostfixMathCommand;
|
|||||||
import com.eactive.eai.common.security.CryptoModuleService;
|
import com.eactive.eai.common.security.CryptoModuleService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JEP 트랜스포머 함수 — DJB ERP 연동 복호화.
|
* JEP 트랜스포머 함수 — DJB 연동 복호화.
|
||||||
*
|
*
|
||||||
* 사용법: DJBErpDecryt(encBase64, moduleName)
|
* 사용법: djbdecryt(encBase64, moduleName)
|
||||||
*
|
*
|
||||||
* 파라미터:
|
* 파라미터:
|
||||||
* encBase64 : Base64 인코딩된 암호문
|
* encBase64 : Base64 인코딩된 암호문
|
||||||
@@ -33,7 +33,7 @@ public class DJBDecrypt extends PostfixMathCommand {
|
|||||||
checkStack(inStack);
|
checkStack(inStack);
|
||||||
|
|
||||||
if (curNumberOfParameters != 2) {
|
if (curNumberOfParameters != 2) {
|
||||||
throw new ParseException("DJBErpDecryt: 파라미터는 2개개여야 합니다 (encBase64, moduleName");
|
throw new ParseException("DJBDecrypt: 파라미터는 2개개여야 합니다 (encBase64, moduleName");
|
||||||
}
|
}
|
||||||
|
|
||||||
String moduleName = inStack.pop().toString();
|
String moduleName = inStack.pop().toString();
|
||||||
@@ -46,7 +46,7 @@ public class DJBDecrypt extends PostfixMathCommand {
|
|||||||
} catch (ParseException e) {
|
} catch (ParseException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception 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;
|
import com.eactive.eai.common.security.CryptoModuleService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JEP 트랜스포머 함수 — DJB ERP 연동 암호화.
|
* JEP 트랜스포머 함수 — DJB 연동 암호화.
|
||||||
*
|
*
|
||||||
* 사용법: DJBErpEncryt(plainText, moduleName) DJBErpEncryt(plainText, moduleName,
|
* 사용법: djbencrypt(plainText, moduleName)
|
||||||
* groupSeq)
|
|
||||||
*
|
*
|
||||||
* 파라미터: plainText : 암호화할 평문 (String) moduleName : DB에 등록된 암호화 모듈명 (String)
|
* 파라미터: plainText : 암호화할 평문 (String), moduleName : DB에 등록된 암호화 모듈명 (String)
|
||||||
* groupSeq : 키 도출용 그룹 시퀀스 (String, 선택). 미전달 시 빈 context로 호출.
|
|
||||||
*
|
*
|
||||||
* 반환값: Base64 인코딩된 암호문 (String)
|
* 반환값: Base64 인코딩된 암호문 (String)
|
||||||
*/
|
*/
|
||||||
@@ -33,7 +31,7 @@ public class DJBEncrypt extends PostfixMathCommand {
|
|||||||
checkStack(inStack);
|
checkStack(inStack);
|
||||||
|
|
||||||
if (curNumberOfParameters != 2) {
|
if (curNumberOfParameters != 2) {
|
||||||
throw new ParseException("DJBErpEncryt: 파라미터는 2개여야 합니다 (plainText, moduleName)");
|
throw new ParseException("DJBEncrypt: 파라미터는 2개여야 합니다 (plainText, moduleName)");
|
||||||
}
|
}
|
||||||
|
|
||||||
String moduleName = inStack.pop().toString();
|
String moduleName = inStack.pop().toString();
|
||||||
@@ -46,7 +44,7 @@ public class DJBEncrypt extends PostfixMathCommand {
|
|||||||
} catch (ParseException e) {
|
} catch (ParseException e) {
|
||||||
throw e;
|
throw e;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new ParseException("DJBErpEncryt 암호화 실패: " + e.getMessage());
|
throw new ParseException("DJBEncrypt 암호화 실패: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-3
@@ -1,12 +1,12 @@
|
|||||||
package com.eactive.eai.custom.transformer.function.userdefined;
|
package com.eactive.eai.custom.transformer.function.userdefined;
|
||||||
|
|
||||||
import com.eactive.eai.common.context.ElinkTransactionContext;
|
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.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.jayway.jsonpath.Configuration;
|
import com.jayway.jsonpath.Configuration;
|
||||||
import com.jayway.jsonpath.JsonPath;
|
import com.jayway.jsonpath.JsonPath;
|
||||||
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
|
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
|
||||||
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
|
|
||||||
import org.nfunk.jep.ParseException;
|
import org.nfunk.jep.ParseException;
|
||||||
import org.nfunk.jep.function.PostfixMathCommand;
|
import org.nfunk.jep.function.PostfixMathCommand;
|
||||||
|
|
||||||
@@ -14,7 +14,9 @@ import java.util.Stack;
|
|||||||
|
|
||||||
public class JsonPathExtractRequestMessage extends PostfixMathCommand {
|
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() {
|
public JsonPathExtractRequestMessage() {
|
||||||
numberOfParameters = -1;
|
numberOfParameters = -1;
|
||||||
@@ -33,7 +35,7 @@ public class JsonPathExtractRequestMessage extends PostfixMathCommand {
|
|||||||
try {
|
try {
|
||||||
// Jackson을 JsonPath의 JSON 프로바이더로 설정
|
// Jackson을 JsonPath의 JSON 프로바이더로 설정
|
||||||
Configuration config = Configuration.builder()
|
Configuration config = Configuration.builder()
|
||||||
.jsonProvider(new JacksonJsonNodeJsonProvider())
|
.jsonProvider(new JacksonJsonNodeJsonProvider(objectMapper))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
JsonNode resultNode = JsonPath.using(config).parse(bizData).read(path);
|
JsonNode resultNode = JsonPath.using(config).parse(bizData).read(path);
|
||||||
|
|||||||
@@ -168,7 +168,7 @@ err_chrg_cnpl_no,3,2,0,1,20,1,,,
|
|||||||
# ============================================================
|
# ============================================================
|
||||||
# DATA - 데이터부
|
# 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_dvcd,2,2,1,1,2,1,,,IO
|
||||||
data_scop_len,2,2,1,1,8,2,,,
|
data_scop_len,2,2,1,1,8,2,,,
|
||||||
BIZ_DATA,2,9,1,1,0,1,,,
|
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];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -40,6 +40,7 @@ import static org.mockito.ArgumentMatchers.anyString;
|
|||||||
* 5. 비표준 수신 → 정상 응답 표준 생성 (coordinateAfterRecvNonStdSyncResponse → JSON)
|
* 5. 비표준 수신 → 정상 응답 표준 생성 (coordinateAfterRecvNonStdSyncResponse → JSON)
|
||||||
* 6. 오류 응답 표준 생성 (coordinateSetStandardMessageError → JSON)
|
* 6. 오류 응답 표준 생성 (coordinateSetStandardMessageError → JSON)
|
||||||
* 7. JSON 왕복(parse → serialize) 일관성
|
* 7. JSON 왕복(parse → serialize) 일관성
|
||||||
|
* 8. 상대 헤더가 표준을 어긴 응답 파싱 (2026-09 사고 회귀 방지)
|
||||||
*/
|
*/
|
||||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||||
class StandardMessageJsonFlowTest {
|
class StandardMessageJsonFlowTest {
|
||||||
@@ -80,11 +81,11 @@ class StandardMessageJsonFlowTest {
|
|||||||
+ "\"frst_mesg_dman_dt\":\"20260420\","
|
+ "\"frst_mesg_dman_dt\":\"20260420\","
|
||||||
+ "\"frst_mesg_dman_time\":\"120000000\""
|
+ "\"frst_mesg_dman_time\":\"120000000\""
|
||||||
+ "},"
|
+ "},"
|
||||||
+ "\"DATA\":{"
|
+ "\"DATA\":[{"
|
||||||
+ "\"data_dvcd\":\"IO\","
|
+ "\"data_dvcd\":\"IO\","
|
||||||
+ "\"data_scop_len\":\"37\","
|
+ "\"data_scop_len\":\"37\","
|
||||||
+ "\"BIZ_DATA\":{\"acct_no\":\"123456789\",\"amt\":\"100000\"}"
|
+ "\"BIZ_DATA\":{\"acct_no\":\"123456789\",\"amt\":\"100000\"}"
|
||||||
+ "}"
|
+ "}]"
|
||||||
+ "}";
|
+ "}";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -121,10 +122,58 @@ class StandardMessageJsonFlowTest {
|
|||||||
+ "\"msg_list_rowcnt\":\"1\""
|
+ "\"msg_list_rowcnt\":\"1\""
|
||||||
+ "}"
|
+ "}"
|
||||||
+ "},"
|
+ "},"
|
||||||
+ "\"DATA\":{"
|
+ "\"DATA\":[{"
|
||||||
+ "\"data_dvcd\":\"IO\","
|
+ "\"data_dvcd\":\"IO\","
|
||||||
+ "\"data_scop_len\":\"37\","
|
+ "\"data_scop_len\":\"37\","
|
||||||
+ "\"BIZ_DATA\":{\"acct_no\":\"123456789\",\"bal\":\"900000\"}"
|
+ "\"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 {
|
void 요청JSON_파싱_DATA_BIZ_DATA_JSON_오브젝트_저장() throws Exception {
|
||||||
StandardMessage msg = parseReq();
|
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");
|
assertNotNull(bizData, "BIZ_DATA가 null");
|
||||||
assertFalse(bizData.trim().isEmpty(), "BIZ_DATA가 공백");
|
assertFalse(bizData.trim().isEmpty(), "BIZ_DATA가 공백");
|
||||||
// JSON 오브젝트로 파싱 가능한지 검증
|
// JSON 오브젝트로 파싱 가능한지 검증
|
||||||
@@ -344,9 +397,11 @@ class StandardMessageJsonFlowTest {
|
|||||||
|
|
||||||
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
String json = msg.getDataString(MessageType.JSON, "utf-8");
|
||||||
JsonNode root = jacksonMapper.readTree(json);
|
JsonNode root = jacksonMapper.readTree(json);
|
||||||
|
// DATA는 GRID(반복부)이므로 직렬화하면 JSON 배열이다. 표준 레이아웃상 1건 고정.
|
||||||
// BIZ_DATA는 JSON 문자열 또는 JSON 오브젝트로 들어갈 수 있음
|
// BIZ_DATA는 JSON 문자열 또는 JSON 오브젝트로 들어갈 수 있음
|
||||||
assertNotNull(root.path("DATA").get("BIZ_DATA"),
|
assertTrue(root.path("DATA").isArray(), "직렬화 JSON의 DATA가 배열이 아님");
|
||||||
"직렬화 JSON에 DATA.BIZ_DATA 없음");
|
assertNotNull(root.path("DATA").path(0).get("BIZ_DATA"),
|
||||||
|
"직렬화 JSON에 DATA[0].BIZ_DATA 없음");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ================================================================
|
// ================================================================
|
||||||
@@ -490,6 +545,40 @@ class StandardMessageJsonFlowTest {
|
|||||||
"응답 JSON 왕복 후 msg_dvcd 불일치");
|
"응답 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
|
// helper
|
||||||
// ================================================================
|
// ================================================================
|
||||||
@@ -505,4 +594,10 @@ class StandardMessageJsonFlowTest {
|
|||||||
jsonReader.parse(msg, RSP_JSON_OK);
|
jsonReader.parse(msg, RSP_JSON_OK);
|
||||||
return msg;
|
return msg;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private StandardMessage parseRspBadHeader() throws Exception {
|
||||||
|
StandardMessage msg = manager.getStandardMessage();
|
||||||
|
jsonReader.parse(msg, RSP_JSON_BAD_HEADER);
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user