Compare commits
45 Commits
cc315f2ad0
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 8231318f14 | |||
| c44b331a32 | |||
| 88f774e6b5 | |||
| a77f4d4ef0 | |||
| 73a50e5db4 | |||
| ebf3cfa98d | |||
| 15ac0fa2a2 | |||
| e0039aca81 | |||
| 5c094ef9b4 | |||
| 3772805301 | |||
| d31b7a343c | |||
| 47cb243ff4 | |||
| e3fb52343d | |||
| 46463a27a4 | |||
| 7e1af96fcf | |||
| f91b50a121 | |||
| 9cf16c9f49 | |||
| 7e83c36a79 | |||
| c5577fd973 | |||
| 0dd3c89238 | |||
| 6343ff23b7 | |||
| 6597464515 | |||
| 72a39b8d9c | |||
| 4094058745 | |||
| 0a692f8a07 | |||
| 0dfab56d0c | |||
| c38643b099 | |||
| 1ba8de1e3b | |||
| e5fe9b853f | |||
| 918c4b5c3e | |||
| c12ead1f97 | |||
| ebeaa6af17 | |||
| 133c482ef8 | |||
| f72348ae67 | |||
| 704a9ff90e | |||
| db78cbac2e | |||
| 403b201168 | |||
| ec0cdfd221 | |||
| d277e37798 | |||
| e4851999ba | |||
| 110b0c0039 | |||
| d85642c5a8 | |||
| 49620c5e21 | |||
| 1ab25d634e | |||
| 984be8b1ee |
@@ -5,6 +5,7 @@ gradle.properties
|
||||
|
||||
src/main/generated
|
||||
WebContent/generated
|
||||
src/main/resources/version.info
|
||||
|
||||
# Eclipse #
|
||||
.metadata
|
||||
|
||||
Vendored
+157
@@ -0,0 +1,157 @@
|
||||
pipeline {
|
||||
agent none
|
||||
|
||||
options {
|
||||
timestamps()
|
||||
disableConcurrentBuilds()
|
||||
skipDefaultCheckout() // stage별 agent의 자동 SCM checkout 방지 (Deploy 노드는 git 접근 불필요, unstash로만 WAR 수신)
|
||||
buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '20'))
|
||||
}
|
||||
|
||||
environment {
|
||||
GIT_SSH_COMMAND = 'ssh -o StrictHostKeyChecking=accept-new'
|
||||
WEBHOOK_URL = 'http://172.30.1.50:18000/api/hooks/01ba51b01d3c4c98ae8f3183a23a84ed713197857d024b5da4f303458195eb32'
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('Build (djb-vm)') {
|
||||
agent { label 'djb-vm' }
|
||||
environment {
|
||||
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'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy (weblogic)') {
|
||||
agent { label 'weblogic' }
|
||||
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 '''
|
||||
set +e
|
||||
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"
|
||||
'''
|
||||
}
|
||||
}
|
||||
failure {
|
||||
node('weblogic') {
|
||||
sh '''
|
||||
set +e
|
||||
payload=$(printf '{"text":"[%s #%s](%s) FAILURE"}' "$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"
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,8 @@ hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
|
||||
#inst.Name=${HOSTNAME}
|
||||
inst.Name=agwSvr11
|
||||
eai.jdbc.Name=jdbc/dsOBP_AGW
|
||||
eai.rmiport=30111
|
||||
eai.rmiserviceport=30112
|
||||
eai.rmiport=39111
|
||||
eai.rmiserviceport=39112
|
||||
eai.systemmode=D
|
||||
# EAI FEP MCI GW ...
|
||||
eai.systemtype=API
|
||||
|
||||
@@ -23,15 +23,15 @@
|
||||
<url-pattern>/mgr/*</url-pattern>
|
||||
</filter-mapping>
|
||||
|
||||
<filter>
|
||||
<!-- <filter>
|
||||
<filter-name>ApiRequestBodyFilter</filter-name>
|
||||
<filter-class>com.eactive.eai.adapter.controller.ApiRequestBodyFilter</filter-class>
|
||||
</filter>
|
||||
<filter-mapping>
|
||||
<filter-name>ApiRequestBodyFilter</filter-name>
|
||||
<url-pattern>/api/*</url-pattern> <!-- 필요한 URL 패턴 -->
|
||||
<url-pattern>/dj/*</url-pattern> <!-- 필요한 URL 패턴 -->
|
||||
</filter-mapping>
|
||||
<url-pattern>/api/*</url-pattern> 필요한 URL 패턴
|
||||
<url-pattern>/dj/*</url-pattern> 필요한 URL 패턴
|
||||
</filter-mapping> -->
|
||||
|
||||
|
||||
<context-param>
|
||||
|
||||
@@ -172,6 +172,54 @@ task initDirs() {
|
||||
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 {
|
||||
wtp {
|
||||
component {
|
||||
|
||||
+1
-1
Submodule elink-online-common updated: bf03a97fa3...a923ff3f9f
+1
-1
Submodule elink-online-core updated: 658f2a0485...2929fc753f
+1
-1
Submodule elink-online-transformer updated: 05e887f7f1...a1d822c2d7
@@ -1,380 +0,0 @@
|
||||
//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,8 +35,7 @@ public class ApiRequestBodyFilter extends OncePerRequestFilter {
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
System.out.println("ApiRequestBodyFilter : " + request.getRequestURI());
|
||||
if (!isTarget(request)) {
|
||||
if (!isTarget(request)) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
+120
-66
@@ -23,28 +23,33 @@ import com.eactive.eai.adapter.handler.AdapterErrorMessageHandler;
|
||||
import com.eactive.eai.adapter.handler.AdapterErrorMessageHandlerFactory;
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.FilterException;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.adapter.service.DJErpApiAdapterService;
|
||||
import com.eactive.eai.adapter.service.DJBApiAdapterService;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
|
||||
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.RestSendBodyLogUtils;
|
||||
import com.eactive.eai.common.util.TxFileLogger;
|
||||
import com.eactive.eai.common.util.TxSiftContext;
|
||||
import com.eactive.eai.common.util.UUIDGenerator;
|
||||
import com.eactive.eai.inbound.error.InboundErrorInfoVO;
|
||||
import com.eactive.eai.util.HexaConverter;
|
||||
|
||||
@RestController
|
||||
public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
public class DJBApiAdapterController implements HttpAdapterServiceKey {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
@Autowired
|
||||
DJErpApiAdapterService service;
|
||||
DJBApiAdapterService service;
|
||||
|
||||
/**
|
||||
* DJErp OAuth 조기 적용을 위한 Controller
|
||||
@@ -62,6 +67,7 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
"/tsb/{path:^(?!oauth).*$}", "/tsb/{path:^(?!oauth).*$}/**",
|
||||
"/shb/{path:^(?!oauth).*$}", "/shb/{path:^(?!oauth).*$}/**",
|
||||
"/tst/{path:^(?!oauth).*$}", "/tst/{path:^(?!oauth).*$}/**",
|
||||
"/**/{path:^(?!oauth)(?!favicon\\.ico$).*$}", "/**/{path:^(?!oauth)(?!favicon\\.ico$).*$}/**",
|
||||
})
|
||||
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
||||
throws Exception {
|
||||
@@ -77,17 +83,25 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
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);
|
||||
|
||||
ResponseEntity<String> responseEntity = null;
|
||||
Properties transactionProp = new Properties();
|
||||
String uuid = 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 adapterName = adptUri.getAdptName();
|
||||
AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
@@ -95,6 +109,8 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
if (adapterVO == null) {
|
||||
String errorMsg = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_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)
|
||||
.body(errorMsg);
|
||||
}
|
||||
@@ -106,16 +122,10 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
||||
String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||
|
||||
ResponseEntity<String> responseEntity = null;
|
||||
Properties transactionProp = new Properties();
|
||||
String uuid = UUIDGenerator.getUUID().toString().replaceAll("-", "");
|
||||
transactionProp.setProperty(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
|
||||
TxSiftContext.begin(uuid);
|
||||
|
||||
// jwhong, put api received time, eaiSvcCode
|
||||
transactionProp.put(INBOUND_REQUESTED_TIME, receivedTimeStr);
|
||||
|
||||
String responseData = "";
|
||||
try {
|
||||
responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||
@@ -133,24 +143,46 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
} catch (Exception e) {
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
|
||||
String errorMsg = null;
|
||||
String responseErrorMsg = null;
|
||||
|
||||
errorMsg = genErrorResponseMessage(adapterGroupName, adapterName,
|
||||
transactionProp, e, adptMsgType, encode, errorResponseFormat);
|
||||
if (e instanceof HttpStatusException) {
|
||||
logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||
HttpStatusException e1 = (HttpStatusException) e;
|
||||
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(errorMsg);
|
||||
if (e instanceof FilterException) {
|
||||
responseErrorMsg = genErrorResponseMessage(adapterGroupName, adapterName,
|
||||
transactionProp, MessageUtil.ERROR_CODE_AP_ERROR, e, adptMsgType, encode, errorResponseFormat);
|
||||
FilterException e1 = (FilterException) e;
|
||||
this.logError(servletRequest, adapterGroupName, e1.getCode(), responseErrorMsg, transactionProp, e);
|
||||
logger.error("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(responseErrorMsg);
|
||||
} else if (e instanceof JwtAuthException) {
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||
responseErrorMsg = genErrorResponseMessage(adapterGroupName, adapterName,
|
||||
transactionProp, MessageUtil.ERROR_CODE_AP_ERROR, e, adptMsgType, encode, errorResponseFormat);
|
||||
JwtAuthException e1 = (JwtAuthException) e;
|
||||
this.logError(servletRequest, adapterGroupName, e1.getCode(), responseErrorMsg, transactionProp, e);
|
||||
logger.error("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(responseErrorMsg);
|
||||
} else if (e instanceof HttpStatusException) {
|
||||
responseErrorMsg = genErrorResponseMessage(adapterGroupName, adapterName,
|
||||
transactionProp, MessageUtil.ERROR_CODE_AUTH_FAIL, e, adptMsgType, encode, errorResponseFormat);
|
||||
logger.error("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||
HttpStatusException e1 = (HttpStatusException) e;
|
||||
responseEntity = ResponseEntity.status(e1.getStatus()).contentType(mediaType).body(responseErrorMsg);
|
||||
} 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);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType).body(errorMsg);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType).body(responseErrorMsg);
|
||||
}
|
||||
responseData = errorMsg;
|
||||
responseData = responseErrorMsg;
|
||||
|
||||
} 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로 전달
|
||||
* 추후 더 좋은방법이 생길경우 개선 요망
|
||||
@@ -168,7 +200,7 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
}
|
||||
|
||||
private String genErrorResponseMessage(String adapterGroupName, String adapterName,
|
||||
Properties callProp, Throwable e, String adptMsgType, String encode, String errorResponseFormat) {
|
||||
Properties callProp, String code, Throwable e, String adptMsgType, String encode, String errorResponseFormat) {
|
||||
String errorHandlerClass = AdapterPropManager.getInstance().getProperty(adapterName, "ERR_MSG_HANDLER");
|
||||
if (StringUtils.isNotBlank(errorHandlerClass)) {
|
||||
if (logger.isInfo())
|
||||
@@ -177,6 +209,7 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
if (handler != null) {
|
||||
Object resposne;
|
||||
try {
|
||||
callProp.put("INBOUND_RESULT_CODE", code);
|
||||
resposne = handler.generateNonStandardInboundErrorResponseMessage(adapterGroupName, adapterName,
|
||||
callProp, null, null, e);
|
||||
return (String)resposne;
|
||||
@@ -187,7 +220,7 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
}
|
||||
}
|
||||
return MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage(), errorResponseFormat);
|
||||
code, e.getMessage(), errorResponseFormat);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -203,14 +236,15 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
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());
|
||||
if(logger.isDebug()) {
|
||||
logger.debug("===== adptUriMap 상세 내용 =====");
|
||||
for (Map.Entry<String, HttpDynamicInAdapterUri> entry : manager.adptUriMap.entrySet()) {
|
||||
HttpDynamicInAdapterUri uriObj = entry.getValue();
|
||||
logger.debug("GroupName=" + uriObj.getAdptGrpName() + ", AdapterName=" + uriObj.getAdptName() + ", URI="
|
||||
+ uriObj.getUri());
|
||||
}
|
||||
logger.debug("================================");
|
||||
}
|
||||
logger.warn("================================");
|
||||
|
||||
//
|
||||
for (int i = 0; i < 10; i++) {
|
||||
@@ -236,38 +270,58 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
||||
}
|
||||
|
||||
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);
|
||||
try {
|
||||
String errorCode = "RECEAIIRP010";
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = request.getRequestURI();
|
||||
this.logError(request, "HTTP_IN_NO_URI", errorCode,
|
||||
ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs), null, null);
|
||||
} catch (Throwable t) {
|
||||
logger.warn("inbound logging failed", t);
|
||||
}
|
||||
}
|
||||
|
||||
private void logError(HttpServletRequest request, String adapterGroupName, String errorCode,
|
||||
String errorMsg, Properties prop, Exception e) {
|
||||
try {
|
||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||
String serverName = eaiServerManager.getLocalServerName();
|
||||
|
||||
InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||
|
||||
String txId = prop.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
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.setErrCd(errorCode); // 에러코드
|
||||
errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||
errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
||||
errorInfoVO.setErrDstcd(" ");
|
||||
StringBuffer sb = new StringBuffer();
|
||||
String clientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
||||
String hexClientId = clientId != null ? HexaConverter.bytesToHexa(clientId.getBytes()) : "";
|
||||
|
||||
sb.append(errorMsg).append("\n").append("Remote Addr : ").append(request.getRemoteAddr()).append("\n")
|
||||
.append("Request URI : ").append(request.getRequestURI()).append("\n").append("clientId=")
|
||||
.append(clientId).append(",hexClientId=").append(hexClientId).append(",txProp=").append(prop)
|
||||
.append("\n");
|
||||
if (e != null)
|
||||
sb.append("Exception : ").append(e.getMessage());
|
||||
|
||||
errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
||||
errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
||||
|
||||
InboundErrorLogger.error(errorInfoVO);
|
||||
} catch (Throwable t) {
|
||||
logger.warn("inbound logging failed", t);
|
||||
}
|
||||
}
|
||||
// private String makeResponseBodyMsg() {
|
||||
//
|
||||
// Map<String, Object> dataMap = new HashMap<>();
|
||||
@@ -1,22 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
+18
-10
@@ -1,19 +1,22 @@
|
||||
package com.eactive.eai.adapter.interceptor;
|
||||
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
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 javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
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.Logger;
|
||||
|
||||
public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
|
||||
|
||||
@@ -55,6 +58,11 @@ public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
|
||||
logger.debug(String.format( "httpHeader logging Interceptor headerKey=%s, headerValue=%s", 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();
|
||||
HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName, adapterName, headerMap, url, method, httpStatusCode);
|
||||
|
||||
@@ -1,847 +0,0 @@
|
||||
package com.eactive.eai.adapter.service;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.Keys;
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.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;
|
||||
}
|
||||
}
|
||||
+93
-101
@@ -11,7 +11,6 @@ import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -27,7 +26,6 @@ import org.dom4j.Element;
|
||||
import org.dom4j.Node;
|
||||
import org.dom4j.io.OutputFormat;
|
||||
import org.dom4j.io.XMLWriter;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
@@ -47,7 +45,7 @@ import com.eactive.eai.common.context.ElinkTransactionContext;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.eactive.eai.common.util.JSONUtils;
|
||||
import com.eactive.eai.common.util.JacksonUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.TxFileLogger;
|
||||
import com.eactive.eai.common.util.XMLUtils;
|
||||
@@ -55,13 +53,16 @@ import com.eactive.eai.inbound.action.ActionFactory;
|
||||
import com.eactive.eai.inbound.action.RequestAction;
|
||||
import com.eactive.eai.inbound.processor.Processor;
|
||||
import com.eactive.eai.message.StandardMessageUtil;
|
||||
import com.eactive.eai.util.JsonPathUtil;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
|
||||
@Service
|
||||
public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
public class DJBApiAdapterService extends HttpAdapterServiceSupport {
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
static Logger siftLogger = Logger.getLogger(Logger.LOGGER_SIFT);
|
||||
|
||||
@@ -73,7 +74,9 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
|
||||
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id"; // jwhong
|
||||
|
||||
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp,
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp,
|
||||
AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
|
||||
int traceLevel = 0;
|
||||
|
||||
@@ -151,6 +154,8 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
transactionProp.put(HEADER_GROUP, headerGroupName);
|
||||
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로 사용함
|
||||
String seedkey = inboundHeaderProp.getOrDefault("x-obp-partnercode", "").toString();
|
||||
ElinkTransactionContext.setSeedKey(seedkey);
|
||||
@@ -302,48 +307,17 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
|
||||
|
||||
adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
// HttpHeaders responseHeaders = new HttpHeaders();
|
||||
// responseHeaders.setContentType(MediaType.valueOf("application/json;charset=" + encode));
|
||||
|
||||
// HEADER_GROUP 셋팅
|
||||
// if (MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)
|
||||
// && StringUtils.isNotBlank(relayRequestHeaderKeys)) {
|
||||
// JSONObject jsonMessage = (JSONObject) JSONValue.parse(message);
|
||||
// JSONObject headerJson = new JSONObject();
|
||||
// if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||
// for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
||||
// String key = e.nextElement();
|
||||
// headerJson.put(key, request.getHeader(key));
|
||||
// }
|
||||
// } else {
|
||||
// String[] relayKeyArr = org.springframework.util.StringUtils
|
||||
// .tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
||||
//
|
||||
// for (String key : relayKeyArr) {
|
||||
// String headerValue = request.getHeader(key);
|
||||
// if (StringUtils.isNotBlank(headerValue)) {
|
||||
// headerJson.put(key, headerValue);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if (headerJson.size() > 0) {
|
||||
// jsonMessage.put(headerGroupName, headerJson);
|
||||
// message = jsonMessage.toJSONString();
|
||||
// }
|
||||
// }
|
||||
|
||||
Object reqObject = assignHeaderGroupRequestHeaders(adptGrpName, adptName, message,
|
||||
transactionProp, request, response, adptMsgType);
|
||||
|
||||
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
|
||||
// transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
|
||||
// 로컬 서비스 호출 ,encoding 처리 추가
|
||||
|
||||
ApiKeyExtractFilter apiKeyExtractor = new ApiKeyExtractFilter();
|
||||
apiKeyExtractor.doPreFilter(adptGrpName, adptName, reqObject, transactionProp, request, response);
|
||||
apiKeyExtractor.doPreFilter(adptGrpName, adptName, transactionProp.get(INBOUND_REQUEST_MESSAGE), transactionProp, request, response);
|
||||
|
||||
String result = (String) service(adptGrpName, adptName, reqObject, transactionProp, request, response);
|
||||
Object result = service(adptGrpName, adptName, reqObject, transactionProp, request, response);
|
||||
|
||||
// bypass만 필요
|
||||
applyOutboundResponseHeaders(transactionProp, response);
|
||||
@@ -357,10 +331,9 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
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);
|
||||
ObjectNode rootNode = (ObjectNode) JacksonUtil.readTree(result, mapper);
|
||||
JsonNode headerGroup = rootNode.get(headerGroupName);
|
||||
if(headerGroup != null) {
|
||||
for(Iterator<String> it = headerGroup.fieldNames(); it.hasNext();) {
|
||||
@@ -369,23 +342,22 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
response.addHeader(name, value);
|
||||
}
|
||||
rootNode.remove(headerGroupName);
|
||||
result = mapper.writeValueAsString(rootNode);
|
||||
result = 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;
|
||||
String strResult = null;
|
||||
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,
|
||||
HttpServletRequest request, HttpServletResponse response, String adptMsgType) throws DocumentException, IOException {
|
||||
HttpServletRequest request, HttpServletResponse response, String adptMsgType) throws DocumentException, IOException, Exception {
|
||||
// XML 지원 개발
|
||||
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
||||
String relayRequestHeaderKeys = prop.getProperty(HEADER_KEYS);
|
||||
@@ -394,31 +366,37 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
if(message instanceof String && StringUtils.isEmpty((String)message))
|
||||
message = "{}";
|
||||
|
||||
JSONObject jsonMessage = JSONUtils.parseJson(message);
|
||||
JSONObject headerJson = JSONUtils.getChildJson(jsonMessage, headerGroupName);
|
||||
if (headerJson == null)
|
||||
headerJson = new JSONObject();
|
||||
|
||||
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
||||
String key = e.nextElement();
|
||||
headerJson.put(StringUtils.lowerCase(key), request.getHeader(key));
|
||||
}
|
||||
} else {
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils
|
||||
.tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
||||
JsonNode jsonMessageNode = JacksonUtil.readTree(message, mapper);
|
||||
if (jsonMessageNode == null || !jsonMessageNode.isObject()) {
|
||||
jsonMessageNode = OBJECT_MAPPER.createObjectNode();
|
||||
}
|
||||
ObjectNode jsonNode = (ObjectNode) jsonMessageNode;
|
||||
|
||||
for (String key : relayKeyArr) {
|
||||
String headerValue = request.getHeader(key);
|
||||
if (StringUtils.isNotBlank(headerValue)) {
|
||||
headerJson.put(StringUtils.lowerCase(key), headerValue);
|
||||
}
|
||||
}
|
||||
JsonNode childNode = jsonNode.get(headerGroupName);
|
||||
ObjectNode headerJson = (childNode != null && childNode.isObject())
|
||||
? (ObjectNode) childNode
|
||||
: OBJECT_MAPPER.createObjectNode();
|
||||
|
||||
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
||||
String key = e.nextElement();
|
||||
headerJson.put(StringUtils.lowerCase(key), request.getHeader(key));
|
||||
}
|
||||
} else {
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils
|
||||
.tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
||||
|
||||
for (String key : relayKeyArr) {
|
||||
String headerValue = request.getHeader(key);
|
||||
if (StringUtils.isNotBlank(headerValue)) {
|
||||
headerJson.put(StringUtils.lowerCase(key), headerValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (headerJson.size() > 0) {
|
||||
jsonMessage.put(headerGroupName, headerJson);
|
||||
message = jsonMessage.toJSONString();
|
||||
if (!headerJson.isEmpty()) {
|
||||
jsonNode.set(headerGroupName, headerJson);
|
||||
message = jsonNode;
|
||||
}
|
||||
} else if(MessageType.XML.equals(adptMsgType)) {
|
||||
Document document = XMLUtils.convertXmlDocument(message);
|
||||
@@ -533,10 +511,10 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
}
|
||||
}
|
||||
|
||||
private String applyHeaderGroupResponseHeaders(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
private Object applyHeaderGroupResponseHeaders(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response, String adptMsgType) throws Exception {
|
||||
// body headergroup -> http header 세팅
|
||||
String headerGroupName = prop.getProperty(ApiAdapterService.HEADER_GROUP);
|
||||
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
||||
|
||||
if (StringUtils.isNotBlank(headerGroupName)) {
|
||||
if (resultMessage instanceof Node) {
|
||||
@@ -552,34 +530,44 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
adptMsgType = MessageType.XML;
|
||||
}
|
||||
}
|
||||
|
||||
if (MessageType.JSON.equals(adptMsgType)) {
|
||||
JSONObject jsonObject = JSONUtils.parseJson(resultMessage);
|
||||
JSONObject headerGroup = (JSONObject)jsonObject.get(headerGroupName);
|
||||
if (headerGroup != null) {
|
||||
Set<Map.Entry<String, Object>> fieldEntrySet = JSONUtils.getField(headerGroup);
|
||||
|
||||
for (Map.Entry<String, Object> fieldEntry : fieldEntrySet) {
|
||||
logger.info("header group entry : {} , {}", fieldEntry.getKey(), fieldEntry.getValue());
|
||||
|
||||
if (fieldEntry.getValue() instanceof String) {
|
||||
if(fieldEntry.getKey().equalsIgnoreCase("content-type")) {
|
||||
logger.debug("set content-type {}: {}", fieldEntry.getKey(), fieldEntry.getValue());
|
||||
response.setContentType((String) fieldEntry.getValue());
|
||||
} else {
|
||||
logger.debug("add header {}: {}", fieldEntry.getKey(), fieldEntry.getValue());
|
||||
response.addHeader(fieldEntry.getKey(), (String) fieldEntry.getValue());
|
||||
if (MessageType.JSON.equals(adptMsgType)) {
|
||||
JsonNode jsonNode = JacksonUtil.readTree(resultMessage, OBJECT_MAPPER); // 또는
|
||||
// objectMapper.readTree(resultMessage)
|
||||
JsonNode headerGroup = jsonNode.get(headerGroupName);
|
||||
|
||||
if (headerGroup != null && !headerGroup.isNull()) {
|
||||
Iterator<Map.Entry<String, JsonNode>> fieldIterator = headerGroup.fields();
|
||||
|
||||
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 {
|
||||
logger.info("fieldEntry value is not String. {}", fieldEntry.getValue());
|
||||
logger.info("fieldEntry value is not String. {}", valueNode);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.info("headerGroup is null");
|
||||
}
|
||||
|
||||
jsonObject.remove(headerGroupName);
|
||||
return jsonObject.toJSONString();
|
||||
} else {
|
||||
logger.info("headerGroup is null");
|
||||
}
|
||||
|
||||
((ObjectNode) jsonNode).remove(headerGroupName);
|
||||
return jsonNode;
|
||||
} else if(MessageType.XML.equals(adptMsgType)) {
|
||||
Document document = XMLUtils.convertXmlDocument(resultMessage);
|
||||
if(document != null) {
|
||||
@@ -594,8 +582,12 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
String value = headerElement.getTextTrim();
|
||||
|
||||
if(StringUtils.isNoneBlank(value)) {
|
||||
if(value.equalsIgnoreCase("content-type")) {
|
||||
response.setContentType(value);
|
||||
if(StringUtils.equalsIgnoreCase(name, "content-type")) {
|
||||
logger.debug("set content-type {}: {}", name, value);
|
||||
response.setContentType(value);
|
||||
} else if(StringUtils.equalsIgnoreCase(name, "content-length")) {
|
||||
logger.debug("skip content-length {}: {}", name, value);
|
||||
continue;
|
||||
} else {
|
||||
logger.debug("add header {}: {}", name, value);
|
||||
response.addHeader(name, value);
|
||||
@@ -700,7 +692,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||
if (sb.length() > 0) sb.append(", ");
|
||||
sb.append(values.nextElement());
|
||||
}
|
||||
prop.setProperty(key, sb.toString());
|
||||
prop.setProperty(key.toLowerCase(), sb.toString());
|
||||
}
|
||||
|
||||
return prop;
|
||||
@@ -36,6 +36,7 @@ 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.KeyStoreKeyFactory;
|
||||
|
||||
import com.eactive.eai.agent.encryption.EncryptionManager;
|
||||
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
||||
import com.eactive.eai.authserver.jwt.PssJwtAccessTokenConverter;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
@@ -131,10 +132,11 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
|
||||
String keyAlias = "elink-oauth";
|
||||
String keyPassword = "elink1234";
|
||||
if (vo != null) {
|
||||
keystorePath = vo.getProperty(PROP_KEYSTORE_PATH);
|
||||
keystorePassword = vo.getProperty(PROP_KEYSTORE_PW);
|
||||
keyAlias = vo.getProperty(PROP_KEY_ALIAS);
|
||||
keyPassword = vo.getProperty(PROP_KEY_PW);
|
||||
EncryptionManager encManager = EncryptionManager.getInstance();
|
||||
keystorePath = encManager.decryptDBData(vo.getProperty(PROP_KEYSTORE_PATH));
|
||||
keystorePassword = encManager.decryptDBData(vo.getProperty(PROP_KEYSTORE_PW));
|
||||
keyAlias = encManager.decryptDBData(vo.getProperty(PROP_KEY_ALIAS));
|
||||
keyPassword = encManager.decryptDBData(vo.getProperty(PROP_KEY_PW));
|
||||
} else {
|
||||
logger.warn("The properties has not been set.[" + PROP_GROUP_AUTH_SERVER + "]");
|
||||
}
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.authserver.config.RequestContextData;
|
||||
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
||||
import com.eactive.eai.authserver.service.BearerTokenService;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.vo.ClientVO;
|
||||
import com.eactive.eai.common.logger.EAIDBLogControl;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.data.entity.onl.authserver.TokenIssuanceLog;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth/oauth/v2")
|
||||
public class BearerTokenController {
|
||||
|
||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
private final BearerTokenService tokenService;
|
||||
|
||||
@Autowired
|
||||
private TokenIssuanceLogDAO tokenIssuanceLogDAO;
|
||||
|
||||
public BearerTokenController(BearerTokenService tokenService) {
|
||||
this.tokenService = tokenService;
|
||||
}
|
||||
|
||||
@RequestMapping(
|
||||
value = "/token",
|
||||
method = {RequestMethod.POST, RequestMethod.GET}
|
||||
)
|
||||
public ResponseEntity<?> issueCAToken(HttpServletRequest request, @RequestParam MultiValueMap<String, String> req) throws JwtAuthException {
|
||||
JSONObject resObject = new JSONObject();
|
||||
String clientId = req.getFirst("client_id");
|
||||
String grantType = req.getFirst("grant_type");
|
||||
String clientSecret = req.getFirst("client_secret");
|
||||
String scopes = req.getFirst("scope");
|
||||
|
||||
try {
|
||||
|
||||
|
||||
RequestContextData data = new RequestContextData();
|
||||
data.setClientId(request.getParameter("client_id"));
|
||||
data.setIpAddress(extractIpAddress(request));
|
||||
data.setGrantType(request.getParameter("grant_type"));
|
||||
data.setScope(request.getParameter("scope"));
|
||||
data.setUsername(request.getParameter("username"));
|
||||
data.setResource(request.getParameter("resource"));
|
||||
|
||||
RequestContextData.ThreadLocalRequestContext.set(data);
|
||||
|
||||
|
||||
|
||||
if (!StringUtils.equals(grantType, "client_credentials") ) {
|
||||
throw new JwtAuthException("unsupported_grant_type", "Unsupported grant type");
|
||||
}
|
||||
|
||||
ClientDetails clientDetails = OAuth2Manager.getInstance().getClientDeatilsStore().get(clientId);
|
||||
if (clientDetails == null) {
|
||||
throw new JwtAuthException("invalid_client", "Bad client credentials(not found)");
|
||||
}
|
||||
|
||||
String tokenType = "Bearer";
|
||||
|
||||
|
||||
|
||||
|
||||
Long expiresIn = Long.valueOf(clientDetails.getAccessTokenValiditySeconds());
|
||||
|
||||
String[] reqScopeArr = org.springframework.util.StringUtils.tokenizeToStringArray(scopes, " ");
|
||||
Set<String> scopeSet = new HashSet<String>();
|
||||
for (String scope : reqScopeArr) {
|
||||
scopeSet.add(scope);
|
||||
}
|
||||
veryfyClient(clientDetails, clientSecret, scopeSet);
|
||||
|
||||
String token = tokenService.generateCAToken(clientId, expiresIn, scopeSet);
|
||||
|
||||
Map<String, Object> tokenMap = new HashMap<>();
|
||||
tokenMap.put("token_type", tokenType);
|
||||
tokenMap.put("access_token", token);
|
||||
tokenMap.put("expires_in", expiresIn);
|
||||
tokenMap.put("scope", scopes);
|
||||
// ... and so on for all key-value pairs
|
||||
resObject.putAll(tokenMap);
|
||||
|
||||
logTokenIssuance(true,false, resObject.toJSONString(), token);
|
||||
|
||||
return ResponseEntity.ok(resObject);
|
||||
} catch (JwtAuthException e) {
|
||||
logger.error("Token request[/auth/oauth/v2/token] => clientId: {}, grantType: {}, scope: {}",
|
||||
clientId, grantType, scopes);
|
||||
logger.error(e);
|
||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage());
|
||||
logTokenIssuance(false ,false, e.getMessage(), null);
|
||||
return ResponseEntity.status(401).body(errorJson);
|
||||
} catch (Exception e) {
|
||||
logger.error("Token request[/auth/oauth/v2/token] => clientId: {}, grantType: {}, scope: {}",
|
||||
clientId, grantType, scopes);
|
||||
logger.error(e);
|
||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AP_ERROR, e.getMessage());
|
||||
logTokenIssuance(false ,false, e.getMessage(), null);
|
||||
return ResponseEntity.status(500).body(errorJson);
|
||||
}finally {
|
||||
RequestContextData.ThreadLocalRequestContext.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private String extractIpAddress(HttpServletRequest request) {
|
||||
String ipAddress = request.getHeader("X-Forwarded-For");
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getRemoteAddr();
|
||||
}
|
||||
return ipAddress;
|
||||
}
|
||||
|
||||
private void logTokenIssuance(boolean isSuccess, boolean isRestrictionExempt, String resultMessage, String accessToken) {
|
||||
try {
|
||||
if (!EAIDBLogControl.isEnable()) {
|
||||
logger.warn("DB logging is disabled. Skipping token issuance logging.");
|
||||
return;
|
||||
}
|
||||
RequestContextData data = RequestContextData.ThreadLocalRequestContext.get();
|
||||
OAuth2Manager.getInstance();
|
||||
|
||||
TokenIssuanceLog log = new TokenIssuanceLog();
|
||||
String clientId = data.getClientId();
|
||||
log.setClientId(clientId);
|
||||
|
||||
if(StringUtils.isNotBlank(clientId)) {
|
||||
ClientVO clientVO = OAuth2Manager.getInstance().getClientInfo(clientId);
|
||||
log.setAppName(clientVO.getClientName());
|
||||
log.setOrgId(clientVO.getOrgId());
|
||||
log.setOrgName(clientVO.getOrgName());
|
||||
}
|
||||
|
||||
log.setGrantType(data.getGrantType());
|
||||
log.setScope(data.getScope());
|
||||
log.setIpAddress(data.getIpAddress());
|
||||
log.setSuccessYn(isSuccess ? "Y" : "N");
|
||||
log.setIssuanceDateTime(LocalDateTime.now());
|
||||
log.setRestrictionExemptYn(isRestrictionExempt ? "Y" : "N");
|
||||
log.setResultMessage(resultMessage);
|
||||
log.setAccessToken(accessToken); // Add access token value to the log
|
||||
|
||||
tokenIssuanceLogDAO.saveTokenIssuanceLog(log);
|
||||
} catch (Throwable th) {
|
||||
logger.error("Error while logging token issuance: " + th.getMessage(), th);
|
||||
}
|
||||
}
|
||||
|
||||
private void veryfyClient(ClientDetails clientDetails, String clientSecret, Set<String> scopeSet) throws JwtAuthException {
|
||||
if (!StringUtils.equals(clientDetails.getClientSecret(), clientSecret)) {
|
||||
throw new JwtAuthException("invalid_client", "Bad client credentials(client_secret is empty or not match)");
|
||||
}
|
||||
|
||||
if (scopeSet.isEmpty()) {
|
||||
throw new JwtAuthException("invalid_client", "Bad client credentials(Scope is empty)");
|
||||
}
|
||||
|
||||
if (!clientDetails.getScope().containsAll(scopeSet)) {
|
||||
throw new JwtAuthException("invalid_client", "Bad client credentials(Include unacceptable scope)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import java.io.Serializable;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class DJErpOAuth2AccessTokenRequest implements Serializable {
|
||||
public class DJBOAuth2AccessTokenRequest implements Serializable {
|
||||
|
||||
@JsonProperty("grant_type")
|
||||
private String grantType;
|
||||
+1
-1
@@ -10,7 +10,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
@SuppressWarnings("serial")
|
||||
@JsonInclude(Include.NON_NULL)
|
||||
@JsonPropertyOrder({ "access_token", "token_type", "expires_in", "scope", "jti", "client_id" })
|
||||
public class DJErpOAuth2AccessTokenResponse implements Serializable {
|
||||
public class DJBOAuth2AccessTokenResponse implements Serializable {
|
||||
|
||||
@JsonProperty("access_token")
|
||||
private String accessToken;
|
||||
+12
-12
@@ -30,7 +30,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.UnkownMessageLogUtils;
|
||||
import com.eactive.eai.adapter.http.dynamic.UnknownMessageLogUtils;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.authserver.config.RequestContextData;
|
||||
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
||||
@@ -46,7 +46,7 @@ import com.eactive.eai.data.entity.onl.authserver.TokenIssuanceLog;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@Controller
|
||||
public class DJErpOAuth2Controller {
|
||||
public class DJBOAuth2Controller {
|
||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
private static final String HEADER_TRACEID = "traceId";
|
||||
@@ -55,20 +55,20 @@ public class DJErpOAuth2Controller {
|
||||
@Autowired
|
||||
private TokenIssuanceLogDAO tokenIssuanceLogDAO;
|
||||
|
||||
@RequestMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, method = RequestMethod.POST,
|
||||
@RequestMapping(value = { "/*/oauth/token", "/*/oauth2/token" }, method = RequestMethod.POST,
|
||||
consumes = "application/json", produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<?> tokenJson(@RequestBody DJErpOAuth2AccessTokenRequest tokenRequest,
|
||||
public ResponseEntity<?> tokenJson(@RequestBody DJBOAuth2AccessTokenRequest tokenRequest,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
@RequestMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, method = RequestMethod.POST,
|
||||
@RequestMapping(value = { "/*/oauth/token", "/*/oauth2/token" }, method = RequestMethod.POST,
|
||||
consumes = "application/x-www-form-urlencoded", produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<?> tokenForm(@RequestParam Map<String, String> params,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
DJErpOAuth2AccessTokenRequest tokenRequest = new DJErpOAuth2AccessTokenRequest();
|
||||
DJBOAuth2AccessTokenRequest tokenRequest = new DJBOAuth2AccessTokenRequest();
|
||||
tokenRequest.setGrantType(params.get("grant_type"));
|
||||
tokenRequest.setClientId(params.get("client_id"));
|
||||
tokenRequest.setClientSecret(params.get("client_secret"));
|
||||
@@ -76,11 +76,11 @@ public class DJErpOAuth2Controller {
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
@GetMapping(value = { "/dj/oauth/token", "/dj/oauth2/token" }, produces = "application/json; charset=UTF-8")
|
||||
@GetMapping(value = { "/*/oauth/token", "/*/oauth2/token" }, produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<?> tokenGet(@RequestParam Map<String, String> params,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
DJErpOAuth2AccessTokenRequest tokenRequest = new DJErpOAuth2AccessTokenRequest();
|
||||
DJBOAuth2AccessTokenRequest tokenRequest = new DJBOAuth2AccessTokenRequest();
|
||||
tokenRequest.setGrantType(params.get("grant_type"));
|
||||
tokenRequest.setClientId(params.get("client_id"));
|
||||
tokenRequest.setClientSecret(params.get("client_secret"));
|
||||
@@ -88,7 +88,7 @@ public class DJErpOAuth2Controller {
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
private ResponseEntity<?> issueToken(DJErpOAuth2AccessTokenRequest tokenRequest,
|
||||
private ResponseEntity<?> issueToken(DJBOAuth2AccessTokenRequest tokenRequest,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
if (logger.isDebug()) {
|
||||
@@ -143,7 +143,7 @@ public class DJErpOAuth2Controller {
|
||||
ResponseEntity<OAuth2AccessToken> result = tokenEndpoint().postAccessToken(principal, authorizationParameters);
|
||||
OAuth2AccessToken token = result.getBody();
|
||||
|
||||
DJErpOAuth2AccessTokenResponse responseToken = new DJErpOAuth2AccessTokenResponse();
|
||||
DJBOAuth2AccessTokenResponse responseToken = new DJBOAuth2AccessTokenResponse();
|
||||
responseToken.setAccessToken(token.getValue());
|
||||
responseToken.setTokenType(token.getTokenType());
|
||||
responseToken.setExpiresIn(Long.valueOf(token.getExpiresIn()));
|
||||
@@ -164,7 +164,7 @@ public class DJErpOAuth2Controller {
|
||||
|
||||
Properties logProp = new Properties();
|
||||
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);
|
||||
|
||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage());
|
||||
@@ -179,7 +179,7 @@ public class DJErpOAuth2Controller {
|
||||
|
||||
Properties logProp = new Properties();
|
||||
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);
|
||||
|
||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, "Unauthorized. [Unknown]");
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class KjbMGOAuth2AccessTokenRequest implements Serializable {
|
||||
@JsonProperty("grant_type")
|
||||
private String grantType;
|
||||
@JsonProperty("client_id")
|
||||
private String clientId;
|
||||
@JsonProperty("client_secret")
|
||||
private String clientSecret;
|
||||
private String resource;
|
||||
private String scope;
|
||||
|
||||
public String getGrantType() {
|
||||
return grantType;
|
||||
}
|
||||
|
||||
public void setGrantType(String grantType) {
|
||||
this.grantType = grantType;
|
||||
}
|
||||
|
||||
public String getClientId() {
|
||||
return clientId;
|
||||
}
|
||||
|
||||
public void setClientId(String clientId) {
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
public String getClientSecret() {
|
||||
return clientSecret;
|
||||
}
|
||||
|
||||
public void setClientSecret(String clientSecret) {
|
||||
this.clientSecret = clientSecret;
|
||||
}
|
||||
|
||||
public String getResource() {
|
||||
return resource;
|
||||
}
|
||||
|
||||
public void setResource(String resource) {
|
||||
this.resource = resource;
|
||||
}
|
||||
|
||||
public String getScope() {
|
||||
return scope;
|
||||
}
|
||||
|
||||
public void setScope(String scope) {
|
||||
this.scope = scope;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "KjbMGOAuth2AccessTokenRequest [grantType=" + grantType + ", clientId=" + clientId + ", clientSecret="
|
||||
+ clientSecret + ", resource=" + resource + ", scope=" + scope + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
@JsonInclude(Include.NON_NULL)
|
||||
public class KjbMGOAuth2AccessTokenResponse implements Serializable {
|
||||
private String responseCode;
|
||||
private String responseMessage;
|
||||
@JsonProperty("access_token")
|
||||
private String accessToken;
|
||||
@JsonProperty("refresh_token")
|
||||
private String refreshToken;
|
||||
@JsonProperty("token_type")
|
||||
private String tokenType;
|
||||
@JsonProperty("expires_in")
|
||||
private Long expiresIn;
|
||||
@JsonProperty("expires_on")
|
||||
private Long expiresOn;
|
||||
private String resource;
|
||||
private String scope;
|
||||
|
||||
public String getResponseCode() {
|
||||
return responseCode;
|
||||
}
|
||||
|
||||
public void setResponseCode(String responseCode) {
|
||||
this.responseCode = responseCode;
|
||||
}
|
||||
|
||||
public String getResponseMessage() {
|
||||
return responseMessage;
|
||||
}
|
||||
|
||||
public void setResponseMessage(String responseMessage) {
|
||||
this.responseMessage = responseMessage;
|
||||
}
|
||||
|
||||
public String getAccessToken() {
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
public void setAccessToken(String accessToken) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
|
||||
public String getrefreshToken() {
|
||||
return refreshToken;
|
||||
}
|
||||
|
||||
public void setrefreshToken(String refreshToken) {
|
||||
this.refreshToken = refreshToken;
|
||||
}
|
||||
|
||||
public String getTokenType() {
|
||||
return tokenType;
|
||||
}
|
||||
|
||||
public void setTokenType(String tokenType) {
|
||||
this.tokenType = tokenType;
|
||||
}
|
||||
|
||||
public Long getExpiresIn() {
|
||||
return expiresIn;
|
||||
}
|
||||
|
||||
public void setExpiresIn(Long expiresIn) {
|
||||
this.expiresIn = expiresIn;
|
||||
}
|
||||
|
||||
public Long getExpiresOn() {
|
||||
return expiresOn;
|
||||
}
|
||||
|
||||
public void setExpiresOn(Long expiresOn) {
|
||||
this.expiresOn = expiresOn;
|
||||
}
|
||||
|
||||
public String getResource() {
|
||||
return resource;
|
||||
}
|
||||
|
||||
public void setResource(String resource) {
|
||||
this.resource = resource;
|
||||
}
|
||||
|
||||
public String getScope() {
|
||||
return scope;
|
||||
}
|
||||
|
||||
public void setScope(String scope) {
|
||||
this.scope = scope;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "KjbMGOAuth2AccessTokenResponse [responseCode=" + responseCode + ", responseMessage=" + responseMessage
|
||||
+ ", accessToken=" + accessToken + ", tokenType=" + tokenType + ", expiresIn=" + expiresIn
|
||||
+ ", refreshToken=" + refreshToken+ ", expiresOn=" + expiresOn+ ", resource=" + resource+ ", scope=" + scope + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,360 +0,0 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.Principal;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Signature;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.util.OAuth2Utils;
|
||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Request;
|
||||
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
|
||||
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.authserver.config.IssueLimitOAuth2Exception;
|
||||
import com.eactive.eai.authserver.config.RequestContextData;
|
||||
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.util.BeanUtils;
|
||||
import com.eactive.eai.authserver.vo.ClientVO;
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.logger.EAIDBLogControl;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.common.util.UUID;
|
||||
import com.eactive.eai.data.entity.onl.authserver.TokenIssuanceLog;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@Controller
|
||||
public class KjbMGOAuth2Controller {
|
||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
private static final String HEADER_TRACEID = "traceId";
|
||||
|
||||
private static final String SERVICE_CODE_ACCESS_TOKEN = "00"; // 임시설정
|
||||
@Autowired
|
||||
private TokenIssuanceLogDAO tokenIssuanceLogDAO;
|
||||
|
||||
|
||||
@RequestMapping(value = "/mapi/oauth2/token", method = RequestMethod.POST, consumes = "application/json", produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<String> tokenJson(@RequestBody KjbMGOAuth2AccessTokenRequest tokenRequest,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/mapi/oauth2/token", method = RequestMethod.POST, consumes = "application/x-www-form-urlencoded", produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<String> tokenForm(@RequestParam Map<String, String> params, HttpServletRequest request,
|
||||
HttpServletResponse response) {
|
||||
|
||||
KjbMGOAuth2AccessTokenRequest tokenRequest = new KjbMGOAuth2AccessTokenRequest();
|
||||
|
||||
tokenRequest.setGrantType(params.get("grant_type"));
|
||||
tokenRequest.setClientId(params.get("client_id"));
|
||||
tokenRequest.setClientSecret(params.get("client_secret"));
|
||||
tokenRequest.setScope(params.get("scope"));
|
||||
tokenRequest.setResource(params.get("resource"));
|
||||
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/mapi/oauth2/token", produces = "application/json; charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<String> tokenGet(@RequestParam Map<String, String> params, HttpServletRequest request,
|
||||
HttpServletResponse response) {
|
||||
|
||||
KjbMGOAuth2AccessTokenRequest tokenRequest = new KjbMGOAuth2AccessTokenRequest();
|
||||
|
||||
tokenRequest.setGrantType(params.get("grant_type"));
|
||||
tokenRequest.setClientId(params.get("client_id"));
|
||||
tokenRequest.setClientSecret(params.get("client_secret"));
|
||||
tokenRequest.setScope(params.get("scope"));
|
||||
tokenRequest.setResource(params.get("resource"));
|
||||
|
||||
return issueToken(tokenRequest, request, response);
|
||||
}
|
||||
|
||||
private ResponseEntity<String> issueToken(
|
||||
KjbMGOAuth2AccessTokenRequest tokenRequest,
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response) {
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(tokenRequest.toString());
|
||||
}
|
||||
|
||||
RequestContextData data = new RequestContextData();
|
||||
data.setClientId(tokenRequest.getClientId());
|
||||
data.setIpAddress(extractIpAddress(request));
|
||||
data.setGrantType(tokenRequest.getGrantType());
|
||||
data.setScope(tokenRequest.getScope());
|
||||
data.setUsername("none");
|
||||
data.setResource("none");
|
||||
|
||||
RequestContextData.ThreadLocalRequestContext.set(data);
|
||||
|
||||
|
||||
KjbMGOAuth2AccessTokenResponse responseToken = new KjbMGOAuth2AccessTokenResponse();
|
||||
|
||||
String grantType = tokenRequest.getGrantType();
|
||||
String clientId = tokenRequest.getClientId();
|
||||
String clientSecret = tokenRequest.getClientSecret();
|
||||
String scopes = tokenRequest.getScope();
|
||||
|
||||
try {
|
||||
if (!StringUtils.equals(tokenRequest.getGrantType(), "client_credentials")) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {grantType}");
|
||||
}
|
||||
|
||||
String[] scopeArr = org.springframework.util.StringUtils.tokenizeToStringArray(scopes, " ");
|
||||
Set<String> scopeSet = new HashSet<String>();
|
||||
for (String scope : scopeArr) {
|
||||
scopeSet.add(scope);
|
||||
}
|
||||
|
||||
String[] resourceArr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenRequest.getResource(), ",");
|
||||
Set<String> resourceSet = new HashSet<String>();
|
||||
for (String resource : resourceArr) {
|
||||
resourceSet.add(resource);
|
||||
}
|
||||
|
||||
ClientDetails clientDetails = OAuth2Manager.getInstance().getClientDeatilsStore().get(clientId);
|
||||
verifyClient(clientDetails, clientId, clientSecret, scopeSet);
|
||||
|
||||
String traceId = UUID.randomUUID().toString().replace("-", "");
|
||||
response.setHeader(HEADER_TRACEID, traceId);
|
||||
|
||||
HashMap<String, String> authorizationParameters = new HashMap<String, String>();
|
||||
authorizationParameters.put(OAuth2Utils.GRANT_TYPE, grantType);
|
||||
authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
|
||||
authorizationParameters.put("client_secret", clientSecret);
|
||||
|
||||
Set<String> responseType = new HashSet<String>();
|
||||
responseType.add(tokenRequest.getGrantType());
|
||||
|
||||
OAuth2Request authorizationRequest = new OAuth2Request(authorizationParameters, clientId, null, true, scopeSet,
|
||||
resourceSet, "", responseType, null);
|
||||
|
||||
Principal principal = new OAuth2Authentication(authorizationRequest, null);
|
||||
ResponseEntity<OAuth2AccessToken> result = tokenEndpoint().postAccessToken(principal,
|
||||
authorizationParameters);
|
||||
OAuth2AccessToken token = result.getBody();
|
||||
if(StringUtils.isNotBlank(token.getTokenType()) && StringUtils.equalsIgnoreCase(token.getTokenType(), "bearer")) {
|
||||
responseToken.setTokenType("Bearer");
|
||||
} else { responseToken.setTokenType(token.getTokenType()); }
|
||||
responseToken.setAccessToken(token.getValue());
|
||||
responseToken.setExpiresIn(Long.valueOf(token.getExpiresIn()));
|
||||
responseToken.setrefreshToken("");
|
||||
responseToken.setExpiresOn(System.currentTimeMillis() + (token.getExpiresIn() * 1000));
|
||||
responseToken.setScope(tokenRequest.getScope());
|
||||
responseToken.setResource(tokenRequest.getResource());
|
||||
|
||||
// 성공 시 JSON 문자열로 변환하여 반환
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
String successJson = mapper.writeValueAsString(responseToken);
|
||||
|
||||
return ResponseEntity.ok(successJson);
|
||||
|
||||
} catch (JwtAuthException e) {
|
||||
logger.info("Token request[/mapi/oauth2/token] => clientId: {}, grantType: {}, scope: {}",
|
||||
clientId, grantType, scopes);
|
||||
logger.error(e.getMessage());
|
||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage());
|
||||
int statusCode = NumberUtils.toInt(StringUtils.left(e.getCode(), 3), HttpStatus.UNAUTHORIZED.value());
|
||||
logTokenIssuance(false ,false, e.getMessage(), null);
|
||||
return ResponseEntity.status(statusCode).body(errorJson);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.info("Token request[/mapi/oauth2/token] => clientId: {}, grantType: {}, scope: {}",
|
||||
clientId, grantType, scopes);
|
||||
logger.error(e.getMessage());
|
||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, "Unauthorized. [Unknown]");
|
||||
logTokenIssuance(false ,false, e.getMessage(), null);
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorJson);
|
||||
}finally {
|
||||
RequestContextData.ThreadLocalRequestContext.clear();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
private String extractIpAddress(HttpServletRequest request) {
|
||||
String ipAddress = request.getHeader("X-Forwarded-For");
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getRemoteAddr();
|
||||
}
|
||||
return ipAddress;
|
||||
}
|
||||
|
||||
private void verifyClient(ClientDetails clientDetails, String clientId, String clientSecret, Set<String> scopeSet)
|
||||
throws JwtAuthException {
|
||||
|
||||
if (StringUtils.isBlank(clientId)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {client_id}");
|
||||
}
|
||||
|
||||
if (clientDetails == null) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [client not found]");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(clientSecret)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {client_secret}");
|
||||
}
|
||||
|
||||
if (!StringUtils.equals(clientDetails.getClientSecret(), clientSecret)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [Bad client credentials(Client Secret is not match)]");
|
||||
}
|
||||
|
||||
if (scopeSet.isEmpty()) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {scope}");
|
||||
}
|
||||
|
||||
if (!clientDetails.getScope().containsAll(scopeSet)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [Bad client credentials(Include unacceptable scope)]");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private TokenEndpoint tokenEndpoint() {
|
||||
return BeanUtils.getBean("tokenEndpoint", TokenEndpoint.class);
|
||||
}
|
||||
|
||||
private void logTokenIssuance(boolean isSuccess, boolean isRestrictionExempt, String resultMessage, String accessToken) {
|
||||
try {
|
||||
if (!EAIDBLogControl.isEnable()) {
|
||||
logger.warn("DB logging is disabled. Skipping token issuance logging.");
|
||||
return;
|
||||
}
|
||||
RequestContextData data = RequestContextData.ThreadLocalRequestContext.get();
|
||||
OAuth2Manager.getInstance();
|
||||
|
||||
TokenIssuanceLog log = new TokenIssuanceLog();
|
||||
String clientId = data.getClientId();
|
||||
log.setClientId(clientId);
|
||||
|
||||
if(StringUtils.isNotBlank(clientId)) {
|
||||
ClientVO clientVO = OAuth2Manager.getInstance().getClientInfo(clientId);
|
||||
log.setAppName(clientVO.getClientName());
|
||||
log.setOrgId(clientVO.getOrgId());
|
||||
log.setOrgName(clientVO.getOrgName());
|
||||
}
|
||||
|
||||
log.setGrantType(data.getGrantType());
|
||||
log.setScope(data.getScope());
|
||||
log.setIpAddress(data.getIpAddress());
|
||||
log.setSuccessYn(isSuccess ? "Y" : "N");
|
||||
log.setIssuanceDateTime(LocalDateTime.now());
|
||||
log.setRestrictionExemptYn(isRestrictionExempt ? "Y" : "N");
|
||||
log.setResultMessage(resultMessage);
|
||||
log.setAccessToken(accessToken); // Add access token value to the log
|
||||
|
||||
tokenIssuanceLogDAO.saveTokenIssuanceLog(log);
|
||||
} catch (Throwable th) {
|
||||
logger.error("Error while logging token issuance: " + th.getMessage(), th);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// First generate a public/private key pair
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
// generator.initialize(512, new SecureRandom());
|
||||
//generator.initialize(1024, new SecureRandom());
|
||||
generator.initialize(2048, new SecureRandom());
|
||||
KeyPair pair = generator.generateKeyPair();
|
||||
|
||||
// The private key can be used to sign (not encrypt!) a message. The public key
|
||||
// holder can then verify the message.
|
||||
|
||||
String message = "sSGJDwlJsel5WeXodzd3J3MQ20KYCZpL|2022-12-21T14:36:19+07:00";
|
||||
|
||||
// Let's sign our message
|
||||
Signature privateSignature = Signature.getInstance("SHA256withRSA");
|
||||
privateSignature.initSign(pair.getPrivate());
|
||||
privateSignature.update(message.getBytes(StandardCharsets.UTF_8));
|
||||
// System.out.println("private key=" + Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));
|
||||
byte[] signature = privateSignature.sign();
|
||||
//System.out.println("signature=" + new String(signature, StandardCharsets.UTF_8));
|
||||
// System.out.println("signature=" + Base64.getEncoder().encodeToString(signature));
|
||||
|
||||
// Let's check the signature
|
||||
Signature publicSignature = Signature.getInstance("SHA256withRSA");
|
||||
publicSignature.initVerify(pair.getPublic());
|
||||
publicSignature.update(message.getBytes(StandardCharsets.UTF_8));
|
||||
boolean isCorrect = publicSignature.verify(signature);
|
||||
// System.out.println("public key=" + Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()));
|
||||
|
||||
// System.out.println("Signature correct: " + isCorrect);
|
||||
|
||||
// The public key can be used to encrypt a message, the private key can be used
|
||||
// to decrypt it.
|
||||
// Encrypt the message
|
||||
Cipher encryptCipher = Cipher.getInstance("RSA");
|
||||
encryptCipher.init(Cipher.ENCRYPT_MODE, pair.getPublic());
|
||||
|
||||
byte[] cipherText = encryptCipher.doFinal(message.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// Now decrypt it
|
||||
Cipher decriptCipher = Cipher.getInstance("RSA");
|
||||
decriptCipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());
|
||||
|
||||
String decipheredMessage = new String(decriptCipher.doFinal(cipherText), StandardCharsets.UTF_8);
|
||||
|
||||
// System.out.println(decipheredMessage);
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class SnapOAuth2AccessTokenRequest implements Serializable {
|
||||
private String grantType;
|
||||
private String authCode;
|
||||
private String refreshToken;
|
||||
private Object additionalInfo;
|
||||
|
||||
public String getGrantType() {
|
||||
return grantType;
|
||||
}
|
||||
|
||||
public void setGrantType(String grantType) {
|
||||
this.grantType = grantType;
|
||||
}
|
||||
|
||||
public String getAuthCode() {
|
||||
return authCode;
|
||||
}
|
||||
|
||||
public void setAuthCode(String authCode) {
|
||||
this.authCode = authCode;
|
||||
}
|
||||
|
||||
public String getRefreshToken() {
|
||||
return refreshToken;
|
||||
}
|
||||
|
||||
public void setRefreshToken(String refreshToken) {
|
||||
this.refreshToken = refreshToken;
|
||||
}
|
||||
|
||||
public Object getAdditionalInfo() {
|
||||
return additionalInfo;
|
||||
}
|
||||
|
||||
public void setAdditionalInfo(Object additionalInfo) {
|
||||
this.additionalInfo = additionalInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SnapOAuth2AccessTokenRequest [grantType=" + grantType + ", authCode=" + authCode + ", refreshToken="
|
||||
+ refreshToken + ", additionalInfo=" + additionalInfo + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
@JsonInclude(Include.NON_NULL)
|
||||
public class SnapOAuth2AccessTokenResponse implements Serializable {
|
||||
private String responseCode;
|
||||
private String responseMessage;
|
||||
private String accessToken;
|
||||
private String tokenType;
|
||||
private String expiresIn;
|
||||
private Object additionalInfo;
|
||||
|
||||
public String getResponseCode() {
|
||||
return responseCode;
|
||||
}
|
||||
|
||||
public void setResponseCode(String responseCode) {
|
||||
this.responseCode = responseCode;
|
||||
}
|
||||
|
||||
public String getResponseMessage() {
|
||||
return responseMessage;
|
||||
}
|
||||
|
||||
public void setResponseMessage(String responseMessage) {
|
||||
this.responseMessage = responseMessage;
|
||||
}
|
||||
|
||||
public String getAccessToken() {
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
public void setAccessToken(String accessToken) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
|
||||
public String getTokenType() {
|
||||
return tokenType;
|
||||
}
|
||||
|
||||
public void setTokenType(String tokenType) {
|
||||
this.tokenType = tokenType;
|
||||
}
|
||||
|
||||
public String getExpiresIn() {
|
||||
return expiresIn;
|
||||
}
|
||||
|
||||
public void setExpiresIn(String expiresIn) {
|
||||
this.expiresIn = expiresIn;
|
||||
}
|
||||
|
||||
public Object getAdditionalInfo() {
|
||||
return additionalInfo;
|
||||
}
|
||||
|
||||
public void setAdditionalInfo(Object additionalInfo) {
|
||||
this.additionalInfo = additionalInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SnapOAuth2AccessTokenResponse [responseCode=" + responseCode + ", responseMessage=" + responseMessage
|
||||
+ ", accessToken=" + accessToken + ", tokenType=" + tokenType + ", expiresIn=" + expiresIn
|
||||
+ ", additionalInfo=" + additionalInfo + "]";
|
||||
}
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.Principal;
|
||||
import java.security.PublicKey;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Signature;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.util.OAuth2Utils;
|
||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Request;
|
||||
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.util.BeanUtils;
|
||||
import com.eactive.eai.authserver.vo.ClientVO;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
@Controller
|
||||
public class SnapOAuth2Controller {
|
||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
private static final String HEADER_TIMESTAMP = "X-TIMESTAMP";
|
||||
private static final String HEADER_CLIENT_ID = "X-CLIENT-KEY";
|
||||
private static final String HEADER_SIGNATURE = "X-SIGNATURE";
|
||||
|
||||
private static final String SERVICE_CODE_ACCESS_TOKEN = "00"; // 임시설정
|
||||
|
||||
@RequestMapping(value = "/bukopin_snap_api/v1.0/access-token/b2b", method = RequestMethod.POST, produces = "application/json; charset=\"UTF-8\"")
|
||||
@ResponseBody
|
||||
public SnapOAuth2AccessTokenResponse token(@RequestBody SnapOAuth2AccessTokenRequest tokenRequest,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(tokenRequest.toString());
|
||||
}
|
||||
|
||||
SnapOAuth2AccessTokenResponse responseToken = new SnapOAuth2AccessTokenResponse();
|
||||
try {
|
||||
if (!StringUtils.equals(tokenRequest.getGrantType(), "client_credentials")) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {grantType}");
|
||||
}
|
||||
|
||||
String timeStamp = request.getHeader(HEADER_TIMESTAMP);
|
||||
String clientId = request.getHeader(HEADER_CLIENT_ID);
|
||||
String signature = request.getHeader(HEADER_SIGNATURE);
|
||||
|
||||
ClientDetails clientDetails = OAuth2Manager.getInstance().getClientDeatilsStore().get(clientId);
|
||||
verifyClient(clientDetails, timeStamp, clientId, signature);
|
||||
|
||||
response.setHeader(HEADER_TIMESTAMP, timeStamp);
|
||||
response.setHeader(HEADER_CLIENT_ID, clientId);
|
||||
|
||||
HashMap<String, String> authorizationParameters = new HashMap<String, String>();
|
||||
authorizationParameters.put(OAuth2Utils.GRANT_TYPE, tokenRequest.getGrantType());
|
||||
authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
|
||||
authorizationParameters.put("client_secret", clientDetails.getClientSecret());
|
||||
|
||||
Set<String> responseType = new HashSet<String>();
|
||||
responseType.add(tokenRequest.getGrantType());
|
||||
|
||||
OAuth2Request authorizationRequest = new OAuth2Request(authorizationParameters, clientId, null, true, null,
|
||||
null, "", responseType, null);
|
||||
|
||||
Principal principal = new OAuth2Authentication(authorizationRequest, null);
|
||||
ResponseEntity<OAuth2AccessToken> result = tokenEndpoint().postAccessToken(principal,
|
||||
authorizationParameters);
|
||||
OAuth2AccessToken token = result.getBody();
|
||||
responseToken.setAccessToken(token.getValue());
|
||||
responseToken.setExpiresIn(String.valueOf(token.getExpiresIn()));
|
||||
responseToken.setTokenType(token.getTokenType());
|
||||
} catch (JwtAuthException e) {
|
||||
response.setStatus(NumberUtils.toInt(StringUtils.left(e.getCode(), 3), HttpStatus.UNAUTHORIZED.value()));
|
||||
responseToken.setResponseCode(e.getCode());
|
||||
responseToken.setResponseMessage(e.getMessage());
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
responseToken.setResponseCode(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"));
|
||||
responseToken.setResponseMessage("Unauthorized. [Unknown]");
|
||||
}
|
||||
|
||||
return responseToken;
|
||||
}
|
||||
|
||||
private void verifyClient(ClientDetails clientDetails, String timeStamp, String clientId, String signatureStr)
|
||||
throws JwtAuthException {
|
||||
if (StringUtils.isBlank(timeStamp)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {" + HEADER_TIMESTAMP + "}");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(clientId)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {" + HEADER_CLIENT_ID + "}");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(signatureStr)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {" + HEADER_SIGNATURE + "}");
|
||||
}
|
||||
|
||||
if (clientDetails == null) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [client not found]");
|
||||
}
|
||||
|
||||
String publicKeyStr = ((ClientVO) clientDetails).getSecurityKey();
|
||||
if (StringUtils.isBlank(publicKeyStr)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [public key not found]");
|
||||
}
|
||||
|
||||
try {
|
||||
String message = clientId + "|" + timeStamp;
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyStr));
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
PublicKey publicKey = keyFactory.generatePublic(keySpec);
|
||||
|
||||
Signature signature = Signature.getInstance("SHA256withRSA");
|
||||
signature.initVerify(publicKey);
|
||||
signature.update(message.getBytes(StandardCharsets.UTF_8));
|
||||
if (!signature.verify(Base64.getDecoder().decode(signatureStr))) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [Signature not matched]");
|
||||
}
|
||||
} catch (JwtAuthException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [Signature fail]");
|
||||
}
|
||||
}
|
||||
|
||||
private TokenEndpoint tokenEndpoint() {
|
||||
return BeanUtils.getBean("tokenEndpoint", TokenEndpoint.class);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// First generate a public/private key pair
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
// generator.initialize(512, new SecureRandom());
|
||||
//generator.initialize(1024, new SecureRandom());
|
||||
generator.initialize(2048, new SecureRandom());
|
||||
KeyPair pair = generator.generateKeyPair();
|
||||
|
||||
// The private key can be used to sign (not encrypt!) a message. The public key
|
||||
// holder can then verify the message.
|
||||
|
||||
String message = "sSGJDwlJsel5WeXodzd3J3MQ20KYCZpL|2022-12-21T14:36:19+07:00";
|
||||
|
||||
// Let's sign our message
|
||||
Signature privateSignature = Signature.getInstance("SHA256withRSA");
|
||||
privateSignature.initSign(pair.getPrivate());
|
||||
privateSignature.update(message.getBytes(StandardCharsets.UTF_8));
|
||||
System.out.println(
|
||||
"private key=" + Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));
|
||||
|
||||
byte[] signature = privateSignature.sign();
|
||||
//System.out.println("signature=" + new String(signature, StandardCharsets.UTF_8));
|
||||
System.out.println("signature=" + Base64.getEncoder().encodeToString(signature));
|
||||
|
||||
// Let's check the signature
|
||||
Signature publicSignature = Signature.getInstance("SHA256withRSA");
|
||||
publicSignature.initVerify(pair.getPublic());
|
||||
publicSignature.update(message.getBytes(StandardCharsets.UTF_8));
|
||||
boolean isCorrect = publicSignature.verify(signature);
|
||||
System.out.println("public key=" + Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()));
|
||||
|
||||
System.out.println("Signature correct: " + isCorrect);
|
||||
|
||||
// The public key can be used to encrypt a message, the private key can be used
|
||||
// to decrypt it.
|
||||
// Encrypt the message
|
||||
Cipher encryptCipher = Cipher.getInstance("RSA");
|
||||
encryptCipher.init(Cipher.ENCRYPT_MODE, pair.getPublic());
|
||||
|
||||
byte[] cipherText = encryptCipher.doFinal(message.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// Now decrypt it
|
||||
Cipher decriptCipher = Cipher.getInstance("RSA");
|
||||
decriptCipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());
|
||||
|
||||
String decipheredMessage = new String(decriptCipher.doFinal(cipherText), StandardCharsets.UTF_8);
|
||||
|
||||
System.out.println(decipheredMessage);
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -73,7 +73,17 @@ public class KakaopayAdapterErrorMsgHandler extends TemplateCodeConvertAdapterEr
|
||||
String jsonStr = (String) responseBody;
|
||||
if (!StringUtils.isBlank(jsonStr)) {
|
||||
JsonNode rootNode = OBJECT_MAPPER.readTree(jsonStr);
|
||||
msgDesc = rootNode.get("error_code").textValue() + "/" + rootNode.get("error_message").textValue();
|
||||
StringBuffer sb = new StringBuffer();
|
||||
JsonNode errorCode = rootNode.get("error_code");
|
||||
if(errorCode != null)
|
||||
sb.append(errorCode.textValue());
|
||||
|
||||
sb.append("/");
|
||||
JsonNode errorMessage = rootNode.get("error_message");
|
||||
if(errorMessage != null)
|
||||
sb.append(errorMessage.textValue());
|
||||
|
||||
msgDesc = sb.toString();
|
||||
msgCd = "BFEX03216";
|
||||
msgCtnt = "참가기관코드 에러입니다.";
|
||||
logger.debug("오류 응답 수신 - {}", jsonStr);
|
||||
|
||||
-897
@@ -1,897 +0,0 @@
|
||||
package com.eactive.eai.custom.adapter.http.client.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.*;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.message.BasicNameValuePair;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.net.URIBuilder;
|
||||
import org.dom4j.Document;
|
||||
import org.dom4j.Element;
|
||||
import org.dom4j.io.SAXReader;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.authoutbound.AccessTokenManagerByDB;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
|
||||
public class HttpClient5AdapterServiceBase64 extends HttpClient5AdapterServiceSupport
|
||||
implements HttpClientAdapterServiceKey {
|
||||
|
||||
public static final String TYPE_VARIABLE_URL_REQUEST = "variableUrlRequest";
|
||||
public static final String TYPE_SIMPLE_REQUEST = "simpleRequest";
|
||||
public static final String REST_OPTION = "REST_OPTION";
|
||||
//public static final String HEADER_CONTENT_TYPE = "Content-Type";
|
||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||
public static final String HTTP_STATUS = "HTTP_STATUS";
|
||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||
public static final String AUTH_TOKEN = "AUTH_TOKEN";
|
||||
|
||||
/**
|
||||
* 1. 기능 : REST API 통신에 사용 <br>
|
||||
* 2. 처리 개요 : - 속성 정보를 설정 하고 수동 시스템 서비스를 호출 한다. <br>
|
||||
* 3. 주의사항 <br>
|
||||
*
|
||||
* @param prop Http Adapter 속성 정보
|
||||
* @return 반환 된 Object
|
||||
* @exception Exception 수동 시스템 간 통신 중 발생
|
||||
**/
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
||||
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
String bizCode = "";
|
||||
String authToken = "";
|
||||
try {
|
||||
Properties authProp = PropManager.getInstance().getProperties(AUTH_TOKEN); //Authorization
|
||||
bizCode = vo.getAdapterGroupName().substring(1, 4);
|
||||
authToken = authProp.getProperty(bizCode, "");
|
||||
} catch (Exception e) {
|
||||
logger.debug("Property Group AUTH_TOKEN is not Exist !!");
|
||||
}
|
||||
|
||||
logger.debug("authToken :::::::::::::::::::::::::::::::::::" + authToken);
|
||||
|
||||
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
||||
String relayResponseHeaderKeys = prop.getProperty(HEADER_KEYS, "");
|
||||
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
||||
|
||||
boolean useForwardProxy = StringUtils.equalsIgnoreCase(prop.getProperty("FORWARD_PROXY_USE_YN", "N"), "Y");
|
||||
String forwardProxyUrl = prop.getProperty("FORWARD_PROXY_URL");
|
||||
|
||||
// ex) $.dataHeader.GW_RSLT_CD
|
||||
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
||||
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
||||
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
||||
|
||||
// 레이아웃 메시지 타입 REST URL 추출 시 활용. Default JSON
|
||||
String messageType = prop.getProperty("MESSAGE_TYPE", MessageType.JSON);
|
||||
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
||||
* - type : simpleRequest, variableUrlRequest
|
||||
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
||||
* - method : get, delete, post, put
|
||||
* - contentType: application/json(default), application/x-www-form-urlencoded
|
||||
* - adapterTokenUseYn: Y, N(default)
|
||||
* ex)
|
||||
* {"type":"simpleRequest","extraPath":"v2.0/accout/balance","method":"post"}
|
||||
* @formatter:on
|
||||
*/
|
||||
|
||||
String restOptionData = tempProp.getProperty(REST_OPTION);
|
||||
|
||||
JSONObject restOptionObject = parseJson(restOptionData);
|
||||
if (restOptionObject == null) {
|
||||
throw new Exception("OptionData parsing result is NULL");
|
||||
}
|
||||
|
||||
String rmethod = (String) restOptionObject.getOrDefault("method", inboundMethod);
|
||||
String contentType = (String) restOptionObject.getOrDefault("contentType", "application/json");
|
||||
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
||||
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
||||
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
||||
}
|
||||
|
||||
HttpClient mclient = this.client;
|
||||
String sendData = "";
|
||||
if (data instanceof String) {
|
||||
sendData = (String) data;
|
||||
} else if (data instanceof byte[]) {
|
||||
sendData = new String((byte[]) data, vo.getEncode());
|
||||
}
|
||||
|
||||
////mclient.getParams().setContentCharset(vo.getEncode());
|
||||
|
||||
JSONObject dataObject = null;
|
||||
|
||||
Object httpHeader = null;
|
||||
Object dataContent = null;
|
||||
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
|
||||
Object parsed = parseJsonGeneric(sendData);
|
||||
|
||||
if(parsed instanceof JSONObject) {
|
||||
dataObject = parseJson(sendData);
|
||||
if (dataObject != null && StringUtils.isNotBlank(headerGroupName)) {
|
||||
httpHeader = dataObject.get(headerGroupName);
|
||||
dataObject.remove(headerGroupName);
|
||||
}
|
||||
|
||||
dataContent = dataObject;
|
||||
if (dataObject.containsKey("innerList")) {
|
||||
JSONArray innerList = (JSONArray) dataObject.get("innerList");
|
||||
dataContent = innerList;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("HttpClientAdapterServiceRest] dataObject1 = [" + dataObject + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] dataContent = [" + dataContent + "]");
|
||||
|
||||
// interface 에 설정된게 우선한다.
|
||||
String uri = null;
|
||||
if (dataObject == null) {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, sendData);
|
||||
} else {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, dataObject);
|
||||
}
|
||||
|
||||
// ////if (vo.getConnectionTimeout() != 0) {
|
||||
// mclient.getHttpConnectionManager().getParams().setConnectionTimeout(vo.getConnectionTimeout());
|
||||
// }
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL=[" + vo.getUrl() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") PARAMETER_NAME=[" + vo.getParameterName() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") ENCODE=[" + vo.getEncode() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") RESPONSE_TYPE=[" + vo.getResponseType() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL_ENCODE_YN=[" + vo.getUrlEncodeYn() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") CONNECTION_TIMEOUT=[" + vo.getConnectionTimeout() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") REST_OPTION=[" + restOptionData + "] ");
|
||||
}
|
||||
|
||||
HttpUriRequestBase method = null;
|
||||
|
||||
// 메소드 타입에 따라 HttpRequestBase 인스턴스 생성
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
case DELETE:
|
||||
method = new HttpDelete(uri);
|
||||
break;
|
||||
case POST:
|
||||
method = new HttpPost(uri);
|
||||
break;
|
||||
case PUT:
|
||||
method = new HttpPut(uri);
|
||||
break;
|
||||
default:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
configureHttpClient(requestConfigBuilder, vo, method);
|
||||
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
case DELETE:
|
||||
HashMap<String, String> h = getParameters(dataObject);
|
||||
URIBuilder uriBuilder = new URIBuilder(uri);
|
||||
for (Map.Entry<String, String> entry : h.entrySet()) {
|
||||
uriBuilder.addParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
URI fullUri = uriBuilder.build();
|
||||
if (method instanceof HttpGet) {
|
||||
((HttpGet) method).setUri(fullUri);
|
||||
} else if (method instanceof HttpDelete) {
|
||||
((HttpDelete) method).setUri(fullUri);
|
||||
}
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] (get Method) QueryString = [" + fullUri.getQuery() + "]");
|
||||
}
|
||||
break;
|
||||
case PUT:
|
||||
case POST:
|
||||
//assignPostBody(dataObject, contentType, vo.getEncode(), method);
|
||||
assignPostBody(dataContent, contentType, vo.getEncode(), method);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") method.getParams()=["
|
||||
+ method.getEntity() + "] ");
|
||||
}
|
||||
|
||||
OAuth2AccessTokenVO accessToken = null;
|
||||
if (useAdapterToken) {
|
||||
AccessTokenManagerByDB tokenManager = AccessTokenManagerByDB.getInstance();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
||||
|
||||
// 토큰이 없거나 만료 됐으면 재발급
|
||||
if (accessToken == null || accessToken.isExpired()) {
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
||||
oldToken);
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
||||
+ accessToken + "]");
|
||||
}
|
||||
|
||||
setAuthHeaders(method, accessToken);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RequestHeader [Authorization=" + method.getHeader("Authorization") + "]");
|
||||
}
|
||||
}
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
if(!StringUtils.isBlank(authToken)) {
|
||||
setAuthHeaders(method, authToken);
|
||||
}
|
||||
|
||||
// 전달 header 셋팅
|
||||
// Adapter 레벨 header 보다 data로 넘어온 httpHeader를 우선 적용(header명이 같다면 덮어씀)
|
||||
assignRequestHeaders(method, httpHeader);
|
||||
|
||||
int status = -1;
|
||||
|
||||
try {
|
||||
byte[] responseMessage = null;
|
||||
Header[] responseHeaders;
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
if (dataContent != null) { //dataObject
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = ["
|
||||
+ dataContent.toString() + "]"); //dataObject.toJSONString()
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(dataContent.toString())); //dataObject.toJSONString()
|
||||
} else {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = [" + sendData
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
}
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"SEND [" + sendData + "]" + CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
|
||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
HttpContext context = new BasicHttpContext();
|
||||
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
||||
Integer logProcessNo = (Integer) tempProp.get(HttpClientAdapterServiceKey.LOG_PROCESS_NO);
|
||||
if (logProcessNo != null && logProcessNo > 0) {
|
||||
context.setAttribute(HttpClientAdapterServiceKey.LOG_PROCESS_NO, logProcessNo);
|
||||
}
|
||||
|
||||
try {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[method getName]" + method.getMethod());
|
||||
logger.debug("[method getEntity]" + method.getEntity());
|
||||
logger.debug("[method getRequestHeaders]" + method.getHeaders().toString());
|
||||
logger.debug("[method getURI]" + method.getPath());
|
||||
}
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = response.getCode();
|
||||
|
||||
if (status >= 200 && status <= 207) {
|
||||
status = 200;
|
||||
}
|
||||
|
||||
// if (status == 404) {
|
||||
// status = 200;
|
||||
// }
|
||||
|
||||
// responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
responseHeaders = response.getHeaders();
|
||||
// 2025/08/06 Response body를 Base64로 Encode 해서 Json으로 만들어서 전달하도록 수정
|
||||
HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
byte[] entityBytes = EntityUtils.toByteArray(response.getEntity());
|
||||
String b64 = Base64.encodeBase64String(entityBytes);
|
||||
JSONObject resultJson = new JSONObject();
|
||||
resultJson.put("base64_file_data", b64);
|
||||
responseMessage = resultJson.toString().getBytes();
|
||||
} else {
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
}
|
||||
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + responseMessage + "]");
|
||||
}
|
||||
}
|
||||
} catch (ConnectException e) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
}
|
||||
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
||||
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
||||
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
||||
*
|
||||
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
||||
* __ex) $.dataHeader.resultCode
|
||||
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
||||
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
||||
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
||||
* @formatter:on
|
||||
*/
|
||||
boolean needReissue = false;
|
||||
|
||||
Properties responseHeaderProp = assignRelayDataToInbound(tempProp, responseHeaders);
|
||||
String responseString = new String(responseMessage, vo.getEncode());
|
||||
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
tempProp.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, responseHeaderProp);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_MESSAGE, responseString);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_STATUS, status);
|
||||
|
||||
if (status >= 200 && status <= 207) {
|
||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
} else if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseString);
|
||||
// logger.error(errMsg);
|
||||
|
||||
if (status >= 400 && status < 500) {
|
||||
if (useAdapterToken) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
|
||||
// if (!needReissue) {
|
||||
// throw new Exception(errMsg);
|
||||
// }
|
||||
} else {
|
||||
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV " + vo.getEncode() + "(" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV MS949 (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "MS949") + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV euc-kr (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "euc-kr") + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = " + CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
if (useAdapterToken) {
|
||||
if (responseMessage == null) {
|
||||
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
||||
}
|
||||
|
||||
// OAuth 토큰 재요청 코드 확인
|
||||
if (needReissue) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] retry access token response code = ["
|
||||
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
}
|
||||
|
||||
// 토큰 재발급
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
OAuth2AccessTokenVO newaccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||
method.setHeader("Authorization", newaccessToken.getAuthorization());
|
||||
|
||||
setAuthHeaders(method, newaccessToken);
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RETRY TOKEN = [" + newaccessToken + "]");
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method)) {
|
||||
status = response.getCode();
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
||||
}
|
||||
}catch (IOException e){
|
||||
throw new Exception("retry excuteMethod Exceptioin = " + e.getMessage());
|
||||
}
|
||||
|
||||
|
||||
if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV " + vo.getEncode() + "("
|
||||
+ vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
// ----------------------------------------------------------
|
||||
}
|
||||
}
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"RECV [" + new String(responseMessage, vo.getEncode()) + "]"
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
|
||||
return assignResponseHeaders(method, responseMessage, headerGroupName, vo.getEncode(), messageType,
|
||||
relayResponseHeaderKeys, status, responseHeaderProp);
|
||||
} catch (SocketTimeoutException ste) { // Read Timeout :: HttpClient 3.1일 경우
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(),
|
||||
ste);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(), ste);
|
||||
throw ste;
|
||||
} catch (ConnectException ce) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(),
|
||||
ce);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(), ce);
|
||||
throw ce;
|
||||
} catch (Exception e) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
||||
e);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status != HttpStatus.SC_OK) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = String.valueOf(status);
|
||||
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Properties assignRelayDataToInbound(Properties prop, Header[] responseHeaders) {
|
||||
Properties headerProp = new Properties();
|
||||
if (responseHeaders == null || responseHeaders.length == 0) {
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
for (Header header : responseHeaders) {
|
||||
headerProp.put(header.getName(), header.getValue());
|
||||
}
|
||||
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 1단계 레이아웃에만 적용되도록 구현됨.
|
||||
*
|
||||
* @param method
|
||||
* @param responseMessage
|
||||
* @param headerGroupName
|
||||
* @param encode
|
||||
* @param messageType
|
||||
* @param relayHeaderKeys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private String assignResponseHeaders(HttpUriRequestBase method, byte[] responseMessage, String headerGroupName,
|
||||
String encode, String messageType, String relayHeaderKeys, int status, Properties responseHeaderProp) throws Exception {
|
||||
if (!MessageType.JSON.equals(messageType) || StringUtils.isBlank(headerGroupName)
|
||||
|| StringUtils.isBlank(relayHeaderKeys)) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils.tokenizeToStringArray(relayHeaderKeys, ",");
|
||||
JSONObject headerJson = new JSONObject();
|
||||
for (String key : relayKeyArr) {
|
||||
String value = responseHeaderProp.getProperty(key);
|
||||
if (StringUtils.isNotBlank(value)) {
|
||||
headerJson.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
headerJson.put(HTTP_STATUS, String.valueOf(status));
|
||||
|
||||
if (headerJson.size() <= 0) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
JSONObject message = null;
|
||||
if (responseMessage == null || responseMessage.length == 0) {
|
||||
message = new JSONObject();
|
||||
} else {
|
||||
message = parseJson(new String(responseMessage, encode));
|
||||
if (message == null) {
|
||||
message = new JSONObject();
|
||||
message.put("Malformed_Response_Message", new String(responseMessage, encode));
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(headerGroupName) && message != null)
|
||||
message.put(headerGroupName, headerJson);
|
||||
|
||||
logger.info("------------- message --------------- : {} ", message);
|
||||
|
||||
return message.toJSONString();
|
||||
}
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
private void setAuthHeaders(HttpUriRequestBase method, String authorization) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s", authorization));
|
||||
}
|
||||
|
||||
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||
String encode) {
|
||||
if (responseMessage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
||||
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
||||
if (StringUtils.isBlank(responseCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
||||
return ArrayUtils.contains(arr, responseCode);
|
||||
} catch (Exception e) {
|
||||
logger.error("HttpClientAdapterServiceRest] checkTokenRetry error=" + e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void assignRequestHeaders(HttpUriRequestBase method, Object httpHeader) {
|
||||
if (httpHeader == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (httpHeader instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) httpHeader;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
method.setHeader((String) key, (String) obj);
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request Header :" + (String) key + "=[" + (String) obj + "]");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private void assignPostBody(Object eaiBody, String contentType, String charset, HttpUriRequestBase method) {
|
||||
if (eaiBody == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(contentType, "application/x-www-form-urlencoded")) {
|
||||
if (eaiBody instanceof JSONObject) {
|
||||
List<NameValuePair> params = new ArrayList<>();
|
||||
JSONObject jsonObject = (JSONObject) eaiBody;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
params.add(new BasicNameValuePair((String) key, (String) jsonObject.get(key)));
|
||||
}
|
||||
|
||||
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
|
||||
method.setEntity(entity);
|
||||
}
|
||||
|
||||
} else {
|
||||
ContentType contentTypeObj = ContentType.create(contentType, charset);
|
||||
|
||||
// 요청 본문을 StringEntity 객체로 생성
|
||||
StringEntity entity = new StringEntity(eaiBody.toString(), contentTypeObj);
|
||||
|
||||
// 요청에 본문 추가
|
||||
method.setEntity(entity);
|
||||
}
|
||||
}
|
||||
|
||||
private HashMap<String, String> getParameters(Object message) throws Exception {
|
||||
|
||||
HashMap<String, String> result = new HashMap<String, String>();
|
||||
|
||||
if (message != null) {
|
||||
if (message instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) message;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
result.put((String) key, getStringValue(obj));
|
||||
}
|
||||
} else {
|
||||
String[] messages = ((String) message).split("&");
|
||||
String[] data = null;
|
||||
|
||||
for (int i = 0; i < messages.length; i++) {
|
||||
data = messages[i].split("=", 2);
|
||||
if (data.length == 2) {
|
||||
result.put(data[0], data[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getStringValue(Object obj) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (obj instanceof String) {
|
||||
return (String) obj;
|
||||
} else if (obj instanceof Long) {
|
||||
return Long.toString((Long) obj);
|
||||
} else if (obj instanceof BigDecimal) {
|
||||
return ((BigDecimal) obj).toPlainString();
|
||||
} else {
|
||||
return (String) obj;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object parseJsonGeneric(String jsonData) {
|
||||
if (StringUtils.isBlank(jsonData)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
JSONParser parser = new JSONParser();
|
||||
Object parsedObj = parser.parse(jsonData);
|
||||
return parsedObj;
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private JSONObject parseJson(String message) throws Exception {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (JSONObject) JSONValue.parse(message);
|
||||
}
|
||||
|
||||
private Document convertXmlDocument(String message) throws Exception {
|
||||
SAXReader builder = new SAXReader();
|
||||
Document document = builder.read(new StringReader(message));
|
||||
return document;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private String changeUrl(String messageType, String url, String restOption, Object sendData) {
|
||||
if ((MessageType.JSON.equals(messageType) || MessageType.XML.equals(messageType))) {
|
||||
try {
|
||||
if (StringUtils.isBlank(restOption)) {
|
||||
return url;
|
||||
}
|
||||
List<String> urlVariableList = new ArrayList<String>();
|
||||
JSONObject restOptionObject = parseJson(restOption);
|
||||
|
||||
if (restOptionObject == null)
|
||||
throw new Exception("restOption is NULL");
|
||||
|
||||
String type = (String) restOptionObject.get("type");
|
||||
String requestExtraPath = (String) restOptionObject.get("extraPath");
|
||||
url = getUrl(url, requestExtraPath);
|
||||
if (TYPE_VARIABLE_URL_REQUEST.equals(type)) {
|
||||
Pattern p = Pattern.compile("\\{(.*?)\\}");
|
||||
Matcher m = p.matcher(requestExtraPath);
|
||||
List<String> uriVariables = new ArrayList<>();
|
||||
while(m.find()) {
|
||||
String fieldName = m.group(1);
|
||||
uriVariables.add(fieldName);
|
||||
}
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
JSONObject jsonObject;
|
||||
if (sendData instanceof JSONObject) {
|
||||
jsonObject = (JSONObject) sendData;
|
||||
} else {
|
||||
jsonObject = (JSONObject) JSONValue.parse((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
String uriVariable = (String) jsonObject.get(urlVaribleId);
|
||||
urlVariableList.add(uriVariable);
|
||||
jsonObject.remove(urlVaribleId);
|
||||
}
|
||||
} else if (MessageType.XML.equals(messageType)) {
|
||||
Document doc;
|
||||
if (sendData instanceof Document) {
|
||||
doc = (Document) sendData;
|
||||
} else {
|
||||
doc = convertXmlDocument((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
Element element = (Element) doc.selectSingleNode("//" + urlVaribleId);
|
||||
urlVariableList.add(element.getText());
|
||||
if (doc.getRootElement() == element) {
|
||||
doc = null;
|
||||
} else {
|
||||
element.getParent().remove(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (urlVariableList.size() > 0) {
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
||||
Object[] urls = urlVariableList.toArray();
|
||||
url = uriComponents.expand(urls).toUriString();
|
||||
logger.debug("HttpClientAdapterServiceRest] after extand url=[" + url + "] ");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to change url", e);
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
private String getUrl(String baseUrl, String extraPath) {
|
||||
if (StringUtils.isBlank(extraPath)) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
||||
return extraPath;
|
||||
}
|
||||
|
||||
String targetUrl = baseUrl;
|
||||
if (!targetUrl.endsWith("/")) {
|
||||
targetUrl += "/";
|
||||
}
|
||||
if (extraPath.startsWith("/")) {
|
||||
targetUrl += extraPath.substring(1);
|
||||
} else {
|
||||
targetUrl += extraPath;
|
||||
}
|
||||
|
||||
logger.debug("HttpClientAdapterServiceRest] after concatenate url=[" + targetUrl + "] ");
|
||||
return targetUrl;
|
||||
}
|
||||
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
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
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
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.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";
|
||||
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
}
|
||||
-680
@@ -1,680 +0,0 @@
|
||||
package com.eactive.eai.custom.adapter.http.client.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.BitSet;
|
||||
import java.util.Formatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
||||
import com.eactive.eai.adapter.http.client.impl.HttpClientAdapterServiceRest;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.impl.HttpAdapterServiceBypass;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
|
||||
public class HttpClient5AdapterServiceBypass extends HttpClient5AdapterServiceSupport
|
||||
implements HttpClientAdapterServiceKey {
|
||||
public static final String TYPE_BYPASS_REQUEST = "bypassRequest";
|
||||
public static final String REST_OPTION = "REST_OPTION";
|
||||
|
||||
protected boolean doSendUrlFragment = true;
|
||||
protected boolean doHandleCompression = false;
|
||||
protected boolean doForwardIP = false;
|
||||
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
||||
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
||||
|
||||
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
||||
|
||||
// ex) $.dataHeader.GW_RSLT_CD
|
||||
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
||||
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
||||
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
||||
* - type : simpleRequest, variableUrlRequest
|
||||
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
||||
* - method : get, delete, post, put
|
||||
* - contentType : application/json, application/x-www-form-urlencoded
|
||||
* - adapterTokenUseYn: Y, N(default)
|
||||
* ex)
|
||||
* {"type":"variableUrlRequest","extraPath":"/aaa/{userId}","uriVariables":["userId"]}
|
||||
* @formatter:on
|
||||
*/
|
||||
String restOptionData = tempProp.getProperty(REST_OPTION, "{}");
|
||||
|
||||
JSONObject restOptionObject = parseJson(restOptionData);
|
||||
|
||||
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
||||
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
||||
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
||||
}
|
||||
|
||||
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
||||
String inboundRewritePath = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_REWRITE_PATH, "");
|
||||
String inboundQueryString = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_QUERY_STRING, "");
|
||||
Properties inboundHeaders = (Properties) tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
||||
Map<String, String> inboundPathVariables = (Map<String, String>) tempProp
|
||||
.get(HttpAdapterServiceKey.INBOUND_PATH_VARIABLES);
|
||||
|
||||
String restMethod = (String) restOptionObject.get("method");
|
||||
if (StringUtils.isBlank(restMethod)) {
|
||||
restMethod = inboundMethod;
|
||||
}
|
||||
|
||||
String url = getRewriteUrl(vo, inboundRewritePath, inboundQueryString, restOptionObject, inboundPathVariables);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] url = [" + url + "]");
|
||||
}
|
||||
|
||||
HttpClient mclient = this.client;
|
||||
HttpUriRequestBase method = generateMethod(restMethod, url);
|
||||
|
||||
assignRequestHeaders(method, inboundHeaders, tempProp);
|
||||
|
||||
if (hasBody(data, method)) {
|
||||
byte[] bodyBytes;
|
||||
if (data instanceof byte[]) {
|
||||
bodyBytes = (byte[]) data;
|
||||
} else if (data instanceof String) {
|
||||
bodyBytes = ((String) data).getBytes(vo.getEncode());
|
||||
} else {
|
||||
bodyBytes = new byte[0];
|
||||
}
|
||||
method.setEntity(new ByteArrayEntity(bodyBytes, null));
|
||||
}
|
||||
|
||||
String contentType = (String) restOptionObject.get("contentType");
|
||||
if (StringUtils.isBlank(contentType) && inboundHeaders != null) {
|
||||
contentType = getIgnoreCaseProp(inboundHeaders, HttpHeaders.CONTENT_TYPE);
|
||||
contentType = StringUtils.substringBefore(contentType, ";");
|
||||
}
|
||||
|
||||
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
|
||||
configureHttpClient(requestConfigBuilder, vo, method);
|
||||
|
||||
OAuth2AccessTokenVO accessToken = null;
|
||||
if (useAdapterToken) {
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
||||
|
||||
// 토큰이 없거나 만료 됐으면 재발급
|
||||
if (accessToken == null || accessToken.isExpired()) {
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
||||
oldToken);
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
||||
+ accessToken + "]");
|
||||
}
|
||||
|
||||
setAuthHeaders(method, accessToken);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RequestHeader [Authorization=" + method.getFirstHeader("Authorization") + "]");
|
||||
}
|
||||
}
|
||||
|
||||
// 로깅 인터셉터에 전달할 컨텍스트 정보 설정
|
||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
HttpContext context = new BasicHttpContext();
|
||||
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
||||
Integer logProcessNo = (Integer) tempProp.get(HttpClientAdapterServiceKey.LOG_PROCESS_NO);
|
||||
if (logProcessNo != null && logProcessNo > 0) {
|
||||
context.setAttribute(HttpClientAdapterServiceKey.LOG_PROCESS_NO, logProcessNo);
|
||||
}
|
||||
|
||||
int status = -1;
|
||||
|
||||
try {
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
byte[] responseMessage = null;
|
||||
Header[] responseHeaders = null;
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"SEND [Bypass Request..]" + CommonLib.getDumpMessage(data));
|
||||
}
|
||||
try {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[method getName]" + method.getMethod());
|
||||
logger.debug("[method getRequestHeaders]" + java.util.Arrays.toString(method.getHeaders()));
|
||||
logger.debug("[method getURI]" + method.getPath());
|
||||
}
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = response.getCode();
|
||||
responseHeaders = response.getHeaders();
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
}
|
||||
}
|
||||
} catch (ConnectException e) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
||||
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
||||
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
||||
*
|
||||
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
||||
* __ex) $.dataHeader.resultCode
|
||||
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
||||
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
||||
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
||||
* @formatter:on
|
||||
*/
|
||||
boolean needReissue = false;
|
||||
|
||||
if (status == 200) {
|
||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
} else if (status >= 400 && status < 500) {
|
||||
if (useAdapterToken) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
|
||||
if (!needReissue) {
|
||||
// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
|
||||
if (responseMessage == null || responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
} else if (status != 200) {
|
||||
responseMessage = responseMessage != null ? responseMessage : new byte[0];
|
||||
// body 값이 없을때만 exception 처리하고, body가 있으면 bypass 한다.
|
||||
if (responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
if (useAdapterToken) {
|
||||
if (responseMessage == null) {
|
||||
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
||||
}
|
||||
|
||||
// OAuth 토큰 재요청 코드 확인
|
||||
if (needReissue) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] retry access token response code = ["
|
||||
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
}
|
||||
|
||||
// 토큰 재발급
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
OAuth2AccessTokenVO newAccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||
method.setHeader("Authorization", newAccessToken.getAuthorization());
|
||||
setAuthHeaders(method, newAccessToken);
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RETRY TOKEN = [" + newAccessToken + "]");
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse retryResponse = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = retryResponse.getCode();
|
||||
responseHeaders = retryResponse.getHeaders();
|
||||
responseMessage = EntityUtils.toByteArray(retryResponse.getEntity());
|
||||
} catch (IOException e) {
|
||||
throw new Exception("retry excuteMethod Exception = " + e.getMessage());
|
||||
}
|
||||
|
||||
if (status != 200) {
|
||||
responseMessage = responseMessage != null ? responseMessage : new byte[0];
|
||||
if (responseMessage.length == 0) {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), url, restMethod,
|
||||
responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RETRY responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClient5AdapterServiceBypass] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"RECV [Bypass Request..]" + CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
// 응답 Content-Type charset 기반 인코딩 결정, 없으면 어댑터 encoding 사용
|
||||
String responseEncode = vo.getEncode();
|
||||
if (responseHeaders != null) {
|
||||
for (Header header : responseHeaders) {
|
||||
if (StringUtils.equalsIgnoreCase(header.getName(), HttpHeaders.CONTENT_TYPE)) {
|
||||
try {
|
||||
MediaType mediaType = MediaType.parseMediaType(header.getValue());
|
||||
if (mediaType.getCharset() != null) {
|
||||
responseEncode = mediaType.getCharset().name();
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assignRelayDataToInbound(tempProp, responseHeaders, status);
|
||||
return responseMessage != null ? new String(responseMessage, responseEncode) : "";
|
||||
} catch (SocketTimeoutException ste) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClient5AdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(),
|
||||
ste);
|
||||
}
|
||||
logger.error("HttpClient5AdapterServiceBypass] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(), ste);
|
||||
throw ste;
|
||||
} catch (ConnectException ce) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClient5AdapterServiceBypass] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(),
|
||||
ce);
|
||||
}
|
||||
logger.error("HttpClient5AdapterServiceBypass] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(), ce);
|
||||
throw ce;
|
||||
} catch (Exception e) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
||||
}
|
||||
logger.error(
|
||||
"HttpClient5AdapterServiceBypass] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
||||
e);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status != HttpStatus.SC_OK) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = String.valueOf(status);
|
||||
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasBody(Object data, HttpUriRequestBase method) {
|
||||
if (data == null) {
|
||||
return false;
|
||||
}
|
||||
// GET, DELETE는 표준 HTTP에서 body를 지원하지 않음
|
||||
return method instanceof HttpPost || method instanceof HttpPut;
|
||||
}
|
||||
|
||||
private HttpUriRequestBase generateMethod(String restMethod, String url) {
|
||||
switch (HttpMethodType.getValue(restMethod)) {
|
||||
case GET:
|
||||
return new HttpGet(url);
|
||||
case DELETE:
|
||||
return new HttpDelete(url);
|
||||
case POST:
|
||||
return new HttpPost(url);
|
||||
case PUT:
|
||||
return new HttpPut(url);
|
||||
default:
|
||||
return new HttpPost(url);
|
||||
}
|
||||
}
|
||||
|
||||
private String getRewriteUrl(HttpClientAdapterVO vo, String inboundRewritePath, String queryString,
|
||||
JSONObject restOptionObject, Map<String, String> inboundPathVariables) {
|
||||
String fragment = null;
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
int fragIdx = queryString.indexOf('#');
|
||||
if (fragIdx >= 0) {
|
||||
fragment = queryString.substring(fragIdx + 1);
|
||||
queryString = queryString.substring(0, fragIdx);
|
||||
}
|
||||
}
|
||||
|
||||
String restExtraPath = (String) restOptionObject.get("extraPath");
|
||||
if (StringUtils.isBlank(restExtraPath)) {
|
||||
StringBuilder uri = new StringBuilder(500);
|
||||
String baseUrl = StringUtils.removeEnd(vo.getUrl(), "/");
|
||||
String rewritePath = inboundRewritePath != null && !inboundRewritePath.startsWith("/")
|
||||
? "/" + inboundRewritePath : inboundRewritePath;
|
||||
uri.append(baseUrl).append(StringUtils.defaultString(rewritePath));
|
||||
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
uri.append('?');
|
||||
uri.append(encodeUriQuery(queryString, false));
|
||||
}
|
||||
|
||||
if (doSendUrlFragment && fragment != null) {
|
||||
uri.append('#');
|
||||
uri.append(encodeUriQuery(fragment, false));
|
||||
}
|
||||
|
||||
return uri.toString();
|
||||
} else {
|
||||
String type = (String) restOptionObject.get("type");
|
||||
String url = getUrl(vo.getUrl(), restExtraPath);
|
||||
|
||||
if (StringUtils.equalsIgnoreCase(type, HttpClientAdapterServiceRest.TYPE_VARIABLE_URL_REQUEST)) {
|
||||
inboundPathVariables = mergeInboundPathVariables(inboundPathVariables, queryString);
|
||||
List<String> urlVariableValueList = new ArrayList<>();
|
||||
JSONArray uriVariables = (JSONArray) restOptionObject.get("uriVariables");
|
||||
if (uriVariables != null && !uriVariables.isEmpty() && inboundPathVariables != null
|
||||
&& !inboundPathVariables.isEmpty()) {
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
String uriVariableValue = inboundPathVariables.get(urlVaribleId);
|
||||
urlVariableValueList.add(uriVariableValue);
|
||||
}
|
||||
|
||||
if (!urlVariableValueList.isEmpty()) {
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
||||
Object[] urls = urlVariableValueList.toArray();
|
||||
url = uriComponents.expand(urls).toUriString();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (StringUtils.isNotBlank(queryString)) {
|
||||
url += "?" + encodeUriQuery(queryString, false);
|
||||
}
|
||||
|
||||
if (doSendUrlFragment && fragment != null) {
|
||||
url += "#" + encodeUriQuery(fragment, false);
|
||||
}
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> mergeInboundPathVariables(Map<String, String> inboundPathVariables,
|
||||
String queryString) {
|
||||
if (StringUtils.isBlank(queryString)) {
|
||||
return inboundPathVariables;
|
||||
}
|
||||
|
||||
if (inboundPathVariables == null) {
|
||||
inboundPathVariables = new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
String[] pairs = queryString.split("&");
|
||||
for (String pair : pairs) {
|
||||
int idx = pair.indexOf("=");
|
||||
inboundPathVariables.put(pair.substring(0, idx), pair.substring(idx + 1));
|
||||
}
|
||||
|
||||
return inboundPathVariables;
|
||||
}
|
||||
|
||||
private String getUrl(String baseUrl, String extraPath) {
|
||||
if (StringUtils.isBlank(extraPath)) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
||||
return extraPath;
|
||||
}
|
||||
|
||||
String targetUrl = baseUrl;
|
||||
if (!targetUrl.endsWith("/")) {
|
||||
targetUrl += "/";
|
||||
}
|
||||
if (extraPath.startsWith("/")) {
|
||||
targetUrl += extraPath.substring(1);
|
||||
} else {
|
||||
targetUrl += extraPath;
|
||||
}
|
||||
|
||||
return targetUrl;
|
||||
}
|
||||
|
||||
protected CharSequence encodeUriQuery(CharSequence in, boolean encodePercent) {
|
||||
StringBuilder outBuf = null;
|
||||
Formatter formatter = null;
|
||||
for (int i = 0; i < in.length(); i++) {
|
||||
char c = in.charAt(i);
|
||||
boolean escape = true;
|
||||
if (c < 128) {
|
||||
if (asciiQueryChars.get(c) && !(encodePercent && c == '%')) {
|
||||
escape = false;
|
||||
}
|
||||
} else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {
|
||||
escape = false;
|
||||
}
|
||||
if (!escape) {
|
||||
if (outBuf != null)
|
||||
outBuf.append(c);
|
||||
} else {
|
||||
if (outBuf == null) {
|
||||
outBuf = new StringBuilder(in.length() + 5 * 3);
|
||||
outBuf.append(in, 0, i);
|
||||
formatter = new Formatter(outBuf);
|
||||
}
|
||||
formatter.format("%%%02X", (int) c);
|
||||
}
|
||||
}
|
||||
return outBuf != null ? outBuf : in;
|
||||
}
|
||||
|
||||
protected static final BitSet asciiQueryChars;
|
||||
static {
|
||||
char[] c_unreserved = "_-!.~'()*".toCharArray();
|
||||
char[] c_punct = ",;:$&+=".toCharArray();
|
||||
char[] c_reserved = "/@".toCharArray();
|
||||
asciiQueryChars = new BitSet(128);
|
||||
for (char c = 'a'; c <= 'z'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c = 'A'; c <= 'Z'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c = '0'; c <= '9'; c++)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_unreserved)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_punct)
|
||||
asciiQueryChars.set(c);
|
||||
for (char c : c_reserved)
|
||||
asciiQueryChars.set(c);
|
||||
asciiQueryChars.set('%');
|
||||
}
|
||||
|
||||
private void assignRelayDataToInbound(Properties prop, Header[] responseHeaders, int status) {
|
||||
Properties headerProp = new Properties();
|
||||
if (responseHeaders != null) {
|
||||
for (Header header : responseHeaders) {
|
||||
String name = header.getName();
|
||||
String value = header.getValue();
|
||||
String existing = headerProp.getProperty(name);
|
||||
if (existing != null) {
|
||||
// 동일 이름의 헤더가 여러 개인 경우 콤마로 합침 (RFC 7230)
|
||||
headerProp.put(name, existing + ", " + value);
|
||||
} else {
|
||||
headerProp.put(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
headerProp.put(HttpAdapterServiceBypass.HTTP_STATUS, String.valueOf(status));
|
||||
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, headerProp);
|
||||
|
||||
prop.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
}
|
||||
|
||||
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||
String encode) {
|
||||
if (responseMessage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
||||
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
||||
if (StringUtils.isBlank(responseCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
||||
return ArrayUtils.contains(arr, responseCode);
|
||||
} catch (Exception e) {
|
||||
logger.error("HttpClient5AdapterServiceBypass] checkTokenRetry error=" + e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void assignRequestHeaders(HttpUriRequestBase method, Properties headerProp, Properties inProp) {
|
||||
if (headerProp == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (Entry<Object, Object> e : headerProp.entrySet()) {
|
||||
String key = (String) e.getKey();
|
||||
String value = (String) e.getValue();
|
||||
|
||||
if (StringUtils.equalsAnyIgnoreCase(key, HttpAdapterServiceBypass.HOP_BY_HOP_HEADERS)
|
||||
|| StringUtils.equalsIgnoreCase(key, HttpHeaders.CONTENT_LENGTH)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (doHandleCompression && StringUtils.equalsIgnoreCase(key, HttpHeaders.ACCEPT_ENCODING)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
method.addHeader(key, value);
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request Header :" + key + "=[" + value + "]");
|
||||
}
|
||||
}
|
||||
|
||||
if (doForwardIP) {
|
||||
String forHeaderName = "X-Forwarded-For";
|
||||
String forHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_REMOTE_ADDR);
|
||||
if (StringUtils.isNotBlank(forHeader)) {
|
||||
String existingForHeader = headerProp.getProperty(forHeaderName);
|
||||
if (existingForHeader != null) {
|
||||
forHeader = existingForHeader + ", " + forHeader;
|
||||
}
|
||||
method.addHeader(forHeaderName, forHeader);
|
||||
}
|
||||
|
||||
String protoHeaderName = "X-Forwarded-Proto";
|
||||
String protoHeader = inProp.getProperty(HttpAdapterServiceKey.INBOUND_SCHEME);
|
||||
if (StringUtils.isNotBlank(protoHeader)) {
|
||||
method.addHeader(protoHeaderName, protoHeader);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private JSONObject parseJson(String message) throws Exception {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (JSONObject) JSONValue.parse(message);
|
||||
}
|
||||
|
||||
public static final String getIgnoreCaseProp(Properties prop, String key) {
|
||||
if (prop == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (Entry<Object, Object> e : prop.entrySet()) {
|
||||
if (StringUtils.equalsIgnoreCase(key, (String) e.getKey())) {
|
||||
return (String) e.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
-888
@@ -1,888 +0,0 @@
|
||||
package com.eactive.eai.custom.adapter.http.client.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.NameValuePair;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.message.BasicNameValuePair;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.net.URIBuilder;
|
||||
import org.dom4j.Document;
|
||||
import org.dom4j.Element;
|
||||
import org.dom4j.io.SAXReader;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.authoutbound.AccessTokenManagerByDB;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
|
||||
public class HttpClient5AdapterServiceKbank extends HttpClient5AdapterServiceSupport
|
||||
implements HttpClientAdapterServiceKey {
|
||||
|
||||
public static final String TYPE_VARIABLE_URL_REQUEST = "variableUrlRequest";
|
||||
public static final String TYPE_SIMPLE_REQUEST = "simpleRequest";
|
||||
public static final String REST_OPTION = "REST_OPTION";
|
||||
//public static final String HEADER_CONTENT_TYPE = "Content-Type";
|
||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||
public static final String HTTP_STATUS = "HTTP_STATUS";
|
||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||
public static final String AUTH_TOKEN = "AUTH_TOKEN";
|
||||
|
||||
/**
|
||||
* 1. 기능 : REST API 통신에 사용 <br>
|
||||
* 2. 처리 개요 : - 속성 정보를 설정 하고 수동 시스템 서비스를 호출 한다. <br>
|
||||
* 3. 주의사항 <br>
|
||||
*
|
||||
* @param prop Http Adapter 속성 정보
|
||||
* @return 반환 된 Object
|
||||
* @exception Exception 수동 시스템 간 통신 중 발생
|
||||
**/
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
||||
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
String bizCode = "";
|
||||
String authToken = "";
|
||||
try {
|
||||
Properties authProp = PropManager.getInstance().getProperties(AUTH_TOKEN); //Authorization
|
||||
bizCode = vo.getAdapterGroupName().substring(1, 4);
|
||||
authToken = authProp.getProperty(bizCode, "");
|
||||
} catch (Exception e) {
|
||||
logger.debug("Property Group AUTH_TOKEN is not Exist !!");
|
||||
}
|
||||
|
||||
logger.debug("authToken :::::::::::::::::::::::::::::::::::" + authToken);
|
||||
|
||||
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
||||
String relayResponseHeaderKeys = prop.getProperty(HEADER_KEYS, "");
|
||||
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
||||
|
||||
boolean useForwardProxy = StringUtils.equalsIgnoreCase(prop.getProperty("FORWARD_PROXY_USE_YN", "N"), "Y");
|
||||
String forwardProxyUrl = prop.getProperty("FORWARD_PROXY_URL");
|
||||
|
||||
// ex) $.dataHeader.GW_RSLT_CD
|
||||
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
||||
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
||||
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
||||
|
||||
// 레이아웃 메시지 타입 REST URL 추출 시 활용. Default JSON
|
||||
String messageType = prop.getProperty("MESSAGE_TYPE", MessageType.JSON);
|
||||
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
||||
* - type : simpleRequest, variableUrlRequest
|
||||
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
||||
* - method : get, delete, post, put
|
||||
* - contentType: application/json(default), application/x-www-form-urlencoded
|
||||
* - adapterTokenUseYn: Y, N(default)
|
||||
* ex)
|
||||
* {"type":"simpleRequest","extraPath":"v2.0/accout/balance","method":"post"}
|
||||
* @formatter:on
|
||||
*/
|
||||
|
||||
String restOptionData = tempProp.getProperty(REST_OPTION);
|
||||
|
||||
JSONObject restOptionObject = parseJson(restOptionData);
|
||||
if (restOptionObject == null) {
|
||||
throw new Exception("OptionData parsing result is NULL");
|
||||
}
|
||||
|
||||
String rmethod = (String) restOptionObject.getOrDefault("method", inboundMethod);
|
||||
String contentType = (String) restOptionObject.getOrDefault("contentType", "application/json");
|
||||
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
||||
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
||||
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
||||
}
|
||||
|
||||
HttpClient mclient = this.client;
|
||||
String sendData = "";
|
||||
if (data instanceof String) {
|
||||
sendData = (String) data;
|
||||
} else if (data instanceof byte[]) {
|
||||
sendData = new String((byte[]) data, vo.getEncode());
|
||||
}
|
||||
|
||||
////mclient.getParams().setContentCharset(vo.getEncode());
|
||||
|
||||
JSONObject dataObject = null;
|
||||
|
||||
Object httpHeader = null;
|
||||
Object dataContent = null;
|
||||
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
|
||||
Object parsed = parseJsonGeneric(sendData);
|
||||
|
||||
if(parsed instanceof JSONObject) {
|
||||
dataObject = parseJson(sendData);
|
||||
if (dataObject != null && StringUtils.isNotBlank(headerGroupName)) {
|
||||
httpHeader = dataObject.get(headerGroupName);
|
||||
dataObject.remove(headerGroupName);
|
||||
}
|
||||
|
||||
dataContent = dataObject;
|
||||
if (dataObject.containsKey("innerList")) {
|
||||
JSONArray innerList = (JSONArray) dataObject.get("innerList");
|
||||
dataContent = innerList;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("HttpClientAdapterServiceRest] dataObject1 = [" + dataObject + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] dataContent = [" + dataContent + "]");
|
||||
|
||||
// interface 에 설정된게 우선한다.
|
||||
String uri = null;
|
||||
if (dataObject == null) {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, sendData);
|
||||
} else {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, dataObject);
|
||||
}
|
||||
|
||||
// ////if (vo.getConnectionTimeout() != 0) {
|
||||
// mclient.getHttpConnectionManager().getParams().setConnectionTimeout(vo.getConnectionTimeout());
|
||||
// }
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL=[" + vo.getUrl() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") PARAMETER_NAME=[" + vo.getParameterName() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") ENCODE=[" + vo.getEncode() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") RESPONSE_TYPE=[" + vo.getResponseType() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL_ENCODE_YN=[" + vo.getUrlEncodeYn() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") CONNECTION_TIMEOUT=[" + vo.getConnectionTimeout() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") REST_OPTION=[" + restOptionData + "] ");
|
||||
}
|
||||
|
||||
HttpUriRequestBase method = null;
|
||||
|
||||
// 메소드 타입에 따라 HttpRequestBase 인스턴스 생성
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
case DELETE:
|
||||
method = new HttpDelete(uri);
|
||||
break;
|
||||
case POST:
|
||||
method = new HttpPost(uri);
|
||||
break;
|
||||
case PUT:
|
||||
method = new HttpPut(uri);
|
||||
break;
|
||||
default:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
configureHttpClient(requestConfigBuilder, vo, method);
|
||||
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
case DELETE:
|
||||
HashMap<String, String> h = getParameters(dataObject);
|
||||
URIBuilder uriBuilder = new URIBuilder(uri);
|
||||
for (Map.Entry<String, String> entry : h.entrySet()) {
|
||||
uriBuilder.addParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
URI fullUri = uriBuilder.build();
|
||||
if (method instanceof HttpGet) {
|
||||
((HttpGet) method).setUri(fullUri);
|
||||
} else if (method instanceof HttpDelete) {
|
||||
((HttpDelete) method).setUri(fullUri);
|
||||
}
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] (get Method) QueryString = [" + fullUri.getQuery() + "]");
|
||||
}
|
||||
break;
|
||||
case PUT:
|
||||
case POST:
|
||||
//assignPostBody(dataObject, contentType, vo.getEncode(), method);
|
||||
assignPostBody(dataContent, contentType, vo.getEncode(), method);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") method.getParams()=["
|
||||
+ method.getEntity() + "] ");
|
||||
}
|
||||
|
||||
OAuth2AccessTokenVO accessToken = null;
|
||||
if (useAdapterToken) {
|
||||
AccessTokenManagerByDB tokenManager = AccessTokenManagerByDB.getInstance();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
||||
|
||||
// 토큰이 없거나 만료 됐으면 재발급
|
||||
if (accessToken == null || accessToken.isExpired()) {
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
||||
oldToken);
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
||||
+ accessToken + "]");
|
||||
}
|
||||
|
||||
setAuthHeaders(method, accessToken);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RequestHeader [Authorization=" + method.getHeader("Authorization") + "]");
|
||||
}
|
||||
}
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
if(!StringUtils.isBlank(authToken)) {
|
||||
setAuthHeaders(method, authToken);
|
||||
}
|
||||
|
||||
// 전달 header 셋팅
|
||||
// Adapter 레벨 header 보다 data로 넘어온 httpHeader를 우선 적용(header명이 같다면 덮어씀)
|
||||
assignRequestHeaders(method, httpHeader);
|
||||
|
||||
int status = -1;
|
||||
|
||||
try {
|
||||
byte[] responseMessage = null;
|
||||
Header[] responseHeaders;
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
if (dataContent != null) { //dataObject
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = ["
|
||||
+ dataContent.toString() + "]"); //dataObject.toJSONString()
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(dataContent.toString())); //dataObject.toJSONString()
|
||||
} else {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = [" + sendData
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
}
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"SEND [" + sendData + "]" + CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
|
||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
HttpContext context = new BasicHttpContext();
|
||||
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
||||
Integer logProcessNo = (Integer) tempProp.get(HttpClientAdapterServiceKey.LOG_PROCESS_NO);
|
||||
if (logProcessNo != null && logProcessNo > 0) {
|
||||
context.setAttribute(HttpClientAdapterServiceKey.LOG_PROCESS_NO, logProcessNo);
|
||||
}
|
||||
|
||||
try {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[method getName]" + method.getMethod());
|
||||
logger.debug("[method getEntity]" + method.getEntity());
|
||||
logger.debug("[method getRequestHeaders]" + method.getHeaders().toString());
|
||||
logger.debug("[method getURI]" + method.getPath());
|
||||
}
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = response.getCode();
|
||||
|
||||
if (status >= 200 && status <= 207) {
|
||||
status = 200;
|
||||
}
|
||||
|
||||
// if (status == 404) {
|
||||
// status = 200;
|
||||
// }
|
||||
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
responseHeaders = response.getHeaders();
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + responseMessage + "]");
|
||||
}
|
||||
}
|
||||
} catch (ConnectException e) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
}
|
||||
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
||||
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
||||
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
||||
*
|
||||
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
||||
* __ex) $.dataHeader.resultCode
|
||||
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
||||
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
||||
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
||||
* @formatter:on
|
||||
*/
|
||||
boolean needReissue = false;
|
||||
|
||||
Properties responseHeaderProp = assignRelayDataToInbound(tempProp, responseHeaders);
|
||||
String responseString = new String(responseMessage, vo.getEncode());
|
||||
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
tempProp.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, responseHeaderProp);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_MESSAGE, responseString);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_STATUS, status);
|
||||
|
||||
if (status >= 200 && status <= 207) {
|
||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
} else if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseString);
|
||||
// logger.error(errMsg);
|
||||
|
||||
if (status >= 400 && status < 500) {
|
||||
if (useAdapterToken) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
|
||||
// if (!needReissue) {
|
||||
// throw new Exception(errMsg);
|
||||
// }
|
||||
} else {
|
||||
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV " + vo.getEncode() + "(" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV MS949 (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "MS949") + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV euc-kr (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "euc-kr") + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = " + CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
if (useAdapterToken) {
|
||||
if (responseMessage == null) {
|
||||
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
||||
}
|
||||
|
||||
// OAuth 토큰 재요청 코드 확인
|
||||
if (needReissue) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] retry access token response code = ["
|
||||
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
}
|
||||
|
||||
// 토큰 재발급
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
OAuth2AccessTokenVO newaccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||
method.setHeader("Authorization", newaccessToken.getAuthorization());
|
||||
|
||||
setAuthHeaders(method, newaccessToken);
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RETRY TOKEN = [" + newaccessToken + "]");
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method)) {
|
||||
status = response.getCode();
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
||||
}
|
||||
}catch (IOException e){
|
||||
throw new Exception("retry excuteMethod Exceptioin = " + e.getMessage());
|
||||
}
|
||||
|
||||
|
||||
if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV " + vo.getEncode() + "("
|
||||
+ vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
// ----------------------------------------------------------
|
||||
}
|
||||
}
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"RECV [" + new String(responseMessage, vo.getEncode()) + "]"
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
|
||||
return assignResponseHeaders(method, responseMessage, headerGroupName, vo.getEncode(), messageType,
|
||||
relayResponseHeaderKeys, status, responseHeaderProp);
|
||||
} catch (SocketTimeoutException ste) { // Read Timeout :: HttpClient 3.1일 경우
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(),
|
||||
ste);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(), ste);
|
||||
throw ste;
|
||||
} catch (ConnectException ce) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(),
|
||||
ce);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(), ce);
|
||||
throw ce;
|
||||
} catch (Exception e) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
||||
e);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status != HttpStatus.SC_OK) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = String.valueOf(status);
|
||||
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Properties assignRelayDataToInbound(Properties prop, Header[] responseHeaders) {
|
||||
Properties headerProp = new Properties();
|
||||
if (responseHeaders == null || responseHeaders.length == 0) {
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
for (Header header : responseHeaders) {
|
||||
headerProp.put(header.getName(), header.getValue());
|
||||
}
|
||||
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 1단계 레이아웃에만 적용되도록 구현됨.
|
||||
*
|
||||
* @param method
|
||||
* @param responseMessage
|
||||
* @param headerGroupName
|
||||
* @param encode
|
||||
* @param messageType
|
||||
* @param relayHeaderKeys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private String assignResponseHeaders(HttpUriRequestBase method, byte[] responseMessage, String headerGroupName,
|
||||
String encode, String messageType, String relayHeaderKeys, int status, Properties responseHeaderProp) throws Exception {
|
||||
if (!MessageType.JSON.equals(messageType) || StringUtils.isBlank(headerGroupName)
|
||||
|| StringUtils.isBlank(relayHeaderKeys)) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils.tokenizeToStringArray(relayHeaderKeys, ",");
|
||||
JSONObject headerJson = new JSONObject();
|
||||
for (String key : relayKeyArr) {
|
||||
String value = responseHeaderProp.getProperty(key);
|
||||
if (StringUtils.isNotBlank(value)) {
|
||||
headerJson.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
headerJson.put(HTTP_STATUS, String.valueOf(status));
|
||||
|
||||
if (headerJson.size() <= 0) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
JSONObject message = null;
|
||||
if (responseMessage == null || responseMessage.length == 0) {
|
||||
message = new JSONObject();
|
||||
} else {
|
||||
message = parseJson(new String(responseMessage, encode));
|
||||
if (message == null) {
|
||||
message = new JSONObject();
|
||||
message.put("Malformed_Response_Message", new String(responseMessage, encode));
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(headerGroupName) && message != null)
|
||||
message.put(headerGroupName, headerJson);
|
||||
|
||||
logger.info("------------- message --------------- : {} ", message);
|
||||
|
||||
return message.toJSONString();
|
||||
}
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
private void setAuthHeaders(HttpUriRequestBase method, String authorization) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s", authorization));
|
||||
}
|
||||
|
||||
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||
String encode) {
|
||||
if (responseMessage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
||||
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
||||
if (StringUtils.isBlank(responseCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
||||
return ArrayUtils.contains(arr, responseCode);
|
||||
} catch (Exception e) {
|
||||
logger.error("HttpClientAdapterServiceRest] checkTokenRetry error=" + e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void assignRequestHeaders(HttpUriRequestBase method, Object httpHeader) {
|
||||
if (httpHeader == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (httpHeader instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) httpHeader;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
method.setHeader((String) key, (String) obj);
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request Header :" + (String) key + "=[" + (String) obj + "]");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private void assignPostBody(Object eaiBody, String contentType, String charset, HttpUriRequestBase method) {
|
||||
if (eaiBody == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(contentType, "application/x-www-form-urlencoded")) {
|
||||
if (eaiBody instanceof JSONObject) {
|
||||
List<NameValuePair> params = new ArrayList<>();
|
||||
JSONObject jsonObject = (JSONObject) eaiBody;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
params.add(new BasicNameValuePair((String) key, (String) jsonObject.get(key)));
|
||||
}
|
||||
|
||||
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
|
||||
method.setEntity(entity);
|
||||
}
|
||||
|
||||
} else {
|
||||
ContentType contentTypeObj = ContentType.create(contentType, charset);
|
||||
|
||||
// 요청 본문을 StringEntity 객체로 생성
|
||||
StringEntity entity = new StringEntity(eaiBody.toString(), contentTypeObj);
|
||||
|
||||
// 요청에 본문 추가
|
||||
method.setEntity(entity);
|
||||
}
|
||||
}
|
||||
|
||||
private HashMap<String, String> getParameters(Object message) throws Exception {
|
||||
|
||||
HashMap<String, String> result = new HashMap<String, String>();
|
||||
|
||||
if (message != null) {
|
||||
if (message instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) message;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
result.put((String) key, getStringValue(obj));
|
||||
}
|
||||
} else {
|
||||
String[] messages = ((String) message).split("&");
|
||||
String[] data = null;
|
||||
|
||||
for (int i = 0; i < messages.length; i++) {
|
||||
data = messages[i].split("=", 2);
|
||||
if (data.length == 2) {
|
||||
result.put(data[0], data[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getStringValue(Object obj) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (obj instanceof String) {
|
||||
return (String) obj;
|
||||
} else if (obj instanceof Long) {
|
||||
return Long.toString((Long) obj);
|
||||
} else if (obj instanceof BigDecimal) {
|
||||
return ((BigDecimal) obj).toPlainString();
|
||||
} else {
|
||||
return (String) obj;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object parseJsonGeneric(String jsonData) {
|
||||
if (StringUtils.isBlank(jsonData)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
JSONParser parser = new JSONParser();
|
||||
Object parsedObj = parser.parse(jsonData);
|
||||
return parsedObj;
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private JSONObject parseJson(String message) throws Exception {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (JSONObject) JSONValue.parse(message);
|
||||
}
|
||||
|
||||
private Document convertXmlDocument(String message) throws Exception {
|
||||
SAXReader builder = new SAXReader();
|
||||
Document document = builder.read(new StringReader(message));
|
||||
return document;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private String changeUrl(String messageType, String url, String restOption, Object sendData) {
|
||||
if ((MessageType.JSON.equals(messageType) || MessageType.XML.equals(messageType))) {
|
||||
try {
|
||||
if (StringUtils.isBlank(restOption)) {
|
||||
return url;
|
||||
}
|
||||
List<String> urlVariableList = new ArrayList<String>();
|
||||
JSONObject restOptionObject = parseJson(restOption);
|
||||
|
||||
if (restOptionObject == null)
|
||||
throw new Exception("restOption is NULL");
|
||||
|
||||
String type = (String) restOptionObject.get("type");
|
||||
String requestExtraPath = (String) restOptionObject.get("extraPath");
|
||||
url = getUrl(url, requestExtraPath);
|
||||
if (TYPE_VARIABLE_URL_REQUEST.equals(type)) {
|
||||
Pattern p = Pattern.compile("\\{(.*?)\\}");
|
||||
Matcher m = p.matcher(requestExtraPath);
|
||||
List<String> uriVariables = new ArrayList<>();
|
||||
while(m.find()) {
|
||||
String fieldName = m.group(1);
|
||||
uriVariables.add(fieldName);
|
||||
}
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
JSONObject jsonObject;
|
||||
if (sendData instanceof JSONObject) {
|
||||
jsonObject = (JSONObject) sendData;
|
||||
} else {
|
||||
jsonObject = (JSONObject) JSONValue.parse((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
String uriVariable = (String) jsonObject.get(urlVaribleId);
|
||||
urlVariableList.add(uriVariable);
|
||||
jsonObject.remove(urlVaribleId);
|
||||
}
|
||||
} else if (MessageType.XML.equals(messageType)) {
|
||||
Document doc;
|
||||
if (sendData instanceof Document) {
|
||||
doc = (Document) sendData;
|
||||
} else {
|
||||
doc = convertXmlDocument((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
Element element = (Element) doc.selectSingleNode("//" + urlVaribleId);
|
||||
urlVariableList.add(element.getText());
|
||||
if (doc.getRootElement() == element) {
|
||||
doc = null;
|
||||
} else {
|
||||
element.getParent().remove(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (urlVariableList.size() > 0) {
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
||||
Object[] urls = urlVariableList.toArray();
|
||||
url = uriComponents.expand(urls).toUriString();
|
||||
logger.debug("HttpClientAdapterServiceRest] after extand url=[" + url + "] ");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to change url", e);
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
private String getUrl(String baseUrl, String extraPath) {
|
||||
if (StringUtils.isBlank(extraPath)) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
||||
return extraPath;
|
||||
}
|
||||
|
||||
String targetUrl = baseUrl;
|
||||
if (!targetUrl.endsWith("/")) {
|
||||
targetUrl += "/";
|
||||
}
|
||||
if (extraPath.startsWith("/")) {
|
||||
targetUrl += extraPath.substring(1);
|
||||
} else {
|
||||
targetUrl += extraPath;
|
||||
}
|
||||
|
||||
logger.debug("HttpClientAdapterServiceRest] after concatenate url=[" + targetUrl + "] ");
|
||||
return targetUrl;
|
||||
}
|
||||
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
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.util.JsonPathUtil;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
/**
|
||||
* 토스 암복호화에 맟추어 커스텀
|
||||
*/
|
||||
public class DouzoneEncFieldOutCryptoFilter extends EncFieldOutCryptoFilter {
|
||||
|
||||
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 = rootObjectNode.get(headerGroupName);
|
||||
rootObjectNode.remove(headerGroupName);
|
||||
|
||||
String xEmpNm = header.get("x-emp-nm").asText();
|
||||
tempProp.setProperty("x-emp-nm", xEmpNm);
|
||||
tempProp.setProperty(InCryptoFilter.PROP_AAD_HEADER, xEmpNm);
|
||||
String xChnlNm = header.get("x-chnl-nm").asText();
|
||||
tempProp.setProperty("x-chnl-nm", xChnlNm);
|
||||
|
||||
Object enc = filter.doPreFilter(adptGrpName, adptName, prop, rootObjectNode, setProp(tempProp));
|
||||
|
||||
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
|
||||
encJson.set(headerGroupName, header);
|
||||
|
||||
return encJson;
|
||||
}
|
||||
|
||||
@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));
|
||||
}
|
||||
|
||||
}
|
||||
+23
-5
@@ -2,8 +2,13 @@ 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.HttpClientAdapterFilter;
|
||||
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 기본 암복호화 필더
|
||||
*/
|
||||
@@ -11,16 +16,29 @@ public class EncFieldOutCryptoFilter implements HttpClientAdapterFilter {
|
||||
|
||||
private final OutCryptoFilter filter = new OutCryptoFilter();
|
||||
|
||||
protected Properties setProp(Properties p) {
|
||||
p.setProperty(OutCryptoFilter.PROP_DEC_FROM_PATH, "/encryptedData");
|
||||
p.setProperty(OutCryptoFilter.PROP_ENC_TO_PATH, "/encryptedData");
|
||||
return p;
|
||||
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 {
|
||||
return filter.doPreFilter(adptGrpName, adptName, prop, message, setProp(tempProp));
|
||||
String headerGroupName = prop.getProperty(HttpClient5AdapterServiceRest.HEADER_GROUP);
|
||||
|
||||
JsonNode root = JacksonUtil.readTree(message);
|
||||
ObjectNode rootObjectNode = (ObjectNode) root;
|
||||
JsonNode header = rootObjectNode.get(headerGroupName);
|
||||
rootObjectNode.remove(headerGroupName);
|
||||
|
||||
Object enc = filter.doPreFilter(adptGrpName, adptName, prop, rootObjectNode, setProp(tempProp));
|
||||
|
||||
ObjectNode encJson = (ObjectNode)JacksonUtil.readTree(enc);
|
||||
encJson.set(headerGroupName, header);
|
||||
|
||||
return encJson;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
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.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.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.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 = null;
|
||||
String jsonStr = null;
|
||||
if (message instanceof String) {
|
||||
jsonStr = (String) message;
|
||||
} else if (message instanceof JSONObject) {
|
||||
jsonStr = ((JSONObject) message).toJSONString();
|
||||
} else {
|
||||
return message;
|
||||
}
|
||||
rootNode = (ObjectNode) OBJECT_MAPPER.readTree(jsonStr);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
+27
-11
@@ -7,11 +7,14 @@ import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
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.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
||||
import com.eactive.eai.common.security.keyderiv.KeyDerivationStrategy;
|
||||
import com.eactive.eai.adapter.service.DJBApiAdapterService;
|
||||
import com.eactive.eai.common.util.JacksonUtil;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
/**
|
||||
* 더존 연동용 수신 암복호화 필터.
|
||||
@@ -30,8 +33,6 @@ import com.eactive.eai.common.security.keyderiv.KeyDerivationStrategy;
|
||||
*/
|
||||
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();
|
||||
|
||||
protected Properties setProp(Properties p) {
|
||||
@@ -42,11 +43,10 @@ public class DouzoneEncFieldInCryptoFilter implements HttpAdapterFilter {
|
||||
|
||||
private void setContext(Properties tempProp) {
|
||||
Properties inboundHeaders = (Properties) tempProp.get(HttpAdapterServiceKey.INBOUND_HEADER);
|
||||
String empNm = inboundHeaders.getProperty("x-emp-nm");
|
||||
tempProp.setProperty(InCryptoFilter.PROP_AAD_HEADER, empNm);
|
||||
|
||||
String chnlNm = inboundHeaders.getProperty("x-chnl-nm");
|
||||
tempProp.setProperty(KeyDerivationStrategy.PARAM_CONTEXT_KEY, chnlNm);
|
||||
tempProp.setProperty("x-chnl-nm", chnlNm);
|
||||
|
||||
tempProp.setProperty(InCryptoFilter.PROP_AAD_HEADER, "x-emp-nm");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -56,7 +56,7 @@ public class DouzoneEncFieldInCryptoFilter implements HttpAdapterFilter {
|
||||
setContext(prop);
|
||||
return filter.doPreFilter(adptGrpName, adptName, message, setProp(prop), request, response);
|
||||
} catch (Exception e) {
|
||||
throw new HttpStatusException(ERROR_DEC_FAIL, "복호화 오류", HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
||||
throw new FilterCryptoException("복호화 오류", InCryptoFilter.ERROR_DEC_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,9 +65,25 @@ public class DouzoneEncFieldInCryptoFilter implements HttpAdapterFilter {
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
try {
|
||||
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) {
|
||||
throw new HttpStatusException(ERROR_ENC_FAIL, "암호화 오류", HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
||||
throw new FilterCryptoException("암호화 오류", InCryptoFilter.ERROR_ENC_FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+28
-2
@@ -5,8 +5,15 @@ import java.util.Properties;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
|
||||
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.service.DJBApiAdapterService;
|
||||
import com.eactive.eai.common.util.JacksonUtil;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
/**
|
||||
* InCryptoFilter를 멤버변수로 관리하는 HttpAdapterFilter 구현체.
|
||||
@@ -27,7 +34,26 @@ public class EncFieldInCryptoFilter implements HttpAdapterFilter {
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return filter.doPostFilter(adptGrpName, adptName, resultMessage, setProp(prop), request, response);
|
||||
try {
|
||||
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) {
|
||||
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
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.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.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 = null;
|
||||
String jsonStr = null;
|
||||
if (message instanceof String) {
|
||||
jsonStr = (String) message;
|
||||
} else if (message instanceof ObjectNode) {
|
||||
rootNode = (ObjectNode) message;
|
||||
} else if (message instanceof JSONObject) {
|
||||
jsonStr = ((JSONObject) message).toJSONString();
|
||||
} else {
|
||||
return message;
|
||||
}
|
||||
if(rootNode == null)
|
||||
rootNode = (ObjectNode) OBJECT_MAPPER.readTree(jsonStr);
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
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.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.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.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 = null;
|
||||
String jsonStr = null;
|
||||
if (message instanceof String) {
|
||||
jsonStr = (String) message;
|
||||
} else if (message instanceof JSONObject) {
|
||||
jsonStr = ((JSONObject) message).toJSONString();
|
||||
} else {
|
||||
return message;
|
||||
}
|
||||
rootNode = (ObjectNode) OBJECT_MAPPER.readTree(jsonStr);
|
||||
|
||||
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
@@ -0,0 +1,80 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* 카카오뱅크 암복호화에 맟추어 커스텀 필요
|
||||
*/
|
||||
public class KakaopayFilter implements HttpAdapterFilter {
|
||||
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
|
||||
JsonNode rootNode = JacksonUtil.readTree(message, OBJECT_MAPPER);
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-14
@@ -2,14 +2,11 @@ package com.eactive.eai.custom.common.security.keyderiv;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
|
||||
import com.eactive.eai.common.hsm.HsmCryptoService;
|
||||
import com.eactive.eai.common.security.keyderiv.DerivedKey;
|
||||
import com.eactive.eai.common.security.keyderiv.KeyDerivationStrategy;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.common.security.keyderiv.strategy.BaseHsmKeyDerivationStrategy;
|
||||
|
||||
/**
|
||||
* HSM 마스터키 + 런타임 컨텍스트값을 연결(concatenate)한 뒤 SHA-256 해싱으로 키를 도출하는 전략.
|
||||
@@ -21,15 +18,18 @@ import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
* "contextKey" : "X-Api-Group-Seq" -- runtimeContext에서 꺼낼 키 이름
|
||||
* }
|
||||
*/
|
||||
public class HsmContextSha256KeyDerivationStrategy implements KeyDerivationStrategy {
|
||||
public class HsmContextSha256KeyDerivationStrategy extends BaseHsmKeyDerivationStrategy {
|
||||
|
||||
@Override
|
||||
public DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext) throws Exception {
|
||||
String hsmKeyAlias = required(params, PARAM_HSM_KEY_ALIAS);
|
||||
String contextKey = required(params, PARAM_CONTEXT_KEY);
|
||||
byte[] masterKeyBytes = super.getHsmKey(params);
|
||||
|
||||
return deriveKey(params, runtimeContext, masterKeyBytes);
|
||||
}
|
||||
|
||||
SecretKey masterKey = hsmCryptoService().getSecretKey(hsmKeyAlias);
|
||||
byte[] masterKeyBytes = masterKey.getEncoded();
|
||||
public DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext, byte[] masterKeyBytes)
|
||||
throws NoSuchAlgorithmException {
|
||||
String contextKey = required(params, PARAM_CONTEXT_KEY);
|
||||
byte[] contextBytes = runtimeContext.getOrDefault(contextKey, "")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
@@ -55,8 +55,4 @@ public class HsmContextSha256KeyDerivationStrategy implements KeyDerivationStrat
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private HsmCryptoService hsmCryptoService() {
|
||||
return ApplicationContextProvider.getContext().getBean(HsmCryptoService.class);
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -24,7 +24,11 @@ public class HsmKeyAndIvSliceDerivationStrategy extends BaseHsmKeyDerivationStra
|
||||
public DerivedKey deriveKey(Map<String, String> params, Map<String, String> runtimeContext) throws Exception {
|
||||
byte[] keyBytes = super.getHsmKey(params);
|
||||
byte[] rawIv = super.getHsmIv(params);
|
||||
String ivHex = DatatypeConverter.printHexBinary(rawIv);
|
||||
return deriveKey(keyBytes, rawIv);
|
||||
}
|
||||
|
||||
public DerivedKey deriveKey(byte[] keyBytes, byte[] rawIv) {
|
||||
String ivHex = DatatypeConverter.printHexBinary(rawIv);
|
||||
if (ivHex.length() < IV_HEX_END) {
|
||||
throw new IllegalArgumentException(
|
||||
"hsmIvAlias hex 길이 부족: 최소 " + IV_HEX_END + "자 필요, 실제=" + ivHex.length()
|
||||
@@ -32,7 +36,7 @@ public class HsmKeyAndIvSliceDerivationStrategy extends BaseHsmKeyDerivationStra
|
||||
}
|
||||
byte[] iv = DatatypeConverter.parseHexBinary(ivHex.substring(IV_HEX_OFFSET, IV_HEX_END));
|
||||
return new DerivedKey(keyBytes, keyBytes, iv);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String buildCacheKey(String cryptoName, Map<String, String> params, Map<String, String> runtimeContext) {
|
||||
|
||||
@@ -156,6 +156,13 @@ public class StandardMessageCoordinatorDJB extends DefaultStandardMessageCoordin
|
||||
standardMessage.setData(HEAD_MESG_RSPN_DT, now.format(FMT_DATE));
|
||||
standardMessage.setData(HEAD_MESG_RSPN_TIME, now.format(FMT_TIME_MILLIS));
|
||||
|
||||
|
||||
StandardItem msgListRowCnt = standardMessage.findItem(StandardMessageCoordinatorDJB.MSG_LIST_ROWCNT);
|
||||
if (msgListRowCnt == null || "0".equals(msgListRowCnt.getValue()) || "".equals(msgListRowCnt.getValue())) {
|
||||
StandardItem msgPart = standardMessage.findItem("MSG");
|
||||
msgPart.getChilds().remove("MSG_LIST");
|
||||
}
|
||||
|
||||
makeupDataScopLen(standardMessage, charset);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
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
@@ -1,134 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user