API 별 오류 응답 템플릿 핸들러 추가

- ApiTemplateAdapterErrorMsgHandler : API ID 별 템플릿, 요청 배열 에코, 코드/메시지 매핑
- 프로퍼티 그룹은 ERR{어댑터그룹명} 자동 해석, 없으면 ERR{API}
- 단위테스트 38건
This commit is contained in:
curry772
2026-09-23 15:44:19 +09:00
parent fee8cb6016
commit 1649a05501
3 changed files with 1125 additions and 2 deletions
@@ -0,0 +1,459 @@
package com.eactive.eai.adapter.handler;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.JacksonUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.message.StandardMessage;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* API 별로 오류 응답 구조가 다른 기관용 템플릿 핸들러.
*
* <p>{@link TemplateAdapterErrorMsgHandler} 가 어댑터 그룹 단위로 템플릿 하나를 쓰는 것과 달리,
* 같은 어댑터 그룹 안에서 <b>API ID 별로</b> 템플릿을 고르고, 요청 배열을 그대로 에코한
* 배열 응답을 만들 수 있다. 응답코드/응답메시지는 표준전문 오류코드를 매핑해 채운다.
*
* <p>기관이 늘어도 클래스를 만들지 않는다. 어댑터 프로퍼티의 <code>ERR_MSG_HANDLER</code> 에
* 이 클래스를 그대로 지정하고, 프로퍼티 그룹 <code>ERR{어댑터그룹명}</code> 만 만들면 된다.
* 기관 고유 로직이 필요할 때만 상속해서 {@link #getPropGroup(String)} 등을 오버라이드한다.
*
* <p>[동작]
* <pre>
* 1. 표준전문 오류코드 추출
* 2. 코드/메시지 매핑 결과 산출 → ${rslt_cd}, ${rslt_msg}
* 3. API ID(= api.key 로 지정한 callProp 값, 기본 API_SERVICE_CODE) 로 템플릿 선택
* 4. 배열 API 면 요청 배열을 돌며 item 템플릿을 렌더해 배열 조립 → ${array}
* 5. 본문 템플릿 렌더
* </pre>
*
* <p>[템플릿에서 쓰는 값]
* <pre>
* ${rslt_cd} 매핑된 응답코드
* ${rslt_msg} 매핑된 응답메시지
* ${item.필드} 배열 요소의 값 (array.item 템플릿 전용)
* ${array} 조립이 끝난 배열 (겉 템플릿, 따옴표 없이)
* ${callprop.INBOUND_REQUEST_MESSAGE.필드} 요청 전문의 값
* </pre>
* 내부 키 표기 <code>${callprop.TPL_RSLT_CD}</code>, <code>${callprop.TPL_RSLT_MSG}</code>,
* <code>${callprop.TPL_ITEM.필드}</code>, <code>${callprop.TPL_ARRAY}</code> 도 동작한다.
*
* <pre>
* api.key = API_SERVICE_CODE API ID 로 쓸 callProp 키 (기본값)
*
* {apiId}.template = {"rows":${array}}
* {apiId}.array.source = rows 요청 배열 경로 (dot 경로 가능)
* {apiId}.array.item = {"no":"${item.no}","rslt_cd":"${rslt_cd}"}
* {apiId}.sys.template / {apiId}.in.template 경로별로 다르게 낼 때만 등록
* (없으면 {apiId}.template 을 그대로 쓴다)
*
* rslt_cd.40000 = CP4000 응답코드 매핑
* rslt_cd.default = CP5000
* rslt_msg.40000 = 형식 오류입니다 응답메시지 매핑
* rslt_msg.default = 시스템 오류입니다
*
* err.code.path = MSG.MAIN_MSG.outp_msg_cd 표준전문 오류코드 경로 (기본값)
*
* template / sys.template / in.template API ID 별 템플릿이 없을 때 공통 폴백
* </pre>
*/
public class ApiTemplateAdapterErrorMsgHandler extends TemplateAdapterErrorMsgHandler {
private static final Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
/**
* 어댑터 그룹 전용 프로퍼티 그룹 이름 형식 : ERR{어댑터그룹명}
* 어댑터 그룹명이 길어 그룹명 길이 제한에 걸리지 않도록 접두어를 짧게 둔다.
*/
public static final String PROP_GROUP_PREFIX = "ERR{";
public static final String PROP_GROUP_SUFFIX = "}";
/** 어댑터 그룹 전용 프로퍼티 그룹이 없을 때 쓰는 기본 그룹 */
public static final String DEFAULT_PROP_GROUP = "ERR{API}";
/** API ID 로 사용할 callProp 키를 지정하는 설정 키 */
static final String KEY_API_KEY = "api.key";
/** 응답코드 매핑 접두어 */
static final String KEY_RSLT_CD_PREFIX = "rslt_cd.";
/** 응답메시지 매핑 접두어 */
static final String KEY_RSLT_MSG_PREFIX = "rslt_msg.";
/** 표준전문 오류코드 경로를 바꿀 때 쓰는 설정 키 */
static final String KEY_ERR_CODE_PATH = "err.code.path";
/** 매핑 폴백 접미어 */
static final String KEY_DEFAULT_SUFFIX = "default";
/** 배열 설정 접미어 */
static final String KEY_ARRAY_SOURCE = "array.source";
static final String KEY_ARRAY_ITEM = "array.item";
static final String DEFAULT_API_KEY = "API_SERVICE_CODE";
static final String DEFAULT_ERR_CODE_PATH = "MSG.MAIN_MSG.outp_msg_cd";
/** 템플릿 별칭 토큰 */
static final String ALIAS_RSLT_CD = "${rslt_cd}";
static final String ALIAS_RSLT_MSG = "${rslt_msg}";
static final String ALIAS_ARRAY = "${array}";
private static final String ALIAS_ITEM_MARK = "${item.";
private static final Pattern ALIAS_ITEM_PATTERN = Pattern.compile("\\$\\{item\\.([^}]+)\\}");
/** 렌더 중 callProp 에 임시로 주입하는 키 */
static final String CP_RSLT_CD = "TPL_RSLT_CD";
static final String CP_RSLT_MSG = "TPL_RSLT_MSG";
static final String CP_ITEM = "TPL_ITEM";
static final String CP_ARRAY = "TPL_ARRAY";
/** 인바운드 필터 오류 시 컨트롤러가 넣어주는 GW 오류코드 */
static final String CP_INBOUND_RESULT_CODE = "INBOUND_RESULT_CODE";
/** 어댑터가 저장해 둔 요청 전문 원본 */
static final String CP_INBOUND_REQUEST_MESSAGE = "INBOUND_REQUEST_MESSAGE";
/** 기본 ObjectMapper 는 선행 0 / 큰 수를 훼손한다. */
private static final ObjectMapper OBJECT_MAPPER = JacksonUtil.newNumberSafeMapper();
/**
* 설정을 읽어올 프로퍼티 그룹을 정한다.
* <pre>
* 1. ERR{어댑터그룹명} 해당 그룹이 등록되어 있으면 사용
* 2. ERR{API} 없으면 전역 기본 그룹
* </pre>
* 기관마다 클래스를 만들 필요 없이 프로퍼티 그룹만 추가하면 된다.
* 기관 고유 로직이 필요할 때만 상속해서 오버라이드한다.
*/
protected String getPropGroup(String adapterGroupName) {
if (StringUtils.isNotBlank(adapterGroupName)) {
String group = PROP_GROUP_PREFIX + adapterGroupName + PROP_GROUP_SUFFIX;
if (hasPropGroup(group)) {
return group;
}
}
return DEFAULT_PROP_GROUP;
}
/** 프로퍼티 그룹이 등록되어 있고 비어 있지 않은지 확인한다. */
protected boolean hasPropGroup(String group) {
Properties props = PropManager.getInstance().getProperties(group);
return props != null && !props.isEmpty();
}
// ================================================================
// AdapterErrorMessageHandler 구현
// ================================================================
/** 업무시스템 오류 응답 */
@Override
public Object generateNonStandardErrorResponseMessage(String inboundAdapterGroupName,
String inboundAdapterName, Properties callProp, Object outboundRequestData,
EAIMessage resEaiMsg) throws Exception {
String group = getPropGroup(inboundAdapterGroupName);
StandardMessage stdMsg = (resEaiMsg != null) ? resEaiMsg.getStandardMessage() : null;
return build(group, callProp, stdMsg, null,
resolveErrorCode(group, stdMsg, resEaiMsg, callProp), "");
}
/** GW 내부 오류 응답 */
@Override
public Object generateNonStandardInternalErrorResponseMessage(String inboundAdapterGroupName,
String inboundAdapterName, Properties callProp, Object inboundRequestData,
EAIMessage resEaiMsg) throws Exception {
String group = getPropGroup(inboundAdapterGroupName);
StandardMessage stdMsg = (resEaiMsg != null) ? resEaiMsg.getStandardMessage() : null;
return build(group, callProp, stdMsg, null,
resolveErrorCode(group, stdMsg, resEaiMsg, callProp), "sys.");
}
/** 인바운드 필터 오류 응답 (StandardMessage 없음) */
@Override
public Object generateNonStandardInboundErrorResponseMessage(String adapterGroupName,
String adapterName, Properties callProp, Object inboundRequestData,
Object inboundResponseData, Throwable e) throws Exception {
String group = getPropGroup(adapterGroupName);
return build(group, callProp, null, e, resolveErrorCode(group, null, null, callProp), "in.");
}
// ================================================================
// 공통 처리
// ================================================================
/**
* 코드/메시지 산출 → 템플릿 선택 → 배열 조립 → 본문 렌더.
*
* @param templateInfix 템플릿 키 중간 구분자 ("" / "sys." / "in.")
* @return 렌더된 본문. 템플릿이 없으면 null (상위에서 기본 오류 응답으로 폴백)
*/
private String build(String group, Properties callProp, StandardMessage stdMsg, Throwable exception,
String errorCode, String templateInfix) {
Properties prop = (callProp != null) ? callProp : new Properties();
String apiId = resolveApiId(group, prop);
String template = findTemplate(group, apiId, templateInfix);
if (StringUtils.isBlank(template)) {
if (logger.isWarn()) {
logger.warn("ApiTemplateAdapterErrorMsgHandler] template not found. group=" + group
+ ", apiId=" + apiId + ", infix=" + templateInfix);
}
return null;
}
try {
String rsltCd = mapValue(group, KEY_RSLT_CD_PREFIX, errorCode);
String rsltMsg = mapValue(group, KEY_RSLT_MSG_PREFIX, errorCode);
// ${callprop.TPL_RSLT_CD} 표기로도 참조할 수 있게 callProp 에 넣어둔다
prop.setProperty(CP_RSLT_CD, rsltCd);
prop.setProperty(CP_RSLT_MSG, rsltMsg);
String arrayJson = buildArray(group, apiId, prop, stdMsg, exception, rsltCd, rsltMsg);
if (arrayJson != null) {
prop.setProperty(CP_ARRAY, arrayJson);
}
return render(applyAliases(template, rsltCd, rsltMsg, null, arrayJson),
stdMsg, prop, exception);
} catch (Exception e) {
logger.error("ApiTemplateAdapterErrorMsgHandler] build fail - " + e.getMessage(), e);
return null;
} finally {
// 거래 Properties 를 그대로 쓰므로 임시 키는 반드시 걷어낸다 (로깅에 섞이는 것 방지)
prop.remove(CP_RSLT_CD);
prop.remove(CP_RSLT_MSG);
prop.remove(CP_ARRAY);
prop.remove(CP_ITEM);
}
}
/**
* 요청 배열을 돌며 item 템플릿을 렌더해 JSON 배열 문자열을 만든다.
* 배열 설정이 없으면 null.
* 요청 배열이 없거나 파싱 실패면 에코 없이 1건만 만들어 오류코드를 전달한다.
*/
private String buildArray(String group, String apiId, Properties prop, StandardMessage stdMsg,
Throwable exception, String rsltCd, String rsltMsg) {
String sourcePath = getApiProp(group, apiId, KEY_ARRAY_SOURCE);
String itemTemplate = getApiProp(group, apiId, KEY_ARRAY_ITEM);
if (StringUtils.isBlank(sourcePath) || StringUtils.isBlank(itemTemplate)) {
return null; // 배열 API 가 아니다
}
JsonNode sourceArray = readRequestArray(prop, sourcePath);
if (sourceArray == null || !sourceArray.isArray() || sourceArray.size() == 0) {
// 요청 전문이 비정상이거나 배열이 비었어도 오류코드는 전달되어야 한다.
// 배열 요소 안에만 응답코드 자리가 있는 전문(카카오뱅크 등)에서 빈 배열로 내보내면
// 수신측이 오류 내용을 알 수 없으므로, 에코 필드는 빈 값으로 두고 1건을 만든다.
if (logger.isWarn()) {
logger.warn("ApiTemplateAdapterErrorMsgHandler] request array not found. path=" + sourcePath
+ " - 에코 없이 1건으로 응답한다");
}
return "[" + render(applyAliases(itemTemplate, rsltCd, rsltMsg, null, null),
stdMsg, prop, exception) + "]";
}
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < sourceArray.size(); i++) {
JsonNode item = sourceArray.get(i);
// ${callprop.TPL_ITEM.필드} 표기로도 참조할 수 있게 callProp 에 실어둔다
prop.setProperty(CP_ITEM, item.toString());
if (i > 0) {
sb.append(",");
}
sb.append(render(applyAliases(itemTemplate, rsltCd, rsltMsg, item, null),
stdMsg, prop, exception));
}
prop.remove(CP_ITEM);
return sb.append("]").toString();
}
/**
* 템플릿의 별칭 토큰을 렌더 전에 치환한다.
* <pre>
* ${rslt_cd} / ${rslt_msg} → 매핑 결과
* ${array} → 조립한 배열 (null 이면 빈 문자열)
* ${item.경로} → 현재 배열 요소의 값 (item 이 null 이면 빈 문자열)
* </pre>
* 치환값의 제어문자는 render 와 동일한 이유로 제거한다.
*/
private String applyAliases(String template, String rsltCd, String rsltMsg,
JsonNode item, String arrayJson) {
String result = template
.replace(ALIAS_RSLT_CD, MessageUtil.stripControlChars(StringUtils.defaultString(rsltCd)))
.replace(ALIAS_RSLT_MSG, MessageUtil.stripControlChars(StringUtils.defaultString(rsltMsg)))
.replace(ALIAS_ARRAY, StringUtils.defaultString(arrayJson));
if (!result.contains(ALIAS_ITEM_MARK)) {
return result;
}
Matcher matcher = ALIAS_ITEM_PATTERN.matcher(result);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String value = (item != null) ? extractText(item, matcher.group(1).trim()) : "";
matcher.appendReplacement(sb,
Matcher.quoteReplacement(MessageUtil.stripControlChars(value)));
}
matcher.appendTail(sb);
return sb.toString();
}
/** JsonNode 에서 dot 경로로 값을 꺼낸다. 값 노드가 아니면 JSON 문자열 그대로 반환. */
private String extractText(JsonNode node, String path) {
JsonNode current = node;
for (String part : path.split("\\.", -1)) {
if (current == null) {
return "";
}
current = current.get(part);
}
if (current == null || current.isNull()) {
return "";
}
return current.isValueNode() ? current.asText() : current.toString();
}
/** 요청 전문에서 dot 경로로 배열 노드를 꺼낸다. */
private JsonNode readRequestArray(Properties prop, String sourcePath) {
String requestMessage = prop.getProperty(CP_INBOUND_REQUEST_MESSAGE);
if (StringUtils.isBlank(requestMessage)) {
return null;
}
try {
// 상대 시스템이 제어문자를 이스케이프하지 않고 보내는 경우가 있어 정규화 후 파싱한다.
JsonNode node = OBJECT_MAPPER.readTree(JacksonUtil.escapeControlChars(requestMessage));
for (String part : sourcePath.split("\\.", -1)) {
if (node == null) {
return null;
}
node = node.get(part);
}
return node;
} catch (Exception e) {
if (logger.isWarn()) {
logger.warn("ApiTemplateAdapterErrorMsgHandler] request parse fail - " + e.getMessage());
}
return null;
}
}
// ================================================================
// 설정 조회
// ================================================================
/**
* 템플릿 조회. API ID 별 → 공통 순으로 찾고, 그래도 없으면 기본 템플릿으로 폴백한다.
* <pre>
* infix="sys." → {apiId}.sys.template → sys.template → {apiId}.template → template
* infix="" → {apiId}.template → template
* </pre>
* 경로별로 응답을 달리 할 필요가 없으면 {@code sys.template}/{@code in.template} 을
* 등록하지 않아도 된다. 이때 코드/메시지는 매핑의 default 로 떨어진다.
*/
private String findTemplate(String group, String apiId, String infix) {
String template = getApiProp(group, apiId, infix + "template");
if (StringUtils.isNotBlank(template)) {
return template;
}
template = getProp(group, infix + "template");
if (StringUtils.isNotBlank(template)) {
return template;
}
if (StringUtils.isBlank(infix)) {
return null;
}
// sys / in 전용 템플릿이 없으면 업무오류용 기본 템플릿을 그대로 쓴다
template = getApiProp(group, apiId, "template");
if (StringUtils.isNotBlank(template)) {
return template;
}
return getProp(group, "template");
}
/** "{apiId}.{suffix}" 설정 값. apiId 가 없으면 null. */
private String getApiProp(String group, String apiId, String suffix) {
if (StringUtils.isBlank(apiId)) {
return null;
}
return getProp(group, apiId + "." + suffix);
}
/**
* API ID 를 구한다. api.key 로 지정한 callProp 값을 그대로 쓴다.
* (기본 API_SERVICE_CODE. FINAL_STD_MESSAGE_KEY 로 바꾸면 요청 경로가 API ID 가 된다)
*/
private String resolveApiId(String group, Properties callProp) {
String apiKey = StringUtils.defaultIfBlank(getProp(group, KEY_API_KEY), DEFAULT_API_KEY);
String apiId = callProp.getProperty(apiKey);
if (StringUtils.isBlank(apiId) && logger.isWarn()) {
logger.warn("ApiTemplateAdapterErrorMsgHandler] api id value not found. key=" + apiKey);
}
return apiId;
}
/**
* 표준전문 오류코드를 찾는다.
* 표준전문 경로 → EAIMessage 응답코드 → callProp INBOUND_RESULT_CODE 순.
*/
private String resolveErrorCode(String group, StandardMessage stdMsg, EAIMessage resEaiMsg,
Properties callProp) {
if (stdMsg != null) {
String path = StringUtils.defaultIfBlank(getProp(group, KEY_ERR_CODE_PATH), DEFAULT_ERR_CODE_PATH);
String code = stdMsg.findItemValue(path);
if (StringUtils.isNotBlank(code)) {
return code;
}
}
if (resEaiMsg != null && StringUtils.isNotBlank(resEaiMsg.getRspErrCd())) {
return resEaiMsg.getRspErrCd();
}
if (callProp != null) {
return StringUtils.trimToEmpty(callProp.getProperty(CP_INBOUND_RESULT_CODE));
}
return "";
}
/** {접두어}{오류코드} → 없으면 {접두어}default → 없으면 빈 문자열 */
private String mapValue(String group, String prefix, String errorCode) {
if (StringUtils.isNotBlank(errorCode)) {
String mapped = getProp(group, prefix + errorCode);
if (mapped != null) {
return mapped;
}
}
return StringUtils.defaultString(getProp(group, prefix + KEY_DEFAULT_SUFFIX));
}
/**
* 설정 값 조회. 서브클래스가 다른 저장소에서 읽거나
* 단위테스트에서 PropManager 없이 검증할 수 있게 분리한다.
*/
protected String getProp(String group, String key) {
return PropManager.getInstance().getProperty(group, key);
}
}
@@ -161,9 +161,10 @@ public class TemplateAdapterErrorMsgHandler implements AdapterErrorMessageHandle
/**
* 템플릿에 StandardMessage, callProp, exception 값을 치환해 최종 문자열을 반환한다.
* foreach 블록과 스칼라 변수를 좌→우 순서로 단일 패스 처리한다.
* package-private: 단위 테스트에서 직접 호출 가능
* protected: 다른 패키지의 확장 핸들러가 템플릿 조회는 직접 하고 렌더만 재사용할 수 있게 공개한다.
* (단위 테스트는 같은 패키지에서 직접 호출)
*/
String render(String template, StandardMessage msg, Properties callProp, Throwable exception) {
protected String render(String template, StandardMessage msg, Properties callProp, Throwable exception) {
// 관리 UI 등에서 HTML 인코딩된 엔티티를 복원 (예: &#35; → #)
template = template.replace("&#35;", "#")
.replace("&amp;", "&")