Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d04435f13 | |||
| 4a7669d4c0 |
@@ -5,7 +5,6 @@ gradle.properties
|
|||||||
|
|
||||||
src/main/generated
|
src/main/generated
|
||||||
WebContent/generated
|
WebContent/generated
|
||||||
src/main/resources/version.info
|
|
||||||
|
|
||||||
# Eclipse #
|
# Eclipse #
|
||||||
.metadata
|
.metadata
|
||||||
|
|||||||
Vendored
+138
-145
@@ -1,170 +1,163 @@
|
|||||||
pipeline {
|
pipeline {
|
||||||
agent none
|
agent { label 'djb-vm' }
|
||||||
|
|
||||||
|
triggers {
|
||||||
|
pollSCM('H/10 * * * *')
|
||||||
|
}
|
||||||
|
|
||||||
options {
|
options {
|
||||||
timestamps()
|
timestamps()
|
||||||
disableConcurrentBuilds()
|
disableConcurrentBuilds()
|
||||||
skipDefaultCheckout() // stage별 agent의 자동 SCM checkout 방지 (Deploy 노드는 git 접근 불필요, unstash로만 WAR 수신)
|
|
||||||
buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '20'))
|
buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '20'))
|
||||||
}
|
}
|
||||||
|
|
||||||
environment {
|
environment {
|
||||||
|
JAVA_HOME = '/apps/opts/jdk8'
|
||||||
|
JAVA_HOME_TOMCAT = '/apps/opts/jdk17'
|
||||||
|
GRADLE_HOME = '/apps/opts/gradle-8.7'
|
||||||
|
GRADLE_USER_HOME = '/apps/opts/gradle-home'
|
||||||
|
NODE_HOME = '/apps/opts/node-v24'
|
||||||
|
PATH = "/apps/opts/jdk8/bin:/apps/opts/gradle-8.7/bin:/apps/opts/node-v24/bin:/apps/opts/bin:${env.PATH}"
|
||||||
GIT_SSH_COMMAND = 'ssh -o StrictHostKeyChecking=accept-new'
|
GIT_SSH_COMMAND = 'ssh -o StrictHostKeyChecking=accept-new'
|
||||||
WEBHOOK_URL = 'http://172.30.1.50:18000/api/hooks/01ba51b01d3c4c98ae8f3183a23a84ed713197857d024b5da4f303458195eb32'
|
CATALINA_BASE = '/prod/eapim/apigw'
|
||||||
|
CATALINA_HOME = '/prod/eapim/apache-tomcat-9.0.116'
|
||||||
|
CATALINA_PID = '/prod/eapim/apigw/logs/catalina.pid'
|
||||||
|
DEPLOY_HTTP_PORT = '39110'
|
||||||
}
|
}
|
||||||
|
|
||||||
stages {
|
stages {
|
||||||
stage('Build (djb-vm)') {
|
stage('Checkout') {
|
||||||
agent { label 'djb-vm' }
|
steps {
|
||||||
environment {
|
checkout scm
|
||||||
JAVA_HOME = '/apps/opts/jdk8'
|
|
||||||
GRADLE_HOME = '/apps/opts/gradle-8.7'
|
|
||||||
GRADLE_USER_HOME = '/apps/opts/gradle-home'
|
|
||||||
NODE_HOME = '/apps/opts/node-v24'
|
|
||||||
PATH = "/apps/opts/jdk8/bin:/apps/opts/gradle-8.7/bin:/apps/opts/node-v24/bin:/apps/opts/bin:${env.PATH}"
|
|
||||||
}
|
|
||||||
stages {
|
|
||||||
stage('Checkout') {
|
|
||||||
steps { checkout scm }
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('Checkout modules') {
|
|
||||||
steps {
|
|
||||||
sh '''
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
for REPO in elink-online-core elink-online-transformer elink-online-common elink-online-emsclient elink-online-core-jpa; do
|
|
||||||
if [ ! -e "$REPO/.git" ]; then
|
|
||||||
rm -rf "$REPO"
|
|
||||||
git clone --depth=1 --branch master \
|
|
||||||
"ssh://git@172.30.1.50:2222/djb-eapim/$REPO.git" \
|
|
||||||
"$REPO"
|
|
||||||
else
|
|
||||||
git -C "$REPO" fetch --depth=1 origin master
|
|
||||||
git -C "$REPO" reset --hard origin/master
|
|
||||||
git -C "$REPO" clean -fdx
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
'''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('Verify toolchain') {
|
|
||||||
steps {
|
|
||||||
sh '''
|
|
||||||
set -eu
|
|
||||||
java -version
|
|
||||||
gradle --version
|
|
||||||
'''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('Build WAR') {
|
|
||||||
steps { sh 'gradle clean build -x test --no-daemon -Pprofile=weblogic' }
|
|
||||||
post {
|
|
||||||
success {
|
|
||||||
sh '''
|
|
||||||
set -eu
|
|
||||||
cd build/libs
|
|
||||||
sha256sum eapim-online.war > eapim-online.war.sha256
|
|
||||||
'''
|
|
||||||
archiveArtifacts artifacts: 'build/libs/eapim-online.war,build/libs/eapim-online.war.sha256', fingerprint: true
|
|
||||||
stash name: 'war', includes: 'build/libs/eapim-online.war'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
stage('Deploy (weblogic)') {
|
stage('Checkout modules') {
|
||||||
agent { label 'weblogic' }
|
steps {
|
||||||
environment {
|
|
||||||
JENKINS_NODE_COOKIE = 'dontKillMe' // background weblogic를 빌드 종료 시 죽이지 않게
|
|
||||||
WL_HOME = '/app/eapim/apigw'
|
|
||||||
WL_DEPLOY_DIR = '/app/eapim/apigw'
|
|
||||||
WL_WAR_NAME = 'eapim-online.war'
|
|
||||||
WL_HTTP_PORT = '39110'
|
|
||||||
WL_NOHUP = '/logs/weblogic/domains/eapimDomain/nohup.agwSvr11.out'
|
|
||||||
}
|
|
||||||
stages {
|
|
||||||
stage('Stop WebLogic') {
|
|
||||||
steps {
|
|
||||||
sh '"$WL_HOME/stopAgw11.sh"' // 동기: 완전 종료까지 블록, 미기동 시에도 안전
|
|
||||||
}
|
|
||||||
}
|
|
||||||
stage('Deploy WAR') {
|
|
||||||
steps {
|
|
||||||
unstash 'war'
|
|
||||||
sh '''
|
|
||||||
set -eu
|
|
||||||
cp build/libs/eapim-online.war "$WL_DEPLOY_DIR/$WL_WAR_NAME"
|
|
||||||
ls -la "$WL_DEPLOY_DIR"
|
|
||||||
'''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
stage('Start WebLogic and readiness') {
|
|
||||||
steps {
|
|
||||||
sh '''
|
|
||||||
set -eu
|
|
||||||
"$WL_HOME/startAgw11.sh" # nohup & 로 백그라운드 기동, 즉시 리턴
|
|
||||||
|
|
||||||
DEADLINE=$(($(date +%s) + 300))
|
|
||||||
STATUS=000
|
|
||||||
while [ "$(date +%s)" -lt "$DEADLINE" ]; do
|
|
||||||
STATUS=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 3 \
|
|
||||||
"http://localhost:$WL_HTTP_PORT/" 2>/dev/null || echo "000")
|
|
||||||
case "$STATUS" in
|
|
||||||
200|302|401|403|404) echo "Readiness OK (/ HTTP $STATUS)"; break ;;
|
|
||||||
esac
|
|
||||||
sleep 3
|
|
||||||
done
|
|
||||||
|
|
||||||
case "$STATUS" in
|
|
||||||
200|302|401|403|404) ;;
|
|
||||||
*)
|
|
||||||
echo "Readiness failed within 300s, last HTTP=$STATUS"
|
|
||||||
[ -f "$WL_NOHUP" ] && tail -120 "$WL_NOHUP"
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
'''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
post {
|
|
||||||
success {
|
|
||||||
node('weblogic') {
|
|
||||||
sh '''
|
sh '''
|
||||||
set +e
|
set -eu
|
||||||
payload=$(printf '{"text":"[%s #%s](%s) SUCCESS"}' "$JOB_NAME" "$BUILD_NUMBER" "$BUILD_URL")
|
|
||||||
curl -sS --fail --max-time 5 -H 'Content-Type: application/json' -X POST --data "$payload" "$WEBHOOK_URL" >/dev/null || echo "Webhook failed"
|
for REPO in elink-online-core elink-online-transformer elink-online-common elink-online-emsclient elink-online-core-jpa; do
|
||||||
|
if [ ! -e "$REPO/.git" ]; then
|
||||||
|
rm -rf "$REPO"
|
||||||
|
git clone --depth=1 --branch master \
|
||||||
|
"ssh://git@172.30.1.50:2222/djb-eapim/$REPO.git" \
|
||||||
|
"$REPO"
|
||||||
|
else
|
||||||
|
git -C "$REPO" fetch --depth=1 origin master
|
||||||
|
git -C "$REPO" reset --hard origin/master
|
||||||
|
git -C "$REPO" clean -fdx
|
||||||
|
fi
|
||||||
|
done
|
||||||
'''
|
'''
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
failure {
|
|
||||||
node('weblogic') {
|
stage('Verify toolchain') {
|
||||||
|
steps {
|
||||||
|
sh '''
|
||||||
|
set -eu
|
||||||
|
java -version
|
||||||
|
gradle --version
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Build WAR') {
|
||||||
|
steps {
|
||||||
|
sh 'gradle clean build -x test --no-daemon'
|
||||||
|
}
|
||||||
|
post {
|
||||||
|
success {
|
||||||
|
sh '''
|
||||||
|
set -eu
|
||||||
|
cd build/libs
|
||||||
|
sha1sum eapim-online.war > SHA1SUMS
|
||||||
|
sha256sum eapim-online.war > SHA256SUMS
|
||||||
|
'''
|
||||||
|
archiveArtifacts artifacts: 'build/libs/eapim-online.war,build/libs/SHA1SUMS,build/libs/SHA256SUMS', fingerprint: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Stop Tomcat') {
|
||||||
|
steps {
|
||||||
sh '''
|
sh '''
|
||||||
set +e
|
set +e
|
||||||
payload=$(printf '{"text":"[%s #%s](%s) FAILURE"}' "$JOB_NAME" "$BUILD_NUMBER" "$BUILD_URL")
|
systemctl --user stop eapim-apigw 2>/dev/null
|
||||||
curl -sS --fail --max-time 5 -H 'Content-Type: application/json' -X POST --data "$payload" "$WEBHOOK_URL" >/dev/null || echo "Webhook failed"
|
|
||||||
|
if [ -f "$CATALINA_PID" ] && kill -0 "$(cat "$CATALINA_PID")" 2>/dev/null; then
|
||||||
|
JAVA_HOME="$JAVA_HOME_TOMCAT" "$CATALINA_HOME/bin/shutdown.sh" 30 -force || true
|
||||||
|
for i in $(seq 1 30); do
|
||||||
|
[ -f "$CATALINA_PID" ] && kill -0 "$(cat "$CATALINA_PID")" 2>/dev/null || break
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
rm -f "$CATALINA_PID"
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Deploy ROOT.war') {
|
||||||
|
steps {
|
||||||
|
sh '''
|
||||||
|
set -eu
|
||||||
|
DEPLOY_DIR="$CATALINA_BASE/webapps"
|
||||||
|
rm -rf "$DEPLOY_DIR/ROOT" "$DEPLOY_DIR/ROOT.war"
|
||||||
|
cp build/libs/eapim-online.war "$DEPLOY_DIR/ROOT.war"
|
||||||
|
ls -la "$DEPLOY_DIR"
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Start Tomcat and readiness') {
|
||||||
|
steps {
|
||||||
|
sh '''
|
||||||
|
set -eu
|
||||||
|
LOG="$CATALINA_BASE/logs/catalina.$(date +%Y-%m-%d).log"
|
||||||
|
BEFORE=0
|
||||||
|
[ -f "$LOG" ] && BEFORE=$(stat -c %s "$LOG")
|
||||||
|
|
||||||
|
systemctl --user start eapim-apigw
|
||||||
|
|
||||||
|
PROBE_URL="http://localhost:$DEPLOY_HTTP_PORT/"
|
||||||
|
DEADLINE=$(($(date +%s) + 300))
|
||||||
|
STATUS=000
|
||||||
|
|
||||||
|
while [ "$(date +%s)" -lt "$DEADLINE" ]; do
|
||||||
|
STATUS=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 3 \
|
||||||
|
"$PROBE_URL" 2>/dev/null || echo "000")
|
||||||
|
case "$STATUS" in
|
||||||
|
200|302|401|403|404)
|
||||||
|
echo "Readiness OK ($PROBE_URL HTTP $STATUS)"
|
||||||
|
break
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -f "$LOG" ] && tail -c +$((BEFORE+1)) "$LOG" | grep -qE "Application listener .* Exception|SEVERE.*startup.Catalina"; then
|
||||||
|
echo "Startup error detected in log"
|
||||||
|
tail -c +$((BEFORE+1)) "$LOG" | tail -80
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
|
||||||
|
case "$STATUS" in
|
||||||
|
200|302|401|403|404) ;;
|
||||||
|
*)
|
||||||
|
echo "Readiness probe failed within 300s, last HTTP status: $STATUS"
|
||||||
|
echo "--- last 300 lines of catalina log ---"
|
||||||
|
[ -f "$LOG" ] && tail -c +$((BEFORE+1)) "$LOG" | tail -300
|
||||||
|
echo "--- systemd unit status ---"
|
||||||
|
systemctl --user status eapim-apigw --no-pager || true
|
||||||
|
echo "--- listening ports ---"
|
||||||
|
ss -tlnp 2>/dev/null | grep -E ":$DEPLOY_HTTP_PORT\\b" || echo "(port $DEPLOY_HTTP_PORT not listening)"
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
echo "--- key boot log lines ---"
|
||||||
|
tail -c +$((BEFORE+1)) "$LOG" | grep -E "Server startup|Deployment of web" | head -10 || true
|
||||||
'''
|
'''
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,10 +66,6 @@
|
|||||||
<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>
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
|
|||||||
#inst.Name=${HOSTNAME}
|
#inst.Name=${HOSTNAME}
|
||||||
inst.Name=agwSvr11
|
inst.Name=agwSvr11
|
||||||
eai.jdbc.Name=jdbc/dsOBP_AGW
|
eai.jdbc.Name=jdbc/dsOBP_AGW
|
||||||
eai.rmiport=39111
|
eai.rmiport=30111
|
||||||
eai.rmiserviceport=39112
|
eai.rmiserviceport=30112
|
||||||
eai.systemmode=D
|
eai.systemmode=D
|
||||||
# EAI FEP MCI GW ...
|
# EAI FEP MCI GW ...
|
||||||
eai.systemtype=API
|
eai.systemtype=API
|
||||||
|
|||||||
@@ -9,12 +9,6 @@ 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.tableowner=AGWAPP
|
eai.server.extractor=[0,2],[0,2],[-2]
|
||||||
eai.server.extractor=[0,2],[0,2],[-2]
|
|
||||||
|
|||||||
@@ -1,13 +1,10 @@
|
|||||||
# 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.initsize=8
|
logger.async.pool.intsize=8
|
||||||
logger.async.pool.maxsize=10
|
logger.async.pool.maxsize=10
|
||||||
logger.async.queue.size=1024
|
logger.async.queue.size=1024
|
||||||
# worker.size=1 batch, 2~ 1Commit
|
logger.async.worker.size=16
|
||||||
logger.async.worker.size=1
|
|
||||||
# batch max sizeˆ˜
|
|
||||||
logger.async.batch.size=100
|
|
||||||
|
|
||||||
# cloud option
|
# cloud option
|
||||||
scalable=false
|
scalable=false
|
||||||
|
|||||||
@@ -23,15 +23,15 @@
|
|||||||
<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>
|
||||||
<filter-mapping>
|
<filter-mapping>
|
||||||
<filter-name>ApiRequestBodyFilter</filter-name>
|
<filter-name>ApiRequestBodyFilter</filter-name>
|
||||||
<url-pattern>/api/*</url-pattern> 필요한 URL 패턴
|
<url-pattern>/api/*</url-pattern> <!-- 필요한 URL 패턴 -->
|
||||||
<url-pattern>/dj/*</url-pattern> 필요한 URL 패턴
|
<url-pattern>/dj/*</url-pattern> <!-- 필요한 URL 패턴 -->
|
||||||
</filter-mapping> -->
|
</filter-mapping>
|
||||||
|
|
||||||
|
|
||||||
<context-param>
|
<context-param>
|
||||||
|
|||||||
@@ -19,11 +19,10 @@
|
|||||||
<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>
|
||||||
@@ -31,7 +30,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>
|
||||||
|
|||||||
+1
-79
@@ -5,7 +5,6 @@ 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'
|
||||||
@@ -110,11 +109,7 @@ dependencies {
|
|||||||
|
|
||||||
|
|
||||||
implementation "org.springframework:spring-webmvc:${springVersion}"
|
implementation "org.springframework:spring-webmvc:${springVersion}"
|
||||||
// bcpkix/bcprov-jdk15on:1.64 전이 차단 — BouncyCastle 은 elink-online-common 이
|
implementation "org.springframework.security:spring-security-jwt:1.1.1.RELEASE"
|
||||||
// 제공하는 jdk18on 라인만 사용한다(구버전 클래스 중복 방지).
|
|
||||||
implementation ("org.springframework.security:spring-security-jwt:1.1.1.RELEASE") {
|
|
||||||
exclude group: 'org.bouncycastle'
|
|
||||||
}
|
|
||||||
|
|
||||||
//implementation "com.eactive:ojdbc8:1.0"
|
//implementation "com.eactive:ojdbc8:1.0"
|
||||||
//implementation "org.postgresql:postgresql:42.2.23"
|
//implementation "org.postgresql:postgresql:42.2.23"
|
||||||
@@ -161,28 +156,6 @@ test {
|
|||||||
configurations.all {
|
configurations.all {
|
||||||
exclude group: 'log4j', module: 'log4j'
|
exclude group: 'log4j', module: 'log4j'
|
||||||
exclude group: 'org.codehaus.jackson'
|
exclude group: 'org.codehaus.jackson'
|
||||||
|
|
||||||
// commons-fileupload: elink-online-common 이 api 로 선언(build.gradle:85)하지만,
|
|
||||||
// 사용처는 HttpAdapterServiceRest / HttpAdapterServiceVirtualAccount 두 클래스뿐이다.
|
|
||||||
// 두 클래스는 정적 참조가 없고 HttpAdapterServiceFactory 의
|
|
||||||
// Class.forName(DB 설정 클래스명) 으로만 로드되는데, DJB 는 자체 DJBApiAdapterService 를
|
|
||||||
// 사용하므로 이 어댑터 서비스가 기동되지 않는다(= 런타임 미사용).
|
|
||||||
// 공유 모듈인 elink-online-common 에서 의존성을 지우면 타 사이트가 깨지므로,
|
|
||||||
// 루트에서만 배제해 배포 WAR(WEB-INF/lib)에서 제외한다.
|
|
||||||
// ※ 운영 DB 어댑터 설정에 위 두 클래스가 등록되면 NoClassDefFoundError 가 발생하므로,
|
|
||||||
// 해당 어댑터를 사용하게 되는 시점에 이 exclude 를 반드시 제거할 것.
|
|
||||||
exclude group: 'commons-fileupload'
|
|
||||||
|
|
||||||
// BouncyCastle jdk15on 라인 최종 차단.
|
|
||||||
// jdk15on 과 jdk18on 은 artifactId 가 달라 Gradle 이 같은 라이브러리로 보지 않는다.
|
|
||||||
// 어느 경로로든 유입되면 org.bouncycastle.* 가 WEB-INF/lib 에 중복 적재되므로
|
|
||||||
// 배포 WAR 기준으로 한 번 더 배제한다(사용 버전: bcprov/bcpkix-jdk18on 1.78.1).
|
|
||||||
exclude group: 'org.bouncycastle', module: 'bcprov-jdk15on'
|
|
||||||
exclude group: 'org.bouncycastle', module: 'bcpkix-jdk15on'
|
|
||||||
|
|
||||||
// 구 groupId 의 dom4j(=1.6.1) 최종 차단. org.dom4j:dom4j:2.1.3 만 사용한다.
|
|
||||||
// (groupId 가 달라 Gradle 이 버전 충돌로 인식하지 못하므로 명시적으로 배제)
|
|
||||||
exclude group: 'dom4j', module: 'dom4j'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
task settingEclipseEncoding {
|
task settingEclipseEncoding {
|
||||||
@@ -199,54 +172,6 @@ task initDirs() {
|
|||||||
file(generatedJavaDir).mkdirs()
|
file(generatedJavaDir).mkdirs()
|
||||||
}
|
}
|
||||||
|
|
||||||
// version.info 를 classpath 리소스로 생성해 WAR의 WEB-INF/classes에 포함시킨다.
|
|
||||||
// elink-online-common 등 공유 라이브러리 모듈이 아니라, 실제 배포 아티팩트(eapim-online.war)를
|
|
||||||
// 만드는 이 루트 프로젝트에서 생성해야 "지금 배포된 게이트웨이가 정확히 어느 커밋인지"를
|
|
||||||
// eapim-online 소스 변경 여부와 무관하게 항상 최신으로 반영한다.
|
|
||||||
// ToolsController(/manage/tools/version, elink-online-common 모듈)는 이 파일을
|
|
||||||
// Class.getResourceAsStream("/version.info")로 읽는데, WAR는 WEB-INF/classes와
|
|
||||||
// WEB-INF/lib 전체가 하나의 클래스로더를 공유하므로 어느 모듈의 클래스에서 조회하든 찾을 수 있다.
|
|
||||||
//
|
|
||||||
// elink-online-common/elink-online-core/... 는 별도 저장소를 참조하는 git submodule이라
|
|
||||||
// 루트(eapim-online)의 describe/dirty 만으로는 "어느 서브모듈이 바뀌었는지"를 알 수 없다
|
|
||||||
// (서브모듈 포인터가 커밋되고 나면 루트는 다시 clean 해져서 -dirty 흔적도 사라진다).
|
|
||||||
// 그래서 서브모듈 각각에 대해서도 describe를 실행해 module.<이름>=<결과> 형식으로 함께 기록한다.
|
|
||||||
def describeGit(File dir) {
|
|
||||||
try {
|
|
||||||
def proc = "git describe --tags --always --dirty".execute(null, dir)
|
|
||||||
// proc.text는 JVM/OS 기본 charset(Windows 환경에선 CP949 등)으로 stdout을 디코딩한다.
|
|
||||||
// git 태그명은 UTF-8 바이트이므로 기본 charset이 UTF-8이 아니면 여기서 한글이 깨진다.
|
|
||||||
// stream을 명시적으로 UTF-8로 읽어서 이 문제를 피한다.
|
|
||||||
def output = proc.inputStream.getText("UTF-8")
|
|
||||||
proc.waitFor()
|
|
||||||
return (proc.exitValue() == 0) ? output.trim() : "unknown"
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.warn("${dir} git describe 실행 불가, unknown 으로 대체: ${e.message}")
|
|
||||||
return "unknown"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
task generateVersionInfo {
|
|
||||||
doLast {
|
|
||||||
def gitVersion = describeGit(projectDir)
|
|
||||||
|
|
||||||
def sb = new StringBuilder()
|
|
||||||
sb.append("version=${gitVersion}\n")
|
|
||||||
sb.append("buildTime=${new Date().format("yyyy-MM-dd HH:mm:ss")}\n")
|
|
||||||
subprojects.sort { it.name }.each { sub ->
|
|
||||||
if (file("${sub.projectDir}/.git").exists()) {
|
|
||||||
sb.append("module.${sub.name}=${describeGit(sub.projectDir)}\n")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
def versionInfoFile = file("$projectDir/src/main/resources/version.info")
|
|
||||||
versionInfoFile.parentFile.mkdirs()
|
|
||||||
versionInfoFile.write(sb.toString(), "UTF-8")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
processResources.dependsOn generateVersionInfo
|
|
||||||
|
|
||||||
eclipse {
|
eclipse {
|
||||||
wtp {
|
wtp {
|
||||||
component {
|
component {
|
||||||
@@ -276,6 +201,3 @@ eclipse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// CycloneDX SBOM -> xlsx 변환 (gradle sbomXlsx)
|
|
||||||
apply from: "$projectDir/gradle/sbom-xlsx.gradle"
|
|
||||||
|
|||||||
+1
-1
Submodule elink-online-common updated: 1c48dd834a...fef16d1b99
+1
-1
Submodule elink-online-core updated: 495241c5d0...52b968e8f8
+1
-1
Submodule elink-online-core-jpa updated: 6651e0e809...9620845daf
+1
-1
Submodule elink-online-transformer updated: 8701f5d459...05e887f7f1
@@ -1,326 +0,0 @@
|
|||||||
/*
|
|
||||||
* 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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,380 @@
|
|||||||
|
//package com.eactive.eai.adapter.controller;
|
||||||
|
//
|
||||||
|
//import java.util.ArrayList;
|
||||||
|
//import java.util.Collections;
|
||||||
|
//import java.util.Date;
|
||||||
|
//import java.util.Enumeration;
|
||||||
|
//import java.util.HashMap;
|
||||||
|
//import java.util.List;
|
||||||
|
//import java.util.Map;
|
||||||
|
//import java.util.Properties;
|
||||||
|
//
|
||||||
|
//import javax.servlet.http.HttpServletRequest;
|
||||||
|
//import javax.servlet.http.HttpServletResponse;
|
||||||
|
//
|
||||||
|
//import org.apache.commons.lang3.StringUtils;
|
||||||
|
//// jwhong
|
||||||
|
//import org.json.simple.JSONObject;
|
||||||
|
//import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
//import org.springframework.http.HttpStatus;
|
||||||
|
//import org.springframework.http.MediaType;
|
||||||
|
//import org.springframework.http.ResponseEntity;
|
||||||
|
//import org.springframework.util.AntPathMatcher;
|
||||||
|
//import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
//import org.springframework.web.bind.annotation.RestController;
|
||||||
|
//
|
||||||
|
//import com.eactive.eai.adapter.AdapterGroupVO;
|
||||||
|
//import com.eactive.eai.adapter.AdapterManager;
|
||||||
|
//import com.eactive.eai.adapter.AdapterPropManager;
|
||||||
|
//import com.eactive.eai.adapter.AdapterVO;
|
||||||
|
//import com.eactive.eai.adapter.Keys;
|
||||||
|
//import com.eactive.eai.adapter.http.HttpStatusException;
|
||||||
|
//import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||||
|
//import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||||
|
//import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
||||||
|
//import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
||||||
|
//import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||||
|
//import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilterFactoryKjb;
|
||||||
|
//import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||||
|
//import com.eactive.eai.adapter.service.ApiAdapterService;
|
||||||
|
//import com.eactive.eai.common.TransactionContextKeys;
|
||||||
|
//import com.eactive.eai.common.exception.ExceptionUtil;
|
||||||
|
//import com.eactive.eai.common.server.EAIServerManager;
|
||||||
|
//import com.eactive.eai.common.stdmessage.STDMessageManager;
|
||||||
|
//import com.eactive.eai.common.stdmessage.STDMsgInfoAddOnVO;
|
||||||
|
//import com.eactive.eai.common.util.DatetimeUtil;
|
||||||
|
//import com.eactive.eai.common.util.InboundErrorLogger;
|
||||||
|
//import com.eactive.eai.common.util.Logger;
|
||||||
|
//import com.eactive.eai.common.util.MessageUtil;
|
||||||
|
//import com.eactive.eai.common.util.UUIDGenerator;
|
||||||
|
//import com.eactive.eai.inbound.action.ActionException;
|
||||||
|
//import com.eactive.eai.inbound.action.ActionFactory;
|
||||||
|
//import com.eactive.eai.inbound.action.RequestAction;
|
||||||
|
//import com.eactive.eai.inbound.error.InboundErrorInfoVO;
|
||||||
|
//
|
||||||
|
//@RestController
|
||||||
|
//public class ApiAdapterController implements HttpAdapterServiceKey {
|
||||||
|
// static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||||
|
//
|
||||||
|
// @Autowired
|
||||||
|
// ApiAdapterService service;
|
||||||
|
//
|
||||||
|
// /**
|
||||||
|
// * KJBANK 요구사항으로 /mapi/oauth2/token 과 같은 형태로 토큰 발급거래를 수행해야해서 예외처리함
|
||||||
|
// *
|
||||||
|
// * @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
|
||||||
|
// * endpoints)
|
||||||
|
// */
|
||||||
|
// @RequestMapping(value = { "/api/*", "/mapi/*", "/api/*/{path:^(?!.*oauth).*$}/**",
|
||||||
|
// "/mapi/{path:^(?!.*oauth2).*$}/**" })
|
||||||
|
//// @RequestMapping(value = {"/api/**"})
|
||||||
|
// public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
||||||
|
// throws Exception {
|
||||||
|
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
||||||
|
// String apiUri = servletRequest.getRequestURI();
|
||||||
|
// // /api/v1/public/getUserInfo.svc
|
||||||
|
// apiUri = StringUtils.removeStart(apiUri, servletRequest.getContextPath());
|
||||||
|
// apiUri = StringUtils.removeEnd(apiUri, "/");
|
||||||
|
//
|
||||||
|
// HttpDynamicInAdapterUri adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), "");
|
||||||
|
//
|
||||||
|
// if (logger.isDebug()) {
|
||||||
|
// logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// if (adptUri == null) {
|
||||||
|
// logError(servletRequest);
|
||||||
|
// String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
||||||
|
// "can not find Adapter Uri");
|
||||||
|
// return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(errorMsg);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // Received time , jwhong
|
||||||
|
// long receivedTimeMillis = System.currentTimeMillis(); // 밀리세컨 단위로 보내야함
|
||||||
|
// String receivedTimeStr = String.valueOf(receivedTimeMillis);
|
||||||
|
//
|
||||||
|
// String adapterGroupName = adptUri.getAdptGrpName();
|
||||||
|
// String adapterName = adptUri.getAdptName();
|
||||||
|
// AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||||
|
// AdapterVO adapterVO = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName);
|
||||||
|
// if (adapterVO == null) {
|
||||||
|
// String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR,
|
||||||
|
// "Adapter not found error");
|
||||||
|
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
|
||||||
|
// .body(errorMsg);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// Properties httpProp = AdapterPropManager.getInstance().getProperties(adapterVO.getPropGroupName());
|
||||||
|
//
|
||||||
|
// String adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||||
|
// String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||||
|
// MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
||||||
|
// String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||||
|
//
|
||||||
|
// String responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
|
||||||
|
// ResponseEntity responseEntity = null;
|
||||||
|
// Properties transactionProp = new Properties();
|
||||||
|
// // jwhong, put api received time, eaiSvcCode
|
||||||
|
// transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
||||||
|
//
|
||||||
|
// // ** jwhong TSEAIHS04의 api full path와 비교하여 adapter를 가져온다
|
||||||
|
//// String bzwkSvcKeyName = ""; // Adapter Group별 Action Class에 따라 구성이 달라짐. 예)
|
||||||
|
//// // _AGW_IN_RST_SyS:POST/account/{acc_no}
|
||||||
|
//// String adapterGrpName = ""; // Adapter Group명 예) _AGW_IN_RST_SyS : API_PATH(/api/test)
|
||||||
|
// String apiSvcCode = ""; // eaiSvcCd 예) LONNCHCON00005S2
|
||||||
|
// String apiFullPathKey = ""; // 예) POST|/api/test/account/list, POST|/api/test/account/{acc_no}
|
||||||
|
// Map<String, String> pathVariables = null;
|
||||||
|
// try {
|
||||||
|
// // PathVariable(ex:/api/test/account/{acc_no}) 대응 및 DAO조회 제거.
|
||||||
|
// // /api/test/account/1234567 호출시 /api/test/account/{acc_no} API 로 식별.
|
||||||
|
//
|
||||||
|
//// String methodAndUri = getRequestRuledPath(servletRequest, apiUri, adapterVO, transactionProp);
|
||||||
|
// String methodAndUri = servletRequest.getMethod() + "|" + apiUri;
|
||||||
|
// STDMessageManager manager = STDMessageManager.getInstance();
|
||||||
|
// STDMsgInfoAddOnVO stdMsgInfo = manager.getStdMsgInfoAddOn(methodAndUri);
|
||||||
|
//// bzwkSvcKeyName = stdMsgInfo.getBzwksvckeyname();
|
||||||
|
// apiSvcCode = stdMsgInfo.getEaiSvcCd();
|
||||||
|
// transactionProp.put(API_SERVICE_CODE, apiSvcCode);
|
||||||
|
//
|
||||||
|
//// adapterGrpName = stdMsgInfo.gAdapterGroupName();
|
||||||
|
// apiFullPathKey = stdMsgInfo.getApiFullPath();
|
||||||
|
// if (STDMessageManager.isPathVariable(apiFullPathKey)) {
|
||||||
|
// pathVariables = new AntPathMatcher().extractUriTemplateVariables(apiFullPathKey, methodAndUri);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
//// adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance(), adapterGrpName);
|
||||||
|
// } catch (Exception e) {
|
||||||
|
//// adptUri = null;
|
||||||
|
// }
|
||||||
|
// // ***
|
||||||
|
// if (pathVariables != null) {
|
||||||
|
// transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// try {
|
||||||
|
// String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||||
|
// transactionProp);
|
||||||
|
// // if (RESPONSE_TYPE_ASYNC.equals(responseType)) { // table의 값이 ASYNC 로 들어가 있는데
|
||||||
|
// // response_type_async는 ASYN 로 되어 있어 아래처럼 비교함 jwhong 2025
|
||||||
|
// if ("ASYNC".equals(responseType)) {
|
||||||
|
// // responseEntity = ResponseEntity.ok("dummy"); // comment by jwhong
|
||||||
|
// // servletResponse.addHeader("traceId", responseData); // uuid를 response header에
|
||||||
|
// servletResponse.addHeader("traceId",
|
||||||
|
// transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||||
|
// int httpStatus = servletResponse.getStatus();
|
||||||
|
// if (httpStatus == 200) {
|
||||||
|
// // 업체별 aync response message 가 다르다.
|
||||||
|
// String asyncMsgStyle = httpProp.getProperty("ASYNC_RTNMSG_TYPE", "");
|
||||||
|
// String responseBody = "";
|
||||||
|
// boolean encryptAsyncAckApply = StringUtils
|
||||||
|
// .equalsIgnoreCase(httpProp.getProperty("ASYNC_ENCRYPT_ACK", "N"), "Y");
|
||||||
|
//
|
||||||
|
// if (asyncMsgStyle == null || asyncMsgStyle.trim().isEmpty()) {
|
||||||
|
// responseBody = makeResponseBodyMsg();
|
||||||
|
// } else {
|
||||||
|
// responseBody = asyncMsgStyle;
|
||||||
|
// }
|
||||||
|
// if (encryptAsyncAckApply) {
|
||||||
|
// responseBody = service.doPostEncryption(responseBody, transactionProp, servletRequest);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseBody);
|
||||||
|
// // jwhong
|
||||||
|
// } else {
|
||||||
|
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||||
|
// }
|
||||||
|
// } else {
|
||||||
|
//// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||||
|
//// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
|
||||||
|
//// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
|
||||||
|
//
|
||||||
|
// servletResponse.addHeader("traceId",
|
||||||
|
// transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||||
|
// int httpStatus = servletResponse.getStatus();
|
||||||
|
// if (httpStatus != 200) {
|
||||||
|
// responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||||
|
// } else {
|
||||||
|
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// } catch (Exception e) {
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||||
|
//
|
||||||
|
// String errorMsg = null;
|
||||||
|
//
|
||||||
|
// if( e instanceof HttpStatusException ) {
|
||||||
|
// logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||||
|
// HttpStatusException e1 = (HttpStatusException) e;
|
||||||
|
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||||
|
// MessageUtil.ERROR_CODE_AP_ERROR, e1.getMessage(), errorResponseFormat);
|
||||||
|
// responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||||
|
// }
|
||||||
|
// else if( e instanceof JwtAuthException )
|
||||||
|
// {
|
||||||
|
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||||
|
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||||
|
// MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage(), errorResponseFormat);
|
||||||
|
// responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||||
|
// }
|
||||||
|
// else
|
||||||
|
// {
|
||||||
|
// logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||||
|
// errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||||
|
// MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
||||||
|
// responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType)
|
||||||
|
// .body(errorMsg);
|
||||||
|
// }
|
||||||
|
// String postFilterNames = httpProp.getProperty("POST_FILTERS","");
|
||||||
|
//
|
||||||
|
// if( postFilterNames.contains("HMAC_SHA256") ) {
|
||||||
|
// HttpAdapterFilter filter = HttpAdapterFilterFactoryKjb.createFilter("HMAC_SHA256");
|
||||||
|
// filter.doPostFilter(adapterGroupName, postFilterNames, errorMsg, transactionProp, servletRequest, servletResponse);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// } finally {
|
||||||
|
// /**
|
||||||
|
// * 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
||||||
|
// * 추후 더 좋은방법이 생길경우 개선 요망
|
||||||
|
// */
|
||||||
|
// try {
|
||||||
|
//
|
||||||
|
// servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
||||||
|
//
|
||||||
|
// if (!"ASYNC".equals(responseType)) {
|
||||||
|
// String uuid = transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||||
|
// String url = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
|
||||||
|
// String method = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
|
||||||
|
// int httpStatusCode = servletResponse.getStatus();
|
||||||
|
//
|
||||||
|
// Map<Object, Object> headerMap = new HashMap<>();
|
||||||
|
// // 응답 헤더 로깅
|
||||||
|
// for (String headerName : servletResponse.getHeaderNames()) {
|
||||||
|
// String headerValue = servletResponse.getHeader(headerName);
|
||||||
|
// logger.debug(String.format("httpHeader logging headerKey=%s, headerValue=%s",
|
||||||
|
// headerName, headerValue));
|
||||||
|
// headerMap.put(headerName, headerValue);
|
||||||
|
// }
|
||||||
|
// //HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName,adapterName, headerMap, url, method, httpStatusCode);
|
||||||
|
// }
|
||||||
|
// } catch (Exception e) {
|
||||||
|
// logger.warn("http header db logging fail.", e);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// return responseEntity;
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// /**
|
||||||
|
// * url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
|
||||||
|
// * /api/v1/public/getUserInfo.svc
|
||||||
|
// *
|
||||||
|
// * @param apiUri
|
||||||
|
// * @return
|
||||||
|
// */
|
||||||
|
// private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager,
|
||||||
|
// String adapterGrpName) throws Exception {
|
||||||
|
// if (StringUtils.isBlank(apiUri)) {
|
||||||
|
// return null;
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // * manager 출력
|
||||||
|
// logger.warn("===== adptUriMap 상세 내용 =====");
|
||||||
|
// for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
||||||
|
// HttpDynamicInAdapterUri uriObj = entry.getValue();
|
||||||
|
// logger.warn("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
||||||
|
// + uriObj.getUri());
|
||||||
|
// }
|
||||||
|
// logger.warn("================================");
|
||||||
|
//
|
||||||
|
// //
|
||||||
|
// for (int i = 0; i < 10; i++) {
|
||||||
|
// HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
|
||||||
|
// if (adptUri != null) {
|
||||||
|
// if (StringUtils.isNotEmpty(adapterGrpName)) {
|
||||||
|
// if(adptUri.getAdptGrpName().equals(adapterGrpName)) {
|
||||||
|
// return adptUri;
|
||||||
|
// }
|
||||||
|
// } else {
|
||||||
|
// return adptUri;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // /api/v1/public
|
||||||
|
// apiUri = StringUtils.substringBeforeLast(apiUri, "/");
|
||||||
|
// if (apiUri.length() < 4) { // /api
|
||||||
|
// return null;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// return null;
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// private void logError(HttpServletRequest request) {
|
||||||
|
// InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||||
|
//
|
||||||
|
// EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||||
|
// String serverName = eaiServerManager.getLocalServerName();
|
||||||
|
// String uuid = null;
|
||||||
|
// StringBuffer sb = new StringBuffer();
|
||||||
|
//
|
||||||
|
// String instanceid1 = serverName.substring(0, 2);
|
||||||
|
// String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||||
|
// String instid = instanceid1 + instanceid2;
|
||||||
|
// uuid = instid + UUIDGenerator.getUUID();
|
||||||
|
//
|
||||||
|
// String[] msgArgs = new String[1];
|
||||||
|
// msgArgs[0] = request.getRequestURI();
|
||||||
|
//
|
||||||
|
// String errorCode = "RECEAIIRP010";
|
||||||
|
// String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
|
||||||
|
//
|
||||||
|
// errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
||||||
|
// errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
|
||||||
|
// errorInfoVO.setErrCd(errorCode); // 에러코드
|
||||||
|
// errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||||
|
// errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
||||||
|
// errorInfoVO.setErrDstcd(" ");
|
||||||
|
// sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
|
||||||
|
// .append(request.getRequestURI());
|
||||||
|
// errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
||||||
|
// errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
||||||
|
//
|
||||||
|
// InboundErrorLogger.error(errorInfoVO);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// private String makeResponseBodyMsg() {
|
||||||
|
//
|
||||||
|
// Map<String, Object> dataMap = new HashMap<>();
|
||||||
|
// dataMap.put("result", 1);
|
||||||
|
// Map<String, Object> map = new HashMap<>();
|
||||||
|
//
|
||||||
|
// map.put("code", "200");
|
||||||
|
// map.put("data", dataMap);
|
||||||
|
// map.put("message", "정상 처리 되었습니다.");
|
||||||
|
//
|
||||||
|
// JSONObject json = new JSONObject();
|
||||||
|
// json.putAll(map);
|
||||||
|
//
|
||||||
|
// return json.toJSONString();
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// /*
|
||||||
|
// * private String makeResponseBodyMsg(String asyncMsgStyle) {
|
||||||
|
// *
|
||||||
|
// * Map<String, Object> dataMap = new HashMap<>(); dataMap.put("result", 1);
|
||||||
|
// * Map<String, Object> map = new HashMap<>();
|
||||||
|
// *
|
||||||
|
// * switch (asyncMsgStyle) { case "TB_SUC": map.put("rspCode", "TB_SUC_000");
|
||||||
|
// * map.put("rspMsg", "정상"); map.put("data", dataMap); break; case "ONLYDATA":
|
||||||
|
// * map.put("data", dataMap); map.put("success", "true"); break; default:
|
||||||
|
// * map.put("code", "200"); map.put("data", dataMap); map.put("message",
|
||||||
|
// * "정상 처리 되었습니다."); break; }
|
||||||
|
// *
|
||||||
|
// * JSONObject json = new JSONObject(); json.putAll(map);
|
||||||
|
// *
|
||||||
|
// * return json.toJSONString(); }
|
||||||
|
// */
|
||||||
|
//}
|
||||||
@@ -35,7 +35,8 @@ public class ApiRequestBodyFilter extends OncePerRequestFilter {
|
|||||||
HttpServletResponse response,
|
HttpServletResponse response,
|
||||||
FilterChain filterChain)
|
FilterChain filterChain)
|
||||||
throws ServletException, IOException {
|
throws ServletException, IOException {
|
||||||
if (!isTarget(request)) {
|
System.out.println("ApiRequestBodyFilter : " + request.getRequestURI());
|
||||||
|
if (!isTarget(request)) {
|
||||||
filterChain.doFilter(request, response);
|
filterChain.doFilter(request, response);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,11 +33,9 @@ import com.eactive.eai.common.TransactionContextKeys;
|
|||||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||||
import com.eactive.eai.common.server.EAIServerManager;
|
import com.eactive.eai.common.server.EAIServerManager;
|
||||||
import com.eactive.eai.common.util.DatetimeUtil;
|
import com.eactive.eai.common.util.DatetimeUtil;
|
||||||
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
|
|
||||||
import com.eactive.eai.common.util.InboundErrorLogger;
|
import com.eactive.eai.common.util.InboundErrorLogger;
|
||||||
import com.eactive.eai.common.util.Logger;
|
import com.eactive.eai.common.util.Logger;
|
||||||
import com.eactive.eai.common.util.MessageUtil;
|
import com.eactive.eai.common.util.MessageUtil;
|
||||||
import com.eactive.eai.common.util.RestSendBodyLogUtils;
|
|
||||||
import com.eactive.eai.common.util.TxFileLogger;
|
import com.eactive.eai.common.util.TxFileLogger;
|
||||||
import com.eactive.eai.common.util.TxSiftContext;
|
import com.eactive.eai.common.util.TxSiftContext;
|
||||||
import com.eactive.eai.common.util.UUIDGenerator;
|
import com.eactive.eai.common.util.UUIDGenerator;
|
||||||
@@ -50,8 +48,7 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
DJBApiAdapterService service;
|
DJBApiAdapterService service;
|
||||||
|
|
||||||
EAIServerManager eaiServerManager;
|
|
||||||
/**
|
/**
|
||||||
* DJErp OAuth 조기 적용을 위한 Controller
|
* DJErp OAuth 조기 적용을 위한 Controller
|
||||||
*
|
*
|
||||||
@@ -68,7 +65,6 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
"/tsb/{path:^(?!oauth).*$}", "/tsb/{path:^(?!oauth).*$}/**",
|
"/tsb/{path:^(?!oauth).*$}", "/tsb/{path:^(?!oauth).*$}/**",
|
||||||
"/shb/{path:^(?!oauth).*$}", "/shb/{path:^(?!oauth).*$}/**",
|
"/shb/{path:^(?!oauth).*$}", "/shb/{path:^(?!oauth).*$}/**",
|
||||||
"/tst/{path:^(?!oauth).*$}", "/tst/{path:^(?!oauth).*$}/**",
|
"/tst/{path:^(?!oauth).*$}", "/tst/{path:^(?!oauth).*$}/**",
|
||||||
"/**/{path:^(?!oauth)(?!favicon\\.ico$).*$}", "/**/{path:^(?!oauth)(?!favicon\\.ico$).*$}/**",
|
|
||||||
})
|
})
|
||||||
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
||||||
throws Exception {
|
throws Exception {
|
||||||
@@ -84,31 +80,17 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (adptUri == null) {
|
||||||
|
logError(servletRequest);
|
||||||
|
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
||||||
|
"can not find Adapter Uri");
|
||||||
|
return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(errorMsg);
|
||||||
|
}
|
||||||
|
|
||||||
// Received time , jwhong
|
// Received time , jwhong
|
||||||
long receivedTimeMillis = System.currentTimeMillis(); // 밀리세컨 단위로 보내야함
|
long receivedTimeMillis = System.currentTimeMillis(); // 밀리세컨 단위로 보내야함
|
||||||
String receivedTimeStr = String.valueOf(receivedTimeMillis);
|
String receivedTimeStr = String.valueOf(receivedTimeMillis);
|
||||||
|
|
||||||
ResponseEntity<String> responseEntity = null;
|
|
||||||
Properties transactionProp = new Properties();
|
|
||||||
|
|
||||||
if(eaiServerManager == null)
|
|
||||||
eaiServerManager = EAIServerManager.getInstance();
|
|
||||||
|
|
||||||
String instid = eaiServerManager.getGroupInstId();
|
|
||||||
String uuid = instid+UUIDGenerator.getUUID().toString().replaceAll("-", "");
|
|
||||||
|
|
||||||
transactionProp.setProperty(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
|
||||||
transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
|
||||||
|
|
||||||
if (adptUri == null) {
|
|
||||||
//logError(servletRequest);
|
|
||||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
|
||||||
"can not find Adapter Uri");
|
|
||||||
logError(servletRequest, "HTTP_IN_NO_URI", MessageUtil.ERROR_CODE_SERVICE_NOT_FOUND,
|
|
||||||
errorMsg, transactionProp, null);
|
|
||||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(errorMsg);
|
|
||||||
}
|
|
||||||
|
|
||||||
String adapterGroupName = adptUri.getAdptGrpName();
|
String adapterGroupName = adptUri.getAdptGrpName();
|
||||||
String adapterName = adptUri.getAdptName();
|
String adapterName = adptUri.getAdptName();
|
||||||
AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||||
@@ -116,8 +98,6 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
if (adapterVO == null) {
|
if (adapterVO == null) {
|
||||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR,
|
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR,
|
||||||
"Adapter not found error");
|
"Adapter not found error");
|
||||||
logError(servletRequest, adapterGroupName, MessageUtil.ERROR_CODE_AP_ERROR,
|
|
||||||
errorMsg, transactionProp, null);
|
|
||||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
|
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
|
||||||
.body(errorMsg);
|
.body(errorMsg);
|
||||||
}
|
}
|
||||||
@@ -129,10 +109,16 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
||||||
String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||||
|
|
||||||
|
ResponseEntity<String> responseEntity = null;
|
||||||
|
Properties transactionProp = new Properties();
|
||||||
|
String uuid = UUIDGenerator.getUUID().toString().replaceAll("-", "");
|
||||||
|
transactionProp.setProperty(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||||
|
|
||||||
TxSiftContext.begin(uuid);
|
TxSiftContext.begin(uuid);
|
||||||
|
|
||||||
// jwhong, put api received time, eaiSvcCode
|
// jwhong, put api received time, eaiSvcCode
|
||||||
|
transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
||||||
|
|
||||||
String responseData = "";
|
String responseData = "";
|
||||||
try {
|
try {
|
||||||
responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||||
@@ -150,46 +136,31 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||||
|
|
||||||
String responseErrorMsg = null;
|
String errorMsg = null;
|
||||||
|
|
||||||
|
errorMsg = genErrorResponseMessage(adapterGroupName, adapterName,
|
||||||
|
transactionProp, e, adptMsgType, encode, errorResponseFormat);
|
||||||
if (e instanceof FilterException) {
|
if (e instanceof FilterException) {
|
||||||
responseErrorMsg = genErrorResponseMessage(adapterGroupName, adapterName,
|
|
||||||
transactionProp, MessageUtil.ERROR_CODE_AP_ERROR, e, adptMsgType, encode, errorResponseFormat);
|
|
||||||
FilterException e1 = (FilterException) e;
|
FilterException e1 = (FilterException) e;
|
||||||
this.logError(servletRequest, adapterGroupName, e1.getCode(), responseErrorMsg, transactionProp, e);
|
this.logError(servletRequest, uuid, adapterGroupName, e1.getCode(), errorMsg, transactionProp, e);
|
||||||
logger.error("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
logger.error("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||||
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(responseErrorMsg);
|
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||||
} else if (e instanceof JwtAuthException) {
|
} else if (e instanceof JwtAuthException) {
|
||||||
responseErrorMsg = genErrorResponseMessage(adapterGroupName, adapterName,
|
|
||||||
transactionProp, MessageUtil.ERROR_CODE_AUTH_FAIL, e, adptMsgType, encode, errorResponseFormat);
|
|
||||||
JwtAuthException e1 = (JwtAuthException) e;
|
JwtAuthException e1 = (JwtAuthException) e;
|
||||||
this.logError(servletRequest, adapterGroupName, e1.getCode(), responseErrorMsg, transactionProp, e);
|
this.logError(servletRequest, uuid, adapterGroupName, e1.getCode(), errorMsg, transactionProp, e);
|
||||||
logger.error("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
logger.error("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||||
responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(responseErrorMsg);
|
responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||||
} else if (e instanceof HttpStatusException) {
|
} else if (e instanceof HttpStatusException) {
|
||||||
responseErrorMsg = genErrorResponseMessage(adapterGroupName, adapterName,
|
|
||||||
transactionProp, MessageUtil.ERROR_CODE_AP_ERROR, e, adptMsgType, encode, errorResponseFormat);
|
|
||||||
logger.error("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
logger.error("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||||
HttpStatusException e1 = (HttpStatusException) e;
|
HttpStatusException e1 = (HttpStatusException) e;
|
||||||
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(responseErrorMsg);
|
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||||
} else {
|
} else {
|
||||||
responseErrorMsg = genErrorResponseMessage(adapterGroupName, adapterName,
|
|
||||||
transactionProp, MessageUtil.ERROR_CODE_AP_ERROR, e, adptMsgType, encode, errorResponseFormat);
|
|
||||||
this.logError(servletRequest, adapterGroupName, MessageUtil.ERROR_CODE_AP_ERROR, responseErrorMsg, transactionProp, e);
|
|
||||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||||
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType).body(responseErrorMsg);
|
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType).body(errorMsg);
|
||||||
}
|
}
|
||||||
responseData = responseErrorMsg;
|
responseData = errorMsg;
|
||||||
|
|
||||||
} finally {
|
} finally {
|
||||||
|
|
||||||
// 어댑터 HTTP 로그에 응답 body 출력
|
|
||||||
if (RestSendBodyLogUtils.isBodyLoggingApi(transactionProp.getProperty("API_SERVICE_CODE"))) {
|
|
||||||
String trimmedBody = RestSendBodyLogUtils.getBodyByMaxSize(responseData);
|
|
||||||
transactionProp.setProperty(HttpAdapterExtraLogUtil.BODY_FIELD_NAME, trimmedBody);
|
|
||||||
}
|
|
||||||
servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
* 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
||||||
* 추후 더 좋은방법이 생길경우 개선 요망
|
* 추후 더 좋은방법이 생길경우 개선 요망
|
||||||
@@ -207,7 +178,7 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String genErrorResponseMessage(String adapterGroupName, String adapterName,
|
private String genErrorResponseMessage(String adapterGroupName, String adapterName,
|
||||||
Properties callProp, String code, Throwable e, String adptMsgType, String encode, String errorResponseFormat) {
|
Properties callProp, Throwable e, String adptMsgType, String encode, String errorResponseFormat) {
|
||||||
String errorHandlerClass = AdapterPropManager.getInstance().getProperty(adapterName, "ERR_MSG_HANDLER");
|
String errorHandlerClass = AdapterPropManager.getInstance().getProperty(adapterName, "ERR_MSG_HANDLER");
|
||||||
if (StringUtils.isNotBlank(errorHandlerClass)) {
|
if (StringUtils.isNotBlank(errorHandlerClass)) {
|
||||||
if (logger.isInfo())
|
if (logger.isInfo())
|
||||||
@@ -216,7 +187,6 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
if (handler != null) {
|
if (handler != null) {
|
||||||
Object resposne;
|
Object resposne;
|
||||||
try {
|
try {
|
||||||
callProp.put("INBOUND_RESULT_CODE", code);
|
|
||||||
resposne = handler.generateNonStandardInboundErrorResponseMessage(adapterGroupName, adapterName,
|
resposne = handler.generateNonStandardInboundErrorResponseMessage(adapterGroupName, adapterName,
|
||||||
callProp, null, null, e);
|
callProp, null, null, e);
|
||||||
return (String)resposne;
|
return (String)resposne;
|
||||||
@@ -227,7 +197,7 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
return MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||||
code, e.getMessage(), errorResponseFormat);
|
MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -243,15 +213,14 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(logger.isDebug()) {
|
// * manager 출력
|
||||||
logger.debug("===== adptUriMap 상세 내용 =====");
|
logger.warn("===== adptUriMap 상세 내용 =====");
|
||||||
for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
||||||
HttpDynamicInAdapterUri uriObj = entry.getValue();
|
HttpDynamicInAdapterUri uriObj = entry.getValue();
|
||||||
logger.debug("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
logger.warn("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
||||||
+ uriObj.getUri());
|
+ uriObj.getUri());
|
||||||
}
|
|
||||||
logger.debug("================================");
|
|
||||||
}
|
}
|
||||||
|
logger.warn("================================");
|
||||||
|
|
||||||
//
|
//
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
@@ -281,14 +250,21 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
String errorCode = "RECEAIIRP010";
|
String errorCode = "RECEAIIRP010";
|
||||||
String[] msgArgs = new String[1];
|
String[] msgArgs = new String[1];
|
||||||
msgArgs[0] = request.getRequestURI();
|
msgArgs[0] = request.getRequestURI();
|
||||||
this.logError(request, "HTTP_IN_NO_URI", errorCode,
|
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||||
|
String serverName = eaiServerManager.getLocalServerName();
|
||||||
|
|
||||||
|
String instanceid1 = serverName.substring(0, 2);
|
||||||
|
String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||||
|
String instid = instanceid1 + instanceid2;
|
||||||
|
String uuid = instid + UUIDGenerator.getUUID();
|
||||||
|
this.logError(request, uuid, "HTTP_IN_NO_URI", errorCode,
|
||||||
ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs), null, null);
|
ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs), null, null);
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
logger.warn("inbound logging failed", t);
|
logger.warn("inbound logging failed", t);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void logError(HttpServletRequest request, String adapterGroupName, String errorCode,
|
private void logError(HttpServletRequest request, String uuid, String adapterGroupName, String errorCode,
|
||||||
String errorMsg, Properties prop, Exception e) {
|
String errorMsg, Properties prop, Exception e) {
|
||||||
try {
|
try {
|
||||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||||
@@ -296,15 +272,7 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
|
|
||||||
InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||||
|
|
||||||
String txId = prop.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
||||||
if (StringUtils.isEmpty(txId)) {
|
|
||||||
String instanceid1 = serverName.substring(0, 2);
|
|
||||||
String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
|
||||||
String instid = instanceid1 + instanceid2;
|
|
||||||
txId = instid + UUIDGenerator.getUUID();
|
|
||||||
}
|
|
||||||
|
|
||||||
errorInfoVO.setEaiSvcSno(txId); // EAI서비스일련번호
|
|
||||||
errorInfoVO.setAdptBwkGrpNm(adapterGroupName); // 어댑터업무그룹명
|
errorInfoVO.setAdptBwkGrpNm(adapterGroupName); // 어댑터업무그룹명
|
||||||
errorInfoVO.setErrCd(errorCode); // 에러코드
|
errorInfoVO.setErrCd(errorCode); // 에러코드
|
||||||
errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.eactive.eai.adapter.controller;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import javax.servlet.ServletException;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
public class TokenRedirectController {
|
||||||
|
|
||||||
|
@PostMapping("/sample/v1/oauth/token")
|
||||||
|
public void redirectPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||||
|
// 포워딩할 URL을 지정
|
||||||
|
String targetUrl = "/api/v1/oauth/token";
|
||||||
|
// 요청과 응답을 다른 URL로 포워딩
|
||||||
|
request.getRequestDispatcher(targetUrl).forward(request, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-17
@@ -1,23 +1,20 @@
|
|||||||
package com.eactive.eai.adapter.interceptor;
|
package com.eactive.eai.adapter.interceptor;
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import org.apache.commons.lang.StringUtils;
|
|
||||||
import org.springframework.web.servlet.HandlerInterceptor;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||||
import com.eactive.eai.common.TransactionContextKeys;
|
import com.eactive.eai.common.TransactionContextKeys;
|
||||||
import com.eactive.eai.common.logger.HttpAdapterExtraHeaderVo;
|
|
||||||
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
|
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
|
||||||
import com.eactive.eai.common.util.Logger;
|
import com.eactive.eai.common.util.Logger;
|
||||||
|
|
||||||
|
import org.apache.commons.lang.StringUtils;
|
||||||
|
import org.springframework.web.servlet.HandlerInterceptor;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
|
public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
|
||||||
|
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||||
@@ -58,11 +55,6 @@ public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
|
|||||||
logger.debug(String.format( "httpHeader logging Interceptor headerKey=%s, headerValue=%s", headerName, headerValue));
|
logger.debug(String.format( "httpHeader logging Interceptor headerKey=%s, headerValue=%s", headerName, headerValue));
|
||||||
headerMap.put(headerName, headerValue);
|
headerMap.put(headerName, headerValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
String body = transactionProp.getProperty(HttpAdapterExtraLogUtil.BODY_FIELD_NAME);
|
|
||||||
if (StringUtils.isNotEmpty(body)) {
|
|
||||||
headerMap.put(HttpAdapterExtraLogUtil.BODY_FIELD_NAME, body);
|
|
||||||
}
|
|
||||||
|
|
||||||
int httpStatusCode = response.getStatus();
|
int httpStatusCode = response.getStatus();
|
||||||
HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName, adapterName, headerMap, url, method, httpStatusCode);
|
HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName, adapterName, headerMap, url, method, httpStatusCode);
|
||||||
|
|||||||
@@ -0,0 +1,847 @@
|
|||||||
|
package com.eactive.eai.adapter.service;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||||
|
import com.eactive.eai.adapter.AdapterPropManager;
|
||||||
|
import com.eactive.eai.adapter.AdapterVO;
|
||||||
|
import com.eactive.eai.adapter.Keys;
|
||||||
|
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||||
|
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthFilter;
|
||||||
|
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||||
|
import com.eactive.eai.common.message.MessageType;
|
||||||
|
import com.eactive.eai.common.util.CommonLib;
|
||||||
|
import com.eactive.eai.common.util.Logger;
|
||||||
|
import com.eactive.eai.inbound.action.ActionFactory;
|
||||||
|
import com.eactive.eai.inbound.action.RequestAction;
|
||||||
|
import com.eactive.eai.inbound.processor.Processor;
|
||||||
|
import com.eactive.eai.message.StandardMessageUtil;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.apache.commons.lang3.time.StopWatch;
|
||||||
|
import org.apache.mina.common.ByteBuffer;
|
||||||
|
import org.json.simple.JSONObject;
|
||||||
|
import org.json.simple.JSONValue;
|
||||||
|
import org.json.simple.parser.JSONParser;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.util.AntPathMatcher;
|
||||||
|
|
||||||
|
import javax.servlet.ServletInputStream;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import java.net.URLDecoder;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
//for encrypt/decrypt jwhong
|
||||||
|
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||||
|
import com.kjbank.encrypt.exchange.crypto.AES256Cipher;
|
||||||
|
import com.kjbank.encrypt.exchange.crypto.AESCipher;
|
||||||
|
import com.kjbank.encrypt.exchange.crypto.AES256GCMCipher;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.ObjectOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import org.springframework.security.oauth2.provider.ClientDetails;
|
||||||
|
import com.nimbusds.jwt.SignedJWT;
|
||||||
|
import com.eactive.eai.common.context.ElinkTransactionContext;
|
||||||
|
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class ApiAdapterService extends HttpAdapterServiceSupport {
|
||||||
|
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||||
|
|
||||||
|
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||||
|
public static final String HTTP_STATUS = "HTTP_STATUS"; // jwhong
|
||||||
|
// HEADER_GROUP JSON에 추가할 항목 정의, 없으면 전체 header 추가
|
||||||
|
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||||
|
public static final String PROPERTIES_NAME_HTTP_REQUEST_METHOD = "httpRequestMethod";
|
||||||
|
|
||||||
|
private static final String JSON_CONTENT_TYPE = "application/json";
|
||||||
|
private static final String JSON_FIELD_NAME = "json-body";
|
||||||
|
private static final String FILE_GROUP_NAME = "image-file";
|
||||||
|
private static final String UPLOAD_ROOT_PATH = "UPLOAD_ROOT_PATH";
|
||||||
|
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id"; // jwhong
|
||||||
|
private boolean encryptResponseApply; // inbound에 대한 응답 암호화 여부 flag
|
||||||
|
|
||||||
|
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp, AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
|
||||||
|
int traceLevel = 0;
|
||||||
|
|
||||||
|
AdapterPropManager manager = null;
|
||||||
|
String adptGrpName = adapterGroupVO.getName();
|
||||||
|
String adptName = adapterVO.getName();
|
||||||
|
|
||||||
|
String urlDecodeYn = httpProp.getProperty(URL_DECODE_YN, "N");
|
||||||
|
String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||||
|
|
||||||
|
String traceLevelTemp = httpProp.getProperty(TRACE_LEVEL, "0");
|
||||||
|
String relayRequestHeaderKeys = httpProp.getProperty(HEADER_KEYS);
|
||||||
|
String headerGroupName = httpProp.getProperty(HEADER_GROUP);
|
||||||
|
|
||||||
|
boolean isParameterType = false;
|
||||||
|
String message = null;
|
||||||
|
|
||||||
|
String paramValue = null;
|
||||||
|
String adptMsgType = null;
|
||||||
|
|
||||||
|
transactionProp.put(INBOUND_METHOD, request.getMethod());
|
||||||
|
transactionProp.put(INBOUND_URI, request.getRequestURI());
|
||||||
|
transactionProp.put(INBOUND_HEADER, getHeaders(request));
|
||||||
|
transactionProp.put(INBOUND_EXTPARAMS, StringUtils.defaultString(request.getQueryString()));
|
||||||
|
if (StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_REST)
|
||||||
|
|| StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_HTTP_CUSTOM)) {
|
||||||
|
// /api/v1/public/getUserInfo.svc
|
||||||
|
String extUrl = StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
|
||||||
|
transactionProp.put(INBOUND_EXTURI, extUrl);
|
||||||
|
} else {
|
||||||
|
transactionProp.put(INBOUND_EXTURI, getExtUri(request));
|
||||||
|
}
|
||||||
|
transactionProp.put(INBOUND_CLIENT_IP, getClientIp(request)); // Client IP 추가
|
||||||
|
transactionProp.put(Processor.REQUEST_ACTION, adapterVO.getAdapterGroupVO().getRefClass());
|
||||||
|
transactionProp.put(API_PATH, httpProp.getProperty(API_PATH, ""));
|
||||||
|
transactionProp.put(PRE_FILTERS, httpProp.getProperty(PRE_FILTERS, ""));
|
||||||
|
transactionProp.put(POST_FILTERS, httpProp.getProperty(POST_FILTERS, ""));
|
||||||
|
transactionProp.put(PROPERTIES_NAME_HTTP_REQUEST_METHOD, request.getMethod());
|
||||||
|
transactionProp.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
|
||||||
|
transactionProp.put("BLOCK_IP", httpProp.getProperty("BLOCK_IP", ""));
|
||||||
|
|
||||||
|
transactionProp.put(ENC_PATHS, httpProp.getProperty(ENC_PATHS, ""));
|
||||||
|
|
||||||
|
transactionProp.put(ENCRYPT_ALGORITHM, httpProp.getProperty(ENCRYPT_ALGORITHM, "")); //jwhong
|
||||||
|
if (getHeaders(request).get(HEADER_NAME_CLIENT_ID) != null) { // jwhong
|
||||||
|
transactionProp.put(HEADER_NAME_CLIENT_ID, getHeaders(request).get(HEADER_NAME_CLIENT_ID));
|
||||||
|
}
|
||||||
|
transactionProp.put(ENCRYPT_BASE_TYPE, httpProp.getProperty(ENCRYPT_BASE_TYPE, "")); //jwhong
|
||||||
|
// //transactionProp.put(INBOUND_TOKEN, getHeaders(request).get(INBOUND_TOKEN)); // jwhong
|
||||||
|
// transactionProp.put(INBOUND_TOKEN, getHeaders(request).get(INBOUND_TOKEN) != null ? getHeaders(request).get(INBOUND_TOKEN) : ""); //jwhong , null 이면 default로 "" put
|
||||||
|
String inboundToken = getHeaders(request).getOrDefault(INBOUND_TOKEN, "").toString();
|
||||||
|
if (StringUtils.isNotBlank(inboundToken) && StringUtils.startsWith(inboundToken, "Bearer ")) {
|
||||||
|
inboundToken = inboundToken.substring(7);
|
||||||
|
}
|
||||||
|
transactionProp.put(INBOUND_TOKEN, inboundToken);
|
||||||
|
transactionProp.put(ENCRYPT_AES256_IV, httpProp.getProperty(ENCRYPT_AES256_IV, "")); //jwhong
|
||||||
|
transactionProp.put(ENCRYPT_AES256_KEY, httpProp.getProperty(ENCRYPT_AES256_KEY, "")); //jwhong
|
||||||
|
|
||||||
|
// SEED 컬럼암호하 시 Key로 사용함
|
||||||
|
String seedkey = getHeaders(request).getOrDefault("x-obp-partnercode", "").toString();
|
||||||
|
ElinkTransactionContext.setSeedKey(seedkey);
|
||||||
|
|
||||||
|
try {
|
||||||
|
traceLevel = Integer.parseInt(traceLevelTemp);
|
||||||
|
} catch (Exception e) {
|
||||||
|
traceLevel = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
StopWatch stopWatch = new StopWatch();
|
||||||
|
stopWatch.start();
|
||||||
|
|
||||||
|
logger.debug("시작 >> encode = [" + encode + "]");
|
||||||
|
|
||||||
|
switch (HttpMethodType.getValue(request.getMethod())) {
|
||||||
|
case GET:
|
||||||
|
case DELETE:
|
||||||
|
isParameterType = true;
|
||||||
|
break;
|
||||||
|
case POST:
|
||||||
|
case PUT:
|
||||||
|
if (StringUtils.contains(request.getContentType(), "application/x-www-form-urlencoded")) {
|
||||||
|
isParameterType = true;
|
||||||
|
} else if ( StringUtils.isNoneBlank(request.getQueryString()) ) { // jwhong
|
||||||
|
isParameterType = true;
|
||||||
|
} else {
|
||||||
|
isParameterType = false;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isParameterType) {
|
||||||
|
paramValue = request.getQueryString();
|
||||||
|
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(paramValue)); // Filter에서 QueryString 검증을 위해 저장
|
||||||
|
if (paramValue == null)
|
||||||
|
paramValue = "";
|
||||||
|
if (traceLevel >= 3) {
|
||||||
|
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||||
|
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(paramValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
// json으로 변환
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
sb.append("{");
|
||||||
|
Map<String, String[]> paramMap = assignParameterMap(request, adptGrpName, adptName, null, transactionProp);
|
||||||
|
int i = 0;
|
||||||
|
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
|
||||||
|
if (i > 0) {
|
||||||
|
sb.append(",");
|
||||||
|
}
|
||||||
|
sb.append("\"").append(entry.getKey()).append("\":");
|
||||||
|
String[] values = entry.getValue();
|
||||||
|
if (values.length > 1) {
|
||||||
|
// ["111", "222"]
|
||||||
|
sb.append("[");
|
||||||
|
for (int j = 0; j < values.length; j++) {
|
||||||
|
if (j > 0) {
|
||||||
|
sb.append(",");
|
||||||
|
}
|
||||||
|
sb.append("\"").append(JSONValue.escape(values[j])).append("\"");
|
||||||
|
}
|
||||||
|
sb.append("]");
|
||||||
|
} else {
|
||||||
|
sb.append("\"").append(JSONValue.escape(values[0])).append("\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.append("}");
|
||||||
|
|
||||||
|
paramValue = sb.toString();
|
||||||
|
|
||||||
|
if (logger.isDebug()) {
|
||||||
|
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
||||||
|
+ CommonLib.getDumpMessage(paramValue.getBytes(encode)));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (request.getContentLength() > 0) {
|
||||||
|
ServletInputStream sis = request.getInputStream();
|
||||||
|
ByteBuffer bb = ByteBuffer.allocate(1024).setAutoExpand(true);
|
||||||
|
int i = 0;
|
||||||
|
byte[] cbuf = new byte[1024];
|
||||||
|
while ((i = sis.read(cbuf, 0, 1024)) != -1) {
|
||||||
|
if (i == 1024) {
|
||||||
|
bb.put(cbuf);
|
||||||
|
} else {
|
||||||
|
byte[] tail = new byte[i];
|
||||||
|
System.arraycopy(cbuf, 0, tail, 0, i);
|
||||||
|
bb.put(tail);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
byte[] data = new byte[bb.position()];
|
||||||
|
bb.position(0);
|
||||||
|
bb.get(data);
|
||||||
|
paramValue = new String(data, encode);
|
||||||
|
|
||||||
|
if (traceLevel >= 3) {
|
||||||
|
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||||
|
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (logger.isDebug()) {
|
||||||
|
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
||||||
|
+ CommonLib.getDumpMessage(data));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (paramValue == null) { // parameter가 없는 경우때문에 처리
|
||||||
|
paramValue = "";
|
||||||
|
}
|
||||||
|
// 순수한 Body값을 저장을 위해 위치 변경.
|
||||||
|
transactionProp.put(INBOUND_REQUEST_MESSAGE, paramValue);
|
||||||
|
|
||||||
|
// paramValue가 null이 아닌 빈문자열(""," ")인 경우에 대비하여 조건 수정.
|
||||||
|
if (StringUtils.isNotBlank(paramValue)) { // jwhong decrypt
|
||||||
|
paramValue = doPreDecryption(paramValue, transactionProp, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ("Y".equals(urlDecodeYn) && isParameterType) {
|
||||||
|
message = URLDecoder.decode(paramValue);
|
||||||
|
} else {
|
||||||
|
message = paramValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (logger.isDebug()) {
|
||||||
|
String[] msgArgs = new String[2];
|
||||||
|
msgArgs[0] = adptGrpName;
|
||||||
|
msgArgs[1] = message;
|
||||||
|
String resMsg = ExceptionUtil.make("RICEAIAHA005", msgArgs);
|
||||||
|
logger.debug(resMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||||
|
// HttpHeaders responseHeaders = new HttpHeaders();
|
||||||
|
// responseHeaders.setContentType(MediaType.valueOf("application/json;charset=" + encode));
|
||||||
|
|
||||||
|
|
||||||
|
// HEADER_GROUP 셋팅
|
||||||
|
if (MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)
|
||||||
|
&& StringUtils.isNotBlank(relayRequestHeaderKeys)) {
|
||||||
|
JSONObject jsonMessage = (JSONObject) JSONValue.parse(message);
|
||||||
|
JSONObject headerJson = new JSONObject();
|
||||||
|
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||||
|
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
||||||
|
String key = e.nextElement();
|
||||||
|
headerJson.put(key, request.getHeader(key));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
String[] relayKeyArr = org.springframework.util.StringUtils
|
||||||
|
.tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
||||||
|
|
||||||
|
for (String key : relayKeyArr) {
|
||||||
|
String headerValue = request.getHeader(key);
|
||||||
|
if (StringUtils.isNotBlank(headerValue)) {
|
||||||
|
headerJson.put(key, headerValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (headerJson.size() > 0) {
|
||||||
|
jsonMessage.put(headerGroupName, headerJson);
|
||||||
|
message = jsonMessage.toJSONString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message == null) {
|
||||||
|
message = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
|
||||||
|
// transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
|
||||||
|
// 로컬 서비스 호출 ,encoding 처리 추가
|
||||||
|
String result = (String) service(adptGrpName, adptName, message, transactionProp, request, response);
|
||||||
|
|
||||||
|
if (logger.isDebug()) {
|
||||||
|
logger.debug("HttpAdapterServiceRest] result " + encode + " (" + adptGrpName + ") = [" + result + "]");
|
||||||
|
}
|
||||||
|
|
||||||
|
stopWatch.stop();
|
||||||
|
|
||||||
|
String syncAsyncType = transactionProp.getProperty(INBOUND_SYNC_ASYNC_TYPE);
|
||||||
|
|
||||||
|
if (!"ASYN".equals(syncAsyncType) && MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)) {
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
ObjectNode rootNode = (ObjectNode) mapper.readTree(result);
|
||||||
|
JsonNode headerGroup = rootNode.get(headerGroupName);
|
||||||
|
if(headerGroup != null) {
|
||||||
|
for(Iterator<String> it = headerGroup.fieldNames(); it.hasNext();) {
|
||||||
|
String name = it.next();
|
||||||
|
String value = headerGroup.get(name).asText();
|
||||||
|
response.addHeader(name, value);
|
||||||
|
}
|
||||||
|
rootNode.remove(headerGroupName);
|
||||||
|
result = mapper.writeValueAsString(rootNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// KJBank는 요청에 대한 응답 (Sync응답, Aync 에 대한 Ack응답) 에 대하여 암호화 하지 않는다. 무조건 안한다. 따라서 아래부분은 구현은 했지만 사용하지 않는다.
|
||||||
|
// 위 2가지 경우 암호화 하는걸로 요청 변경되어 아래 암호화 수행하도록 수정함
|
||||||
|
encryptResponseApply = StringUtils.equalsIgnoreCase(httpProp.getProperty("ENCRYPT_RESPONSE_APPLY", "N"), "Y");
|
||||||
|
if ( encryptResponseApply) {
|
||||||
|
result = doPostEncryption(result, transactionProp, request); // jwhong Encrypt
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// jwhong decrypt
|
||||||
|
|
||||||
|
private String doPreDecryption(String eaiBody, Properties transactionProp, HttpServletRequest request) throws Exception {
|
||||||
|
String decryptAlgorithm = transactionProp.getProperty(ENCRYPT_ALGORITHM, "");
|
||||||
|
String xElinkClientId = transactionProp.getProperty(HEADER_NAME_CLIENT_ID, ""); // 이 값이 OAuth의 client id 값이다 . http header 에 포함되어 온다. jwhong
|
||||||
|
String encryptBaseKeyType = transactionProp.getProperty(ENCRYPT_BASE_TYPE);
|
||||||
|
//String inboundToken2 = transactionProp.getProperty(INBOUND_TOKEN, ""); // 이건 token 값이 아니고 authorization 값이다
|
||||||
|
String inboundToken = "";
|
||||||
|
|
||||||
|
String secretAES256Iv = transactionProp.getProperty("ENCRYPT_AES256_IV");
|
||||||
|
String secretAES256Key = transactionProp.getProperty("ENCRYPT_AES256_KEY");
|
||||||
|
|
||||||
|
if ( decryptAlgorithm == "" ) { // 복호화 대상이 아님
|
||||||
|
return eaiBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
inboundToken = JwtTokenExtractor(request);
|
||||||
|
xElinkClientId = JwtClientIdExtractor(inboundToken); // token에서 client id를 추출함
|
||||||
|
|
||||||
|
// 암호화 key를 token 내용으로 할지 client secret 내용으로 할지 결정함. adapter property에 정의함
|
||||||
|
// ENCRYPT_ALGORITHM 을 설정했는데 ENCRYPT_BASE_TYPE을 설정안하면 Decrypt 수행시 Exception 발생함
|
||||||
|
String clientSecret = "";
|
||||||
|
if ("TOKEN".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||||
|
clientSecret = inboundToken;
|
||||||
|
} else if ( "SECRETKEY".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||||
|
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||||
|
ClientDetails clientDetail = manager.getClientDeatilsStore().get(xElinkClientId);
|
||||||
|
|
||||||
|
if ( clientDetail != null ) { // 여기서 not null 이라는 것은 apim oauth server에서 발급된 token 임.
|
||||||
|
// 즉 KJBank 에서 요청이 들어온 것이다.
|
||||||
|
clientSecret = clientDetail.getClientSecret();
|
||||||
|
} // 그럼 업체에서 요청이 들어오면?? 업체도 apim oauth server에서 발급된 token을 사용하는것이다.
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] decryptedMessage = null;
|
||||||
|
decryptedMessage = doInboundPreDecrypt(eaiBody, decryptAlgorithm,clientSecret,secretAES256Iv, secretAES256Key );
|
||||||
|
|
||||||
|
if (decryptedMessage == null) {
|
||||||
|
throw new Exception("[ApiAdapterService] Decrypt Error : Invalid encrypted message");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
String resultMessage = new String(decryptedMessage, StandardCharsets.UTF_8 );
|
||||||
|
return resultMessage;
|
||||||
|
//return new String(decryptedMessage, StandardCharsets.UTF_8 );
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// jwhong encrypt
|
||||||
|
public String doPostEncryption(String eaiBody, Properties transactionProp, HttpServletRequest request) throws Exception {
|
||||||
|
|
||||||
|
String decryptAlgorithm = transactionProp.getProperty(ENCRYPT_ALGORITHM, "");
|
||||||
|
String xElinkClientId = transactionProp.getProperty(HEADER_NAME_CLIENT_ID, ""); // 이 값이 OAuth의 client id 값이다 . http header 에 포함되어 온다. jwhong
|
||||||
|
String encryptBaseKeyType = transactionProp.getProperty(ENCRYPT_BASE_TYPE);
|
||||||
|
String inboundToken = "";
|
||||||
|
|
||||||
|
String secretAES256Iv = transactionProp.getProperty("ENCRYPT_AES256_IV");
|
||||||
|
String secretAES256Key = transactionProp.getProperty("ENCRYPT_AES256_KEY");
|
||||||
|
|
||||||
|
if ( decryptAlgorithm == "" ) { // 복호화 대상이 아님
|
||||||
|
return eaiBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
inboundToken = JwtTokenExtractor(request);
|
||||||
|
xElinkClientId = JwtClientIdExtractor(inboundToken); // token에서 client id를 추출함
|
||||||
|
|
||||||
|
// 암호화 key를 token 내용으로 할지 client secret 내용으로 할지 결정함. adapter property에 정의함
|
||||||
|
// ENCRYPT_ALGORITHM 을 설정했는데 ENCRYPT_BASE_TYPE을 설정안하면 Decrypt 수행시 Exception 발생함
|
||||||
|
String clientSecret = "";
|
||||||
|
if ("TOKEN".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||||
|
clientSecret = inboundToken;
|
||||||
|
} else if ( "SECRETKEY".equalsIgnoreCase(encryptBaseKeyType)) {
|
||||||
|
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||||
|
ClientDetails clientDetail = manager.getClientDeatilsStore().get(xElinkClientId);
|
||||||
|
|
||||||
|
if ( clientDetail != null ) {
|
||||||
|
clientSecret = clientDetail.getClientSecret();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String encryptedMessage = null;
|
||||||
|
encryptedMessage = doInboundPostEncrypt(eaiBody, decryptAlgorithm,clientSecret,secretAES256Iv, secretAES256Key );
|
||||||
|
|
||||||
|
if (encryptedMessage == null) {
|
||||||
|
throw new Exception("[ApiAdapterService] Encrypt Error : Invalid PlainText message");
|
||||||
|
}
|
||||||
|
|
||||||
|
return encryptedMessage;
|
||||||
|
//String resultMessage = new String(encryptedMessage, StandardCharsets.UTF_8 );
|
||||||
|
//return resultMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private byte[] convertObjectToBytes(Object obj) throws IOException {
|
||||||
|
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||||
|
ObjectOutputStream oos = new ObjectOutputStream(bos);
|
||||||
|
oos.writeObject(obj);
|
||||||
|
oos.flush();
|
||||||
|
return bos.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] convertObjectToBase64Bytes(Object obj) throws IOException {
|
||||||
|
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||||
|
ObjectOutputStream oos = new ObjectOutputStream(bos);
|
||||||
|
oos.writeObject(obj);
|
||||||
|
oos.flush();
|
||||||
|
oos.close();
|
||||||
|
|
||||||
|
// 직렬화된 byte[] → Base64 문자열 → 다시 byte[]로 변환
|
||||||
|
String base64String = Base64.getEncoder().encodeToString(bos.toByteArray());
|
||||||
|
return base64String.getBytes(StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object convertBytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
|
||||||
|
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(bis)) {
|
||||||
|
return ois.readObject();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private byte[] doInboundPreDecrypt(String eaiStringBody, String decryptAlgorithm, String clientSecretKey, String secretAES256Iv, String secretAES256Key) throws Exception {
|
||||||
|
|
||||||
|
byte[] decryptedMessage = null;
|
||||||
|
//String eaiStringBody = new String(eaiBody, StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
eaiStringBody = extractBodyMsg(decryptAlgorithm, eaiStringBody);
|
||||||
|
|
||||||
|
if (eaiStringBody == null) {
|
||||||
|
throw new Exception("[ApiAdapterService] Cannot decrypt Error : input is plain text");
|
||||||
|
}
|
||||||
|
|
||||||
|
//test source
|
||||||
|
logger.debug("Base64 문자열: " + eaiStringBody);
|
||||||
|
logger.debug("Base64 문자열 길이: " + eaiStringBody.length());
|
||||||
|
logger.debug("Base64 문자열 끝: " + eaiStringBody.substring(eaiStringBody.length() - 10));
|
||||||
|
|
||||||
|
// Base64 디코딩 테스트
|
||||||
|
try {
|
||||||
|
byte[] decoded = Base64.getDecoder().decode(eaiStringBody);
|
||||||
|
logger.debug("디코딩 성공, 길이: " + decoded.length);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
logger.debug("Base64 디코딩 실패: " + e.getMessage());
|
||||||
|
}
|
||||||
|
// end test source
|
||||||
|
|
||||||
|
switch (decryptAlgorithm) {
|
||||||
|
case "AES128":
|
||||||
|
case "AES128-TOSS":
|
||||||
|
try {
|
||||||
|
String key128 = clientSecretKey.substring(22,38); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||||
|
//String decryptedStrMessage = AESCipher.decrypt(eaiStringBody, key128);
|
||||||
|
String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
|
||||||
|
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "AES128-TOGETHER":
|
||||||
|
try {
|
||||||
|
String key128 = clientSecretKey.substring(44,60); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||||
|
//String decryptedStrMessage = AESCipher.decrypt(eaiStringBody, key128);
|
||||||
|
String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
|
||||||
|
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "AES256":
|
||||||
|
try {
|
||||||
|
String key = clientSecretKey.substring(10,42);
|
||||||
|
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, key);
|
||||||
|
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "AES256-KAKAO":
|
||||||
|
try {
|
||||||
|
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||||
|
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "AES256-TOSS":
|
||||||
|
try {
|
||||||
|
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||||
|
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "AES256GCM":
|
||||||
|
try {
|
||||||
|
byte[] key = AES256GCMCipher.generateKey();
|
||||||
|
AES256GCMCipher cipher = new AES256GCMCipher(key);
|
||||||
|
byte[] aad = "metadata".getBytes();
|
||||||
|
|
||||||
|
String decryptedStrMessage = cipher.decrypt(eaiStringBody , aad);
|
||||||
|
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
try {
|
||||||
|
decryptedMessage = eaiStringBody.getBytes();
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] doOutboundPostFilter Array copy error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return decryptedMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String extractBodyMsg(String decryptAlgorithm, String eaiStringBody) {
|
||||||
|
|
||||||
|
String decryptedJsonKey = "";
|
||||||
|
String decryptedBodyMessage = "";
|
||||||
|
|
||||||
|
decryptedJsonKey = getJsonKey(decryptAlgorithm);
|
||||||
|
|
||||||
|
try {
|
||||||
|
JSONParser parser = new JSONParser();
|
||||||
|
JSONObject jsonObject = (JSONObject) parser.parse(eaiStringBody);
|
||||||
|
decryptedBodyMessage = (String) jsonObject.get(decryptedJsonKey);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClient5AdapterServiceRest] extractBodyMsg error : " + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return decryptedBodyMessage;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getJsonKey(String Algorithm) {
|
||||||
|
|
||||||
|
String jsonKey = "";
|
||||||
|
|
||||||
|
switch (Algorithm) {
|
||||||
|
case "AES128":
|
||||||
|
case "AES128-TOSS":
|
||||||
|
jsonKey = "preScreeningRequest";
|
||||||
|
break;
|
||||||
|
case "AES128-TOGETHER":
|
||||||
|
jsonKey = "obpTxData";
|
||||||
|
break;
|
||||||
|
case "AES256":
|
||||||
|
jsonKey = "preScreeningRequest";
|
||||||
|
break;
|
||||||
|
case "AES256-KAKAO":
|
||||||
|
jsonKey = "encrypted_data";
|
||||||
|
break;
|
||||||
|
case "AES256-TOSS":
|
||||||
|
jsonKey = "encryptedData";
|
||||||
|
break;
|
||||||
|
case "AES256-NICEON":
|
||||||
|
jsonKey = "enc_data";
|
||||||
|
break;
|
||||||
|
case "AES256GCM":
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return jsonKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String doInboundPostEncrypt(String eaiStringBody, String encryptAlgorithm, String clientSecretKey, String secretAES256Iv, String secretAES256Key) {
|
||||||
|
|
||||||
|
//byte[] encryptedMessage = null;
|
||||||
|
String encryptedStrMessage = null;
|
||||||
|
String encryptedJsonKey = "";
|
||||||
|
|
||||||
|
encryptedJsonKey = getJsonKey(encryptAlgorithm);
|
||||||
|
|
||||||
|
switch (encryptAlgorithm) {
|
||||||
|
case "AES128":
|
||||||
|
case "AES128-TOSS":
|
||||||
|
try {
|
||||||
|
String key128 = clientSecretKey.substring(22,38); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||||
|
encryptedStrMessage = AESCipher.encrypt(eaiStringBody, key128);
|
||||||
|
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "AES128-TOGETHER":
|
||||||
|
try {
|
||||||
|
String key128 = clientSecretKey.substring(44,60); //togetherEncoder 경우는 substring(44,60) 이네??
|
||||||
|
encryptedStrMessage = AESCipher.encrypt(eaiStringBody, key128);
|
||||||
|
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "AES256":
|
||||||
|
try {
|
||||||
|
String key = clientSecretKey.substring(10,42);
|
||||||
|
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, key);
|
||||||
|
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "AES256-KAKAO":
|
||||||
|
try {
|
||||||
|
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||||
|
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "AES256-TOSS":
|
||||||
|
try {
|
||||||
|
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
||||||
|
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "AES256GCM":
|
||||||
|
try {
|
||||||
|
byte[] key = AES256GCMCipher.generateKey();
|
||||||
|
AES256GCMCipher cipher = new AES256GCMCipher(key);
|
||||||
|
byte[] aad = "metadata".getBytes();
|
||||||
|
|
||||||
|
encryptedStrMessage = cipher.encrypt(eaiStringBody , aad);
|
||||||
|
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
try {
|
||||||
|
encryptedStrMessage = eaiStringBody;
|
||||||
|
//encryptedMessage = eaiStringBody.getBytes();
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
logger.error("HttpClientAdapterServiceRest] doOutboundPostFilter Array copy error=" + e.getMessage());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> map = new HashMap<>();
|
||||||
|
map.put(encryptedJsonKey, encryptedStrMessage);
|
||||||
|
JSONObject json = new JSONObject();
|
||||||
|
json.putAll(map);
|
||||||
|
return json.toJSONString();
|
||||||
|
//return encryptedMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
private String JwtTokenExtractor(HttpServletRequest request) {
|
||||||
|
|
||||||
|
String Token = "";
|
||||||
|
try {
|
||||||
|
Token = JwtAuthFilter.extractJWTToken(request);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug("Token is: " + Token);
|
||||||
|
return Token;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private String JwtClientIdExtractor(String inboundToken) {
|
||||||
|
|
||||||
|
String tokenClientId ="";
|
||||||
|
try {
|
||||||
|
SignedJWT signedJWT = SignedJWT.parse(inboundToken);
|
||||||
|
tokenClientId = (String) signedJWT.getJWTClaimsSet().getClaim(PAYLOAD_PARAM_NAME_CLIENT_ID);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage());
|
||||||
|
tokenClientId = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug("Token Client ID: " + tokenClientId);
|
||||||
|
return tokenClientId;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// jwhong until here
|
||||||
|
|
||||||
|
|
||||||
|
private Map<String, String[]> assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName,
|
||||||
|
Object requestBytes, Properties prop) {
|
||||||
|
// PathVariable 체크
|
||||||
|
if (StringUtils.equalsAnyIgnoreCase(request.getMethod(), HttpMethod.GET.name(), HttpMethod.DELETE.name())
|
||||||
|
&& StringUtils.isBlank(request.getQueryString())) {
|
||||||
|
try {
|
||||||
|
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||||
|
RequestAction action = ActionFactory.createAction(actionName);
|
||||||
|
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||||
|
String[] keys = action.perform(requestBytes);
|
||||||
|
String requestPath = keys[0];
|
||||||
|
|
||||||
|
// PathVariable 지원 추가
|
||||||
|
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
||||||
|
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
||||||
|
Map<String, String> paramMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath,
|
||||||
|
requestPath);
|
||||||
|
if (paramMap != null && paramMap.size() > 0) {
|
||||||
|
Map<String, String[]> returnMap = new HashMap<>();
|
||||||
|
for (String key : paramMap.keySet()) {
|
||||||
|
if (StringUtils.equalsIgnoreCase(key, "method")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
returnMap.put(key, new String[] { paramMap.get(key) });
|
||||||
|
}
|
||||||
|
|
||||||
|
return returnMap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return request.getParameterMap();
|
||||||
|
}
|
||||||
|
|
||||||
|
private 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getExtUri(HttpServletRequest request) {
|
||||||
|
String orgUri = request.getRequestURI().replaceAll(request.getContextPath(), "");
|
||||||
|
String uri = getExtUri(orgUri, 3);
|
||||||
|
if (uri != null && uri.trim().length() > 0) {
|
||||||
|
return "/" + uri;
|
||||||
|
} else {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String getExtUri(String url, int length) {
|
||||||
|
String[] urls = url.split("/");
|
||||||
|
List<String> newUrls = new ArrayList<>();
|
||||||
|
Collections.addAll(newUrls, urls);
|
||||||
|
return StringUtils.join(newUrls.subList(length, urls.length).toArray(), "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Deprecated
|
||||||
|
public void service(String adptGrpName, String adptName, HttpServletRequest request, HttpServletResponse response) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP 요청에서 클라이언트 IP를 추출합니다.
|
||||||
|
* X-Forwarded-For 헤더가 있는 경우 이를 우선적으로 사용하고,
|
||||||
|
* 없는 경우 remoteAddr을 사용합니다.
|
||||||
|
*/
|
||||||
|
private String getClientIp(HttpServletRequest request) {
|
||||||
|
String ipAddress = request.getHeader("X-Forwarded-For");
|
||||||
|
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||||
|
ipAddress = request.getHeader("Proxy-Client-IP");
|
||||||
|
}
|
||||||
|
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||||
|
ipAddress = request.getHeader("WL-Proxy-Client-IP");
|
||||||
|
}
|
||||||
|
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||||
|
ipAddress = request.getHeader("HTTP_CLIENT_IP");
|
||||||
|
}
|
||||||
|
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||||
|
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||||
|
}
|
||||||
|
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||||
|
ipAddress = request.getRemoteAddr();
|
||||||
|
}
|
||||||
|
return ipAddress;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,9 +2,7 @@ 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;
|
||||||
@@ -12,8 +10,8 @@ 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 java.util.Set;
|
||||||
|
|
||||||
import javax.servlet.ServletInputStream;
|
import javax.servlet.ServletInputStream;
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
@@ -21,7 +19,6 @@ 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;
|
||||||
@@ -30,9 +27,10 @@ import org.dom4j.Element;
|
|||||||
import org.dom4j.Node;
|
import org.dom4j.Node;
|
||||||
import org.dom4j.io.OutputFormat;
|
import org.dom4j.io.OutputFormat;
|
||||||
import org.dom4j.io.XMLWriter;
|
import org.dom4j.io.XMLWriter;
|
||||||
|
import org.json.simple.JSONObject;
|
||||||
import org.json.simple.JSONValue;
|
import org.json.simple.JSONValue;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpMethod;
|
||||||
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;
|
||||||
@@ -44,24 +42,19 @@ 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.JSONUtils;
|
||||||
import com.eactive.eai.common.util.Logger;
|
import com.eactive.eai.common.util.Logger;
|
||||||
import com.eactive.eai.common.util.TxFileLogger;
|
import com.eactive.eai.common.util.TxFileLogger;
|
||||||
import com.eactive.eai.common.util.XMLUtils;
|
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.StandardMessage;
|
import com.eactive.eai.message.StandardMessageUtil;
|
||||||
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;
|
||||||
@@ -69,16 +62,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
|||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
||||||
|
|
||||||
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);
|
||||||
|
|
||||||
@@ -90,9 +73,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 = 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 {
|
||||||
int traceLevel = 0;
|
int traceLevel = 0;
|
||||||
|
|
||||||
@@ -106,6 +87,7 @@ 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;
|
||||||
@@ -141,6 +123,12 @@ 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
|
||||||
@@ -163,8 +151,6 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
transactionProp.put(HEADER_GROUP, headerGroupName);
|
transactionProp.put(HEADER_GROUP, headerGroupName);
|
||||||
transactionProp.put(HEADER_KEYS, relayRequestHeaderKeys);
|
transactionProp.put(HEADER_KEYS, relayRequestHeaderKeys);
|
||||||
|
|
||||||
transactionProp.put(ADAPTER_TOKEN_HEADER_NAME, httpProp.getProperty(ADAPTER_TOKEN_HEADER_NAME, "")); // OAuth 인증 토큰 헤더 이름
|
|
||||||
transactionProp.put(ADAPTER_APIKEY_HEADER_NAME, httpProp.getProperty(ADAPTER_APIKEY_HEADER_NAME, "")); // API-KEY 인증 헤더 이름
|
|
||||||
// SEED 컬럼암호하 시 Key로 사용함
|
// SEED 컬럼암호하 시 Key로 사용함
|
||||||
String seedkey = inboundHeaderProp.getOrDefault("x-obp-partnercode", "").toString();
|
String seedkey = inboundHeaderProp.getOrDefault("x-obp-partnercode", "").toString();
|
||||||
ElinkTransactionContext.setSeedKey(seedkey);
|
ElinkTransactionContext.setSeedKey(seedkey);
|
||||||
@@ -179,8 +165,74 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
stopWatch.start();
|
stopWatch.start();
|
||||||
|
|
||||||
logger.debug("시작 >> encode = [" + encode + "]");
|
logger.debug("시작 >> encode = [" + encode + "]");
|
||||||
String recvBody = "";
|
|
||||||
if (request.getContentLength() > 0) {
|
switch (HttpMethodType.getValue(request.getMethod())) {
|
||||||
|
case GET:
|
||||||
|
case DELETE:
|
||||||
|
isParameterType = true;
|
||||||
|
break;
|
||||||
|
case POST:
|
||||||
|
case PUT:
|
||||||
|
if (StringUtils.contains(request.getContentType(), "application/x-www-form-urlencoded")) {
|
||||||
|
isParameterType = true;
|
||||||
|
} else if ( StringUtils.isNoneBlank(request.getQueryString()) ) { // jwhong
|
||||||
|
isParameterType = true;
|
||||||
|
} else {
|
||||||
|
isParameterType = false;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isParameterType) {
|
||||||
|
paramValue = request.getQueryString();
|
||||||
|
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(paramValue)); // Filter에서 QueryString 검증을 위해 저장
|
||||||
|
if (paramValue == null)
|
||||||
|
paramValue = "";
|
||||||
|
if (traceLevel >= 3) {
|
||||||
|
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||||
|
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(paramValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
// json으로 변환
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
sb.append("{");
|
||||||
|
Map<String, String[]> paramMap = assignParameterMap(request, adptGrpName, adptName, null, transactionProp);
|
||||||
|
int i = 0;
|
||||||
|
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
|
||||||
|
if (i > 0) {
|
||||||
|
sb.append(",");
|
||||||
|
}
|
||||||
|
sb.append("\"").append(entry.getKey()).append("\":");
|
||||||
|
String[] values = entry.getValue();
|
||||||
|
if (values.length > 1) {
|
||||||
|
// ["111", "222"]
|
||||||
|
sb.append("[");
|
||||||
|
for (int j = 0; j < values.length; j++) {
|
||||||
|
if (j > 0) {
|
||||||
|
sb.append(",");
|
||||||
|
}
|
||||||
|
sb.append("\"").append(JSONValue.escape(values[j])).append("\"");
|
||||||
|
}
|
||||||
|
sb.append("]");
|
||||||
|
} else {
|
||||||
|
sb.append("\"").append(JSONValue.escape(values[0])).append("\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.append("}");
|
||||||
|
|
||||||
|
paramValue = sb.toString();
|
||||||
|
|
||||||
|
if (logger.isDebug()) {
|
||||||
|
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
||||||
|
+ CommonLib.getDumpMessage(paramValue.getBytes(encode)));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (request.getContentLength() > 0) {
|
||||||
ServletInputStream sis = request.getInputStream();
|
ServletInputStream sis = request.getInputStream();
|
||||||
ByteBuffer bb = ByteBuffer.allocate(1024).setAutoExpand(true);
|
ByteBuffer bb = ByteBuffer.allocate(1024).setAutoExpand(true);
|
||||||
int i = 0;
|
int i = 0;
|
||||||
@@ -200,68 +252,43 @@ 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) {}
|
||||||
}
|
}
|
||||||
recvBody = new String(data, bodyEncode);
|
paramValue = new String(data, bodyEncode);
|
||||||
|
|
||||||
if (traceLevel >= 3) {
|
if (traceLevel >= 3) {
|
||||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||||
"RECV " + "[" + recvBody + "]" + CommonLib.getDumpMessage(data));
|
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(data));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (logger.isDebug()) {
|
if (logger.isDebug()) {
|
||||||
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + recvBody + "]\n"
|
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\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]");
|
||||||
|
|
||||||
@@ -275,14 +302,48 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
|
|
||||||
|
|
||||||
adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||||
|
// HttpHeaders responseHeaders = new HttpHeaders();
|
||||||
|
// responseHeaders.setContentType(MediaType.valueOf("application/json;charset=" + encode));
|
||||||
|
|
||||||
|
// HEADER_GROUP 셋팅
|
||||||
|
// if (MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)
|
||||||
|
// && StringUtils.isNotBlank(relayRequestHeaderKeys)) {
|
||||||
|
// JSONObject jsonMessage = (JSONObject) JSONValue.parse(message);
|
||||||
|
// JSONObject headerJson = new JSONObject();
|
||||||
|
// if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||||
|
// for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
||||||
|
// String key = e.nextElement();
|
||||||
|
// headerJson.put(key, request.getHeader(key));
|
||||||
|
// }
|
||||||
|
// } else {
|
||||||
|
// String[] relayKeyArr = org.springframework.util.StringUtils
|
||||||
|
// .tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
||||||
|
//
|
||||||
|
// for (String key : relayKeyArr) {
|
||||||
|
// String headerValue = request.getHeader(key);
|
||||||
|
// if (StringUtils.isNotBlank(headerValue)) {
|
||||||
|
// headerJson.put(key, headerValue);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// if (headerJson.size() > 0) {
|
||||||
|
// jsonMessage.put(headerGroupName, headerJson);
|
||||||
|
// message = jsonMessage.toJSONString();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
Object reqObject = assignHeaderGroupRequestHeaders(adptGrpName, adptName, message,
|
Object reqObject = assignHeaderGroupRequestHeaders(adptGrpName, adptName, message,
|
||||||
transactionProp, request, response, adptMsgType);
|
transactionProp, request, response, adptMsgType);
|
||||||
|
|
||||||
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
|
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
|
||||||
// transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
|
// transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
|
||||||
|
// 로컬 서비스 호출 ,encoding 처리 추가
|
||||||
|
|
||||||
Object result = service(adptGrpName, adptName, reqObject, transactionProp, request, response);
|
ApiKeyExtractFilter apiKeyExtractor = new ApiKeyExtractFilter();
|
||||||
|
apiKeyExtractor.doPreFilter(adptGrpName, adptName, reqObject, transactionProp, request, response);
|
||||||
|
|
||||||
|
String result = (String) service(adptGrpName, adptName, reqObject, transactionProp, request, response);
|
||||||
|
|
||||||
// bypass만 필요
|
// bypass만 필요
|
||||||
applyOutboundResponseHeaders(transactionProp, response);
|
applyOutboundResponseHeaders(transactionProp, response);
|
||||||
@@ -296,9 +357,10 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
stopWatch.stop();
|
stopWatch.stop();
|
||||||
|
|
||||||
String syncAsyncType = transactionProp.getProperty(INBOUND_SYNC_ASYNC_TYPE);
|
String syncAsyncType = transactionProp.getProperty(INBOUND_SYNC_ASYNC_TYPE);
|
||||||
|
|
||||||
if (!"ASYN".equals(syncAsyncType) && MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)) {
|
if (!"ASYN".equals(syncAsyncType) && MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)) {
|
||||||
ObjectNode rootNode = (ObjectNode) JacksonUtil.readTree(result, mapper);
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
ObjectNode rootNode = (ObjectNode) mapper.readTree(result);
|
||||||
JsonNode headerGroup = rootNode.get(headerGroupName);
|
JsonNode headerGroup = rootNode.get(headerGroupName);
|
||||||
if(headerGroup != null) {
|
if(headerGroup != null) {
|
||||||
for(Iterator<String> it = headerGroup.fieldNames(); it.hasNext();) {
|
for(Iterator<String> it = headerGroup.fieldNames(); it.hasNext();) {
|
||||||
@@ -307,22 +369,23 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
response.addHeader(name, value);
|
response.addHeader(name, value);
|
||||||
}
|
}
|
||||||
rootNode.remove(headerGroupName);
|
rootNode.remove(headerGroupName);
|
||||||
result = rootNode;
|
result = mapper.writeValueAsString(rootNode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// KJBank는 요청에 대한 응답 (Sync응답, Aync 에 대한 Ack응답) 에 대하여 암호화 하지 않는다. 무조건 안한다. 따라서 아래부분은 구현은 했지만 사용하지 않는다.
|
||||||
|
// 위 2가지 경우 암호화 하는걸로 요청 변경되어 아래 암호화 수행하도록 수정함
|
||||||
|
// encryptResponseApply = StringUtils.equalsIgnoreCase(httpProp.getProperty("ENCRYPT_RESPONSE_APPLY", "N"), "Y");
|
||||||
|
// if ( encryptResponseApply) {
|
||||||
|
// result = doPostEncryption(result, transactionProp, request); // jwhong Encrypt
|
||||||
|
// }
|
||||||
|
|
||||||
String strResult = null;
|
return result;
|
||||||
if(result instanceof JsonNode)
|
|
||||||
strResult = OBJECT_MAPPER.writeValueAsString(result);
|
|
||||||
else
|
|
||||||
strResult = (String) result;
|
|
||||||
|
|
||||||
return strResult;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private Object assignHeaderGroupRequestHeaders(String adptGrpName, String adptName, Object message, Properties prop,
|
private Object assignHeaderGroupRequestHeaders(String adptGrpName, String adptName, Object message, Properties prop,
|
||||||
HttpServletRequest request, HttpServletResponse response, String adptMsgType) throws DocumentException, IOException, Exception {
|
HttpServletRequest request, HttpServletResponse response, String adptMsgType) throws DocumentException, IOException {
|
||||||
// XML 지원 개발
|
// XML 지원 개발
|
||||||
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
||||||
String relayRequestHeaderKeys = prop.getProperty(HEADER_KEYS);
|
String relayRequestHeaderKeys = prop.getProperty(HEADER_KEYS);
|
||||||
@@ -331,37 +394,31 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
if(message instanceof String && StringUtils.isEmpty((String)message))
|
if(message instanceof String && StringUtils.isEmpty((String)message))
|
||||||
message = "{}";
|
message = "{}";
|
||||||
|
|
||||||
JsonNode jsonMessageNode = JacksonUtil.readTree(message, mapper);
|
JSONObject jsonMessage = JSONUtils.parseJson(message);
|
||||||
if (jsonMessageNode == null || !jsonMessageNode.isObject()) {
|
JSONObject headerJson = JSONUtils.getChildJson(jsonMessage, headerGroupName);
|
||||||
jsonMessageNode = OBJECT_MAPPER.createObjectNode();
|
if (headerJson == null)
|
||||||
}
|
headerJson = new JSONObject();
|
||||||
ObjectNode jsonNode = (ObjectNode) jsonMessageNode;
|
|
||||||
|
|
||||||
JsonNode childNode = jsonNode.get(headerGroupName);
|
|
||||||
ObjectNode headerJson = (childNode != null && childNode.isObject())
|
|
||||||
? (ObjectNode) childNode
|
|
||||||
: OBJECT_MAPPER.createObjectNode();
|
|
||||||
|
|
||||||
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||||
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
||||||
String key = e.nextElement();
|
String key = e.nextElement();
|
||||||
headerJson.put(StringUtils.lowerCase(key), request.getHeader(key));
|
headerJson.put(StringUtils.lowerCase(key), request.getHeader(key));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
String[] relayKeyArr = org.springframework.util.StringUtils
|
String[] relayKeyArr = org.springframework.util.StringUtils
|
||||||
.tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
.tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
||||||
|
|
||||||
for (String key : relayKeyArr) {
|
for (String key : relayKeyArr) {
|
||||||
String headerValue = request.getHeader(key);
|
String headerValue = request.getHeader(key);
|
||||||
if (StringUtils.isNotBlank(headerValue)) {
|
if (StringUtils.isNotBlank(headerValue)) {
|
||||||
headerJson.put(StringUtils.lowerCase(key), headerValue);
|
headerJson.put(StringUtils.lowerCase(key), headerValue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!headerJson.isEmpty()) {
|
if (headerJson.size() > 0) {
|
||||||
jsonNode.set(headerGroupName, headerJson);
|
jsonMessage.put(headerGroupName, headerJson);
|
||||||
message = jsonNode;
|
message = jsonMessage.toJSONString();
|
||||||
}
|
}
|
||||||
} else if(MessageType.XML.equals(adptMsgType)) {
|
} else if(MessageType.XML.equals(adptMsgType)) {
|
||||||
Document document = XMLUtils.convertXmlDocument(message);
|
Document document = XMLUtils.convertXmlDocument(message);
|
||||||
@@ -476,10 +533,10 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private Object applyHeaderGroupResponseHeaders(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
private String applyHeaderGroupResponseHeaders(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||||
HttpServletRequest request, HttpServletResponse response, String adptMsgType) throws Exception {
|
HttpServletRequest request, HttpServletResponse response, String adptMsgType) throws Exception {
|
||||||
// body headergroup -> http header 세팅
|
// body headergroup -> http header 세팅
|
||||||
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
String headerGroupName = prop.getProperty(ApiAdapterService.HEADER_GROUP);
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(headerGroupName)) {
|
if (StringUtils.isNotBlank(headerGroupName)) {
|
||||||
if (resultMessage instanceof Node) {
|
if (resultMessage instanceof Node) {
|
||||||
@@ -495,44 +552,34 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
adptMsgType = MessageType.XML;
|
adptMsgType = MessageType.XML;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (MessageType.JSON.equals(adptMsgType)) {
|
||||||
|
JSONObject jsonObject = JSONUtils.parseJson(resultMessage);
|
||||||
|
JSONObject headerGroup = (JSONObject)jsonObject.get(headerGroupName);
|
||||||
|
if (headerGroup != null) {
|
||||||
|
Set<Map.Entry<String, Object>> fieldEntrySet = JSONUtils.getField(headerGroup);
|
||||||
|
|
||||||
|
for (Map.Entry<String, Object> fieldEntry : fieldEntrySet) {
|
||||||
|
logger.info("header group entry : {} , {}", fieldEntry.getKey(), fieldEntry.getValue());
|
||||||
|
|
||||||
if (MessageType.JSON.equals(adptMsgType)) {
|
if (fieldEntry.getValue() instanceof String) {
|
||||||
JsonNode jsonNode = JacksonUtil.readTree(resultMessage, OBJECT_MAPPER); // 또는
|
if(fieldEntry.getKey().equalsIgnoreCase("content-type")) {
|
||||||
// objectMapper.readTree(resultMessage)
|
logger.debug("set content-type {}: {}", fieldEntry.getKey(), fieldEntry.getValue());
|
||||||
JsonNode headerGroup = jsonNode.get(headerGroupName);
|
response.setContentType((String) fieldEntry.getValue());
|
||||||
|
} else {
|
||||||
if (headerGroup != null && !headerGroup.isNull()) {
|
logger.debug("add header {}: {}", fieldEntry.getKey(), fieldEntry.getValue());
|
||||||
Iterator<Map.Entry<String, JsonNode>> fieldIterator = headerGroup.fields();
|
response.addHeader(fieldEntry.getKey(), (String) fieldEntry.getValue());
|
||||||
|
|
||||||
while (fieldIterator.hasNext()) {
|
|
||||||
Map.Entry<String, JsonNode> fieldEntry = fieldIterator.next();
|
|
||||||
JsonNode valueNode = fieldEntry.getValue();
|
|
||||||
|
|
||||||
logger.info("header group entry : {} , {}", fieldEntry.getKey(), valueNode);
|
|
||||||
|
|
||||||
if (valueNode.isTextual()) {
|
|
||||||
String value = valueNode.asText();
|
|
||||||
|
|
||||||
if (StringUtils.equalsIgnoreCase(fieldEntry.getKey(), "content-type")) {
|
|
||||||
logger.debug("set content-type {}: {}", fieldEntry.getKey(), value);
|
|
||||||
response.setContentType(value);
|
|
||||||
} else if (StringUtils.equalsIgnoreCase(fieldEntry.getKey(), HttpHeaders.CONTENT_LENGTH)) {
|
|
||||||
logger.debug("skip content-length {}: {}", fieldEntry.getKey(), value);
|
|
||||||
continue;
|
|
||||||
} else {
|
|
||||||
logger.debug("add header {}: {}", fieldEntry.getKey(), value);
|
|
||||||
response.addHeader(fieldEntry.getKey(), value);
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
logger.info("fieldEntry value is not String. {}", valueNode);
|
logger.info("fieldEntry value is not String. {}", fieldEntry.getValue());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
logger.info("headerGroup is null");
|
logger.info("headerGroup is null");
|
||||||
}
|
}
|
||||||
|
|
||||||
((ObjectNode) jsonNode).remove(headerGroupName);
|
jsonObject.remove(headerGroupName);
|
||||||
return jsonNode;
|
return jsonObject.toJSONString();
|
||||||
} else if(MessageType.XML.equals(adptMsgType)) {
|
} else if(MessageType.XML.equals(adptMsgType)) {
|
||||||
Document document = XMLUtils.convertXmlDocument(resultMessage);
|
Document document = XMLUtils.convertXmlDocument(resultMessage);
|
||||||
if(document != null) {
|
if(document != null) {
|
||||||
@@ -547,12 +594,8 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
String value = headerElement.getTextTrim();
|
String value = headerElement.getTextTrim();
|
||||||
|
|
||||||
if(StringUtils.isNoneBlank(value)) {
|
if(StringUtils.isNoneBlank(value)) {
|
||||||
if(StringUtils.equalsIgnoreCase(name, "content-type")) {
|
if(value.equalsIgnoreCase("content-type")) {
|
||||||
logger.debug("set content-type {}: {}", name, value);
|
response.setContentType(value);
|
||||||
response.setContentType(value);
|
|
||||||
} else if(StringUtils.equalsIgnoreCase(name, "content-length")) {
|
|
||||||
logger.debug("skip content-length {}: {}", name, value);
|
|
||||||
continue;
|
|
||||||
} else {
|
} else {
|
||||||
logger.debug("add header {}: {}", name, value);
|
logger.debug("add header {}: {}", name, value);
|
||||||
response.addHeader(name, value);
|
response.addHeader(name, value);
|
||||||
@@ -577,231 +620,71 @@ 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 + "]");
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean bUrlDecode = StringUtils.equalsIgnoreCase(urlDecode, "Y");
|
private Map<String, String[]> assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName,
|
||||||
if (encoding == null) {
|
Object requestBytes, Properties prop) {
|
||||||
// Content-Type 에 charset 이 없을 때(GET 등)의 기본값은 처리 경로에 따라 다르다.
|
// PathVariable 체크
|
||||||
// - %인코딩 복원(URLDecoder) : HTML5/WHATWG 표준이 UTF-8 이므로 UTF-8.
|
if (StringUtils.equalsAnyIgnoreCase(request.getMethod(), HttpMethod.GET.name(), HttpMethod.DELETE.name())
|
||||||
// ISO-8859-1 로 복원하면 %ED%95%9C%EA%B8%80 이 '한글' 로 깨진다.
|
&& StringUtils.isBlank(request.getQueryString())) {
|
||||||
// - 그 외 : 컨테이너가 디코딩한 문자열의 원본 바이트를 되찾는 용도(byte latch)이므로
|
try {
|
||||||
// 기존 동작인 ISO-8859-1 을 유지한다.
|
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||||
encoding = bUrlDecode ? StandardCharsets.UTF_8.name() : "ISO-8859-1";
|
RequestAction action = ActionFactory.createAction(actionName);
|
||||||
}
|
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||||
|
String[] keys = action.perform(requestBytes);
|
||||||
|
String requestPath = keys[0];
|
||||||
|
|
||||||
// POST 방식의 form data
|
// PathVariable 지원 추가
|
||||||
if (reqMessage instanceof String) {
|
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
||||||
String formData = (String) reqMessage;
|
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
||||||
Map<String, String[]> formDataParamMap = QueryStringUtils.parseQueryString(formData, encoding, bUrlDecode);
|
Map<String, String> paramMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath,
|
||||||
pathMap.putAll(formDataParamMap);
|
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) });
|
||||||
|
}
|
||||||
|
|
||||||
// GET 방식의 query string
|
return returnMap;
|
||||||
String queryString = request.getQueryString();
|
}
|
||||||
Map<String, String[]> paramMap = QueryStringUtils.parseQueryString(queryString, encoding, bUrlDecode);
|
}
|
||||||
pathMap.putAll(paramMap);
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return pathMap;
|
return request.getParameterMap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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,
|
||||||
* 요청 URL 로부터 서비스키를 확정해 tx prop 에 세팅한다.
|
Object requestBytes, Properties prop) {
|
||||||
* (기존 {@link ApiKeyExtractFilter#doPreFilter} 가 하던 일)
|
Map<String, String> variablesMap = null;
|
||||||
*
|
// QueryString 있을때는 체크(X)
|
||||||
* <ul>
|
if (StringUtils.isBlank(request.getQueryString())) {
|
||||||
* <li>{@code STD_MESSAGE_KEY} : Action 이 만들어낸 요청 경로 (ex. {@code GET/api/v1/users/123})</li>
|
try {
|
||||||
* <li>{@code FINAL_STD_MESSAGE_KEY} : 등록된 서비스키 (ex. {@code GET/api/v1/users/{userId}})</li>
|
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||||
* <li>{@code API_SERVICE_CODE} : 서비스키에 매핑된 EAI 서비스 코드</li>
|
RequestAction action = ActionFactory.createAction(actionName);
|
||||||
* </ul>
|
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||||
*
|
String[] keys = action.perform(requestBytes);
|
||||||
* <p>기존에는 이 필터와 PathVariable 추출이 각각 Action 을 생성해 {@code perform()} 을 호출하고
|
String requestPath = keys[0];
|
||||||
* 서비스키 매칭까지 중복 수행했다. 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];
|
|
||||||
|
|
||||||
prop.setProperty(STD_MESSAGE_KEY, requestPath); // action class 통해서 생성
|
// PathVariable 지원 추가
|
||||||
|
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
||||||
// PathVariable 지원 추가
|
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
||||||
// ex) /api/bank/account/12345 --> /api/bank/account/{accountNo}
|
variablesMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath, requestPath);
|
||||||
String ruledPath = ApiKeyExtractFilter.getMatchedKey(requestPath);
|
}
|
||||||
if (StringUtils.isBlank(ruledPath)) {
|
} catch (Exception e) {
|
||||||
throw new FilterException("path not found - " + requestPath, HttpAdapterFilter.ERROR_PRE_FAIL,
|
logger.error(e.getMessage());
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
|
return variablesMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Properties getHeaders(HttpServletRequest request) {
|
private Properties getHeaders(HttpServletRequest request) {
|
||||||
@@ -817,7 +700,7 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
if (sb.length() > 0) sb.append(", ");
|
if (sb.length() > 0) sb.append(", ");
|
||||||
sb.append(values.nextElement());
|
sb.append(values.nextElement());
|
||||||
}
|
}
|
||||||
prop.setProperty(key.toLowerCase(), sb.toString());
|
prop.setProperty(key, sb.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
return prop;
|
return prop;
|
||||||
@@ -871,4 +754,34 @@ 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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,7 +36,6 @@ import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenCo
|
|||||||
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
|
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
|
||||||
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
|
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
|
||||||
|
|
||||||
import com.eactive.eai.agent.encryption.EncryptionManager;
|
|
||||||
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
||||||
import com.eactive.eai.authserver.jwt.PssJwtAccessTokenConverter;
|
import com.eactive.eai.authserver.jwt.PssJwtAccessTokenConverter;
|
||||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||||
@@ -132,11 +131,10 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
|
|||||||
String keyAlias = "elink-oauth";
|
String keyAlias = "elink-oauth";
|
||||||
String keyPassword = "elink1234";
|
String keyPassword = "elink1234";
|
||||||
if (vo != null) {
|
if (vo != null) {
|
||||||
EncryptionManager encManager = EncryptionManager.getInstance();
|
keystorePath = vo.getProperty(PROP_KEYSTORE_PATH);
|
||||||
keystorePath = encManager.decryptDBData(vo.getProperty(PROP_KEYSTORE_PATH));
|
keystorePassword = vo.getProperty(PROP_KEYSTORE_PW);
|
||||||
keystorePassword = encManager.decryptDBData(vo.getProperty(PROP_KEYSTORE_PW));
|
keyAlias = vo.getProperty(PROP_KEY_ALIAS);
|
||||||
keyAlias = encManager.decryptDBData(vo.getProperty(PROP_KEY_ALIAS));
|
keyPassword = vo.getProperty(PROP_KEY_PW);
|
||||||
keyPassword = encManager.decryptDBData(vo.getProperty(PROP_KEY_PW));
|
|
||||||
} else {
|
} else {
|
||||||
logger.warn("The properties has not been set.[" + PROP_GROUP_AUTH_SERVER + "]");
|
logger.warn("The properties has not been set.[" + PROP_GROUP_AUTH_SERVER + "]");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 = "API 관리자에게 문의하세요.";
|
detailMessage = "광주은행 관리자에게 문의하세요.";
|
||||||
}
|
}
|
||||||
request.setAttribute("errorMessage", detailMessage);
|
request.setAttribute("errorMessage", detailMessage);
|
||||||
return "forward:/error.jsp";
|
return "forward:/error.jsp";
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
|||||||
import org.springframework.web.bind.annotation.RequestParam;
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
import org.springframework.web.bind.annotation.ResponseBody;
|
import org.springframework.web.bind.annotation.ResponseBody;
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.UnknownMessageLogUtils;
|
import com.eactive.eai.adapter.http.dynamic.UnkownMessageLogUtils;
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||||
import com.eactive.eai.authserver.config.RequestContextData;
|
import com.eactive.eai.authserver.config.RequestContextData;
|
||||||
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
||||||
@@ -55,7 +55,7 @@ public class DJBOAuth2Controller {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private TokenIssuanceLogDAO tokenIssuanceLogDAO;
|
private TokenIssuanceLogDAO tokenIssuanceLogDAO;
|
||||||
|
|
||||||
@RequestMapping(value = { "/*/oauth/token", "/*/oauth2/token" }, method = RequestMethod.POST,
|
@RequestMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, method = RequestMethod.POST,
|
||||||
consumes = "application/json", produces = "application/json; charset=UTF-8")
|
consumes = "application/json", produces = "application/json; charset=UTF-8")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public ResponseEntity<?> tokenJson(@RequestBody DJBOAuth2AccessTokenRequest tokenRequest,
|
public ResponseEntity<?> tokenJson(@RequestBody DJBOAuth2AccessTokenRequest tokenRequest,
|
||||||
@@ -63,7 +63,7 @@ public class DJBOAuth2Controller {
|
|||||||
return issueToken(tokenRequest, request, response);
|
return issueToken(tokenRequest, request, response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = { "/*/oauth/token", "/*/oauth2/token" }, method = RequestMethod.POST,
|
@RequestMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, method = RequestMethod.POST,
|
||||||
consumes = "application/x-www-form-urlencoded", produces = "application/json; charset=UTF-8")
|
consumes = "application/x-www-form-urlencoded", produces = "application/json; charset=UTF-8")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public ResponseEntity<?> tokenForm(@RequestParam Map<String, String> params,
|
public ResponseEntity<?> tokenForm(@RequestParam Map<String, String> params,
|
||||||
@@ -76,7 +76,7 @@ public class DJBOAuth2Controller {
|
|||||||
return issueToken(tokenRequest, request, response);
|
return issueToken(tokenRequest, request, response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping(value = { "/*/oauth/token", "/*/oauth2/token" }, produces = "application/json; charset=UTF-8")
|
@GetMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, produces = "application/json; charset=UTF-8")
|
||||||
@ResponseBody
|
@ResponseBody
|
||||||
public ResponseEntity<?> tokenGet(@RequestParam Map<String, String> params,
|
public ResponseEntity<?> tokenGet(@RequestParam Map<String, String> params,
|
||||||
HttpServletRequest request, HttpServletResponse response) {
|
HttpServletRequest request, HttpServletResponse response) {
|
||||||
@@ -163,10 +163,8 @@ public class DJBOAuth2Controller {
|
|||||||
logTokenIssuance(false, false, e.getMessage(), null);
|
logTokenIssuance(false, false, e.getMessage(), null);
|
||||||
|
|
||||||
Properties logProp = new Properties();
|
Properties logProp = new Properties();
|
||||||
if(StringUtils.isNotEmpty(clientId))
|
logProp.put("clientId", clientId);
|
||||||
logProp.put("clientId", clientId);
|
UnkownMessageLogUtils.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);
|
||||||
|
|
||||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage());
|
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage());
|
||||||
@@ -180,10 +178,8 @@ public class DJBOAuth2Controller {
|
|||||||
logTokenIssuance(false, false, e.getMessage(), null);
|
logTokenIssuance(false, false, e.getMessage(), null);
|
||||||
|
|
||||||
Properties logProp = new Properties();
|
Properties logProp = new Properties();
|
||||||
if(StringUtils.isNotEmpty(clientId))
|
logProp.put("clientId", clientId);
|
||||||
logProp.put("clientId", clientId);
|
UnkownMessageLogUtils.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);
|
||||||
|
|
||||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, "Unauthorized. [Unknown]");
|
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, "Unauthorized. [Unknown]");
|
||||||
|
|||||||
-101
@@ -1,101 +0,0 @@
|
|||||||
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 "";
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
+30
-35
@@ -2,52 +2,47 @@ 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.message.EAIMessageKeys;
|
import com.eactive.eai.common.util.Logger;
|
||||||
import com.eactive.eai.custom.message.StandardMessageCoordinatorDJB;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.eactive.eai.message.StandardItem;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
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);
|
||||||
* 표준 -> 비표준 거래
|
|
||||||
* 아웃바운드 어댑터에서 Exception이 발생했을 때, Outbound Process 응답 메시지 생성
|
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||||
*/
|
|
||||||
@Override
|
@Override
|
||||||
public Object generateOutboundErrorResponseMessage(String outboundadapterGroupName,
|
public Object generateNonStandardErrorResponseMessage(String inboundAdapterGroupName, String inboundAdapterName,
|
||||||
String outboundadapterName, Properties callProp, Object outboundRequestData, EAIMessage resEaiMsg)
|
Properties callProp, Object outboundRequestData, EAIMessage resEaiMsg) throws Exception {
|
||||||
throws Exception {
|
|
||||||
|
|
||||||
StandardMessage standardMessage = resEaiMsg.getStandardMessage();
|
|
||||||
// msg_dvcd = EM (에러메시지)
|
|
||||||
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_DVCD, "NM");
|
|
||||||
|
|
||||||
// 출력속성코드 = 1(팝업)
|
Object responseMsessage = super.generateNonStandardErrorResponseMessage(inboundAdapterGroupName,
|
||||||
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_OUTP_ATRB_CD, "1");
|
inboundAdapterName, callProp, outboundRequestData, resEaiMsg);
|
||||||
|
|
||||||
// MSG_LIST 1건 구성
|
logger.debug("generateNonStandardErrorResponseMessage - {}", responseMsessage);
|
||||||
standardMessage.setData(StandardMessageCoordinatorDJB.MSG_LIST_ROWCNT, "0");
|
|
||||||
StandardItem msgPart = standardMessage.findItem("MSG");
|
|
||||||
msgPart.getChilds().remove("MSG_LIST");
|
|
||||||
|
|
||||||
StandardMessageManager manager = StandardMessageManager.getInstance();
|
if (!(responseMsessage instanceof String)) {
|
||||||
InterfaceMapper mapper = manager.getMapper();
|
return responseMsessage;
|
||||||
|
}
|
||||||
// mapper 에러코드 설정
|
|
||||||
mapper.setErrorCode(standardMessage, "");
|
|
||||||
mapper.setErrorMsg(standardMessage, "처리오류");
|
|
||||||
|
|
||||||
// 성공 처리 처럼 진행한다.
|
String jsonStr = (String) responseMsessage;
|
||||||
// 단, 거래로그/에러로그는 원본 에러코드 기준으로 남겨야 하므로 별도로 보관한다.
|
if (StringUtils.isBlank(jsonStr)) {
|
||||||
resEaiMsg.setOrgRspErrCd(resEaiMsg.getRspErrCd());
|
return responseMsessage;
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-8
@@ -10,7 +10,6 @@ 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;
|
||||||
@@ -24,8 +23,7 @@ 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);
|
||||||
|
|
||||||
// 기본 ObjectMapper 는 응답 JSON 왕복에서 100000000.00 을 1.0E8 로 바꿔버린다.
|
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||||
private static final ObjectMapper OBJECT_MAPPER = JacksonUtil.newNumberSafeMapper();
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object generateNonStandardErrorResponseMessage(String inboundAdapterGroupName, String inboundAdapterName,
|
public Object generateNonStandardErrorResponseMessage(String inboundAdapterGroupName, String inboundAdapterName,
|
||||||
@@ -45,8 +43,7 @@ public class KakaopayAdapterErrorMsgHandler extends TemplateCodeConvertAdapterEr
|
|||||||
return responseMsessage;
|
return responseMsessage;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 제어문자를 이스케이프하지 않고 보내는 상대 시스템 대응 (JacksonUtil.escapeControlChars 주석 참조)
|
JsonNode rootNode = OBJECT_MAPPER.readTree(jsonStr);
|
||||||
JsonNode rootNode = OBJECT_MAPPER.readTree(JacksonUtil.escapeControlChars(jsonStr));
|
|
||||||
|
|
||||||
boolean modified = false;
|
boolean modified = false;
|
||||||
|
|
||||||
@@ -75,7 +72,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(JacksonUtil.escapeControlChars(jsonStr));
|
JsonNode rootNode = OBJECT_MAPPER.readTree(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)
|
||||||
@@ -116,8 +113,6 @@ 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;
|
||||||
|
|||||||
+4
-2
@@ -15,11 +15,15 @@ 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 응답 메시지 생성
|
||||||
@@ -49,8 +53,6 @@ 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;
|
||||||
|
|||||||
-136
@@ -1,136 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.client.impl;
|
|
||||||
|
|
||||||
import java.io.UnsupportedEncodingException;
|
|
||||||
import java.security.InvalidKeyException;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.crypto.Mac;
|
|
||||||
import javax.crypto.spec.SecretKeySpec;
|
|
||||||
|
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
|
||||||
import com.eactive.eai.adapter.http.client.impl.HttpClient5AdapterServiceRest;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.util.MaskingUtils;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 1. 기능 : EAI HTTP OutBound 용 어댑터로 수동 시스템의 HTTP 웹 컴포넌트를 GET/POST 방식으로 호출할 수 있는
|
|
||||||
* 기능을 제공한다.<br>
|
|
||||||
* 2. 처리 개요 : <br>
|
|
||||||
* * - 2020-09-25: Http Header 받아서 처리할 수 있게 기능 추가<br>
|
|
||||||
* 3. 주의사항 <br>
|
|
||||||
*
|
|
||||||
* @author :
|
|
||||||
* @version : v 1.0.0
|
|
||||||
* @see : HttpClientAdapterServiceFactory.java,
|
|
||||||
* HttpClientAdapterServiceSupport.java
|
|
||||||
* @since :
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class HttpClient5AdapterServiceBigTech extends HttpClient5AdapterServiceRest
|
|
||||||
implements HttpClientAdapterServiceKey {
|
|
||||||
|
|
||||||
private static final char[] _HEX_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
|
|
||||||
'e', 'f' };
|
|
||||||
|
|
||||||
private static String hexEncode(byte[] data) {
|
|
||||||
|
|
||||||
if (data == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
int length = data.length;
|
|
||||||
char[] encoded = new char[length << 1];
|
|
||||||
|
|
||||||
for (int i = 0, j = 0; i < length; i++) {
|
|
||||||
encoded[j++] = _HEX_LOWER[(0xF0 & data[i]) >>> 4];
|
|
||||||
encoded[j++] = _HEX_LOWER[0x0F & data[i]];
|
|
||||||
}
|
|
||||||
|
|
||||||
return new String(encoded);
|
|
||||||
} // end of hex_encode
|
|
||||||
|
|
||||||
private static final String _BTP_CHARSET = "UTF-8";
|
|
||||||
private static final String _BTP_ALGORITHM = "HmacSHA256";
|
|
||||||
private static final String _BTP_ACCESS_KEY = "{BTP_ACCESS_KEY}";
|
|
||||||
private static final String _BTP_SECRET_KEY = "{BTP_SECRET_KEY}";
|
|
||||||
|
|
||||||
private static byte[] mac(String charset, String algorithm, String timestamp, String accessKey, String secretKey,
|
|
||||||
String url) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
|
|
||||||
String message = String.join(" ", Arrays.asList(url, timestamp, accessKey));
|
|
||||||
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(charset), algorithm);
|
|
||||||
Mac mac = Mac.getInstance(algorithm);
|
|
||||||
mac.init(secretKeySpec);
|
|
||||||
|
|
||||||
return mac.doFinal(message.getBytes(charset));
|
|
||||||
}// end of mac
|
|
||||||
|
|
||||||
private static String macHex(String charset, String algorithm, String timestamp, String accessKey, String secretKey,
|
|
||||||
String url) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException {
|
|
||||||
return hexEncode(mac(charset, algorithm, timestamp, accessKey, secretKey, url));
|
|
||||||
}// end of macHex
|
|
||||||
|
|
||||||
protected void assignRequestHeaders(HttpUriRequestBase method, Object httpHeader, Properties prop, Properties tempProp) {
|
|
||||||
super.assignRequestHeaders(method, httpHeader, prop, tempProp);
|
|
||||||
|
|
||||||
try {
|
|
||||||
String adapterGroupName = tempProp.getProperty(ADAPTER_GROUP_NAME);
|
|
||||||
Properties customProp = PropManager.getInstance().getProperties(adapterGroupName);
|
|
||||||
String charset = customProp.getProperty("_BTP_CHARSET", _BTP_CHARSET);
|
|
||||||
String algorithm = customProp.getProperty("_BTP_ALGORITHM", _BTP_ALGORITHM);
|
|
||||||
String timestamp = System.currentTimeMillis() + "";
|
|
||||||
String accessKey = customProp.getProperty("_BTP_ACCESS_KEY", _BTP_ACCESS_KEY);
|
|
||||||
String secretKey = customProp.getProperty("_BTP_SECRET_KEY", _BTP_SECRET_KEY);
|
|
||||||
if(logger.isDebug()) {
|
|
||||||
logger.debug("charset={}", charset);
|
|
||||||
logger.debug("algorithm={}", algorithm);
|
|
||||||
logger.debug("timestamp={}", timestamp);
|
|
||||||
logger.debug("accessKey={}", accessKey);
|
|
||||||
logger.debug("secretKey={}", MaskingUtils.maskPassword(secretKey));
|
|
||||||
logger.debug("url={}", method.getRequestUri());
|
|
||||||
}
|
|
||||||
|
|
||||||
String signature = macHex(charset// charset
|
|
||||||
, algorithm// algorithm
|
|
||||||
, timestamp// timestamp
|
|
||||||
, accessKey// accessKey
|
|
||||||
, secretKey// secretKey
|
|
||||||
, method.getRequestUri());
|
|
||||||
|
|
||||||
method.setHeader("x-btp-access-key", accessKey);
|
|
||||||
method.setHeader("x-btp-timestamp", timestamp);
|
|
||||||
method.setHeader("x-btp-signature-v1", signature);
|
|
||||||
|
|
||||||
} catch (InvalidKeyException | UnsupportedEncodingException | NoSuchAlgorithmException e) {
|
|
||||||
throw new RuntimeException("BigTech 헤더 설정 실패", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// public static void main(String[] args) {
|
|
||||||
// try {
|
|
||||||
// String url = "/rest/v1/service?param0=¶m1=";
|
|
||||||
// String timestamp = System.currentTimeMillis()+"";
|
|
||||||
// String accessKey = _BTP_ACCESS_KEY;
|
|
||||||
// String secretKey = _BTP_SECRET_KEY;
|
|
||||||
// String signature = macHex(
|
|
||||||
// _BTP_CHARSET//charset
|
|
||||||
// , _BTP_ALGORITHM//algorithm
|
|
||||||
// , timestamp// timestamp
|
|
||||||
// , _BTP_ACCESS_KEY//accessKey
|
|
||||||
// , _BTP_SECRET_KEY//secretKey
|
|
||||||
// , url
|
|
||||||
// );
|
|
||||||
// System.out.println(String.format("charset=%s", _BTP_CHARSET));
|
|
||||||
// System.out.println(String.format("algorithm=%s", _BTP_ALGORITHM));
|
|
||||||
// System.out.println(String.format("accessKey=%s", accessKey));
|
|
||||||
// System.out.println(String.format("secretKey=%s", secretKey));
|
|
||||||
// System.out.println(String.format("timestamp=%s", timestamp));
|
|
||||||
// System.out.println(String.format("signature=%s", signature));
|
|
||||||
// } catch (Exception e) {
|
|
||||||
// e.printStackTrace();
|
|
||||||
// }
|
|
||||||
// }// end of main
|
|
||||||
}
|
|
||||||
-149
@@ -1,149 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.client.impl;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.dom4j.Node;
|
|
||||||
import org.json.simple.JSONObject;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
|
||||||
import com.eactive.eai.adapter.http.client.impl.filter.HttpClient5AdapterFilterFactory;
|
|
||||||
import com.eactive.eai.adapter.http.client.impl.filter.HttpClientAdapterFilter;
|
|
||||||
import com.eactive.eai.common.util.JacksonUtil;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 1. 기능 : HttpClient5AdapterServiceRest 호출 전후 Filter 적용할 수 있는 기능을 제공한다.<br>
|
|
||||||
* 2. 처리 개요 : <br>
|
|
||||||
* 3. 주의사항 <br>
|
|
||||||
*
|
|
||||||
* @author :
|
|
||||||
* @version : v 1.0.0
|
|
||||||
* @see : HttpClientAdapterServiceFactory.java,
|
|
||||||
* HttpClientAdapterServiceSupport.java, HttpClient5AdapterServiceRest.java
|
|
||||||
* @since :
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class HttpClient5AdapterServiceBigTechAddFilter extends HttpClient5AdapterServiceBigTech
|
|
||||||
implements HttpClientAdapterServiceKey {
|
|
||||||
|
|
||||||
// 요청전 수행할 필터(쉼표(,)로 구분)
|
|
||||||
static final String PRE_FILTERS = "PRE_FILTERS";
|
|
||||||
|
|
||||||
// 요청후 수행할 필터(쉼표(,)로 구분)
|
|
||||||
static final String POST_FILTERS = "POST_FILTERS";
|
|
||||||
|
|
||||||
// // Adapter에서 Exception이 발생한 경우, 처리할 필터
|
|
||||||
// static final String EXCEPTION_FILTER = "EXCEPTION_FILTER";
|
|
||||||
|
|
||||||
// 기본 ObjectMapper 는 JsonNode 직렬화 시 작은 소수를 1.2E-7 로 바꿔버린다.
|
|
||||||
private ObjectMapper mapper = JacksonUtil.newNumberSafeMapper();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 1. 기능 : HttpClient 호출 전후 Filter 적용용 2. 처리 개요 : <br>
|
|
||||||
* 3. 주의사항 <br>
|
|
||||||
*
|
|
||||||
* @param prop Http Adapter 속성 정보
|
|
||||||
* @return 반환 된 Object
|
|
||||||
* @exception Exception 수동 시스템 간 통신 중 발생
|
|
||||||
*/
|
|
||||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
|
||||||
|
|
||||||
String adptGrpName = tempProp.getProperty(ADAPTER_GROUP_NAME);
|
|
||||||
String adptName = tempProp.getProperty(ADAPTER_NAME);
|
|
||||||
|
|
||||||
data = doPreFilters(adptGrpName, adptName, prop, data, tempProp);
|
|
||||||
|
|
||||||
Object adapterResponse = super.execute(prop, data, tempProp);
|
|
||||||
|
|
||||||
adapterResponse = doPostFilters(adptGrpName, adptName, prop, adapterResponse, tempProp);
|
|
||||||
if (adapterResponse instanceof JSONObject)
|
|
||||||
adapterResponse = ((JSONObject) adapterResponse).toJSONString();
|
|
||||||
else if (adapterResponse instanceof ObjectNode)
|
|
||||||
adapterResponse = mapper.writeValueAsString((ObjectNode) adapterResponse);
|
|
||||||
else if (adapterResponse instanceof Node)
|
|
||||||
adapterResponse = ((Node) adapterResponse).asXML();
|
|
||||||
|
|
||||||
return adapterResponse;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected Object doPreFilters(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
|
|
||||||
// boolean isSetCommonFilterInAdapterProp = false;
|
|
||||||
// 1. adapter에 설정된 필터 수행
|
|
||||||
String preFiltersStr = prop.getProperty(PRE_FILTERS);
|
|
||||||
if (StringUtils.isNotEmpty(preFiltersStr)) {
|
|
||||||
String[] preFilters = StringUtils.split(preFiltersStr, ",");
|
|
||||||
for (String filterName : preFilters) {
|
|
||||||
if (StringUtils.isBlank(filterName)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.debug("HttpClient5AdapterServiceRestAddFilter] Processing Start [" + filterName + "]");
|
|
||||||
HttpClientAdapterFilter adapterFilter = HttpClient5AdapterFilterFactory.createFilter(filterName.trim());
|
|
||||||
|
|
||||||
if (adapterFilter != null) {
|
|
||||||
// if (adapterFilter instanceof IBKOutCommonFilter)
|
|
||||||
// isSetCommonFilterInAdapterProp = true;
|
|
||||||
|
|
||||||
message = adapterFilter.doPreFilter(adptGrpName, adptName, prop, message, tempProp);
|
|
||||||
} else {
|
|
||||||
throw new Exception("Failed get Filter Class: " + filterName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// // 2. IBKOutCommonFilter 필터 수행(adapter 필터에서 수행하지 않을 때만)
|
|
||||||
// if (!isSetCommonFilterInAdapterProp) {
|
|
||||||
// HttpClientAdapterFilter ibkFilter = HttpClient5AdapterFilterFactory
|
|
||||||
// .createFilter(IBKOutCommonFilter.class.getName());
|
|
||||||
// if (ibkFilter != null) {
|
|
||||||
// message = ibkFilter.doPreFilter(adptGrpName, adptName, prop, message, tempProp);
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// logger.debug("IBKOutCommonFilter isSetCommonFilterInAdapterProp 'POST_FILTERS'. already in adapter filters");
|
|
||||||
// }
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected Object doPostFilters(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
|
|
||||||
// boolean isSetCommonFilterInAdapterProp = false;
|
|
||||||
// 1. adapter에 설정된 필터 수행
|
|
||||||
String postFiltersStr = prop.getProperty(POST_FILTERS);
|
|
||||||
if (StringUtils.isNotEmpty(postFiltersStr)) {
|
|
||||||
String[] postFilters = StringUtils.split(postFiltersStr, ",");
|
|
||||||
for (String filterName : postFilters) {
|
|
||||||
if (StringUtils.isBlank(filterName)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
HttpClientAdapterFilter adapterFilter = HttpClient5AdapterFilterFactory.createFilter(filterName.trim());
|
|
||||||
if (adapterFilter != null) {
|
|
||||||
// if (adapterFilter instanceof IBKOutCommonFilter)
|
|
||||||
// isSetCommonFilterInAdapterProp = true;
|
|
||||||
message = adapterFilter.doPostFilter(adptGrpName, adptName, prop, message, tempProp);
|
|
||||||
} else {
|
|
||||||
throw new Exception("Failed get Filter Class: " + filterName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// // 2. IBKOutCommonFilter 필터 수행
|
|
||||||
// if (!isSetCommonFilterInAdapterProp) {
|
|
||||||
// HttpClientAdapterFilter ibkFilter = HttpClient5AdapterFilterFactory
|
|
||||||
// .createFilter(IBKOutCommonFilter.class.getName());
|
|
||||||
// if (ibkFilter != null) {
|
|
||||||
// message = ibkFilter.doPostFilter(adptGrpName, adptName, prop, message, tempProp);
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// logger.debug("IBKOutCommonFilter isSetCommonFilterInAdapterProp 'PRE_FILTERS'. already in adapter filters");
|
|
||||||
// }
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-80
@@ -1,80 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.client.impl.filter;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.client.impl.HttpClient5AdapterServiceRest;
|
|
||||||
import com.eactive.eai.adapter.http.client.impl.filter.OutCryptoFilter;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
|
||||||
import com.eactive.eai.common.util.JacksonUtil;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.eactive.eai.util.JsonPathUtil;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 토스 암복호화에 맟추어 커스텀
|
|
||||||
*/
|
|
||||||
public class DouzoneEncFieldOutCryptoFilter extends EncFieldOutCryptoFilter {
|
|
||||||
|
|
||||||
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
private final OutCryptoFilter filter = new OutCryptoFilter();
|
|
||||||
|
|
||||||
protected Properties setProp(Properties tempProp) {
|
|
||||||
tempProp.setProperty(OutCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
|
|
||||||
tempProp.setProperty(OutCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
|
|
||||||
return tempProp;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Properties prop, Object message, Properties tempProp)
|
|
||||||
throws Exception {
|
|
||||||
String headerGroupName = prop.getProperty(HttpClient5AdapterServiceRest.HEADER_GROUP);
|
|
||||||
|
|
||||||
JsonNode root = JacksonUtil.readTree(message);
|
|
||||||
ObjectNode rootObjectNode = (ObjectNode) root;
|
|
||||||
JsonNode header = (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);
|
|
||||||
|
|
||||||
tempProp.setProperty("x-emp-nm", xEmpNm);
|
|
||||||
tempProp.setProperty(InCryptoFilter.PROP_AAD_HEADER, xEmpNm);
|
|
||||||
tempProp.setProperty("x-chnl-nm", xChnlNm);
|
|
||||||
|
|
||||||
Object enc = filter.doPreFilter(adptGrpName, adptName, prop, rootObjectNode, setProp(tempProp));
|
|
||||||
|
|
||||||
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
|
|
||||||
encJson.set(headerGroupName, header);
|
|
||||||
|
|
||||||
return encJson;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 헤더 그룹에서 지정한 헤더 값을 조회한다. 헤더 그룹 또는 해당 항목이 없으면 null을 반환한다.
|
|
||||||
*/
|
|
||||||
private String getHeaderText(JsonNode header, String name) {
|
|
||||||
if (header == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
JsonNode node = header.get(name);
|
|
||||||
return (node == null) ? null : node.asText();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Properties prop, Object message,
|
|
||||||
Properties tempProp) throws Exception {
|
|
||||||
return filter.doPostFilter(adptGrpName, adptName, setProp(prop), message, setProp(tempProp));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
+5
-27
@@ -2,13 +2,8 @@ package com.eactive.eai.custom.adapter.http.client.impl.filter;
|
|||||||
|
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.client.impl.HttpClient5AdapterServiceRest;
|
|
||||||
import com.eactive.eai.adapter.http.client.impl.filter.HttpClientAdapterFilter;
|
import com.eactive.eai.adapter.http.client.impl.filter.HttpClientAdapterFilter;
|
||||||
import com.eactive.eai.adapter.http.client.impl.filter.OutCryptoFilter;
|
import com.eactive.eai.adapter.http.client.impl.filter.OutCryptoFilter;
|
||||||
import com.eactive.eai.common.util.JacksonUtil;
|
|
||||||
import com.eactive.eai.util.JsonPathUtil;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
/**
|
/**
|
||||||
* 제주은행 Open API 기본 암복호화 필더
|
* 제주은행 Open API 기본 암복호화 필더
|
||||||
*/
|
*/
|
||||||
@@ -16,33 +11,16 @@ public class EncFieldOutCryptoFilter implements HttpClientAdapterFilter {
|
|||||||
|
|
||||||
private final OutCryptoFilter filter = new OutCryptoFilter();
|
private final OutCryptoFilter filter = new OutCryptoFilter();
|
||||||
|
|
||||||
protected Properties setProp(Properties tempProp) {
|
protected Properties setProp(Properties p) {
|
||||||
tempProp.setProperty(OutCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
|
p.setProperty(OutCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
|
||||||
tempProp.setProperty(OutCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
|
p.setProperty(OutCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
|
||||||
return tempProp;
|
return p;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
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);
|
return filter.doPreFilter(adptGrpName, adptName, prop, message, setProp(tempProp));
|
||||||
|
|
||||||
JsonNode root = JacksonUtil.readTree(message);
|
|
||||||
ObjectNode rootObjectNode = (ObjectNode) root;
|
|
||||||
JsonNode header = null;
|
|
||||||
if (headerGroupName != null) {
|
|
||||||
header = rootObjectNode.get(headerGroupName);
|
|
||||||
rootObjectNode.remove(headerGroupName);
|
|
||||||
}
|
|
||||||
|
|
||||||
Object enc = filter.doPreFilter(adptGrpName, adptName, prop, rootObjectNode, setProp(tempProp));
|
|
||||||
|
|
||||||
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
|
|
||||||
if (header != null)
|
|
||||||
encJson.set(headerGroupName, header);
|
|
||||||
|
|
||||||
return encJson;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
-79
@@ -1,79 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.FilterException;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.common.security.AESCryptoModuleExtension;
|
|
||||||
import com.eactive.eai.common.security.ARIACryptoModuleExtension;
|
|
||||||
import com.eactive.eai.common.security.CryptoModuleExtension;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.eactive.eai.util.HexaConverter;
|
|
||||||
import com.eactive.eai.util.JsonPathUtil;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
public class DecrytTestFilter implements HttpAdapterFilter {
|
|
||||||
|
|
||||||
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
try {
|
|
||||||
ObjectNode rootNode = (ObjectNode)JsonPathUtil.toTree(message);
|
|
||||||
|
|
||||||
JsonNode alg = rootNode.get("alg");
|
|
||||||
JsonNode mode = rootNode.get("mode");
|
|
||||||
JsonNode padding = rootNode.get("padding");
|
|
||||||
JsonNode aadNode = rootNode.get("aad");
|
|
||||||
JsonNode iv = rootNode.get("iv");
|
|
||||||
byte[] binIv = null;
|
|
||||||
if(iv != null) {
|
|
||||||
String strIv = iv.asText();
|
|
||||||
binIv = HexaConverter.hexToBin(strIv);
|
|
||||||
}
|
|
||||||
JsonNode encKey = rootNode.get("encKey");
|
|
||||||
String strEncKey = encKey.asText();
|
|
||||||
byte[] binEncKey = HexaConverter.hexToBin(strEncKey);
|
|
||||||
|
|
||||||
CryptoModuleExtension ext = "ARIA".equalsIgnoreCase(alg.asText()) ? new ARIACryptoModuleExtension()
|
|
||||||
: new AESCryptoModuleExtension();
|
|
||||||
ext.init(alg.asText(), mode.asText(), padding.asText(), binIv, binEncKey, binEncKey);
|
|
||||||
|
|
||||||
JsonNode encryptedData = rootNode.get("encryptedData");
|
|
||||||
byte[] cipherBytes = Base64.getDecoder().decode(encryptedData.asText().trim());
|
|
||||||
|
|
||||||
byte[] decryptedBytes = null;
|
|
||||||
if(rootNode.has("aad"))
|
|
||||||
decryptedBytes = ext.decrypt(cipherBytes, HexaConverter.hexToBin(aadNode.asText()));
|
|
||||||
else
|
|
||||||
decryptedBytes = ext.decrypt(cipherBytes);
|
|
||||||
|
|
||||||
rootNode.put("hsmKeyRaw", new String(decryptedBytes));
|
|
||||||
|
|
||||||
String jsonString = OBJECT_MAPPER.writeValueAsString(rootNode);
|
|
||||||
return jsonString;
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error("복호화 실패", e);
|
|
||||||
throw new FilterException("복호화 실패", ERROR_PRE_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
+11
-26
@@ -9,12 +9,10 @@ import org.springframework.http.HttpStatus;
|
|||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.FilterCryptoException;
|
import com.eactive.eai.adapter.http.dynamic.filter.FilterCryptoException;
|
||||||
|
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.adapter.http.dynamic.filter.InCryptoFilter;
|
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
||||||
import com.eactive.eai.adapter.service.DJBApiAdapterService;
|
import com.eactive.eai.common.security.keyderiv.KeyDerivationStrategy;
|
||||||
import com.eactive.eai.common.util.JacksonUtil;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 더존 연동용 수신 암복호화 필터.
|
* 더존 연동용 수신 암복호화 필터.
|
||||||
@@ -33,6 +31,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
|||||||
*/
|
*/
|
||||||
public class DouzoneEncFieldInCryptoFilter implements HttpAdapterFilter {
|
public class DouzoneEncFieldInCryptoFilter implements HttpAdapterFilter {
|
||||||
|
|
||||||
|
public static final String ERROR_DEC_FAIL = "E.DECRYPT_FAIL";
|
||||||
|
public static final String ERROR_ENC_FAIL = "E.ENCRYPT_FAIL";
|
||||||
private final InCryptoFilter filter = new InCryptoFilter();
|
private final InCryptoFilter filter = new InCryptoFilter();
|
||||||
|
|
||||||
protected Properties setProp(Properties p) {
|
protected Properties setProp(Properties p) {
|
||||||
@@ -43,10 +43,11 @@ public class DouzoneEncFieldInCryptoFilter implements HttpAdapterFilter {
|
|||||||
|
|
||||||
private void setContext(Properties tempProp) {
|
private void setContext(Properties tempProp) {
|
||||||
Properties inboundHeaders = (Properties) tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
Properties inboundHeaders = (Properties) tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
||||||
String chnlNm = inboundHeaders.getProperty("x-chnl-nm");
|
String empNm = inboundHeaders.getProperty("x-emp-nm");
|
||||||
tempProp.setProperty("x-chnl-nm", chnlNm);
|
tempProp.setProperty(InCryptoFilter.PROP_AAD_HEADER, empNm);
|
||||||
|
|
||||||
tempProp.setProperty(InCryptoFilter.PROP_AAD_HEADER, "x-emp-nm");
|
String chnlNm = inboundHeaders.getProperty("x-chnl-nm");
|
||||||
|
tempProp.setProperty(KeyDerivationStrategy.PARAM_CONTEXT_KEY, chnlNm);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -56,7 +57,7 @@ public class DouzoneEncFieldInCryptoFilter implements HttpAdapterFilter {
|
|||||||
setContext(prop);
|
setContext(prop);
|
||||||
return filter.doPreFilter(adptGrpName, adptName, message, setProp(prop), request, response);
|
return filter.doPreFilter(adptGrpName, adptName, message, setProp(prop), request, response);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new FilterCryptoException("복호화 오류", InCryptoFilter.ERROR_DEC_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
throw new FilterCryptoException("복호화 오류", ERROR_DEC_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,25 +66,9 @@ public class DouzoneEncFieldInCryptoFilter implements HttpAdapterFilter {
|
|||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||||
try {
|
try {
|
||||||
setContext(prop);
|
setContext(prop);
|
||||||
|
return filter.doPostFilter(adptGrpName, adptName, resultMessage, setProp(prop), request, response);
|
||||||
JsonNode root = JacksonUtil.readTree(resultMessage);
|
|
||||||
ObjectNode rootObjectNode = (ObjectNode) root;
|
|
||||||
String headerGroupName = prop.getProperty(DJBApiAdapterService.HEADER_GROUP);
|
|
||||||
JsonNode header = null;
|
|
||||||
if(headerGroupName != null) {
|
|
||||||
header = rootObjectNode.get(headerGroupName);
|
|
||||||
rootObjectNode.remove(headerGroupName);
|
|
||||||
}
|
|
||||||
|
|
||||||
Object enc = filter.doPostFilter(adptGrpName, adptName, rootObjectNode, setProp(prop), request, response);
|
|
||||||
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
|
|
||||||
if(header != null)
|
|
||||||
encJson.set(headerGroupName, header);
|
|
||||||
|
|
||||||
return encJson;
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new FilterCryptoException("암호화 오류", InCryptoFilter.ERROR_ENC_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
throw new FilterCryptoException("암호화 오류", ERROR_ENC_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-28
@@ -5,15 +5,8 @@ import java.util.Properties;
|
|||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.FilterCryptoException;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
||||||
import com.eactive.eai.adapter.service.DJBApiAdapterService;
|
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||||
import com.eactive.eai.common.util.JacksonUtil;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* InCryptoFilter를 멤버변수로 관리하는 HttpAdapterFilter 구현체.
|
* InCryptoFilter를 멤버변수로 관리하는 HttpAdapterFilter 구현체.
|
||||||
@@ -34,26 +27,7 @@ public class EncFieldInCryptoFilter implements HttpAdapterFilter {
|
|||||||
@Override
|
@Override
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||||
try {
|
return filter.doPostFilter(adptGrpName, adptName, resultMessage, setProp(prop), request, response);
|
||||||
JsonNode root = JacksonUtil.readTree(resultMessage);
|
|
||||||
ObjectNode rootObjectNode = (ObjectNode) root;
|
|
||||||
String headerGroupName = prop.getProperty(DJBApiAdapterService.HEADER_GROUP);
|
|
||||||
JsonNode header = null;
|
|
||||||
if(headerGroupName != null) {
|
|
||||||
header = rootObjectNode.get(headerGroupName);
|
|
||||||
rootObjectNode.remove(headerGroupName);
|
|
||||||
}
|
|
||||||
|
|
||||||
Object enc = filter.doPostFilter(adptGrpName, adptName, rootObjectNode, setProp(prop), request, response);
|
|
||||||
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
|
|
||||||
if(header != null)
|
|
||||||
encJson.set(headerGroupName, header);
|
|
||||||
|
|
||||||
return encJson;
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new FilterCryptoException("암호화 오류", InCryptoFilter.ERROR_ENC_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Properties setProp(Properties p) {
|
protected Properties setProp(Properties p) {
|
||||||
|
|||||||
-138
@@ -1,138 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.security.KeyStore;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.crypto.SecretKey;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.FilterException;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.common.hsm.HsmManager;
|
|
||||||
import com.eactive.eai.common.security.AESCryptoModuleExtension;
|
|
||||||
import com.eactive.eai.common.security.ARIACryptoModuleExtension;
|
|
||||||
import com.eactive.eai.common.security.CryptoModuleExtension;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.eactive.eai.util.HexaConverter;
|
|
||||||
import com.eactive.eai.util.JsonPathUtil;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
public class EncrytTestFilter implements HttpAdapterFilter {
|
|
||||||
|
|
||||||
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
try {
|
|
||||||
ObjectNode rootNode = (ObjectNode)JsonPathUtil.toTree(message);
|
|
||||||
|
|
||||||
// 1. HSM에서 키 가져오기
|
|
||||||
byte[] hsmKeyBytes = null;
|
|
||||||
JsonNode hsmKeyAlias = rootNode.get("hsmKeyAlias");
|
|
||||||
if (hsmKeyAlias != null) {
|
|
||||||
String hsmKeyAliasValue = hsmKeyAlias.textValue();
|
|
||||||
KeyStore keyStore = HsmManager.getInstance().getKeyStore();
|
|
||||||
|
|
||||||
java.security.Key key = keyStore.getKey(hsmKeyAliasValue, null);
|
|
||||||
if (key instanceof SecretKey) {
|
|
||||||
SecretKey secretKey = (SecretKey) key;
|
|
||||||
hsmKeyBytes = secretKey.getEncoded();
|
|
||||||
if (hsmKeyBytes != null) {
|
|
||||||
String hsmKeyBase64 = Base64.getEncoder().encodeToString(hsmKeyBytes);
|
|
||||||
String hsmKeyHex = HexaConverter.binToHex(hsmKeyBytes);
|
|
||||||
logger.debug("HsmManager] HSM - {} : [{}]", hsmKeyAliasValue, hsmKeyHex);
|
|
||||||
rootNode.put("hsmKeyBase64", hsmKeyBase64);
|
|
||||||
rootNode.put("hsmKeyHex", hsmKeyHex);
|
|
||||||
rootNode.put("hsmKeyRaw", new String(hsmKeyBytes));
|
|
||||||
} else {
|
|
||||||
logger.debug("HsmManager] HSM - secretKey null {} : [{}]", hsmKeyAliasValue, secretKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 암호화 파라미터가 있으면 암호화 후 복호화 검증
|
|
||||||
JsonNode alg = rootNode.get("alg");
|
|
||||||
JsonNode mode = rootNode.get("mode");
|
|
||||||
JsonNode padding = rootNode.get("padding");
|
|
||||||
|
|
||||||
JsonNode enc = rootNode.get("enc");
|
|
||||||
String strEnc = "BASE64";
|
|
||||||
if(enc != null)
|
|
||||||
strEnc = enc.asText();
|
|
||||||
|
|
||||||
JsonNode ivNode = rootNode.get("iv");
|
|
||||||
JsonNode aadNode = rootNode.get("aad");
|
|
||||||
JsonNode encKeyNode = rootNode.get("encKey");
|
|
||||||
JsonNode dataNode = rootNode.get("data");
|
|
||||||
|
|
||||||
if (alg != null && mode != null && padding != null && encKeyNode != null
|
|
||||||
&& dataNode != null) {
|
|
||||||
byte[] binIv = null;
|
|
||||||
if(ivNode != null) {
|
|
||||||
String strIvValue = ivNode.asText();
|
|
||||||
if(strIvValue.length() == 32||strEnc.equalsIgnoreCase("HEX"))
|
|
||||||
binIv = HexaConverter.hexToBin(strIvValue);
|
|
||||||
else
|
|
||||||
binIv = Base64.getDecoder().decode(strIvValue.trim());
|
|
||||||
}
|
|
||||||
|
|
||||||
String strEncKeyValue = encKeyNode.asText();
|
|
||||||
byte[] binEncKey = null;
|
|
||||||
if(strEnc.equalsIgnoreCase("BASE64"))
|
|
||||||
binEncKey = Base64.getDecoder().decode(strEncKeyValue.trim());
|
|
||||||
else
|
|
||||||
binEncKey = HexaConverter.hexToBin(strEncKeyValue);
|
|
||||||
|
|
||||||
CryptoModuleExtension ext = "ARIA".equalsIgnoreCase(alg.asText()) ? new ARIACryptoModuleExtension()
|
|
||||||
: new AESCryptoModuleExtension();
|
|
||||||
ext.init(alg.asText(), mode.asText(), padding.asText(), binIv, binEncKey, binEncKey);
|
|
||||||
|
|
||||||
byte[] plainBytes = dataNode.asText().getBytes();
|
|
||||||
|
|
||||||
// 암호화
|
|
||||||
byte[] encryptedBytes = null;
|
|
||||||
if(rootNode.has("aad"))
|
|
||||||
encryptedBytes = ext.encrypt(plainBytes, HexaConverter.hexToBin(aadNode.asText()));
|
|
||||||
else
|
|
||||||
encryptedBytes = ext.encrypt(plainBytes);
|
|
||||||
|
|
||||||
String encryptedBase64 = Base64.getEncoder().encodeToString(encryptedBytes);
|
|
||||||
rootNode.put("encryptedData", encryptedBase64);
|
|
||||||
logger.debug("암호화 결과: [{}]", encryptedBase64);
|
|
||||||
|
|
||||||
// 복호화 검증
|
|
||||||
byte[] decryptedBytes = null;
|
|
||||||
if(rootNode.has("aad"))
|
|
||||||
decryptedBytes = ext.decrypt(encryptedBytes, HexaConverter.hexToBin(aadNode.asText()));
|
|
||||||
else
|
|
||||||
decryptedBytes = ext.decrypt(encryptedBytes);
|
|
||||||
|
|
||||||
rootNode.put("decryptedVerify", new String(decryptedBytes));
|
|
||||||
logger.debug("복호화 검증: [{}]", new String(decryptedBytes));
|
|
||||||
}
|
|
||||||
|
|
||||||
String jsonString = OBJECT_MAPPER.writeValueAsString(rootNode);
|
|
||||||
return jsonString;
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new FilterException("HSM key 암호화/복호화 검증 실패", ERROR_PRE_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.FilterException;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.common.security.keyderiv.DerivedKey;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.eactive.eai.custom.common.security.keyderiv.HsmContextSha256KeyDerivationStrategy;
|
|
||||||
import com.eactive.eai.custom.common.security.keyderiv.HsmKeyAndIvSliceDerivationStrategy;
|
|
||||||
import com.eactive.eai.util.HexaConverter;
|
|
||||||
import com.eactive.eai.util.JsonPathUtil;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
public class GenKeyFilter implements HttpAdapterFilter {
|
|
||||||
|
|
||||||
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
try {
|
|
||||||
ObjectNode rootNode = (ObjectNode)JsonPathUtil.toTree(message);
|
|
||||||
|
|
||||||
JsonNode hsmKey = rootNode.get("hsmKey");
|
|
||||||
JsonNode hsmIv = rootNode.get("hsmIv");
|
|
||||||
JsonNode contextKey = rootNode.get("contextKey");
|
|
||||||
JsonNode type = rootNode.get("type");
|
|
||||||
|
|
||||||
JsonNode enc = rootNode.get("enc");
|
|
||||||
String strEnc = "BASE64";
|
|
||||||
if(enc != null)
|
|
||||||
strEnc = enc.asText();
|
|
||||||
|
|
||||||
byte[] binIv = null;
|
|
||||||
if(hsmIv != null) {
|
|
||||||
String strIvValue = hsmIv.asText();
|
|
||||||
if(strIvValue.length() == 32||strEnc.equalsIgnoreCase("HEX"))
|
|
||||||
binIv = HexaConverter.hexToBin(strIvValue);
|
|
||||||
else
|
|
||||||
binIv = Base64.getDecoder().decode(strIvValue.trim());
|
|
||||||
}
|
|
||||||
|
|
||||||
String strEncKeyValue = hsmKey.asText();
|
|
||||||
byte[] binEncKey = null;
|
|
||||||
if(strEnc.equalsIgnoreCase("BASE64"))
|
|
||||||
binEncKey = Base64.getDecoder().decode(strEncKeyValue.trim());
|
|
||||||
else
|
|
||||||
binEncKey = HexaConverter.hexToBin(strEncKeyValue);
|
|
||||||
|
|
||||||
DerivedKey derivedKey = null;
|
|
||||||
if(type.asText().equals("douzone")) {
|
|
||||||
Map<String, String> params = new HashMap<>();
|
|
||||||
Map<String, String> runtimeContext = new HashMap<>();
|
|
||||||
params.put("contextKey", "contextKey");
|
|
||||||
runtimeContext.put("contextKey", contextKey.asText());
|
|
||||||
HsmContextSha256KeyDerivationStrategy douzoneStrategy = new HsmContextSha256KeyDerivationStrategy();
|
|
||||||
derivedKey = douzoneStrategy.deriveKey(params, runtimeContext, binEncKey);
|
|
||||||
} else if(type.asText().equals("kakaobank")) {
|
|
||||||
HsmKeyAndIvSliceDerivationStrategy kakaobank = new HsmKeyAndIvSliceDerivationStrategy();
|
|
||||||
derivedKey = kakaobank.deriveKey(binEncKey, binIv);
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonNode aad = rootNode.get("aad");
|
|
||||||
if (aad != null) {
|
|
||||||
rootNode.put("generatedAdd", HexaConverter.binToHex(aad.asText().getBytes()));
|
|
||||||
}
|
|
||||||
|
|
||||||
String encBase64 = Base64.getEncoder().encodeToString(derivedKey.getDecKey());
|
|
||||||
logger.debug("generated KEY {} : [{}]", type.asText(), encBase64);
|
|
||||||
rootNode.put("generatedKeyBase64", encBase64);
|
|
||||||
rootNode.put("generatedKeyHex", HexaConverter.binToHex(derivedKey.getDecKey()));
|
|
||||||
rootNode.put("generatedKeyRaw", new String(derivedKey.getDecKey()));
|
|
||||||
|
|
||||||
if(derivedKey.getIv() != null) {
|
|
||||||
String encBase64Iv = Base64.getEncoder().encodeToString(derivedKey.getIv());
|
|
||||||
logger.debug("generated IV {} : [{}]", type.asText(), encBase64Iv);
|
|
||||||
rootNode.put("generatedIvBase64", encBase64Iv);
|
|
||||||
rootNode.put("generatedIvHex", HexaConverter.binToHex(derivedKey.getIv()));
|
|
||||||
rootNode.put("generatedIvRaw", new String(derivedKey.getIv()));
|
|
||||||
}
|
|
||||||
String jsonString = OBJECT_MAPPER.writeValueAsString(rootNode);
|
|
||||||
return jsonString;
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new FilterException("HSM key 암호화/복호화 검증 실패", ERROR_PRE_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-80
@@ -1,80 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.security.KeyStore;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.crypto.SecretKey;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import org.json.simple.JSONObject;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.FilterException;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.common.hsm.HsmManager;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.eactive.eai.util.HexaConverter;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
public class HSMKeyCryptoFilter implements HttpAdapterFilter {
|
|
||||||
|
|
||||||
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
try {
|
|
||||||
ObjectNode rootNode = null;
|
|
||||||
String jsonStr = null;
|
|
||||||
if (message instanceof String) {
|
|
||||||
jsonStr = (String) message;
|
|
||||||
} else if (message instanceof JSONObject) {
|
|
||||||
jsonStr = ((JSONObject) message).toJSONString();
|
|
||||||
} else if (message instanceof ObjectNode) {
|
|
||||||
rootNode = (ObjectNode) message;
|
|
||||||
} else {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rootNode == null)
|
|
||||||
rootNode = (ObjectNode) OBJECT_MAPPER.readTree(jsonStr);
|
|
||||||
|
|
||||||
JsonNode hsmKeyAlias = rootNode.get("hsmKeyAlias");
|
|
||||||
if (hsmKeyAlias != null) {
|
|
||||||
String hsmKeyAliasValue = hsmKeyAlias.textValue();
|
|
||||||
KeyStore keyStore = HsmManager.getInstance().getKeyStore();
|
|
||||||
|
|
||||||
java.security.Key key = keyStore.getKey(hsmKeyAliasValue, null);
|
|
||||||
if (key instanceof SecretKey) {
|
|
||||||
SecretKey secretKey = (SecretKey) key;
|
|
||||||
byte[] encoded = secretKey.getEncoded();
|
|
||||||
if (encoded != null) {
|
|
||||||
String encBase64 = Base64.getEncoder().encodeToString(encoded);
|
|
||||||
logger.debug("HsmManager] HSM - {} : [{}]", hsmKeyAliasValue, encBase64);
|
|
||||||
rootNode.put("hsmKeyBase64", encBase64);
|
|
||||||
rootNode.put("hsmKeyRaw", HexaConverter.binToHex(encoded));
|
|
||||||
} else {
|
|
||||||
logger.debug("HsmManager] HSM - secretKey null {} : [{}]", hsmKeyAliasValue, secretKey);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return rootNode;
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new FilterException("HSM key 가져오기 실패", ERROR_PRE_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.FilterException;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.common.util.JacksonUtil;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 카카오뱅크 암복호화에 맟추어 커스텀 필요
|
|
||||||
*/
|
|
||||||
public class KakaopayFilter implements HttpAdapterFilter {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
|
|
||||||
// 인자 1개 오버로드는 JacksonUtil 내부의 number-safe 싱글턴 mapper 를 쓴다.
|
|
||||||
JsonNode rootNode = JacksonUtil.readTree(message);
|
|
||||||
|
|
||||||
// term_agreements[0].is_agreed 값이 true 인지 확인
|
|
||||||
boolean firstAgreed = JacksonUtil.getBoolean(rootNode, "term_agreements[0].is_agreed", false);
|
|
||||||
|
|
||||||
if (!firstAgreed) {
|
|
||||||
throw new FilterException("EB000003", "금리한도조회실패 - 고객 요청으로 인한 CB 조회 실패", 200);
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
+766
@@ -0,0 +1,766 @@
|
|||||||
|
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);
|
||||||
|
// }
|
||||||
|
}
|
||||||
-336
@@ -1,336 +0,0 @@
|
|||||||
|
|
||||||
package com.eactive.eai.custom.authoutbound.client.impl;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.charset.Charset;
|
|
||||||
import java.security.KeyManagementException;
|
|
||||||
import java.security.KeyStoreException;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.security.UnrecoverableKeyException;
|
|
||||||
import java.security.cert.CertificateException;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
import javax.net.ssl.SSLContext;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
|
||||||
import org.apache.hc.client5.http.config.RequestConfig;
|
|
||||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
|
||||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
|
||||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
|
||||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
|
|
||||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
|
|
||||||
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
|
|
||||||
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
|
|
||||||
import org.apache.hc.client5.http.ssl.TrustAllStrategy;
|
|
||||||
import org.apache.hc.core5.http.HttpEntity;
|
|
||||||
import org.apache.hc.core5.http.HttpHost;
|
|
||||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
|
||||||
import org.apache.hc.core5.ssl.SSLContextBuilder;
|
|
||||||
import org.apache.hc.core5.util.Timeout;
|
|
||||||
import org.springframework.security.web.util.UrlUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
|
||||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
|
||||||
import com.eactive.eai.adapter.http.secure.HttpClient5SSLContextFactory;
|
|
||||||
import com.eactive.eai.authoutbound.OutboundOAuthCredentialVo;
|
|
||||||
import com.eactive.eai.authoutbound.client.HttpClientAccessTokenServiceByDB;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.eactive.eai.httpouttlsinfo.HttpOutTlsInfoManager;
|
|
||||||
import com.eactive.eai.httpouttlsinfo.HttpOutTlsInfoVO;
|
|
||||||
import com.eactive.eai.util.TestModeChecker;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
|
||||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 1. 기능 : HTTP 웹 컴포넌트를 POST 방식으로 호출할 수 있는 기능을 제공한다. 2. 처리 개요 : * - 2009.11.24
|
|
||||||
* retry 로직 제거 : 요청 3. 주의사항
|
|
||||||
*
|
|
||||||
* @author :
|
|
||||||
* @version : v 1.0.0
|
|
||||||
* @see : WLIAdapterFactory.java, WLIAdapter.java, WLIDefaultAdapter.java
|
|
||||||
* @since :
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class DJBErpNsmapiAccessTokenService implements HttpClientAccessTokenServiceByDB {
|
|
||||||
|
|
||||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
|
||||||
|
|
||||||
private static boolean testMode = TestModeChecker.isTestMode();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* mTLS 여부/clientId 조합별로 CloseableHttpClient(및 내부 PoolingHttpClientConnectionManager)를
|
|
||||||
* 1회만 생성해 재사용한다. 이 서비스 인스턴스는 HttpClientAccessTokenServiceFactoryByDB에
|
|
||||||
* className 기준으로 캐시되어 재사용되므로, 이 필드도 인스턴스 생명주기 동안 안전하게 재사용된다.
|
|
||||||
*/
|
|
||||||
private final ConcurrentHashMap<String, CloseableHttpClient> httpClientCache = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 1. 기능 : 법인검증 토큰 발급에 사용 2. 처리 개요 : - 속성 정보를 설정 하고 토큰 발급 URL 호출 한다. 3. 주의사항
|
|
||||||
* - JSON 방식
|
|
||||||
* - ( Header Authorization Basic <base64_Encode(client_id:client_secret)> ) 으로 구성
|
|
||||||
* @param adapterProp Http Adapter 속성 정보
|
|
||||||
* @return 반환 된 AccessTokenVO
|
|
||||||
* @exception Exception 수동 시스템 간 통신 중 발생
|
|
||||||
**/
|
|
||||||
public AccessTokenVO execute(String name, Properties adapterProp, OutboundOAuthCredentialVo oAuthCredentialVo)
|
|
||||||
throws Exception {
|
|
||||||
AdapterGroupVO gvo = AdapterManager.getInstance().getAdapterGroupVO(name);
|
|
||||||
String adapterUrl = adapterProp.getProperty("URL");
|
|
||||||
String encode = gvo.getMessageEncode();
|
|
||||||
String timeoutTemp = adapterProp.getProperty("HTTP_TIME_OUT");
|
|
||||||
if (StringUtils.isBlank(timeoutTemp)) {
|
|
||||||
timeoutTemp = "30000";
|
|
||||||
}
|
|
||||||
String connectionTimeoutTemp = adapterProp.getProperty("CONNECTION_TIMEOUT");
|
|
||||||
if (StringUtils.isBlank(connectionTimeoutTemp)) {
|
|
||||||
connectionTimeoutTemp = "3000";
|
|
||||||
}
|
|
||||||
|
|
||||||
int timeout = Integer.parseInt(timeoutTemp);
|
|
||||||
int connectionTimeout = Integer.parseInt(connectionTimeoutTemp);
|
|
||||||
long currentTime = System.currentTimeMillis();
|
|
||||||
|
|
||||||
String uri = oAuthCredentialVo.getUrl();
|
|
||||||
|
|
||||||
if (!UrlUtils.isAbsoluteUrl(uri)) {
|
|
||||||
uri = appendPath(adapterUrl, uri);
|
|
||||||
}
|
|
||||||
String contentType = "application/json;";
|
|
||||||
|
|
||||||
Charset charset;
|
|
||||||
if (StringUtils.isNotBlank(encode)) {
|
|
||||||
charset = Charset.forName(encode);
|
|
||||||
} else {
|
|
||||||
charset = Charset.defaultCharset();
|
|
||||||
encode = charset.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean useForwardProxy = StringUtils.equalsIgnoreCase(adapterProp.getProperty("FORWARD_PROXY_USE_YN"), "Y");
|
|
||||||
String forwardProxyUrl = adapterProp.getProperty("FORWARD_PROXY_URL");
|
|
||||||
|
|
||||||
logger.debug(
|
|
||||||
"uri:{}, charset:{}, transactionTimeout:{}, connectionTimeout:{}, useForwardProxy:{}, forwardProxyUrl:{}",
|
|
||||||
uri, encode, timeout, connectionTimeout, useForwardProxy, forwardProxyUrl);
|
|
||||||
|
|
||||||
|
|
||||||
// mTLS config with default connection parameters
|
|
||||||
boolean useMtls = StringUtils.equalsIgnoreCase(adapterProp.getProperty(HttpClientAdapterServiceKey.USE_MTLS),
|
|
||||||
"Y");
|
|
||||||
AdapterGroupVO adapterGroup = AdapterManager.getInstance().getAdapterGroup(name);
|
|
||||||
String clientId = adapterGroup.getClientId();
|
|
||||||
|
|
||||||
if (logger.isInfo()) {
|
|
||||||
logger.info("adapterGroupName. : {}, useMtls. : {}, clientId : {}", name, useMtls, clientId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// mTLS 여부(및 clientId)별로 CloseableHttpClient를 재사용한다. 매 호출마다 새로 만들면
|
|
||||||
// PoolingHttpClientConnectionManager를 쓰는 의미가 없어지고 SSL 핸드셰이크 비용만 반복된다.
|
|
||||||
String httpClientCacheKey = useMtls ? "mtls:" + clientId : "default";
|
|
||||||
CloseableHttpClient httpClient = httpClientCache.computeIfAbsent(httpClientCacheKey,
|
|
||||||
key -> buildHttpClient(useMtls, clientId, name));
|
|
||||||
|
|
||||||
//json body setting
|
|
||||||
// Map<String,Object> jsonMap = new HashMap<>();
|
|
||||||
// jsonMap.put("scope",oAuthCredentialVo.getScope());
|
|
||||||
// jsonMap.put("grant_type",oAuthCredentialVo.getGrantType());
|
|
||||||
// ObjectMapper objMapper = new ObjectMapper();
|
|
||||||
// String authJsonBody = objMapper.writeValueAsString(jsonMap);
|
|
||||||
|
|
||||||
{
|
|
||||||
HttpPost httpPost = new HttpPost(uri);
|
|
||||||
// httpPost.setEntity(new StringEntity(authJsonBody));
|
|
||||||
httpPost.setHeader("Content-Type", contentType+" charset=" + encode);
|
|
||||||
|
|
||||||
//HTTP HEADER에 client id, client secret를 base64Encode 한 후 추가
|
|
||||||
// String cId = oAuthCredentialVo.getClientId();
|
|
||||||
// String cSecret = oAuthCredentialVo.getClientSecret();
|
|
||||||
// String authValue = cId + ":" + cSecret;
|
|
||||||
// String encodedAuth = Base64.getEncoder().encodeToString(authValue.getBytes(StandardCharsets.UTF_8));
|
|
||||||
|
|
||||||
String encodedAuth = oAuthCredentialVo.getClientId();
|
|
||||||
httpPost.setHeader("Authorization","Basic "+ encodedAuth);
|
|
||||||
|
|
||||||
|
|
||||||
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
|
|
||||||
|
|
||||||
if (useForwardProxy) {
|
|
||||||
java.net.URL url = new java.net.URL(forwardProxyUrl);
|
|
||||||
|
|
||||||
// 프로토콜, 호스트, 포트 추출
|
|
||||||
String protocol = url.getProtocol();
|
|
||||||
String host = url.getHost();
|
|
||||||
int port = url.getPort();
|
|
||||||
HttpHost proxy = new HttpHost(protocol, host, port);
|
|
||||||
requestConfigBuilder.setProxy(proxy);
|
|
||||||
}
|
|
||||||
|
|
||||||
RequestConfig requestConfig = requestConfigBuilder
|
|
||||||
.setConnectTimeout(Timeout.ofMilliseconds(connectionTimeout))
|
|
||||||
.setResponseTimeout(Timeout.ofMilliseconds(timeout)).build();
|
|
||||||
httpPost.setConfig(requestConfig);
|
|
||||||
|
|
||||||
logger.debug("uri = [" + uri + "]");
|
|
||||||
logger.debug("oauthClientId = [" + oAuthCredentialVo.getClientId() + "]");
|
|
||||||
logger.debug("oauthClientSecret = [" + oAuthCredentialVo.getClientSecret() + "]");
|
|
||||||
logger.debug("oauthScope = [" + oAuthCredentialVo.getScope() + "]");
|
|
||||||
logger.debug("oauthGrantType = [" + oAuthCredentialVo.getGrantType() + "]");
|
|
||||||
logger.debug("oauthauthValue = [" + encodedAuth + "]");
|
|
||||||
logger.debug("contentType = [" + contentType + "]");
|
|
||||||
logger.debug("encode = [" + encode + "]");
|
|
||||||
|
|
||||||
OAuth2AccessTokenVO accessToken = null;
|
|
||||||
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
|
|
||||||
if (response.getCode() != 200) {
|
|
||||||
throw new Exception("OAuth token receive status fail value= " + response.getCode());
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info("DJBErpNsmapiAccessTokenService==>" + response.getCode());
|
|
||||||
|
|
||||||
HttpEntity entity = response.getEntity();
|
|
||||||
String responseString = EntityUtils.toString(entity, encode);
|
|
||||||
logger.debug("Base64Header oauthToken RECV = [" + responseString + "]");
|
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(responseString)) {
|
|
||||||
|
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
JsonNode responseJSON = objectMapper.readTree(responseString);
|
|
||||||
|
|
||||||
if (responseJSON.has("data")) {
|
|
||||||
JsonNode data = responseJSON.path("data");
|
|
||||||
if(data.has("access_token")) {
|
|
||||||
String token = data.path("access_token").asText();
|
|
||||||
long intervalSec = oAuthCredentialVo.getIntervalSec() > 0
|
|
||||||
? oAuthCredentialVo.getIntervalSec()
|
|
||||||
: 24 * 60 * 60;
|
|
||||||
accessToken = new OAuth2AccessTokenVO();
|
|
||||||
accessToken.setAccessToken(token);
|
|
||||||
accessToken.setExpiration(new Date(currentTime + intervalSec * 1000L));
|
|
||||||
logger.debug("oauthToken =" + accessToken.toString());
|
|
||||||
return accessToken;
|
|
||||||
} else {
|
|
||||||
throw new Exception("oauth token return null");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw new Exception("oauth token return null");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw new Exception("oauth token return null");
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error("[DJBErpNsmapiAccessTokenService] retrieve accessToken exception :" + e.getMessage(), e);
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* mTLS 여부/clientId 조합에 맞는 SSLContext로 PoolingHttpClientConnectionManager와
|
|
||||||
* CloseableHttpClient를 생성한다. httpClientCache에 의해 조합당 1회만 호출되며, 반환된
|
|
||||||
* CloseableHttpClient는 재사용을 위해 닫지 않는다(닫으면 커넥션 풀이 함께 종료된다).
|
|
||||||
*/
|
|
||||||
private CloseableHttpClient buildHttpClient(boolean useMtls, String clientId, String adapterGroupName) {
|
|
||||||
int maxTotalConnections = HttpClientAdapterServiceKey.DEFAULT_MAX_TOTAL_CONNECTIONS;
|
|
||||||
int maxHostConnections = HttpClientAdapterServiceKey.DEFAULT_MAX_CONNECTION_PER_HOST;
|
|
||||||
|
|
||||||
HttpOutTlsInfoVO mtlsInfo = null;
|
|
||||||
SSLContext sslContext = null;
|
|
||||||
PoolingHttpClientConnectionManagerBuilder cmBuilder = PoolingHttpClientConnectionManagerBuilder.create();
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (useMtls) {
|
|
||||||
HttpOutTlsInfoManager tlsManager = HttpOutTlsInfoManager.getInstance();
|
|
||||||
if (StringUtils.isNotEmpty(clientId)) {
|
|
||||||
mtlsInfo = tlsManager.getHttpOutTlsInfo(clientId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (useMtls && mtlsInfo != null) {
|
|
||||||
String storeType = mtlsInfo.getStoreType();
|
|
||||||
String keyStoreInfo = mtlsInfo.getKeystoreInfo();
|
|
||||||
String keyStorePassword = mtlsInfo.getKeystorePassword();
|
|
||||||
String trustStoreInfo = mtlsInfo.getTruststoreInfo();
|
|
||||||
String trustStorePassword = mtlsInfo.getTruststorePassword();
|
|
||||||
|
|
||||||
String[] tlsVersions = null;
|
|
||||||
String[] cipherSuites = null;
|
|
||||||
|
|
||||||
if (StringUtils.isAnyEmpty(keyStoreInfo, keyStorePassword)) {
|
|
||||||
throw new Exception("mTLS keyStore config error");
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean skipTrust = false;
|
|
||||||
if (StringUtils.isAnyEmpty(trustStoreInfo, trustStorePassword)) {
|
|
||||||
if (logger.isWarn())
|
|
||||||
logger.warn("Skip trustStore validation adapterGroupName : " + adapterGroupName);
|
|
||||||
skipTrust = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
sslContext = HttpClient5SSLContextFactory.createMTLSContextFromContent(storeType, keyStoreInfo,
|
|
||||||
keyStorePassword, trustStoreInfo, trustStorePassword, skipTrust, tlsVersions, cipherSuites);
|
|
||||||
|
|
||||||
SSLConnectionSocketFactory sslSocketFactory = null;
|
|
||||||
if (testMode) {
|
|
||||||
sslSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
|
|
||||||
} else {
|
|
||||||
sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
|
|
||||||
}
|
|
||||||
cmBuilder.setSSLSocketFactory(sslSocketFactory);
|
|
||||||
} else {
|
|
||||||
sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustAllStrategy()).build();
|
|
||||||
SSLConnectionSocketFactory sslSocketFactory = null;
|
|
||||||
if(testMode) {
|
|
||||||
// Hostname verifier 비활성화 (테스트용)
|
|
||||||
sslSocketFactory = new SSLConnectionSocketFactory(
|
|
||||||
sslContext
|
|
||||||
, NoopHostnameVerifier.INSTANCE
|
|
||||||
);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
sslSocketFactory = new SSLConnectionSocketFactory(
|
|
||||||
sslContext
|
|
||||||
);
|
|
||||||
}
|
|
||||||
cmBuilder.setSSLSocketFactory(sslSocketFactory);
|
|
||||||
}
|
|
||||||
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException
|
|
||||||
| IOException | UnrecoverableKeyException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
|
|
||||||
PoolingHttpClientConnectionManager connectionManager = cmBuilder.build();
|
|
||||||
connectionManager.setMaxTotal(maxTotalConnections);
|
|
||||||
connectionManager.setDefaultMaxPerRoute(maxHostConnections);
|
|
||||||
|
|
||||||
if (logger.isInfo()) {
|
|
||||||
logger.info("DJBErpNsmapiAccessTokenService] HttpClient(재사용) 생성. adapterGroupName={}, useMtls={}, clientId={}",
|
|
||||||
adapterGroupName, useMtls, clientId);
|
|
||||||
}
|
|
||||||
|
|
||||||
return HttpClients.custom().setConnectionManager(connectionManager).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* URL에 경로를 추가합니다. 중복되는 슬래시를 방지합니다.
|
|
||||||
*
|
|
||||||
* @param baseUrl 기본 URL
|
|
||||||
* @param pathToAdd 추가할 경로
|
|
||||||
* @return 완성된 URL 문자열
|
|
||||||
*/
|
|
||||||
public static String appendPath(String baseUrl, String pathToAdd) {
|
|
||||||
if (!baseUrl.endsWith("/") && !pathToAdd.startsWith("/")) {
|
|
||||||
return baseUrl + "/" + pathToAdd;
|
|
||||||
} else if (baseUrl.endsWith("/") && pathToAdd.startsWith("/")) {
|
|
||||||
return baseUrl + pathToAdd.substring(1);
|
|
||||||
} else {
|
|
||||||
return baseUrl + pathToAdd;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+14
-10
@@ -2,11 +2,14 @@ package com.eactive.eai.custom.common.security.keyderiv;
|
|||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.security.MessageDigest;
|
import java.security.MessageDigest;
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
|
import javax.crypto.SecretKey;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.hsm.HsmCryptoService;
|
||||||
import com.eactive.eai.common.security.keyderiv.DerivedKey;
|
import com.eactive.eai.common.security.keyderiv.DerivedKey;
|
||||||
import com.eactive.eai.common.security.keyderiv.strategy.BaseHsmKeyDerivationStrategy;
|
import com.eactive.eai.common.security.keyderiv.KeyDerivationStrategy;
|
||||||
|
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HSM 마스터키 + 런타임 컨텍스트값을 연결(concatenate)한 뒤 SHA-256 해싱으로 키를 도출하는 전략.
|
* HSM 마스터키 + 런타임 컨텍스트값을 연결(concatenate)한 뒤 SHA-256 해싱으로 키를 도출하는 전략.
|
||||||
@@ -18,18 +21,15 @@ import com.eactive.eai.common.security.keyderiv.strategy.BaseHsmKeyDerivationStr
|
|||||||
* "contextKey" : "X-Api-Group-Seq" -- runtimeContext에서 꺼낼 키 이름
|
* "contextKey" : "X-Api-Group-Seq" -- runtimeContext에서 꺼낼 키 이름
|
||||||
* }
|
* }
|
||||||
*/
|
*/
|
||||||
public class HsmContextSha256KeyDerivationStrategy extends BaseHsmKeyDerivationStrategy {
|
public class HsmContextSha256KeyDerivationStrategy implements KeyDerivationStrategy {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext) throws Exception {
|
public DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext) throws Exception {
|
||||||
byte[] masterKeyBytes = super.getHsmKey(params);
|
String hsmKeyAlias = required(params, PARAM_HSM_KEY_ALIAS);
|
||||||
|
|
||||||
return deriveKey(params, runtimeContext, masterKeyBytes);
|
|
||||||
}
|
|
||||||
|
|
||||||
public DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext, byte[] masterKeyBytes)
|
|
||||||
throws NoSuchAlgorithmException {
|
|
||||||
String contextKey = required(params, PARAM_CONTEXT_KEY);
|
String contextKey = required(params, PARAM_CONTEXT_KEY);
|
||||||
|
|
||||||
|
SecretKey masterKey = hsmCryptoService().getSecretKey(hsmKeyAlias);
|
||||||
|
byte[] masterKeyBytes = masterKey.getEncoded();
|
||||||
byte[] contextBytes = runtimeContext.getOrDefault(contextKey, "")
|
byte[] contextBytes = runtimeContext.getOrDefault(contextKey, "")
|
||||||
.getBytes(StandardCharsets.UTF_8);
|
.getBytes(StandardCharsets.UTF_8);
|
||||||
|
|
||||||
@@ -55,4 +55,8 @@ public class HsmContextSha256KeyDerivationStrategy extends BaseHsmKeyDerivationS
|
|||||||
}
|
}
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private HsmCryptoService hsmCryptoService() {
|
||||||
|
return ApplicationContextProvider.getContext().getBean(HsmCryptoService.class);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-6
@@ -24,11 +24,7 @@ public class HsmKeyAndIvSliceDerivationStrategy extends BaseHsmKeyDerivationStra
|
|||||||
public DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext) throws Exception {
|
public DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext) throws Exception {
|
||||||
byte[] keyBytes = super.getHsmKey(params);
|
byte[] keyBytes = super.getHsmKey(params);
|
||||||
byte[] rawIv = super.getHsmIv(params);
|
byte[] rawIv = super.getHsmIv(params);
|
||||||
return deriveKey(keyBytes, rawIv);
|
String ivHex = DatatypeConverter.printHexBinary(rawIv);
|
||||||
}
|
|
||||||
|
|
||||||
public DerivedKey deriveKey(byte[] keyBytes, byte[] rawIv) {
|
|
||||||
String ivHex = DatatypeConverter.printHexBinary(rawIv);
|
|
||||||
if (ivHex.length() < IV_HEX_END) {
|
if (ivHex.length() < IV_HEX_END) {
|
||||||
throw new IllegalArgumentException(
|
throw new IllegalArgumentException(
|
||||||
"hsmIvAlias hex 길이 부족: 최소 " + IV_HEX_END + "자 필요, 실제=" + ivHex.length()
|
"hsmIvAlias hex 길이 부족: 최소 " + IV_HEX_END + "자 필요, 실제=" + ivHex.length()
|
||||||
@@ -36,7 +32,7 @@ public class HsmKeyAndIvSliceDerivationStrategy extends BaseHsmKeyDerivationStra
|
|||||||
}
|
}
|
||||||
byte[] iv = DatatypeConverter.parseHexBinary(ivHex.substring(IV_HEX_OFFSET, IV_HEX_END));
|
byte[] iv = DatatypeConverter.parseHexBinary(ivHex.substring(IV_HEX_OFFSET, IV_HEX_END));
|
||||||
return new DerivedKey(keyBytes, keyBytes, iv);
|
return new DerivedKey(keyBytes, keyBytes, iv);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String buildCacheKey(String cryptoName, Map<String, String> params, Map<String, String> runtimeContext) {
|
public String buildCacheKey(String cryptoName, Map<String, String> params, Map<String, String> runtimeContext) {
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ public final class GUIDGeneratorDJB {
|
|||||||
|
|
||||||
static {
|
static {
|
||||||
// 노드번호(2): 서버명 마지막 2자리, 없으면 "00"
|
// 노드번호(2): 서버명 마지막 2자리, 없으면 "00"
|
||||||
String serverName = System.getProperty(com.eactive.eai.common.server.Keys.SERVER_KEY, "");
|
String serverName = System.getProperty("server.key", "");
|
||||||
if (serverName.length() >= 2) {
|
if (serverName.length() >= 2) {
|
||||||
NODE_NO = serverName.substring(serverName.length() - 2);
|
NODE_NO = serverName.substring(serverName.length() - 2);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -77,15 +77,7 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
|
|||||||
|
|
||||||
// DATA 영역 경로
|
// DATA 영역 경로
|
||||||
public static final String DATA_SCOP_LEN = "DATA.data_scop_len";
|
public static final String DATA_SCOP_LEN = "DATA.data_scop_len";
|
||||||
|
|
||||||
// 정상 응답 메시지.
|
|
||||||
// 예전에는 표준전문 레이아웃의 기본값으로 붙였으나, 그렇게 두면 "아무도 채우지 않은 상태" 와
|
|
||||||
// "정상이라고 판정한 상태" 가 구분되지 않는다. 실제로 2026-09 사고에서 MSG 부 파싱이 통째로
|
|
||||||
// 스킵됐는데도 오류가 "정상처리되었습니다." 로 보고됐다.
|
|
||||||
// 이제 레이아웃 기본값을 없애고, 정상이라고 판정한 지점에서만 명시적으로 설정한다.
|
|
||||||
public static final String NORMAL_OUTP_MSG_CD = "NCMM00001";
|
|
||||||
public static final String NORMAL_OUTP_MSG_CTNT = "정상처리되었습니다.";
|
|
||||||
|
|
||||||
private String[] netInfo;
|
private String[] netInfo;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -164,21 +156,7 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
|
|||||||
standardMessage.setData(HEAD_MESG_RSPN_DT, now.format(FMT_DATE));
|
standardMessage.setData(HEAD_MESG_RSPN_DT, now.format(FMT_DATE));
|
||||||
standardMessage.setData(HEAD_MESG_RSPN_TIME, now.format(FMT_TIME_MILLIS));
|
standardMessage.setData(HEAD_MESG_RSPN_TIME, now.format(FMT_TIME_MILLIS));
|
||||||
|
|
||||||
// 정상 응답의 MSG 코드/메시지를 여기서 채운다. 레이아웃 기본값을 없앴으므로
|
|
||||||
// 이 지점이 정상 응답 메시지의 유일한 출처다.
|
|
||||||
// coordinateBeforeResponse 는 모든 동기 응답이 거치는 마지막 관문이라
|
|
||||||
// (RequestProcessor 에서 호출) 경로를 빠짐없이 덮는다.
|
|
||||||
//
|
|
||||||
// 반드시 두 조건을 함께 본다.
|
|
||||||
// 1) 정상 응답일 때만. 오류 응답에 "정상처리되었습니다." 를 채우면 2026-09 사고
|
|
||||||
// (MSG 부가 버려졌는데 오류가 정상으로 보고됨)를 코드로 재현하는 셈이다.
|
|
||||||
// 2) 값이 비어 있을 때만. 대외계가 표준응답으로 MSG 를 채워 보낸 경우 그 값이
|
|
||||||
// 우선이며 덮어쓰면 안 된다.
|
|
||||||
if (STDMessageKeys.RESPONSE_TYPE_CODE_N.equals(mapper.getResponseType(standardMessage))) {
|
|
||||||
setIfBlank(standardMessage, MSG_OUTP_MSG_CD, NORMAL_OUTP_MSG_CD);
|
|
||||||
setIfBlank(standardMessage, MSG_OUTP_MSG_CTNT, NORMAL_OUTP_MSG_CTNT);
|
|
||||||
}
|
|
||||||
|
|
||||||
StandardItem msgListRowCnt = standardMessage.findItem(StandardMessageCoordinatorDJB.MSG_LIST_ROWCNT);
|
StandardItem msgListRowCnt = standardMessage.findItem(StandardMessageCoordinatorDJB.MSG_LIST_ROWCNT);
|
||||||
if (msgListRowCnt == null || "0".equals(msgListRowCnt.getValue()) || "".equals(msgListRowCnt.getValue())) {
|
if (msgListRowCnt == null || "0".equals(msgListRowCnt.getValue()) || "".equals(msgListRowCnt.getValue())) {
|
||||||
StandardItem msgPart = standardMessage.findItem("MSG");
|
StandardItem msgPart = standardMessage.findItem("MSG");
|
||||||
@@ -231,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) {
|
||||||
setIfPresent(row, "outp_msg_cd", siteErrCode);
|
if (row.containsKey("outp_msg_cd")) row.get("outp_msg_cd").setValue(siteErrCode);
|
||||||
setIfPresent(row, "outp_msg_ctnt", siteErrMsg);
|
if (row.containsKey("outp_msg_ctnt")) row.get("outp_msg_ctnt").setValue(siteErrMsg);
|
||||||
setIfPresent(row, "outp_msg_desc", siteErrDesc);
|
if (row.containsKey("outp_msg_desc")) row.get("outp_msg_desc").setValue(siteErrDesc);
|
||||||
setIfPresent(row, "err_occu_loct", errCode);
|
if (row.containsKey("err_occu_loct")) row.get("err_occu_loct").setValue(errCode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -271,9 +249,8 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
|
|||||||
mainMsgItem.setSize(1);
|
mainMsgItem.setSize(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// msg_dvcd=NM, outp_atrb_cd=0, msg_list_rowcnt=0 → 레이아웃 기본값 사용
|
// msg_dvcd=NM, outp_atrb_cd=0, outp_msg_cd, outp_msg_ctnt, msg_list_rowcnt=0
|
||||||
// outp_msg_cd, outp_msg_ctnt → 레이아웃 기본값을 없앴으므로 여기서는 비워 두고,
|
// → 모두 CSV 기본값 사용
|
||||||
// 모든 동기 응답이 거치는 coordinateBeforeResponse 에서 정상 응답일 때만 채운다.
|
|
||||||
|
|
||||||
makeMsgScopLen(responseMessage);
|
makeMsgScopLen(responseMessage);
|
||||||
}
|
}
|
||||||
@@ -282,28 +259,6 @@ 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 항목이 존재하고 값이 비어 있을 때만 설정한다.
|
|
||||||
* 이미 채워진 값(대외계가 보낸 MSG, 오류 경로가 설정한 값 등)은 그대로 보존한다.
|
|
||||||
*/
|
|
||||||
private void setIfBlank(StandardMessage standardMessage, String path, String value) {
|
|
||||||
StandardItem item = standardMessage.findItem(path);
|
|
||||||
if (item != null && StringUtils.isBlank(item.getValue())) {
|
|
||||||
item.setValue(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void resolveCallPropRefValues(StandardMessage standardMessage, Properties prop) {
|
private void resolveCallPropRefValues(StandardMessage standardMessage, Properties prop) {
|
||||||
if (prop == null) return;
|
if (prop == null) return;
|
||||||
resolveCallPropInChilds(standardMessage.getChilds(), prop);
|
resolveCallPropInChilds(standardMessage.getChilds(), prop);
|
||||||
@@ -320,8 +275,7 @@ 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) : "";
|
||||||
// 패턴상 group(1)은 필수 캡처 그룹이나, 널 역참조 정적분석 지적 대응으로 방어코드 추가
|
String resolved = resolveCallPropValue(prop, key);
|
||||||
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) {
|
||||||
@@ -431,10 +385,18 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
|
|||||||
if (StringUtils.isBlank(refPath) || StringUtils.isBlank(refValue)) {
|
if (StringUtils.isBlank(refPath) || StringUtils.isBlank(refValue)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
// 판정 기준은 StandardItem.matchRefCondition 하나로 통일한다.
|
String actualValue = StringUtils.trimToEmpty(standardMessage.findItemValue(refPath));
|
||||||
// (FlatReader 파싱 / FLAT 직렬화와 같은 기준이어야 블록 유무 판단이 어긋나지 않음)
|
boolean negate = refValue.startsWith("!");
|
||||||
return StandardItem.matchRefCondition(refValue,
|
String compareValue = negate ? refValue.substring(1) : refValue;
|
||||||
StringUtils.trimToEmpty(standardMessage.findItemValue(refPath)));
|
boolean matched = matchesAny(compareValue, actualValue);
|
||||||
|
return negate ? !matched : matched;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean matchesAny(String refValue, String actualValue) {
|
||||||
|
for (String v : refValue.split("\\|")) {
|
||||||
|
if (v.equals(actualValue)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void makeupDataScopLen(StandardMessage standardMessage, String charset) {
|
private void makeupDataScopLen(StandardMessage standardMessage, String charset) {
|
||||||
|
|||||||
+1
-2
@@ -81,8 +81,7 @@ public class MinuteStatsAggregator {
|
|||||||
systemErrCnt.incrementAndGet();
|
systemErrCnt.incrementAndGet();
|
||||||
break;
|
break;
|
||||||
case BUSINESS_ERROR:
|
case BUSINESS_ERROR:
|
||||||
systemErrCnt.incrementAndGet();
|
bizErrCnt.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 연동 복호화.
|
* JEP 트랜스포머 함수 — DJB ERP 연동 복호화.
|
||||||
*
|
*
|
||||||
* 사용법: djbdecryt(encBase64, moduleName)
|
* 사용법: DJBErpDecryt(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("DJBDecrypt: 파라미터는 2개개여야 합니다 (encBase64, moduleName");
|
throw new ParseException("DJBErpDecryt: 파라미터는 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("DJBDecrypt 복호화 실패: " + e.getMessage());
|
throw new ParseException("DJBErpDecryt 복호화 실패: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,11 +11,13 @@ import org.nfunk.jep.function.PostfixMathCommand;
|
|||||||
import com.eactive.eai.common.security.CryptoModuleService;
|
import com.eactive.eai.common.security.CryptoModuleService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JEP 트랜스포머 함수 — DJB 연동 암호화.
|
* JEP 트랜스포머 함수 — DJB ERP 연동 암호화.
|
||||||
*
|
*
|
||||||
* 사용법: djbencrypt(plainText, moduleName)
|
* 사용법: DJBErpEncryt(plainText, moduleName) DJBErpEncryt(plainText, moduleName,
|
||||||
|
* groupSeq)
|
||||||
*
|
*
|
||||||
* 파라미터: plainText : 암호화할 평문 (String), moduleName : DB에 등록된 암호화 모듈명 (String)
|
* 파라미터: plainText : 암호화할 평문 (String) moduleName : DB에 등록된 암호화 모듈명 (String)
|
||||||
|
* groupSeq : 키 도출용 그룹 시퀀스 (String, 선택). 미전달 시 빈 context로 호출.
|
||||||
*
|
*
|
||||||
* 반환값: Base64 인코딩된 암호문 (String)
|
* 반환값: Base64 인코딩된 암호문 (String)
|
||||||
*/
|
*/
|
||||||
@@ -31,7 +33,7 @@ public class DJBEncrypt extends PostfixMathCommand {
|
|||||||
checkStack(inStack);
|
checkStack(inStack);
|
||||||
|
|
||||||
if (curNumberOfParameters != 2) {
|
if (curNumberOfParameters != 2) {
|
||||||
throw new ParseException("DJBEncrypt: 파라미터는 2개여야 합니다 (plainText, moduleName)");
|
throw new ParseException("DJBErpEncryt: 파라미터는 2개여야 합니다 (plainText, moduleName)");
|
||||||
}
|
}
|
||||||
|
|
||||||
String moduleName = inStack.pop().toString();
|
String moduleName = inStack.pop().toString();
|
||||||
@@ -44,7 +46,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("DJBEncrypt 암호화 실패: " + e.getMessage());
|
throw new ParseException("DJBErpEncryt 암호화 실패: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-5
@@ -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,9 +14,7 @@ import java.util.Stack;
|
|||||||
|
|
||||||
public class JsonPathExtractRequestMessage extends PostfixMathCommand {
|
public class JsonPathExtractRequestMessage extends PostfixMathCommand {
|
||||||
|
|
||||||
// JsonPath 의 기본 Jackson 프로바이더는 기본 ObjectMapper 를 쓴다. 그러면 JSON 실수가
|
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||||
// DoubleNode 로 파싱되어, 아래 asText() 결과가 100000000.00 -> "1.0E8" 로 깨진다.
|
|
||||||
private static final ObjectMapper objectMapper = JacksonUtil.newNumberSafeMapper();
|
|
||||||
|
|
||||||
public JsonPathExtractRequestMessage() {
|
public JsonPathExtractRequestMessage() {
|
||||||
numberOfParameters = -1;
|
numberOfParameters = -1;
|
||||||
@@ -35,7 +33,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(objectMapper))
|
.jsonProvider(new JacksonJsonNodeJsonProvider())
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
JsonNode resultNode = JsonPath.using(config).parse(bizData).read(path);
|
JsonNode resultNode = JsonPath.using(config).parse(bizData).read(path);
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package com.eactive.eai.custom.transformer.message;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
|
import com.eactive.eai.transformer.message.ISO8583Message;
|
||||||
|
import com.solab.iso8583.IsoMessage;
|
||||||
|
import com.solab.iso8583.IsoType;
|
||||||
|
import com.solab.iso8583.MessageFactory;
|
||||||
|
import com.solab.iso8583.parse.FieldParseInfo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <pre>
|
||||||
|
* ISO 8583 H2H(전문) 형식의 데이터를 변환하기 위한 메시지.(For KB Bukopin)
|
||||||
|
*
|
||||||
|
* [참조]
|
||||||
|
* https://en.wikipedia.org/wiki/ISO_8583
|
||||||
|
* </pre>
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("serial")
|
||||||
|
public class ISO8583H2HMessage extends ISO8583Message {
|
||||||
|
private static HashMap<Integer, FieldParseInfo> fullSpecMap = null;
|
||||||
|
private static HashMap<Integer, String> fullFieldNameMap = null;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public MessageFactory<IsoMessage> createMessageFactory() {
|
||||||
|
MessageFactory<IsoMessage> mf = new MessageFactory<>();
|
||||||
|
mf.setCharacterEncoding(System.getProperty("file.encoding"));
|
||||||
|
mf.setForceStringEncoding(false);
|
||||||
|
return mf;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HashMap<Integer, FieldParseInfo> getFullSpecMap(String encode) {
|
||||||
|
if (fullSpecMap != null) {
|
||||||
|
return fullSpecMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
fullSpecMap = new HashMap<>();
|
||||||
|
|
||||||
|
fullSpecMap.put(2, FieldParseInfo.getInstance(IsoType.LLVAR, 19, encode));
|
||||||
|
fullSpecMap.put(3, FieldParseInfo.getInstance(IsoType.NUMERIC, 6, encode));
|
||||||
|
fullSpecMap.put(4, FieldParseInfo.getInstance(IsoType.NUMERIC, 12, encode));
|
||||||
|
fullSpecMap.put(6, FieldParseInfo.getInstance(IsoType.NUMERIC, 12, encode));
|
||||||
|
fullSpecMap.put(7, FieldParseInfo.getInstance(IsoType.DATE10, 10, encode));
|
||||||
|
fullSpecMap.put(11, FieldParseInfo.getInstance(IsoType.NUMERIC, 6, encode));
|
||||||
|
fullSpecMap.put(12, FieldParseInfo.getInstance(IsoType.TIME, 6, encode));
|
||||||
|
fullSpecMap.put(13, FieldParseInfo.getInstance(IsoType.DATE4, 4, encode));
|
||||||
|
fullSpecMap.put(14, FieldParseInfo.getInstance(IsoType.DATE_EXP, 4, encode));
|
||||||
|
fullSpecMap.put(15, FieldParseInfo.getInstance(IsoType.DATE4, 4, encode));
|
||||||
|
fullSpecMap.put(18, FieldParseInfo.getInstance(IsoType.NUMERIC, 4, encode));
|
||||||
|
fullSpecMap.put(22, FieldParseInfo.getInstance(IsoType.NUMERIC, 3, encode));
|
||||||
|
fullSpecMap.put(24, FieldParseInfo.getInstance(IsoType.NUMERIC, 3, encode));
|
||||||
|
fullSpecMap.put(25, FieldParseInfo.getInstance(IsoType.NUMERIC, 2, encode));
|
||||||
|
fullSpecMap.put(26, FieldParseInfo.getInstance(IsoType.NUMERIC, 2, encode));
|
||||||
|
fullSpecMap.put(32, FieldParseInfo.getInstance(IsoType.LLVAR, 11, encode));
|
||||||
|
fullSpecMap.put(33, FieldParseInfo.getInstance(IsoType.LLVAR, 11, encode));
|
||||||
|
fullSpecMap.put(35, FieldParseInfo.getInstance(IsoType.LLVAR, 37, encode));
|
||||||
|
fullSpecMap.put(37, FieldParseInfo.getInstance(IsoType.ALPHA, 12, encode));
|
||||||
|
fullSpecMap.put(38, FieldParseInfo.getInstance(IsoType.ALPHA, 6, encode));
|
||||||
|
fullSpecMap.put(39, FieldParseInfo.getInstance(IsoType.ALPHA, 2, encode));
|
||||||
|
fullSpecMap.put(40, FieldParseInfo.getInstance(IsoType.ALPHA, 3, encode));
|
||||||
|
fullSpecMap.put(41, FieldParseInfo.getInstance(IsoType.ALPHA, 8, encode));
|
||||||
|
fullSpecMap.put(42, FieldParseInfo.getInstance(IsoType.ALPHA, 15, encode));
|
||||||
|
fullSpecMap.put(43, FieldParseInfo.getInstance(IsoType.ALPHA, 40, encode));
|
||||||
|
fullSpecMap.put(48, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||||
|
fullSpecMap.put(49, FieldParseInfo.getInstance(IsoType.ALPHA, 3, encode));
|
||||||
|
// fullSpecMap.put(52, FieldParseInfo.getInstance(IsoType.BINARY, 64, encode));
|
||||||
|
fullSpecMap.put(52, FieldParseInfo.getInstance(IsoType.ALPHA, 16, encode)); // 표준X
|
||||||
|
fullSpecMap.put(54, FieldParseInfo.getInstance(IsoType.LLLVAR, 120, encode));
|
||||||
|
fullSpecMap.put(55, FieldParseInfo.getInstance(IsoType.LLLVAR, 765, encode));
|
||||||
|
fullSpecMap.put(60, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||||
|
fullSpecMap.put(61, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||||
|
fullSpecMap.put(62, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||||
|
fullSpecMap.put(63, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||||
|
fullSpecMap.put(70, FieldParseInfo.getInstance(IsoType.NUMERIC, 3, encode));
|
||||||
|
fullSpecMap.put(90, FieldParseInfo.getInstance(IsoType.NUMERIC, 42, encode));
|
||||||
|
fullSpecMap.put(98, FieldParseInfo.getInstance(IsoType.ALPHA, 25, encode));
|
||||||
|
fullSpecMap.put(102, FieldParseInfo.getInstance(IsoType.LLVAR, 28, encode));
|
||||||
|
fullSpecMap.put(103, FieldParseInfo.getInstance(IsoType.LLVAR, 28, encode));
|
||||||
|
fullSpecMap.put(120, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||||
|
// fullSpecMap.put(126, FieldParseInfo.getInstance(IsoType.LLLVAR, 999,
|
||||||
|
// encode));
|
||||||
|
fullSpecMap.put(126, FieldParseInfo.getInstance(IsoType.LLLLVAR, 9999, encode)); // 표준X
|
||||||
|
fullSpecMap.put(127, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||||
|
fullSpecMap.put(128, FieldParseInfo.getInstance(IsoType.BINARY, 64, encode));
|
||||||
|
|
||||||
|
return fullSpecMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFieldName(int key) {
|
||||||
|
if (fullFieldNameMap == null) {
|
||||||
|
fullFieldNameMap = new HashMap<>();
|
||||||
|
fullFieldNameMap.put(1, "Bitmap, Secondary");
|
||||||
|
fullFieldNameMap.put(2, "Primary Account Number");
|
||||||
|
fullFieldNameMap.put(3, "Processing Code");
|
||||||
|
fullFieldNameMap.put(4, "Amount, Transaction");
|
||||||
|
fullFieldNameMap.put(6, "Amount, Cardholder Billing");
|
||||||
|
fullFieldNameMap.put(7, "Transmission Date and Time");
|
||||||
|
fullFieldNameMap.put(11, "System Trace Audit Number");
|
||||||
|
fullFieldNameMap.put(12, "Time, Local Transaction");
|
||||||
|
fullFieldNameMap.put(13, "Date, Local Transaction");
|
||||||
|
fullFieldNameMap.put(14, "Date, Expiration");
|
||||||
|
fullFieldNameMap.put(15, "Date, Settlement");
|
||||||
|
fullFieldNameMap.put(18, "Merchant Type");
|
||||||
|
|
||||||
|
fullFieldNameMap.put(22, "Point of Service Entry Mode");
|
||||||
|
fullFieldNameMap.put(24, "Network/Function Indentification Id");
|
||||||
|
fullFieldNameMap.put(25, "Point-Of-Service Condition Code");
|
||||||
|
|
||||||
|
fullFieldNameMap.put(26, "Point-Of-Service PIN Capture Code");
|
||||||
|
fullFieldNameMap.put(32, "Acquiring Institution Identification Code");
|
||||||
|
fullFieldNameMap.put(33, "Forwarding Institution Identification Code");
|
||||||
|
|
||||||
|
fullFieldNameMap.put(35, "Track 2 Data");
|
||||||
|
fullFieldNameMap.put(37, "Retrieval Reference Number");
|
||||||
|
fullFieldNameMap.put(38, "Authorization Identification Response");
|
||||||
|
|
||||||
|
fullFieldNameMap.put(39, "Response Code");
|
||||||
|
fullFieldNameMap.put(40, "Service Restriction Code");
|
||||||
|
fullFieldNameMap.put(41, "Card Acceptor Terminal Identification");
|
||||||
|
|
||||||
|
fullFieldNameMap.put(42, "Card Acceptor Identification");
|
||||||
|
fullFieldNameMap.put(43, "Card Acceptor Name and Location");
|
||||||
|
fullFieldNameMap.put(48, "Additional Data – Private");
|
||||||
|
|
||||||
|
fullFieldNameMap.put(49, "Transaction Currency Code");
|
||||||
|
fullFieldNameMap.put(52, "Personal Identification Number");
|
||||||
|
fullFieldNameMap.put(54, "Amount, Additional");
|
||||||
|
|
||||||
|
fullFieldNameMap.put(55, "Integrated Circuit Card (ICC) System Related Data");
|
||||||
|
|
||||||
|
fullFieldNameMap.put(60, "Reserved Private F60");
|
||||||
|
fullFieldNameMap.put(61, "Reserved Private F61");
|
||||||
|
fullFieldNameMap.put(62, "Reserved Private F62");
|
||||||
|
|
||||||
|
fullFieldNameMap.put(63, "Reserved Private F63");
|
||||||
|
fullFieldNameMap.put(70, "Network Management Information Code");
|
||||||
|
fullFieldNameMap.put(90, "Original Data Element");
|
||||||
|
|
||||||
|
fullFieldNameMap.put(98, "Payee");
|
||||||
|
fullFieldNameMap.put(102, "Account Identification 1");
|
||||||
|
fullFieldNameMap.put(103, "Account Identification 2");
|
||||||
|
|
||||||
|
fullFieldNameMap.put(120, "Reserved Private F120");
|
||||||
|
fullFieldNameMap.put(126, "Reserved Private F126");
|
||||||
|
fullFieldNameMap.put(127, "Destination Institution Identification Code");
|
||||||
|
fullFieldNameMap.put(128, "Message Authentication Code Field");
|
||||||
|
}
|
||||||
|
|
||||||
|
return fullFieldNameMap.get(new Integer(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String toString() {
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
sb.append(
|
||||||
|
"[ISO8583H2H message]");
|
||||||
|
sb.append("\n" + super.toString());
|
||||||
|
sb.append(
|
||||||
|
"\n");
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
+134
@@ -0,0 +1,134 @@
|
|||||||
|
package com.eactive.eai.custom.transformer.message;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
|
import com.eactive.eai.transformer.message.ISO8583Message;
|
||||||
|
import com.solab.iso8583.IsoMessage;
|
||||||
|
import com.solab.iso8583.IsoType;
|
||||||
|
import com.solab.iso8583.MessageFactory;
|
||||||
|
import com.solab.iso8583.parse.FieldParseInfo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @formatter:off
|
||||||
|
* ISO 8583 Silverlake(전문) 형식의 데이터를 변환하기 위한 메시지.(For KB Bukopin)
|
||||||
|
* - Binary, EBCDIC
|
||||||
|
*
|
||||||
|
* [참조] https://en.wikipedia.org/wiki/ISO_8583
|
||||||
|
* @formatter:on
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("serial")
|
||||||
|
public class ISO8583SilverlakeMessage extends ISO8583Message {
|
||||||
|
private static HashMap<Integer, FieldParseInfo> fullSpecMap = null;
|
||||||
|
private static HashMap<Integer, String> fullFieldNameMap = null;
|
||||||
|
private static String encode = "Cp1047"; // EBCDIC(1047)
|
||||||
|
|
||||||
|
public MessageFactory<IsoMessage> createMessageFactory() {
|
||||||
|
MessageFactory<IsoMessage> mf = new MessageFactory<>();
|
||||||
|
mf.setUseBinaryMessages(true);
|
||||||
|
mf.setUseBinaryBitmap(true);
|
||||||
|
mf.setVariableLengthFieldsInHex(false);
|
||||||
|
mf.setCharacterEncoding(encode);
|
||||||
|
mf.setForceStringEncoding(true);
|
||||||
|
return mf;
|
||||||
|
}
|
||||||
|
|
||||||
|
public HashMap<Integer, FieldParseInfo> getFullSpecMap(String enc) {
|
||||||
|
if (fullSpecMap != null) {
|
||||||
|
return fullSpecMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
fullSpecMap = new HashMap<>();
|
||||||
|
|
||||||
|
fullSpecMap.put(2, FieldParseInfo.getInstance(IsoType.LLBCDBIN, 10, encode));
|
||||||
|
fullSpecMap.put(3, FieldParseInfo.getInstance(IsoType.BINARY, 3, encode));
|
||||||
|
fullSpecMap.put(4, FieldParseInfo.getInstance(IsoType.BINARY, 6, encode));
|
||||||
|
fullSpecMap.put(7, FieldParseInfo.getInstance(IsoType.BINARY, 5, encode));
|
||||||
|
fullSpecMap.put(11, FieldParseInfo.getInstance(IsoType.BINARY, 3, encode));
|
||||||
|
fullSpecMap.put(12, FieldParseInfo.getInstance(IsoType.BINARY, 3, encode));
|
||||||
|
fullSpecMap.put(13, FieldParseInfo.getInstance(IsoType.BINARY, 2, encode));
|
||||||
|
fullSpecMap.put(14, FieldParseInfo.getInstance(IsoType.BINARY, 2, encode));
|
||||||
|
fullSpecMap.put(18, FieldParseInfo.getInstance(IsoType.BINARY, 2, encode));
|
||||||
|
fullSpecMap.put(22, FieldParseInfo.getInstance(IsoType.BINARY, 2, encode));
|
||||||
|
fullSpecMap.put(23, FieldParseInfo.getInstance(IsoType.BINARY, 2, encode));
|
||||||
|
fullSpecMap.put(25, FieldParseInfo.getInstance(IsoType.BINARY, 1, encode));
|
||||||
|
fullSpecMap.put(35, FieldParseInfo.getInstance(IsoType.LLBCDBIN, 19, encode));
|
||||||
|
fullSpecMap.put(37, FieldParseInfo.getInstance(IsoType.ALPHA, 12, encode));
|
||||||
|
fullSpecMap.put(38, FieldParseInfo.getInstance(IsoType.ALPHA, 6, encode));
|
||||||
|
fullSpecMap.put(39, FieldParseInfo.getInstance(IsoType.ALPHA, 2, encode));
|
||||||
|
fullSpecMap.put(41, FieldParseInfo.getInstance(IsoType.ALPHA, 8, encode));
|
||||||
|
fullSpecMap.put(42, FieldParseInfo.getInstance(IsoType.ALPHA, 15, encode));
|
||||||
|
fullSpecMap.put(43, FieldParseInfo.getInstance(IsoType.ALPHA, 40, encode));
|
||||||
|
fullSpecMap.put(47, FieldParseInfo.getInstance(IsoType.LLLVAR, 256, encode));
|
||||||
|
fullSpecMap.put(48, FieldParseInfo.getInstance(IsoType.LLLVAR, 256, encode));
|
||||||
|
fullSpecMap.put(52, FieldParseInfo.getInstance(IsoType.BINARY, 8, encode));
|
||||||
|
fullSpecMap.put(54, FieldParseInfo.getInstance(IsoType.LLLVAR, 120, encode));
|
||||||
|
fullSpecMap.put(55, FieldParseInfo.getInstance(IsoType.LLLVAR, 255, encode));
|
||||||
|
fullSpecMap.put(57, FieldParseInfo.getInstance(IsoType.LLLVAR, 255, encode));
|
||||||
|
fullSpecMap.put(58, FieldParseInfo.getInstance(IsoType.LLLVAR, 255, encode));
|
||||||
|
fullSpecMap.put(60, FieldParseInfo.getInstance(IsoType.LLLVAR, 120, encode));
|
||||||
|
fullSpecMap.put(61, FieldParseInfo.getInstance(IsoType.LLLVAR, 120, encode));
|
||||||
|
fullSpecMap.put(62, FieldParseInfo.getInstance(IsoType.LLLVAR, 512, encode));
|
||||||
|
fullSpecMap.put(63, FieldParseInfo.getInstance(IsoType.LLLVAR, 512, encode));
|
||||||
|
fullSpecMap.put(120, FieldParseInfo.getInstance(IsoType.LLLVAR, 700, encode));
|
||||||
|
fullSpecMap.put(121, FieldParseInfo.getInstance(IsoType.LLLVAR, 500, encode));
|
||||||
|
fullSpecMap.put(122, FieldParseInfo.getInstance(IsoType.LLLVAR, 350, encode));
|
||||||
|
fullSpecMap.put(123, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||||
|
fullSpecMap.put(124, FieldParseInfo.getInstance(IsoType.LLLVAR, 450, encode));
|
||||||
|
fullSpecMap.put(125, FieldParseInfo.getInstance(IsoType.LLLVAR, 255, encode));
|
||||||
|
|
||||||
|
return fullSpecMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFieldName(int key) {
|
||||||
|
if (fullFieldNameMap == null) {
|
||||||
|
fullFieldNameMap = new HashMap<>();
|
||||||
|
fullFieldNameMap.put(1, "Secondary Bit Map");
|
||||||
|
fullFieldNameMap.put(2, "Primary Account Number");
|
||||||
|
fullFieldNameMap.put(3, "Processing code");
|
||||||
|
fullFieldNameMap.put(4, "Amount,transaction");
|
||||||
|
fullFieldNameMap.put(7, "Transmission date & time");
|
||||||
|
fullFieldNameMap.put(11, "System audit trace number");
|
||||||
|
fullFieldNameMap.put(12, "Time, local transaction");
|
||||||
|
fullFieldNameMap.put(13, "Date, local transaction");
|
||||||
|
fullFieldNameMap.put(14, "Date, expiration");
|
||||||
|
fullFieldNameMap.put(18, "Merchant type");
|
||||||
|
fullFieldNameMap.put(22, "POS entry mode");
|
||||||
|
fullFieldNameMap.put(23, "Card sequence number");
|
||||||
|
fullFieldNameMap.put(25, "POS condition code");
|
||||||
|
fullFieldNameMap.put(35, "Track 2 data");
|
||||||
|
fullFieldNameMap.put(37, "Retrieval reference number");
|
||||||
|
fullFieldNameMap.put(38, "Authorisation ID response");
|
||||||
|
fullFieldNameMap.put(39, "Response code");
|
||||||
|
fullFieldNameMap.put(41, "Terminal ID");
|
||||||
|
fullFieldNameMap.put(42, "Card acceptor ID");
|
||||||
|
fullFieldNameMap.put(43, "Card acceptor name/location");
|
||||||
|
fullFieldNameMap.put(47, "Private Use");
|
||||||
|
fullFieldNameMap.put(48, "Request header");
|
||||||
|
fullFieldNameMap.put(52, "PIN data");
|
||||||
|
fullFieldNameMap.put(54, "Private Use");
|
||||||
|
fullFieldNameMap.put(55, "ICC system related data");
|
||||||
|
fullFieldNameMap.put(57, "Private Use");
|
||||||
|
fullFieldNameMap.put(58, "Private Use");
|
||||||
|
fullFieldNameMap.put(60, "Private Use");
|
||||||
|
fullFieldNameMap.put(61, "Private Use");
|
||||||
|
fullFieldNameMap.put(62, "Private Use");
|
||||||
|
fullFieldNameMap.put(63, "Private Use");
|
||||||
|
fullFieldNameMap.put(120, "Private Use");
|
||||||
|
fullFieldNameMap.put(121, "Private Use");
|
||||||
|
fullFieldNameMap.put(122, "Response detail");
|
||||||
|
fullFieldNameMap.put(123, "Response detail");
|
||||||
|
fullFieldNameMap.put(124, "Private Use");
|
||||||
|
fullFieldNameMap.put(125, "Private Use");
|
||||||
|
}
|
||||||
|
|
||||||
|
return fullFieldNameMap.get(new Integer(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String toString() {
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
sb.append("[ISO8583 Silverlake message]");
|
||||||
|
sb.append("\n" + super.toString());
|
||||||
|
sb.append("\n");
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -151,8 +151,8 @@ msg_dvcd,2,2,0,1,2,1,,,NM
|
|||||||
msg_scop_len,2,2,0,1,8,2,,,
|
msg_scop_len,2,2,0,1,8,2,,,
|
||||||
MAIN_MSG,2,3,0,1,0,1,,,
|
MAIN_MSG,2,3,0,1,0,1,,,
|
||||||
outp_atrb_cd,3,2,1,1,1,1,,,0
|
outp_atrb_cd,3,2,1,1,1,1,,,0
|
||||||
outp_msg_cd,3,2,1,1,12,1,,,
|
outp_msg_cd,3,2,1,1,12,1,,,NCMM00001
|
||||||
outp_msg_ctnt,3,2,1,1,200,1,,,
|
outp_msg_ctnt,3,2,1,1,200,1,,,정상처리되었습니다.
|
||||||
outp_msg_desc,3,2,1,1,300,1,,,
|
outp_msg_desc,3,2,1,1,300,1,,,
|
||||||
mngm_msg_cd,3,2,1,1,12,1,,,
|
mngm_msg_cd,3,2,1,1,12,1,,,
|
||||||
msg_list_rowcnt,3,2,0,1,5,2,,,0
|
msg_list_rowcnt,3,2,0,1,5,2,,,0
|
||||||
@@ -168,7 +168,7 @@ err_chrg_cnpl_no,3,2,0,1,20,1,,,
|
|||||||
# ============================================================
|
# ============================================================
|
||||||
# DATA - 데이터부
|
# DATA - 데이터부
|
||||||
# ============================================================
|
# ============================================================
|
||||||
DATA,1,4,1,1,0,1,,,
|
DATA,1,3,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,,,
|
||||||
|
|||||||
|
@@ -1,694 +0,0 @@
|
|||||||
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];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-108
@@ -1,108 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.FilterException;
|
|
||||||
|
|
||||||
class KakaopayFilterTest {
|
|
||||||
|
|
||||||
private KakaopayFilter filter;
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
void setUp() {
|
|
||||||
filter = new KakaopayFilter();
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------
|
|
||||||
// doPreFilter
|
|
||||||
// -----------------------------------------------------------------------
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void preFilter_firstAgreedTrue_returnsMessage() throws Exception {
|
|
||||||
String message = "{\"term_agreements\":[{\"is_agreed\":true}]}";
|
|
||||||
|
|
||||||
Object result = filter.doPreFilter(null, null, message, null, null, null);
|
|
||||||
|
|
||||||
assertSame(message, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void preFilter_firstAgreedFalse_throwsFilterException() throws Exception {
|
|
||||||
String message = "{\"term_agreements\":[{\"is_agreed\":false}]}";
|
|
||||||
|
|
||||||
FilterException ex = assertThrows(FilterException.class,
|
|
||||||
() -> filter.doPreFilter(null, null, message, null, null, null));
|
|
||||||
assertEquals("EB000003", ex.getMessage());
|
|
||||||
assertEquals(200, ex.getStatus());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void preFilter_isAgreedFieldMissing_throwsFilterException() {
|
|
||||||
// is_agreed 필드 없음 → getBoolean 기본값 false → 예외
|
|
||||||
String message = "{\"term_agreements\":[{}]}";
|
|
||||||
|
|
||||||
assertThrows(FilterException.class,
|
|
||||||
() -> filter.doPreFilter(null, null, message, null, null, null));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void preFilter_termAgreementsEmpty_throwsFilterException() {
|
|
||||||
// 배열이 비어있어 [0] 접근 불가 → getBoolean 기본값 false → 예외
|
|
||||||
String message = "{\"term_agreements\":[]}";
|
|
||||||
|
|
||||||
assertThrows(FilterException.class,
|
|
||||||
() -> filter.doPreFilter(null, null, message, null, null, null));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void preFilter_termAgreementsMissing_throwsFilterException() {
|
|
||||||
// term_agreements 필드 자체 없음 → getBoolean 기본값 false → 예외
|
|
||||||
String message = "{}";
|
|
||||||
|
|
||||||
assertThrows(FilterException.class,
|
|
||||||
() -> filter.doPreFilter(null, null, message, null, null, null));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void preFilter_multipleEntries_firstAgreedTrue_returnsMessage() throws Exception {
|
|
||||||
// 첫 번째 true, 두 번째 false → 통과
|
|
||||||
String message = "{\"term_agreements\":["
|
|
||||||
+ "{\"is_agreed\":true},"
|
|
||||||
+ "{\"is_agreed\":false}"
|
|
||||||
+ "]}";
|
|
||||||
|
|
||||||
Object result = filter.doPreFilter(null, null, message, null, null, null);
|
|
||||||
|
|
||||||
assertSame(message, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void preFilter_multipleEntries_firstAgreedFalse_throwsFilterException() {
|
|
||||||
// 첫 번째 false, 두 번째 true → 예외
|
|
||||||
String message = "{\"term_agreements\":["
|
|
||||||
+ "{\"is_agreed\":false},"
|
|
||||||
+ "{\"is_agreed\":true}"
|
|
||||||
+ "]}";
|
|
||||||
|
|
||||||
assertThrows(FilterException.class,
|
|
||||||
() -> filter.doPreFilter(null, null, message, null, null, null));
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------
|
|
||||||
// doPostFilter
|
|
||||||
// -----------------------------------------------------------------------
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void postFilter_alwaysReturnsResultMessage() throws Exception {
|
|
||||||
String resultMessage = "{\"result\":\"ok\"}";
|
|
||||||
|
|
||||||
Object result = filter.doPostFilter(null, null, resultMessage, null, null, null);
|
|
||||||
|
|
||||||
assertSame(resultMessage, result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+6
-49
@@ -324,59 +324,20 @@ class StandardMessageCoordinatorDJBTest {
|
|||||||
"정상 수신 시 msg_dvcd는 NM이어야 함");
|
"정상 수신 시 msg_dvcd는 NM이어야 함");
|
||||||
}
|
}
|
||||||
|
|
||||||
// outp_msg_cd / outp_msg_ctnt 는 레이아웃 기본값을 없앴으므로 이 시점에는 비어 있고,
|
|
||||||
// 실제 흐름대로 coordinateBeforeResponse 까지 거쳐야 채워진다.
|
|
||||||
@Test
|
@Test
|
||||||
void 정상수신시_outp_msg_cd_는_응답조정후_설정됨() {
|
void 정상수신시_outp_msg_cd_설정됨() {
|
||||||
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
|
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
|
||||||
assertTrue(isBlankValue(message.findItemValue("MSG.MAIN_MSG.outp_msg_cd")),
|
|
||||||
"수신 조정 단계에서는 아직 비어 있어야 함 (레이아웃 기본값이 없어야 한다)");
|
|
||||||
|
|
||||||
coordinator.coordinateBeforeResponse(message, null, null, "utf-8");
|
String msgCd = message.findItemValue("MSG.MAIN_MSG.outp_msg_cd");
|
||||||
|
assertFalse(msgCd == null || msgCd.trim().isEmpty(), "outp_msg_cd가 설정되어야 함");
|
||||||
assertEquals(StandardMessageCoordinatorDJB.NORMAL_OUTP_MSG_CD,
|
|
||||||
message.findItemValue("MSG.MAIN_MSG.outp_msg_cd"),
|
|
||||||
"정상 응답의 outp_msg_cd 가 설정되어야 함");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void 정상수신시_outp_msg_ctnt_는_응답조정후_설정됨() {
|
void 정상수신시_outp_msg_ctnt_설정됨() {
|
||||||
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
|
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
|
||||||
assertTrue(isBlankValue(message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt")),
|
|
||||||
"수신 조정 단계에서는 아직 비어 있어야 함 (레이아웃 기본값이 없어야 한다)");
|
|
||||||
|
|
||||||
coordinator.coordinateBeforeResponse(message, null, null, "utf-8");
|
String ctnt = message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt");
|
||||||
|
assertFalse(ctnt == null || ctnt.trim().isEmpty(), "outp_msg_ctnt가 설정되어야 함");
|
||||||
assertEquals(StandardMessageCoordinatorDJB.NORMAL_OUTP_MSG_CTNT,
|
|
||||||
message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt"),
|
|
||||||
"정상 응답의 outp_msg_ctnt 가 설정되어야 함");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void 오류응답에는_정상메시지가_채워지지_않는다() {
|
|
||||||
coordinator.coordinateSetStandardMessageError(message, mapper, "RECEAIINA001", "테스트오류");
|
|
||||||
coordinator.coordinateBeforeResponse(message, null, null, "utf-8");
|
|
||||||
|
|
||||||
assertNotEquals(StandardMessageCoordinatorDJB.NORMAL_OUTP_MSG_CD,
|
|
||||||
message.findItemValue("MSG.MAIN_MSG.outp_msg_cd"),
|
|
||||||
"오류 응답에 정상코드가 채워지면 안 됨");
|
|
||||||
assertNotEquals(StandardMessageCoordinatorDJB.NORMAL_OUTP_MSG_CTNT,
|
|
||||||
message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt"),
|
|
||||||
"오류 응답에 '정상처리되었습니다.' 가 채워지면 안 됨 — 2026-09 사고의 재현");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void 대외계가_보낸_MSG_값은_덮어쓰지_않는다() {
|
|
||||||
coordinator.coordinateAfterRecvNonStdSyncResponse(message);
|
|
||||||
message.setData("MSG.MAIN_MSG.outp_msg_cd", "ABC00001");
|
|
||||||
message.setData("MSG.MAIN_MSG.outp_msg_ctnt", "상대가 보낸 메시지");
|
|
||||||
|
|
||||||
coordinator.coordinateBeforeResponse(message, null, null, "utf-8");
|
|
||||||
|
|
||||||
assertEquals("ABC00001", message.findItemValue("MSG.MAIN_MSG.outp_msg_cd"),
|
|
||||||
"이미 채워진 outp_msg_cd 를 덮어쓰면 안 됨");
|
|
||||||
assertEquals("상대가 보낸 메시지", message.findItemValue("MSG.MAIN_MSG.outp_msg_ctnt"),
|
|
||||||
"이미 채워진 outp_msg_ctnt 를 덮어쓰면 안 됨");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -535,8 +496,4 @@ class StandardMessageCoordinatorDJBTest {
|
|||||||
f.setAccessible(true);
|
f.setAccessible(true);
|
||||||
f.set(item, refValue);
|
f.set(item, refValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean isBlankValue(String value) {
|
|
||||||
return value == null || value.trim().isEmpty();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,20 +32,19 @@ import static org.mockito.ArgumentMatchers.anyString;
|
|||||||
* 검증 시나리오:
|
* 검증 시나리오:
|
||||||
* 1. FlatReader 등록 확인
|
* 1. FlatReader 등록 확인
|
||||||
* 2. 비ERP 요청 FLAT 왕복 — HEAD 보존, EZDATA/MSG 바이트 미포함
|
* 2. 비ERP 요청 FLAT 왕복 — HEAD 보존, EZDATA/MSG 바이트 미포함
|
||||||
* 2-1. ERP 요청인데 JSON 에 EZDATA 가 없는 경우 — EZDATA 바이트 포함
|
|
||||||
* 3. ERP 요청 FLAT 왕복 — EZDATA 포함 보존
|
* 3. ERP 요청 FLAT 왕복 — EZDATA 포함 보존
|
||||||
* 4. 오류 응답 FLAT 왕복 — MSG EM 포함 보존
|
* 4. 오류 응답 FLAT 왕복 — MSG EM 포함 보존
|
||||||
* 5. 정상 응답 FLAT 왕복 — MSG NM 포함 보존
|
* 5. 정상 응답 FLAT 왕복 — MSG NM 포함 보존
|
||||||
* 6. 거래로그 시나리오 — FLAT 바이트 길이 검증 (조건부 블록 포함 여부)
|
* 6. 거래로그 시나리오 — FLAT 바이트 길이 검증 (조건부 블록 포함 여부)
|
||||||
*
|
*
|
||||||
* 핵심: FLAT 은 위치 기반이라 블록의 존재 여부를 전문에서 알 수 없고 ref 조건으로만 판단한다.
|
* 핵심 버그 (EZDATA FLAT 오류):
|
||||||
* 따라서 직렬화와 파싱이 같은 기준을 써야 한다.
|
* JSON 파싱 시 JSON에 없는 조건부 블록(EZDATA, MSG)은 isHidden=false 로 남는다.
|
||||||
|
* toByteArray() GROUP 케이스에서 size=0 이면서 refPath/refValue 가 있는 경우
|
||||||
|
* isHidden 체크만으로는 불충분 → FLAT에 비활성 블록 바이트가 잘못 포함된다.
|
||||||
*
|
*
|
||||||
* 기준: 조건부 블록(refPath/refValue)은 ref 조건 성립 여부로 FLAT 포함 여부를 정한다.
|
* 수정: toByteArray() / getBytesDataLength() GROUP 케이스를
|
||||||
* - 조건 불성립 → JSON 에 블록이 있어도 FLAT 미포함
|
* toJson() 과 동일하게 size==0 이면 무조건 skip 으로 변경
|
||||||
* - 조건 성립 → JSON 에 블록이 없어도(size=0) 레이아웃 기본값으로 FLAT 포함
|
* (StandardItem.java 두 곳)
|
||||||
* (StandardItem.isFlatGroupActive / FlatReader.traverse 가 공유하는
|
|
||||||
* StandardItem.matchRefCondition 로 판정)
|
|
||||||
*/
|
*/
|
||||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||||
class StandardMessageFlatFlowTest {
|
class StandardMessageFlatFlowTest {
|
||||||
@@ -128,42 +127,6 @@ class StandardMessageFlatFlowTest {
|
|||||||
+ "}"
|
+ "}"
|
||||||
+ "}";
|
+ "}";
|
||||||
|
|
||||||
/**
|
|
||||||
* ERP 요청인데 EZDATA 블록을 보내지 않은 JSON.
|
|
||||||
* corp_tlwn_virt_brcd=ERP 이므로 레이아웃상 EZDATA 는 "있어야 하는" 블록이지만
|
|
||||||
* 수신 JSON 에 없어 size=0 으로 남는다. 실제 거래로그에서 확인된 케이스다.
|
|
||||||
*/
|
|
||||||
private static final String ERP_REQ_NO_EZDATA_JSON =
|
|
||||||
"{"
|
|
||||||
+ "\"HEAD\":{"
|
|
||||||
+ "\"nxgn_stnd_idfr\":\"JERA\","
|
|
||||||
+ "\"guid\":\"" + TEST_GUID + "\","
|
|
||||||
+ "\"guid_prgs_no\":\"1\","
|
|
||||||
+ "\"stnd_mesg_ver\":\"R10\","
|
|
||||||
+ "\"ortr_guid\":\"" + TEST_GUID + "\","
|
|
||||||
+ "\"dman_rspn_dvcd\":\"S\","
|
|
||||||
+ "\"if_id\":\"" + TEST_IF_ID + "\","
|
|
||||||
+ "\"procs_rslt_dvcd\":\"S\","
|
|
||||||
+ "\"tx_id\":\"" + TEST_TX_ID + "\","
|
|
||||||
+ "\"chnl_tycd\":\"EAI\","
|
|
||||||
+ "\"hmab_dvcd\":\"1\","
|
|
||||||
+ "\"corp_tlwn_virt_brcd\":\"ERP\","
|
|
||||||
+ "\"trnm_sys_dvcd\":\"OPA\","
|
|
||||||
+ "\"frst_trnm_sys_dvcd\":\"OPA\","
|
|
||||||
+ "\"sys_env_dvcd\":\"D\","
|
|
||||||
+ "\"frst_mesg_dman_dt\":\"20260420\","
|
|
||||||
+ "\"frst_mesg_dman_time\":\"120000000\""
|
|
||||||
+ "},"
|
|
||||||
+ "\"DATA\":{"
|
|
||||||
+ "\"data_dvcd\":\"IO\","
|
|
||||||
+ "\"data_scop_len\":\"00000037\","
|
|
||||||
+ "\"BIZ_DATA\":{\"acct_no\":\"987654321\",\"amt\":\"500000\"}"
|
|
||||||
+ "}"
|
|
||||||
+ "}";
|
|
||||||
|
|
||||||
/** EZDATA 블록 선언 길이 (standard-layout-djb.csv 기준) */
|
|
||||||
private static final int EZDATA_BLOCK_SIZE = 1500;
|
|
||||||
|
|
||||||
private StandardMessageManager manager;
|
private StandardMessageManager manager;
|
||||||
private InterfaceMapper mapper;
|
private InterfaceMapper mapper;
|
||||||
private StandardReader flatReader;
|
private StandardReader flatReader;
|
||||||
@@ -290,78 +253,6 @@ class StandardMessageFlatFlowTest {
|
|||||||
"비ERP FLAT 왕복 후 EZDATA 블록이 활성 상태이면 안 됨");
|
"비ERP FLAT 왕복 후 EZDATA 블록이 활성 상태이면 안 됨");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ================================================================
|
|
||||||
// 2-1. ERP 요청인데 JSON 에 EZDATA 가 없는 경우
|
|
||||||
//
|
|
||||||
// [버그] corp_tlwn_virt_brcd=ERP 라 FlatReader 는 EZDATA(1500B)가 있다고 보고 읽는데,
|
|
||||||
// 직렬화는 size==0 이라 건너뛰어 헤더가 678B 로 기록된다.
|
|
||||||
// → cut() underflow → 거래로그 화면에서 헤더 파싱 실패(원문 노출)
|
|
||||||
// [수정] ref 조건이 성립하면 size==0 이어도 레이아웃 기본값으로 FLAT 출력
|
|
||||||
// (StandardItem.isFlatGroupActive)
|
|
||||||
// ================================================================
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void ERP요청_EZDATA미포함_FLAT_파싱_예외없음() throws Exception {
|
|
||||||
StandardMessage src = parseJson(ERP_REQ_NO_EZDATA_JSON);
|
|
||||||
String flatStr = src.toFixedString(false, FLAT_CHARSET);
|
|
||||||
|
|
||||||
StandardMessage dst = manager.getStandardMessage();
|
|
||||||
assertDoesNotThrow(() -> flatReader.parse(dst, flatStr),
|
|
||||||
"ERP 요청(EZDATA 미포함) FLAT 파싱 중 예외 발생 — "
|
|
||||||
+ "corp_tlwn_virt_brcd=ERP 이면 EZDATA 바이트가 FLAT 에 포함되어야 함");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void ERP요청_EZDATA미포함_FLAT에_EZDATA_바이트_포함() throws Exception {
|
|
||||||
byte[] nonErpBytes = parseJson(NON_ERP_REQ_JSON)
|
|
||||||
.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
|
|
||||||
byte[] erpNoEzBytes = parseJson(ERP_REQ_NO_EZDATA_JSON)
|
|
||||||
.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
|
|
||||||
|
|
||||||
assertEquals(nonErpBytes.length + EZDATA_BLOCK_SIZE, erpNoEzBytes.length,
|
|
||||||
String.format("ERP 요청(EZDATA 미포함) FLAT 길이(%d)는 "
|
|
||||||
+ "비ERP FLAT 길이(%d) + EZDATA(%d) 여야 함",
|
|
||||||
erpNoEzBytes.length, nonErpBytes.length, EZDATA_BLOCK_SIZE));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void ERP요청_EZDATA_포함여부와_무관하게_FLAT_길이_동일() throws Exception {
|
|
||||||
byte[] withEzBytes = parseJson(ERP_REQ_JSON)
|
|
||||||
.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
|
|
||||||
byte[] noEzBytes = parseJson(ERP_REQ_NO_EZDATA_JSON)
|
|
||||||
.toFixedString(false, FLAT_CHARSET).getBytes(FLAT_CHARSET);
|
|
||||||
|
|
||||||
// 블록 유무는 JSON 수신 여부가 아니라 ref 조건(corp_tlwn_virt_brcd=ERP)이 정한다
|
|
||||||
assertEquals(withEzBytes.length, noEzBytes.length,
|
|
||||||
String.format("EZDATA 포함 JSON(%d)과 미포함 JSON(%d)의 FLAT 길이가 달라짐",
|
|
||||||
withEzBytes.length, noEzBytes.length));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void ERP요청_EZDATA미포함_FLAT_왕복_HEAD_corp_tlwn_virt_brcd_ERP() throws Exception {
|
|
||||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_NO_EZDATA_JSON));
|
|
||||||
|
|
||||||
assertEquals("ERP", dst.findItemValue("HEAD.corp_tlwn_virt_brcd").trim(),
|
|
||||||
"ERP 요청(EZDATA 미포함) FLAT 왕복 후 HEAD.corp_tlwn_virt_brcd 불일치");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void ERP요청_EZDATA미포함_FLAT_왕복_HEAD_if_id_보존() throws Exception {
|
|
||||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_NO_EZDATA_JSON));
|
|
||||||
|
|
||||||
assertEquals(TEST_IF_ID, dst.findItemValue("HEAD.if_id").trim(),
|
|
||||||
"ERP 요청(EZDATA 미포함) FLAT 왕복 후 HEAD.if_id 불일치");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void ERP요청_EZDATA미포함_FLAT_왕복_DATA_data_dvcd_IO() throws Exception {
|
|
||||||
// 거래로그 화면에서 깨졌던 지점: EZDATA 를 건너뛰면 DATA 부 오프셋이 어긋난다
|
|
||||||
StandardMessage dst = flatRoundTrip(parseJson(ERP_REQ_NO_EZDATA_JSON));
|
|
||||||
|
|
||||||
assertEquals("IO", dst.findItemValue("DATA.data_dvcd").trim(),
|
|
||||||
"ERP 요청(EZDATA 미포함) FLAT 왕복 후 DATA.data_dvcd 불일치 — EZDATA 오프셋 어긋남");
|
|
||||||
}
|
|
||||||
|
|
||||||
// ================================================================
|
// ================================================================
|
||||||
// 3. ERP 요청 FLAT 왕복 — EZDATA 포함
|
// 3. ERP 요청 FLAT 왕복 — EZDATA 포함
|
||||||
// ================================================================
|
// ================================================================
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ 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 {
|
||||||
@@ -81,11 +80,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\"}"
|
||||||
+ "}]"
|
+ "}"
|
||||||
+ "}";
|
+ "}";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -122,58 +121,10 @@ 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"
|
|
||||||
+ "}"
|
|
||||||
+ "}"
|
+ "}"
|
||||||
+ "}";
|
+ "}";
|
||||||
|
|
||||||
@@ -257,11 +208,7 @@ class StandardMessageJsonFlowTest {
|
|||||||
void 요청JSON_파싱_DATA_BIZ_DATA_JSON_오브젝트_저장() throws Exception {
|
void 요청JSON_파싱_DATA_BIZ_DATA_JSON_오브젝트_저장() throws Exception {
|
||||||
StandardMessage msg = parseReq();
|
StandardMessage msg = parseReq();
|
||||||
|
|
||||||
// DATA는 GRID(반복부)라 값은 행(row 0)에 들어간다. 인덱스 없는 "DATA.BIZ_DATA"는
|
String bizData = msg.findItemValue("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 오브젝트로 파싱 가능한지 검증
|
||||||
@@ -397,11 +344,9 @@ 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 오브젝트로 들어갈 수 있음
|
||||||
assertTrue(root.path("DATA").isArray(), "직렬화 JSON의 DATA가 배열이 아님");
|
assertNotNull(root.path("DATA").get("BIZ_DATA"),
|
||||||
assertNotNull(root.path("DATA").path(0).get("BIZ_DATA"),
|
"직렬화 JSON에 DATA.BIZ_DATA 없음");
|
||||||
"직렬화 JSON에 DATA[0].BIZ_DATA 없음");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ================================================================
|
// ================================================================
|
||||||
@@ -443,15 +388,11 @@ class StandardMessageJsonFlowTest {
|
|||||||
void 비표준수신_정상응답_JSON_직렬화_outp_msg_ctnt_설정됨() throws Exception {
|
void 비표준수신_정상응답_JSON_직렬화_outp_msg_ctnt_설정됨() throws Exception {
|
||||||
StandardMessage msg = manager.getStandardMessage();
|
StandardMessage msg = manager.getStandardMessage();
|
||||||
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
coordinator.coordinateAfterRecvNonStdSyncResponse(msg);
|
||||||
// outp_msg_cd/ctnt 는 레이아웃 기본값이 없으므로, 실제 흐름대로 응답 직전 조정까지
|
|
||||||
// 거쳐야 채워진다 (StandardMessageCoordinatorDJB.coordinateBeforeResponse)
|
|
||||||
coordinator.coordinateBeforeResponse(msg, null, null, "utf-8");
|
|
||||||
|
|
||||||
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);
|
||||||
String ctnt = root.path("MSG").path("MAIN_MSG").path("outp_msg_ctnt").asText();
|
String ctnt = root.path("MSG").path("MAIN_MSG").path("outp_msg_ctnt").asText();
|
||||||
assertEquals(StandardMessageCoordinatorDJB.NORMAL_OUTP_MSG_CTNT, ctnt,
|
assertFalse(ctnt.isEmpty(), "정상응답 JSON의 outp_msg_ctnt가 설정되어야 함");
|
||||||
"정상응답 JSON의 outp_msg_ctnt가 설정되어야 함");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ================================================================
|
// ================================================================
|
||||||
@@ -549,40 +490,6 @@ 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
|
||||||
// ================================================================
|
// ================================================================
|
||||||
@@ -598,10 +505,4 @@ 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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,262 +0,0 @@
|
|||||||
package com.eactive.eai.message;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import com.eactive.eai.message.parser.FlatReader;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 조건부 GROUP 블록의 FLAT 직렬화 판정 단위 테스트
|
|
||||||
*
|
|
||||||
* 검증 대상:
|
|
||||||
* - {@link StandardItem#matchRefCondition(String, String)} : ref 조건 판정 규칙
|
|
||||||
* - {@link StandardItem#isFlatGroupActive(StandardMessage, boolean)} : GROUP 의 FLAT 출력 여부
|
|
||||||
* (관측 가능한 계약인 toByteArray() / getBytesDataLength() 결과로 검증)
|
|
||||||
*
|
|
||||||
* 핵심 계약:
|
|
||||||
* FLAT 은 위치 기반이라 전문만 보고 블록 존재 여부를 알 수 없고 ref 조건으로만 판단한다.
|
|
||||||
* 따라서 직렬화(StandardItem)와 파싱(FlatReader)이 반드시 같은 기준을 써야 하며,
|
|
||||||
* 조건이 성립하면 수신 전문에 블록이 없어(size=0) 도 레이아웃 기본값으로 출력해야 한다.
|
|
||||||
* 출력하지 않으면 파서는 블록이 있다고 보고 읽어 오프셋이 어긋난다.
|
|
||||||
*/
|
|
||||||
class StandardItemFlatGroupTest {
|
|
||||||
|
|
||||||
private static final String CHARSET = "euc-kr";
|
|
||||||
|
|
||||||
// 테스트 레이아웃 블록별 선언 길이
|
|
||||||
private static final int HEAD_LEN = 3; // mode(3)
|
|
||||||
private static final int COND_SUB_LEN = 4; // SUB.s1(4)
|
|
||||||
private static final int COND_LEN = 5 + COND_SUB_LEN; // c1(5) + SUB
|
|
||||||
private static final int TAIL_LEN = 2; // t1(2)
|
|
||||||
|
|
||||||
private static final int LEN_WITH_COND = HEAD_LEN + COND_LEN + TAIL_LEN; // 14
|
|
||||||
private static final int LEN_WITHOUT_COND = HEAD_LEN + TAIL_LEN; // 5
|
|
||||||
|
|
||||||
// ================================================================
|
|
||||||
// 1. matchRefCondition — ref 조건 판정 규칙
|
|
||||||
// ================================================================
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void matchRefCondition_단일값_일치() {
|
|
||||||
assertTrue(StandardItem.matchRefCondition("ERP", "ERP"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void matchRefCondition_단일값_불일치() {
|
|
||||||
assertFalse(StandardItem.matchRefCondition("ERP", "XXX"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void matchRefCondition_실제값_공백패딩_무시() {
|
|
||||||
// FLAT 필드는 스페이스로 우측 패딩되므로 trim 후 비교해야 한다
|
|
||||||
assertTrue(StandardItem.matchRefCondition("ERP", "ERP "));
|
|
||||||
assertTrue(StandardItem.matchRefCondition("ERP", " ERP "));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void matchRefCondition_실제값_null이면_불일치() {
|
|
||||||
assertFalse(StandardItem.matchRefCondition("ERP", null));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void matchRefCondition_refValue_null이면_불일치() {
|
|
||||||
assertFalse(StandardItem.matchRefCondition(null, "ERP"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void matchRefCondition_OR조건() {
|
|
||||||
assertTrue(StandardItem.matchRefCondition("NM|EM", "NM"));
|
|
||||||
assertTrue(StandardItem.matchRefCondition("NM|EM", "EM"));
|
|
||||||
assertFalse(StandardItem.matchRefCondition("NM|EM", "XX"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void matchRefCondition_NOT조건() {
|
|
||||||
assertFalse(StandardItem.matchRefCondition("!S", "S"));
|
|
||||||
assertTrue(StandardItem.matchRefCondition("!S", "R"));
|
|
||||||
// 응답구분이 비어 있으면 S 가 아니므로 조건 성립
|
|
||||||
assertTrue(StandardItem.matchRefCondition("!S", " "));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void matchRefCondition_NOT와_OR_조합() {
|
|
||||||
assertFalse(StandardItem.matchRefCondition("!NM|EM", "NM"));
|
|
||||||
assertFalse(StandardItem.matchRefCondition("!NM|EM", "EM"));
|
|
||||||
assertTrue(StandardItem.matchRefCondition("!NM|EM", "XX"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ================================================================
|
|
||||||
// 2. 조건부 GROUP 의 FLAT 출력 여부
|
|
||||||
// ================================================================
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void 조건성립이면_size0이어도_FLAT에_포함() throws Exception {
|
|
||||||
// 수신 전문에 COND 블록이 없어 size=0 이지만 조건(mode=ERP)이 성립하는 상황
|
|
||||||
StandardMessage msg = newMessage("ERP");
|
|
||||||
assertEquals(0, msg.findItem("COND").getSize(), "전제조건: COND 는 미활성(size=0) 이어야 함");
|
|
||||||
|
|
||||||
assertEquals(LEN_WITH_COND, msg.toByteArray(false, CHARSET).length,
|
|
||||||
"조건 성립 시 COND 블록이 레이아웃 기본값으로 FLAT 에 포함되어야 함");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void 조건불성립이면_FLAT에_미포함() throws Exception {
|
|
||||||
StandardMessage msg = newMessage("XXX");
|
|
||||||
|
|
||||||
assertEquals(LEN_WITHOUT_COND, msg.toByteArray(false, CHARSET).length,
|
|
||||||
"조건 불성립 시 COND 블록은 FLAT 에서 제외되어야 함");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void 조건성립으로_활성화된_블록의_하위_무조건GROUP도_포함() throws Exception {
|
|
||||||
StandardMessage msg = newMessage("ERP");
|
|
||||||
assertEquals(0, msg.findItem("COND.SUB").getSize(), "전제조건: SUB 도 미활성(size=0) 이어야 함");
|
|
||||||
|
|
||||||
// SUB(4바이트)가 빠지면 FlatReader 가 SUB 를 읽을 때 오프셋이 어긋난다
|
|
||||||
int len = msg.toByteArray(false, CHARSET).length;
|
|
||||||
assertEquals(LEN_WITH_COND, len,
|
|
||||||
String.format("활성화된 COND 하위의 무조건 GROUP(SUB %d바이트)도 함께 출력되어야 함. 실제=%d",
|
|
||||||
COND_SUB_LEN, len));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void hidden블록은_조건성립이어도_미포함() throws Exception {
|
|
||||||
StandardMessage msg = newMessage("ERP");
|
|
||||||
msg.findItem("COND").setHidden(true);
|
|
||||||
|
|
||||||
assertEquals(LEN_WITHOUT_COND, msg.toByteArray(false, CHARSET).length,
|
|
||||||
"isHidden=true 인 블록은 조건이 성립해도 출력하지 않아야 함");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void 명시적으로_활성화된_블록은_조건불성립이어도_포함() throws Exception {
|
|
||||||
// 코디네이터가 setSize(1) 로 직접 활성화한 블록(오류응답 MSG 등)의 기존 동작 보존
|
|
||||||
StandardMessage msg = newMessage("XXX");
|
|
||||||
msg.findItem("COND").setSize(1);
|
|
||||||
|
|
||||||
assertEquals(LEN_WITH_COND, msg.toByteArray(false, CHARSET).length,
|
|
||||||
"size>0 으로 명시 활성화된 블록은 조건과 무관하게 출력되어야 함");
|
|
||||||
}
|
|
||||||
|
|
||||||
// ================================================================
|
|
||||||
// 3. 길이 계산(getBytesDataLength)과 직렬화(toByteArray)의 일관성
|
|
||||||
// FlatMessageFilter 가 전문길이 필드를 이 값으로 채우므로 어긋나면 안 된다
|
|
||||||
// ================================================================
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void 조건성립_길이계산과_직렬화결과_일치() throws Exception {
|
|
||||||
StandardMessage msg = newMessage("ERP");
|
|
||||||
|
|
||||||
assertEquals(msg.toByteArray(false, CHARSET).length, msg.getBytesDataLength(CHARSET),
|
|
||||||
"조건 성립 시 getBytesDataLength 와 toByteArray 길이가 달라짐");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void 조건불성립_길이계산과_직렬화결과_일치() throws Exception {
|
|
||||||
StandardMessage msg = newMessage("XXX");
|
|
||||||
|
|
||||||
assertEquals(msg.toByteArray(false, CHARSET).length, msg.getBytesDataLength(CHARSET),
|
|
||||||
"조건 불성립 시 getBytesDataLength 와 toByteArray 길이가 달라짐");
|
|
||||||
}
|
|
||||||
|
|
||||||
// ================================================================
|
|
||||||
// 4. 기존 시그니처 호환 — root 없이 호출하면 종전 규칙(size==0 skip) 유지
|
|
||||||
// ================================================================
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void root없이_호출하면_조건평가없이_size규칙_적용() throws Exception {
|
|
||||||
StandardMessage msg = newMessage("ERP");
|
|
||||||
StandardItem cond = msg.findItem("COND");
|
|
||||||
|
|
||||||
// 조건을 평가할 root 가 없으므로 size==0 인 블록은 출력하지 않는다
|
|
||||||
assertEquals(0, cond.toByteArray(false, CHARSET).length,
|
|
||||||
"root 미전달 시에는 기존 규칙(size==0 → skip)이 유지되어야 함");
|
|
||||||
assertEquals(0, cond.getBytesDataLength(CHARSET),
|
|
||||||
"root 미전달 시에는 기존 규칙(size==0 → skip)이 유지되어야 함");
|
|
||||||
}
|
|
||||||
|
|
||||||
// ================================================================
|
|
||||||
// 5. 직렬화 ↔ 파싱 대칭성 (FlatReader 와 같은 기준인지)
|
|
||||||
// ================================================================
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void 조건성립_FLAT_왕복_남는바이트없이_파싱() throws Exception {
|
|
||||||
String flat = newMessage("ERP").toFixedString(false, CHARSET);
|
|
||||||
StandardMessage dst = newMessage("");
|
|
||||||
|
|
||||||
// FlatReader 는 다 읽고 남은 바이트가 있으면 예외를 던진다(overflow),
|
|
||||||
// 블록이 모자라면 cut() 에서 underflow 예외를 던진다
|
|
||||||
assertDoesNotThrow(() -> new FlatReader().parse(dst, flat),
|
|
||||||
"조건 성립 FLAT 파싱 중 예외 발생 — 직렬화와 파싱 기준 불일치");
|
|
||||||
assertEquals("ERP", dst.findItemValue("HEAD.mode").trim(), "왕복 후 HEAD.mode 불일치");
|
|
||||||
assertEquals("IO", dst.findItemValue("TAIL.t1").trim(),
|
|
||||||
"왕복 후 TAIL.t1 불일치 — COND 블록 오프셋이 어긋남");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void 조건불성립_FLAT_왕복_남는바이트없이_파싱() throws Exception {
|
|
||||||
String flat = newMessage("XXX").toFixedString(false, CHARSET);
|
|
||||||
StandardMessage dst = newMessage("");
|
|
||||||
|
|
||||||
assertDoesNotThrow(() -> new FlatReader().parse(dst, flat),
|
|
||||||
"조건 불성립 FLAT 파싱 중 예외 발생 — 직렬화와 파싱 기준 불일치");
|
|
||||||
assertEquals("XXX", dst.findItemValue("HEAD.mode").trim(), "왕복 후 HEAD.mode 불일치");
|
|
||||||
assertEquals("IO", dst.findItemValue("TAIL.t1").trim(), "왕복 후 TAIL.t1 불일치");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void 조건성립_FLAT_왕복후_COND블록_기본값_보존() throws Exception {
|
|
||||||
StandardMessage src = newMessage("ERP");
|
|
||||||
String flat = src.toFixedString(false, CHARSET);
|
|
||||||
|
|
||||||
StandardMessage dst = newMessage("");
|
|
||||||
new FlatReader().parse(dst, flat);
|
|
||||||
|
|
||||||
assertEquals("C1", dst.findItemValue("COND.c1").trim(),
|
|
||||||
"왕복 후 COND.c1 레이아웃 기본값 불일치");
|
|
||||||
assertEquals("S1", dst.findItemValue("COND.SUB.s1").trim(),
|
|
||||||
"왕복 후 COND.SUB.s1 레이아웃 기본값 불일치");
|
|
||||||
}
|
|
||||||
|
|
||||||
// ================================================================
|
|
||||||
// helpers
|
|
||||||
// ================================================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 테스트용 최소 레이아웃 (DJBank 표준전문의 HEAD / EZDATA / DATA 구조를 축약)
|
|
||||||
*
|
|
||||||
* <pre>
|
|
||||||
* HEAD GROUP size=1
|
|
||||||
* mode (3) 조건 판정 필드
|
|
||||||
* COND GROUP size=0, 조건 HEAD.mode=ERP
|
|
||||||
* c1 (5)
|
|
||||||
* SUB GROUP size=0, 조건 없음 (상위 활성화 전파 검증용)
|
|
||||||
* s1 (4)
|
|
||||||
* TAIL GROUP size=1
|
|
||||||
* t1 (2)
|
|
||||||
* </pre>
|
|
||||||
*/
|
|
||||||
private StandardMessage newMessage(String modeValue) throws Exception {
|
|
||||||
return StandardMessageUtil.generate(layout(
|
|
||||||
"HEAD,1,3,1,1,0,1,,,",
|
|
||||||
"mode,2,2,1,1,3,1,,," + modeValue,
|
|
||||||
"COND,1,3,0,1,0,1,HEAD.mode,ERP,",
|
|
||||||
"c1,2,2,1,1,5,1,,,C1",
|
|
||||||
"SUB,2,3,0,1,0,1,,,",
|
|
||||||
"s1,3,2,1,1,4,1,,,S1",
|
|
||||||
"TAIL,1,3,1,1,0,1,,,",
|
|
||||||
"t1,2,2,1,1,2,1,,,IO"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** CsvFileReader 와 동일한 방식으로 레이아웃 행을 StandardItem 으로 만든다 */
|
|
||||||
private ArrayList<StandardItem> layout(String... rows) throws Exception {
|
|
||||||
ArrayList<StandardItem> list = new ArrayList<StandardItem>();
|
|
||||||
for (String row : rows) {
|
|
||||||
list.add(new StandardItem(row.split(",", StandardItem.ITEM_COUNT)));
|
|
||||||
}
|
|
||||||
return list;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user