Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a5a072fef4 | |||
| 078331b3b8 | |||
| 428ab1103a | |||
| 4813a2ef0e | |||
| 752156b86f | |||
| 5732ddf962 | |||
| 5ffc48c039 | |||
| cbb6f33ce5 | |||
| 44093681b7 | |||
| a24b437f5c | |||
| 67dba6ca4a | |||
| f4d7ac2fad | |||
| 6ca653aa1e | |||
| 90941bff54 |
Binary file not shown.
@@ -127,6 +127,9 @@ public class TemplateAdapterErrorMsgHandler implements AdapterErrorMessageHandle
|
||||
StandardMessage resStandardMessage = resEaiMsg.getStandardMessage();
|
||||
String templateKey = inboundAdapterGroupName + ".template";
|
||||
String template = PropManager.getInstance().getProperty(PROP_GROUP, templateKey);
|
||||
|
||||
if (StringUtils.isBlank(template))
|
||||
template = PropManager.getInstance().getProperty(PROP_GROUP, "default.template");
|
||||
|
||||
if (StringUtils.isBlank(template)) {
|
||||
if (logger.isWarn()) {
|
||||
@@ -320,6 +323,8 @@ public class TemplateAdapterErrorMsgHandler implements AdapterErrorMessageHandle
|
||||
? expr.substring(closeIdx + 2)
|
||||
: "";
|
||||
|
||||
if (msg == null) return defaultVal;
|
||||
|
||||
String key = msg.findItemValue(msgPath);
|
||||
if (StringUtils.isBlank(key)) return defaultVal;
|
||||
if (callProp == null) return defaultVal;
|
||||
@@ -409,6 +414,9 @@ public class TemplateAdapterErrorMsgHandler implements AdapterErrorMessageHandle
|
||||
String templateKey = inboudnAdapterGroupName + ".sys.template";
|
||||
String template = PropManager.getInstance().getProperty(PROP_GROUP, templateKey);
|
||||
|
||||
if (StringUtils.isBlank(template))
|
||||
template = PropManager.getInstance().getProperty(PROP_GROUP, "default.sys.template");
|
||||
|
||||
if (StringUtils.isBlank(template)) {
|
||||
if (logger.isWarn()) {
|
||||
logger.warn("TemplateAdapterErrorMsgHandler] template not found. group=" + PROP_GROUP
|
||||
@@ -456,6 +464,10 @@ public class TemplateAdapterErrorMsgHandler implements AdapterErrorMessageHandle
|
||||
throws Exception {
|
||||
String templateKey = outboundadapterGroupName + ".template";
|
||||
String template = PropManager.getInstance().getProperty(PROP_GROUP, templateKey);
|
||||
|
||||
if (StringUtils.isBlank(template))
|
||||
template = PropManager.getInstance().getProperty(PROP_GROUP, "default.template");
|
||||
|
||||
if (StringUtils.isBlank(template)) {
|
||||
return null;
|
||||
}
|
||||
@@ -466,15 +478,27 @@ public class TemplateAdapterErrorMsgHandler implements AdapterErrorMessageHandle
|
||||
String adptMsgType, String encode, Throwable e1, int httpCode) {
|
||||
String templateKey = adapterGroupName + ".in." + httpCode + ".template";
|
||||
String template = PropManager.getInstance().getProperty(PROP_GROUP, templateKey);
|
||||
if (StringUtils.isBlank(template)) {
|
||||
templateKey = "default.in." + httpCode + ".template";
|
||||
template = PropManager.getInstance().getProperty(PROP_GROUP, templateKey);
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(template)) {
|
||||
templateKey = adapterGroupName + ".in.template";
|
||||
template = PropManager.getInstance().getProperty(PROP_GROUP, templateKey);
|
||||
if (StringUtils.isBlank(template)) {
|
||||
String errorResponseFormat = httpProp.getProperty("ERROR_RESPONSE_FORMAT");
|
||||
return MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AP_ERROR, e1.getMessage(), errorResponseFormat);
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(template)) {
|
||||
templateKey = "default.in.template";
|
||||
template = PropManager.getInstance().getProperty(PROP_GROUP, templateKey);
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(template)) {
|
||||
String errorResponseFormat = httpProp.getProperty("ERROR_RESPONSE_FORMAT");
|
||||
return MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode,
|
||||
MessageUtil.ERROR_CODE_AP_ERROR, e1.getMessage(), errorResponseFormat);
|
||||
}
|
||||
|
||||
return render(template, null, callProp, e1);
|
||||
}
|
||||
|
||||
|
||||
+6
-7
@@ -527,8 +527,8 @@ public class HttpClient5AdapterServiceRest extends HttpClient5AdapterServiceSupp
|
||||
// 이경우 정상으로 처리함
|
||||
} else if (status >= 200 && status <= 207) {
|
||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
needReissue = checkTokenRetry(status, responseMessage, tokenErrorHttpStatusCode, tokenErrorCodeKey,
|
||||
tokenErrorCodeValues, vo.getEncode());
|
||||
}
|
||||
} else if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
@@ -542,15 +542,14 @@ public class HttpClient5AdapterServiceRest extends HttpClient5AdapterServiceSupp
|
||||
|
||||
if (status >= 400 && status < 500) {
|
||||
if (useAdapterToken) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
needReissue = checkTokenRetry(status, responseMessage, tokenErrorHttpStatusCode,
|
||||
tokenErrorCodeKey, tokenErrorCodeValues, vo.getEncode());
|
||||
}
|
||||
|
||||
if (!needReissue) {
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
} else {
|
||||
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
@@ -882,8 +881,8 @@ public class HttpClient5AdapterServiceRest extends HttpClient5AdapterServiceSupp
|
||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||
String encode) {
|
||||
protected boolean checkTokenRetry(int status, byte[] responseMessage, String tokenErrorHttpStatusCode,
|
||||
String tokenErrorCodeKey, String tokenErrorCodeValues, String encode) {
|
||||
if (responseMessage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilterFactory;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilterType;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.TxSiftContext;
|
||||
import com.eactive.eai.common.util.UUIDGenerator;
|
||||
@@ -31,13 +32,20 @@ public abstract class HttpAdapterServiceSupport implements HttpAdapterService, H
|
||||
public static final String PROPERTIES_NAME_CLIENT_ID = "clientId";
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
EAIServerManager eaiServerManager;
|
||||
String instid = null;
|
||||
|
||||
public Object service(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
String uuid = prop.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
boolean bMDCput = false;
|
||||
|
||||
if(uuid == null) {
|
||||
uuid = UUIDGenerator.getUUID().toString().replaceAll("-", "");
|
||||
if(instid == null) {
|
||||
eaiServerManager = EAIServerManager.getInstance();
|
||||
instid = eaiServerManager.getGroupInstId();
|
||||
}
|
||||
uuid = instid + UUIDGenerator.getUUID().toString().replaceAll("-", "");
|
||||
prop.setProperty(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
}
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ public class ApiAuthFilter implements HttpAdapterFilter {
|
||||
|
||||
public static final String PROP_GROUP_AUTH_SERVER = "OAuthServer";
|
||||
public static final String PROP_KEYSTORE_PATH = "certification.publicKeyPath";
|
||||
public static final String PASS_SCOPE_LIST = "pass.scope.list";
|
||||
|
||||
public static final String ERROR_AUTHENTICATION_FAIL = "E.AUTHENTICATION_FAIL";
|
||||
public static final String ERROR_AUTHORIZATION_FAIL = "E.AUTHORIZATION_FAIL";
|
||||
@@ -59,7 +60,7 @@ public class ApiAuthFilter implements HttpAdapterFilter {
|
||||
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id";
|
||||
|
||||
private JWSVerifier jwsVerifier;
|
||||
|
||||
private String[] passScopeArr = {};
|
||||
// // CA 토큰 저장소
|
||||
// private final Map<String, BearerTokenInfo> CATokenStore = new ConcurrentHashMap<>();
|
||||
|
||||
@@ -89,6 +90,10 @@ public class ApiAuthFilter implements HttpAdapterFilter {
|
||||
} catch (IOException | NoSuchAlgorithmException | RuntimeException | InvalidKeySpecException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
String passScope = vo.getProperty(PASS_SCOPE_LIST, "oob,public");
|
||||
passScopeArr = org.springframework.util.StringUtils.tokenizeToStringArray(passScope, ",");
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -316,9 +321,6 @@ public class ApiAuthFilter implements HttpAdapterFilter {
|
||||
return false;
|
||||
}
|
||||
|
||||
String passScope = "oob,public";
|
||||
String[] passScopeArr = org.springframework.util.StringUtils.tokenizeToStringArray(passScope, ",");
|
||||
|
||||
for (String scope : scopeArr) {
|
||||
for (String pScope : passScopeArr) {
|
||||
if ( StringUtils.equalsAny(scope, pScope)) {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.util.JsonPathUtil;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
public class JsonToSetStatusFilter implements HttpAdapterFilter {
|
||||
private static final String PROPGROUP = "JsonToSetStatusFilter";
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
/** HTTP 상태코드 유효 범위 (RFC 7231) */
|
||||
private static final int MIN_HTTP_STATUS = 100;
|
||||
private static final int MAX_HTTP_STATUS = 599;
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
// do nothing
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
String fieldName = "";
|
||||
String statusParam = "";
|
||||
try {
|
||||
JsonNode rootNode = parseJson(adptGrpName, resultMessage);
|
||||
fieldName = getFieldName(adptGrpName);
|
||||
if (rootNode != null && StringUtils.isNotBlank(fieldName) && rootNode.has(fieldName)) {
|
||||
statusParam = rootNode.get(fieldName).asText();
|
||||
int httpStatus = Integer.parseInt(statusParam);
|
||||
if (isValidHttpStatus(httpStatus)) {
|
||||
response.setStatus(httpStatus);
|
||||
} else {
|
||||
logger.warn("유효하지 않은 HTTP 상태코드. 상태코드를 설정하지 않음. fieldName={}, value={}", fieldName, statusParam);
|
||||
}
|
||||
} else {
|
||||
logger.warn("설정과 맞지 않는 메시지. 상태코드를 설정하지 않음. fieldName={}", fieldName);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("상태코드 추출 실패. fieldName={}, value={}", fieldName, statusParam, e);
|
||||
}
|
||||
|
||||
return resultMessage;
|
||||
}
|
||||
|
||||
/** HTTP 상태코드로 사용 가능한 값인지 확인한다. (100 ~ 599) */
|
||||
private boolean isValidHttpStatus(int httpStatus) {
|
||||
return httpStatus >= MIN_HTTP_STATUS && httpStatus <= MAX_HTTP_STATUS;
|
||||
}
|
||||
|
||||
private String getFieldName(String adptGrpName) {
|
||||
return PropManager.getInstance().getProperty(PROPGROUP, adptGrpName);
|
||||
}
|
||||
|
||||
private JsonNode parseJson(String adptGrpName, Object message) throws Exception {
|
||||
return JsonPathUtil.toTree(message);
|
||||
}
|
||||
}
|
||||
@@ -163,7 +163,14 @@ public class EncryptionManager implements Lifecycle {
|
||||
if (this.isEncrypted(dbData)) {
|
||||
if ("DAMO".equals(dbEncryptSolutionName)) {
|
||||
com.eactive.ext.djb.DamoManager damoManager = new com.eactive.ext.djb.DamoManager();
|
||||
return damoManager.decrypt(dbData);
|
||||
try {
|
||||
return damoManager.decrypt(dbData);
|
||||
} catch (Exception e) {
|
||||
// 복호화 실패시 원본 반환
|
||||
String logData = dbData.length() <= 3 ? dbData : dbData.substring(0, 3) + "...";
|
||||
logger.warn("DB 복호화 실패: 복호화하지 않고 원본 반환. dbData={} (Length : {})", logData, dbData.length());
|
||||
return dbData;
|
||||
}
|
||||
} else if ("SAFEDB".equals(dbEncryptSolutionName)) {
|
||||
KjbSafedbWrapper safeDBWrapper = KjbSafedbWrapper.getInstance();
|
||||
try {
|
||||
|
||||
@@ -2,10 +2,8 @@ package com.eactive.eai.common.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
@@ -63,13 +61,17 @@ public class HttpAdapterExtraLogUtil {
|
||||
httpAdapterExtraLogVo.setHttpMethod(httpMethod);
|
||||
|
||||
for (HttpAdapterExtraHeaderVo httpAdapterExtraHeaderVo : headerVoList) {
|
||||
// String name = httpAdapterExtraHeaderVo.getName();
|
||||
String name = httpAdapterExtraHeaderVo.getName();
|
||||
// if(StringUtils.isNotBlank(name) && "authorization".equals(name.toLowerCase())) {
|
||||
// httpAdapterExtraHeaderVo.setValue("{hidden}");
|
||||
// }
|
||||
|
||||
if(StringUtils.isNotBlank(name) && BODY_FIELD_NAME.equals(name))
|
||||
continue;
|
||||
|
||||
String value = httpAdapterExtraHeaderVo.getValue();
|
||||
if(StringUtils.isNotBlank(value) && value.length() > MAX_HEADER_VALUE_SIZE) {
|
||||
value = value.substring(0, 400) + "...";
|
||||
value = value.substring(0, MAX_HEADER_VALUE_SIZE) + "...";
|
||||
httpAdapterExtraHeaderVo.setValue(value);
|
||||
}else if(value == null){
|
||||
httpAdapterExtraHeaderVo.setValue(" ");
|
||||
@@ -116,7 +118,7 @@ public class HttpAdapterExtraLogUtil {
|
||||
}
|
||||
|
||||
public static List<HttpAdapterExtraHeaderVo> convertHeaderToListOfHttpAdapterExtraHeaderVo(Header[] headers) {
|
||||
Set<String> seenNames = new HashSet<>();
|
||||
// Set<String> seenNames = new HashSet<>();
|
||||
return Arrays.stream(headers)
|
||||
// .filter(header -> seenNames.add(header.getName())) // 중복된 이름을 스킵
|
||||
.map(header -> new HttpAdapterExtraHeaderVo(header.getName(), header.getValue()))
|
||||
|
||||
@@ -123,7 +123,7 @@ public class RequestProcessor extends RequestProcessorSupport {
|
||||
|
||||
// UUID 생성 : UUID에서 - 없는 32자리
|
||||
String uuid = prop.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
uuid = uuid == null ? UUIDGenerator.getUUID().toString().replaceAll("-", "") : uuid;
|
||||
uuid = uuid == null ? instid+UUIDGenerator.getUUID().toString().replaceAll("-", "") : uuid;
|
||||
// UUID 생성 : UUID = server구분4자리 + UUID
|
||||
/*
|
||||
String uuid = "";
|
||||
|
||||
@@ -704,6 +704,18 @@ public abstract class DefaultProcess extends Process {
|
||||
Object responseObj = adapterErrorMessageHandler.generateNonStandardErrorResponseMessage(inboudnAdapterGroupName, inboudnAdapterName, this.callProp, this.tgtTranObject, this.resEaiMsg);
|
||||
if(responseObj != null) {
|
||||
resStandardMessage.setBizData(responseObj, inboundAdapterGroupVO.getMessageEncode());
|
||||
} else {
|
||||
if ((com.eactive.eai.adapter.Keys.IF_STANDARD.equals(this.adptrMsgPtrnCd)
|
||||
||com.eactive.eai.adapter.Keys.IF_SUBSTANDARD.equals(this.adptrMsgPtrnCd))) {
|
||||
String errorCode = mapper.getErrorCode(resStandardMessage);
|
||||
String errorMsg = StringUtils.trim(mapper.getErrorMsg(resStandardMessage));
|
||||
String errorDesc = StringUtils.trim(resStandardMessage.findItemValue("MSG.MAIN_MSG.outp_msg_desc"));
|
||||
this.resEaiMsg.setRspErr("RECEAIINA001", String.format("[%s] %s (%s)", errorCode, errorMsg, errorDesc));
|
||||
return;
|
||||
} else {
|
||||
this.resEaiMsg.setRspErr("RECEAIINA001", "비표준 오류 응답 수신");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this.resEaiMsg.setRspErrCd(EAIMessageKeys.BWK_FAILMSG_CODE, false);
|
||||
|
||||
+424
@@ -1383,4 +1383,428 @@ class TemplateAdapterErrorMsgHandlerTest {
|
||||
assertNotNull(result);
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// default.* 템플릿 폴백
|
||||
//
|
||||
// 그룹 전용 키가 미설정/공백이면 "default." 로 시작하는 공통 키를 재조회한다.
|
||||
// generateNonStandardErrorResponseMessage : {group}.template → default.template
|
||||
// generateOutboundErrorResponseMessage : {group}.template → default.template
|
||||
// generateNonStandardInternalErrorResponseMessage : {group}.sys.template → default.sys.template
|
||||
// generateNonStandardInboundErrorResponseMessage : {group}.in.{code}.template
|
||||
// → default.in.{code}.template
|
||||
// → {group}.in.template
|
||||
// → default.in.template
|
||||
// → MessageUtil 폴백
|
||||
// ================================================================
|
||||
|
||||
@Nested
|
||||
@DisplayName("default.* 템플릿 폴백")
|
||||
class DefaultTemplateFallback {
|
||||
|
||||
private static final String G = TemplateAdapterErrorMsgHandler.PROP_GROUP;
|
||||
|
||||
private PropManager mockPropManager;
|
||||
private AdapterManager mockAdapterManager;
|
||||
private AdapterPropManager mockAdapterPropManager;
|
||||
|
||||
@BeforeEach
|
||||
void setUpDefaults() throws Exception {
|
||||
mockPropManager = Mockito.mock(PropManager.class);
|
||||
mockAdapterManager = Mockito.mock(AdapterManager.class);
|
||||
mockAdapterPropManager = Mockito.mock(AdapterPropManager.class);
|
||||
|
||||
// 명시적으로 stub 하지 않은 모든 키는 미설정(null) 로 간주
|
||||
Mockito.when(mockPropManager.getProperty(anyString(), anyString())).thenReturn(null);
|
||||
Mockito.when(mockPropManager.getProperty(anyString(), anyString(), anyString()))
|
||||
.thenAnswer(invocation -> invocation.getArgument(2));
|
||||
|
||||
AdapterGroupVO adapterGroupVO = Mockito.mock(AdapterGroupVO.class);
|
||||
AdapterVO adapterVO = Mockito.mock(AdapterVO.class);
|
||||
Mockito.when(adapterGroupVO.getMessageType()).thenReturn("JSON");
|
||||
Mockito.when(adapterGroupVO.getMessageEncode()).thenReturn("UTF-8");
|
||||
Mockito.when(adapterVO.getPropGroupName()).thenReturn("TEST_PROP");
|
||||
Mockito.when(adapterVO.getAdapterGroupVO()).thenReturn(adapterGroupVO);
|
||||
Mockito.when(mockAdapterManager.getAdapterGroupVO("MY_GROUP")).thenReturn(adapterGroupVO);
|
||||
Mockito.when(mockAdapterManager.getAdapterVO("MY_GROUP", "MY_ADAPTER")).thenReturn(adapterVO);
|
||||
|
||||
Properties httpProp = new Properties();
|
||||
httpProp.setProperty("ERROR_RESPONSE_FORMAT", "");
|
||||
Mockito.when(mockAdapterPropManager.getProperties("TEST_PROP")).thenReturn(httpProp);
|
||||
|
||||
ApplicationContext mockCtx = Mockito.mock(ApplicationContext.class);
|
||||
Mockito.when(mockCtx.getBean(PropManager.class)).thenReturn(mockPropManager);
|
||||
Mockito.when(mockCtx.getBean(AdapterManager.class)).thenReturn(mockAdapterManager);
|
||||
Mockito.when(mockCtx.getBean(AdapterPropManager.class)).thenReturn(mockAdapterPropManager);
|
||||
Field ctxField = ApplicationContextProvider.class.getDeclaredField("context");
|
||||
ctxField.setAccessible(true);
|
||||
ctxField.set(null, mockCtx);
|
||||
}
|
||||
|
||||
private void prop(String key, String value) {
|
||||
Mockito.when(mockPropManager.getProperty(eq(G), eq(key))).thenReturn(value);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
// generateNonStandardErrorResponseMessage : default.template
|
||||
// ------------------------------------------------------------
|
||||
|
||||
@Nested
|
||||
@DisplayName("generateNonStandardErrorResponseMessage – default.template")
|
||||
class NonStandardError {
|
||||
|
||||
@Test
|
||||
@DisplayName("그룹 템플릿이 있으면 default.template 을 조회하지 않는다")
|
||||
void 그룹_템플릿_우선() throws Exception {
|
||||
prop("MY_GROUP.template", "{\"code\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}");
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E001", "오류", "", null)));
|
||||
|
||||
assertEquals("{\"code\":\"E001\"}", result);
|
||||
Mockito.verify(mockPropManager, Mockito.never()).getProperty(G, "default.template");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("그룹 템플릿 미설정 시 default.template 으로 폴백")
|
||||
void default_폴백() throws Exception {
|
||||
prop("default.template", "{\"code\":\"${MSG.MAIN_MSG.outp_msg_cd}\",\"src\":\"default\"}");
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E777", "오류", "", null)));
|
||||
|
||||
assertEquals("{\"code\":\"E777\",\"src\":\"default\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("그룹 템플릿이 공백 문자열이어도 default.template 으로 폴백")
|
||||
void 공백_템플릿도_폴백() throws Exception {
|
||||
prop("MY_GROUP.template", " ");
|
||||
prop("default.template", "{\"src\":\"default\"}");
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E001", "오류", "", null)));
|
||||
|
||||
assertEquals("{\"src\":\"default\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("그룹/default 둘 다 없으면 기존대로 null 반환")
|
||||
void 둘다_없으면_null() throws Exception {
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E001", "오류", "", null)));
|
||||
|
||||
assertNull(result);
|
||||
// 폴백 조회가 실제로 시도되었는지 확인
|
||||
Mockito.verify(mockPropManager).getProperty(G, "MY_GROUP.template");
|
||||
Mockito.verify(mockPropManager).getProperty(G, "default.template");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("조회 순서: {group}.template → default.template")
|
||||
void 조회_순서() throws Exception {
|
||||
handler.generateNonStandardErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E001", "오류", "", null)));
|
||||
|
||||
InOrder inOrder = Mockito.inOrder(mockPropManager);
|
||||
inOrder.verify(mockPropManager).getProperty(G, "MY_GROUP.template");
|
||||
inOrder.verify(mockPropManager).getProperty(G, "default.template");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("default.template 에서도 callProp/foreach 치환이 동일하게 동작")
|
||||
void default_템플릿_전체_치환() throws Exception {
|
||||
prop("default.template",
|
||||
"{\"adapter\":\"${callprop.ADAPTER_NAME}\"," +
|
||||
"\"code\":\"${MSG.MAIN_MSG.outp_msg_cd}\"," +
|
||||
"\"errors\":[{{#foreach MSG.MSG_LIST}}{\"c\":\"${outp_msg_cd}\"}{{/foreach}}]}");
|
||||
|
||||
Object result = handler.generateNonStandardErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", props("ADAPTER_NAME", "REAL"), null,
|
||||
toEaiMessage(buildMsg("E001", "대표오류", "",
|
||||
new String[][]{{"E001", "오류A", "", ""}, {"E002", "오류B", "", ""}})));
|
||||
|
||||
assertEquals(
|
||||
"{\"adapter\":\"REAL\",\"code\":\"E001\"," +
|
||||
"\"errors\":[{\"c\":\"E001\"},{\"c\":\"E002\"}]}",
|
||||
result);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
// generateNonStandardInternalErrorResponseMessage : default.sys.template
|
||||
// ------------------------------------------------------------
|
||||
|
||||
@Nested
|
||||
@DisplayName("generateNonStandardInternalErrorResponseMessage – default.sys.template")
|
||||
class InternalError {
|
||||
|
||||
@Test
|
||||
@DisplayName("그룹 sys 템플릿이 있으면 default.sys.template 을 조회하지 않는다")
|
||||
void 그룹_템플릿_우선() throws Exception {
|
||||
prop("MY_GROUP.sys.template", "{\"code\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}");
|
||||
|
||||
Object result = handler.generateNonStandardInternalErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E500", "내부오류", "", null)));
|
||||
|
||||
assertEquals("{\"code\":\"E500\"}", result);
|
||||
Mockito.verify(mockPropManager, Mockito.never()).getProperty(G, "default.sys.template");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("그룹 sys 템플릿 미설정 시 default.sys.template 으로 폴백")
|
||||
void default_폴백() throws Exception {
|
||||
prop("default.sys.template",
|
||||
"{\"code\":\"${MSG.MAIN_MSG.outp_msg_cd}\",\"msg\":\"${MSG.MAIN_MSG.outp_msg_ctnt}\"}");
|
||||
|
||||
Object result = handler.generateNonStandardInternalErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E500", "시스템오류", "", null)));
|
||||
|
||||
assertEquals("{\"code\":\"E500\",\"msg\":\"시스템오류\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("내부오류는 default.template 이 아니라 default.sys.template 을 조회한다")
|
||||
void sys_전용_키_사용() throws Exception {
|
||||
// default.template 만 설정된 상태 → 내부오류에는 적용되지 않아야 한다
|
||||
prop("default.template", "{\"src\":\"non-sys\"}");
|
||||
|
||||
Object result = handler.generateNonStandardInternalErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E500", "시스템오류", "", null)));
|
||||
|
||||
assertNull(result);
|
||||
Mockito.verify(mockPropManager).getProperty(G, "default.sys.template");
|
||||
Mockito.verify(mockPropManager, Mockito.never()).getProperty(G, "default.template");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("그룹/default 둘 다 없으면 기존대로 null 반환")
|
||||
void 둘다_없으면_null() throws Exception {
|
||||
Object result = handler.generateNonStandardInternalErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E500", "오류", "", null)));
|
||||
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("조회 순서: {group}.sys.template → default.sys.template")
|
||||
void 조회_순서() throws Exception {
|
||||
handler.generateNonStandardInternalErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E500", "오류", "", null)));
|
||||
|
||||
InOrder inOrder = Mockito.inOrder(mockPropManager);
|
||||
inOrder.verify(mockPropManager).getProperty(G, "MY_GROUP.sys.template");
|
||||
inOrder.verify(mockPropManager).getProperty(G, "default.sys.template");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
// generateOutboundErrorResponseMessage : default.template
|
||||
// ------------------------------------------------------------
|
||||
|
||||
@Nested
|
||||
@DisplayName("generateOutboundErrorResponseMessage – default.template")
|
||||
class OutboundError {
|
||||
|
||||
@Test
|
||||
@DisplayName("그룹 템플릿이 있으면 default.template 을 조회하지 않는다")
|
||||
void 그룹_템플릿_우선() throws Exception {
|
||||
prop("OUT_GROUP.template", "{\"code\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}");
|
||||
|
||||
Object result = handler.generateOutboundErrorResponseMessage(
|
||||
"OUT_GROUP", "OUT_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E001", "오류", "", null)));
|
||||
|
||||
assertEquals("{\"code\":\"E001\"}", result);
|
||||
Mockito.verify(mockPropManager, Mockito.never()).getProperty(G, "default.template");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("그룹 템플릿 미설정 시 default.template 으로 폴백")
|
||||
void default_폴백() throws Exception {
|
||||
prop("default.template", "{\"code\":\"${MSG.MAIN_MSG.outp_msg_cd}\",\"src\":\"default\"}");
|
||||
|
||||
Object result = handler.generateOutboundErrorResponseMessage(
|
||||
"OUT_GROUP", "OUT_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E888", "오류", "", null)));
|
||||
|
||||
assertEquals("{\"code\":\"E888\",\"src\":\"default\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("아웃바운드/인바운드가 동일한 default.template 을 공유한다")
|
||||
void inbound_outbound_default_공유() throws Exception {
|
||||
prop("default.template", "{\"shared\":\"${MSG.MAIN_MSG.outp_msg_cd}\"}");
|
||||
|
||||
Object outbound = handler.generateOutboundErrorResponseMessage(
|
||||
"OUT_GROUP", "OUT_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E001", "오류", "", null)));
|
||||
Object inbound = handler.generateNonStandardErrorResponseMessage(
|
||||
"IN_GROUP", "IN_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E001", "오류", "", null)));
|
||||
|
||||
// 두 경로 모두 같은 키를 쓰므로 결과가 동일하다.
|
||||
// 방향별로 다른 기본 응답이 필요하면 그룹 전용 키를 설정해야 한다.
|
||||
assertEquals("{\"shared\":\"E001\"}", outbound);
|
||||
assertEquals(outbound, inbound);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("그룹/default 둘 다 없으면 기존대로 null 반환")
|
||||
void 둘다_없으면_null() throws Exception {
|
||||
Object result = handler.generateOutboundErrorResponseMessage(
|
||||
"OUT_GROUP", "OUT_ADAPTER", null, null,
|
||||
toEaiMessage(buildMsg("E001", "오류", "", null)));
|
||||
|
||||
assertNull(result);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
// generateNonStandardInboundErrorResponseMessage : default.in.*
|
||||
// ------------------------------------------------------------
|
||||
|
||||
@Nested
|
||||
@DisplayName("generateNonStandardInboundErrorResponseMessage – default.in.*")
|
||||
class InboundError {
|
||||
|
||||
/** 500 으로 매핑되는 일반 예외로 호출한다. */
|
||||
private Object call500(Properties callProp) throws Exception {
|
||||
return handler.generateNonStandardInboundErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", callProp, null, null,
|
||||
new RuntimeException("처리 중 오류"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1순위: {group}.in.{code}.template 이 있으면 그것을 사용")
|
||||
void 그룹_코드별_템플릿_우선() throws Exception {
|
||||
prop("MY_GROUP.in.500.template", "{\"src\":\"group-code\"}");
|
||||
prop("default.in.500.template", "{\"src\":\"default-code\"}");
|
||||
prop("MY_GROUP.in.template", "{\"src\":\"group-common\"}");
|
||||
prop("default.in.template", "{\"src\":\"default-common\"}");
|
||||
|
||||
assertEquals("{\"src\":\"group-code\"}", call500(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2순위: {group}.in.{code} 가 없으면 default.in.{code}.template 사용")
|
||||
void default_코드별_템플릿() throws Exception {
|
||||
prop("default.in.500.template", "{\"src\":\"default-code\"}");
|
||||
prop("MY_GROUP.in.template", "{\"src\":\"group-common\"}");
|
||||
prop("default.in.template", "{\"src\":\"default-common\"}");
|
||||
|
||||
// 주의: 현재 구현은 코드별 default 가 그룹 공통보다 우선한다.
|
||||
assertEquals("{\"src\":\"default-code\"}", call500(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3순위: 코드별 키가 모두 없으면 {group}.in.template 사용")
|
||||
void 그룹_공통_템플릿() throws Exception {
|
||||
prop("MY_GROUP.in.template", "{\"src\":\"group-common\"}");
|
||||
prop("default.in.template", "{\"src\":\"default-common\"}");
|
||||
|
||||
assertEquals("{\"src\":\"group-common\"}", call500(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("4순위: 앞의 3개가 모두 없으면 default.in.template 사용")
|
||||
void default_공통_템플릿() throws Exception {
|
||||
prop("default.in.template", "{\"src\":\"default-common\"}");
|
||||
|
||||
assertEquals("{\"src\":\"default-common\"}", call500(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("4개 키가 모두 없으면 MessageUtil 폴백")
|
||||
void 전부_없으면_MessageUtil_폴백() throws Exception {
|
||||
Object result = call500(null);
|
||||
|
||||
assertNotNull(result);
|
||||
Mockito.verify(mockPropManager).getProperty(G, "MY_GROUP.in.500.template");
|
||||
Mockito.verify(mockPropManager).getProperty(G, "default.in.500.template");
|
||||
Mockito.verify(mockPropManager).getProperty(G, "MY_GROUP.in.template");
|
||||
Mockito.verify(mockPropManager).getProperty(G, "default.in.template");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("조회 순서: group.code → default.code → group.common → default.common")
|
||||
void 조회_순서_4단계() throws Exception {
|
||||
handler.generateNonStandardInboundErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null, null,
|
||||
new HttpStatusException("Service Unavailable", 503));
|
||||
|
||||
InOrder inOrder = Mockito.inOrder(mockPropManager);
|
||||
inOrder.verify(mockPropManager).getProperty(G, "MY_GROUP.in.503.template");
|
||||
inOrder.verify(mockPropManager).getProperty(G, "default.in.503.template");
|
||||
inOrder.verify(mockPropManager).getProperty(G, "MY_GROUP.in.template");
|
||||
inOrder.verify(mockPropManager).getProperty(G, "default.in.template");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("코드별 default 키 형식은 'default.in.{code}.template' (점 누락 회귀 방지)")
|
||||
void default_코드별_키_형식_검증() throws Exception {
|
||||
handler.generateNonStandardInboundErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null, null,
|
||||
new HttpStatusException("Bad Request", 400));
|
||||
|
||||
Mockito.verify(mockPropManager).getProperty(G, "default.in.400.template");
|
||||
// 점이 빠진 잘못된 키로 조회하지 않아야 한다
|
||||
Mockito.verify(mockPropManager, Mockito.never()).getProperty(G, "default.in400.template");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("JwtAuthException 은 default.in.401.template 로 폴백")
|
||||
void jwt_401_default_폴백() throws Exception {
|
||||
prop("default.in.401.template", "{\"code\":\"${exception.code}\",\"msg\":\"${exception.message}\"}");
|
||||
|
||||
Object result = handler.generateNonStandardInboundErrorResponseMessage(
|
||||
"MY_GROUP", "MY_ADAPTER", null, null, null,
|
||||
new JwtAuthException("JWT_EXPIRED", "토큰이 만료되었습니다"));
|
||||
|
||||
assertEquals("{\"code\":\"JWT_EXPIRED\",\"msg\":\"토큰이 만료되었습니다\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("default.in.template 에서 exception/callProp 치환이 동일하게 동작")
|
||||
void default_공통_템플릿_치환() throws Exception {
|
||||
prop("default.in.template",
|
||||
"{\"adapter\":\"${callprop.ADAPTER_NAME}\",\"msg\":\"${exception.message}\"}");
|
||||
|
||||
Object result = call500(props("ADAPTER_NAME", "REAL"));
|
||||
|
||||
assertEquals("{\"adapter\":\"REAL\",\"msg\":\"처리 중 오류\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("default.in.template 에 ${callprop[경로]} 를 써도 msg=null 로 NPE 없이 기본값 반환")
|
||||
void default_공통_템플릿_간접참조_NPE_회귀방지() throws Exception {
|
||||
// 인바운드 경로는 render(template, null, ...) 로 호출되므로
|
||||
// 간접 참조의 표준전문 경로 조회 대상이 없다 → 기본값으로 처리되어야 한다.
|
||||
prop("default.in.template", "{\"key\":\"${callprop[MSG.cp_key]:NO_MSG}\"}");
|
||||
|
||||
Object result = call500(props("ADAPTER_NAME", "REAL"));
|
||||
|
||||
assertEquals("{\"key\":\"NO_MSG\"}", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("그룹 코드별 템플릿이 공백이면 default 로 폴백")
|
||||
void 공백_템플릿도_폴백() throws Exception {
|
||||
prop("MY_GROUP.in.500.template", " ");
|
||||
prop("default.in.500.template", "{\"src\":\"default-code\"}");
|
||||
|
||||
assertEquals("{\"src\":\"default-code\"}", call500(null));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+319
@@ -0,0 +1,319 @@
|
||||
package com.eactive.eai.adapter.http.dynamic.filter;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.json.simple.JSONObject;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.context.support.GenericApplicationContext;
|
||||
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* JsonToSetStatusFilter 단위 테스트.
|
||||
*
|
||||
* 상태코드 필드명은 PropManager(그룹: JsonToSetStatusFilter, 키: 어댑터그룹명)에서 조회하므로
|
||||
* PropManager 를 Mock 으로 등록하고 필터 로직만 검증한다.
|
||||
*
|
||||
* 4번 그룹은 "현재 구현의 동작을 그대로 고정(characterization)"한 테스트로,
|
||||
* 개선 여부 판단용이다. 구현을 보완하면 해당 테스트도 함께 수정해야 한다.
|
||||
*/
|
||||
@TestMethodOrder(MethodOrderer.DisplayName.class)
|
||||
class JsonToSetStatusFilterTest {
|
||||
|
||||
private static final String GRP = "TEST_GRP";
|
||||
private static final String ADPT = "TEST_ADPT";
|
||||
private static final String FIELD = "apiRsltCd";
|
||||
private static final String PROP_GROUP = "JsonToSetStatusFilter";
|
||||
|
||||
private static GenericApplicationContext ctx;
|
||||
private static PropManager mockPropManager;
|
||||
private static JsonToSetStatusFilter filter;
|
||||
|
||||
private HttpServletRequest mockRequest;
|
||||
private HttpServletResponse mockResponse;
|
||||
private Properties prop;
|
||||
|
||||
@BeforeAll
|
||||
static void setUpClass() {
|
||||
mockPropManager = mock(PropManager.class);
|
||||
|
||||
ctx = new GenericApplicationContext();
|
||||
ctx.getBeanFactory().registerSingleton("propManager", mockPropManager);
|
||||
ctx.registerBeanDefinition("applicationContextProvider",
|
||||
BeanDefinitionBuilder.genericBeanDefinition(ApplicationContextProvider.class)
|
||||
.getBeanDefinition());
|
||||
ctx.refresh();
|
||||
|
||||
filter = new JsonToSetStatusFilter();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void tearDownClass() {
|
||||
if (ctx != null) ctx.close();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
reset(mockPropManager);
|
||||
mockRequest = mock(HttpServletRequest.class);
|
||||
mockResponse = mock(HttpServletResponse.class);
|
||||
prop = new Properties();
|
||||
|
||||
when(mockPropManager.getProperty(PROP_GROUP, GRP)).thenReturn(FIELD);
|
||||
}
|
||||
|
||||
private String body(String rsltCd) {
|
||||
return "{\"" + FIELD + "\":\"" + rsltCd + "\",\"msg\":\"OK\"}";
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 1. 상태코드 정상 반영
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("1-1. 문자열 body의 상태코드 필드값을 HTTP 상태코드로 설정한다")
|
||||
void testPostFilter_string_setsStatus() throws Exception {
|
||||
Object result = filter.doPostFilter(GRP, ADPT, body("404"), prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse).setStatus(404);
|
||||
assertEquals(body("404"), result, "원 메시지를 그대로 반환해야 한다");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-2. 숫자 타입 필드값도 상태코드로 설정한다")
|
||||
void testPostFilter_numericNode_setsStatus() throws Exception {
|
||||
filter.doPostFilter(GRP, ADPT, "{\"" + FIELD + "\":503}", prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse).setStatus(503);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-3. 업무팀 주 사용 케이스 - 2xx 상태코드를 설정한다")
|
||||
void testPostFilter_successStatusCodes() throws Exception {
|
||||
for (int status : new int[] { 200, 201, 202, 204 }) {
|
||||
reset(mockResponse);
|
||||
|
||||
filter.doPostFilter(GRP, ADPT, body(String.valueOf(status)), prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse).setStatus(status);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-4. 어댑터 그룹마다 다른 필드명을 사용할 수 있다")
|
||||
void testPostFilter_perGroupFieldName() throws Exception {
|
||||
when(mockPropManager.getProperty(PROP_GROUP, GRP)).thenReturn("rspCd");
|
||||
|
||||
filter.doPostFilter(GRP, ADPT, "{\"rspCd\":\"403\",\"" + FIELD + "\":\"500\"}", prop,
|
||||
mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse).setStatus(403);
|
||||
verify(mockResponse, never()).setStatus(500);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-5. JSONObject 타입 응답도 처리한다")
|
||||
void testPostFilter_jsonObjectMessage_setsStatus() throws Exception {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put(FIELD, "404");
|
||||
|
||||
Object result = filter.doPostFilter(GRP, ADPT, json, prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse).setStatus(404);
|
||||
assertSame(json, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-6. JsonNode 타입 응답도 처리한다")
|
||||
void testPostFilter_jsonNodeMessage_setsStatus() throws Exception {
|
||||
JsonNode node = new ObjectMapper().readTree(body("401"));
|
||||
|
||||
Object result = filter.doPostFilter(GRP, ADPT, node, prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse).setStatus(401);
|
||||
assertSame(node, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("1-7. 경계값 100 / 599는 설정한다")
|
||||
void testPostFilter_boundaryValues() throws Exception {
|
||||
filter.doPostFilter(GRP, ADPT, body("100"), prop, mockRequest, mockResponse);
|
||||
verify(mockResponse).setStatus(100);
|
||||
|
||||
reset(mockResponse);
|
||||
filter.doPostFilter(GRP, ADPT, body("599"), prop, mockRequest, mockResponse);
|
||||
verify(mockResponse).setStatus(599);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 2. 상태코드를 변경하지 않는 경우
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("2-1. 상태코드 필드가 없으면 setStatus를 호출하지 않는다")
|
||||
void testPostFilter_fieldAbsent_noStatusChange() throws Exception {
|
||||
filter.doPostFilter(GRP, ADPT, "{\"msg\":\"OK\"}", prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-2. 상태코드 필드값이 빈 문자열이면 setStatus를 호출하지 않는다")
|
||||
void testPostFilter_emptyValue_noStatusChange() throws Exception {
|
||||
filter.doPostFilter(GRP, ADPT, body(""), prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-3. 프로퍼티에 필드명 설정이 없으면(null) 예외 없이 통과한다")
|
||||
void testPostFilter_noConfiguredField_noStatusChange() throws Exception {
|
||||
when(mockPropManager.getProperty(PROP_GROUP, GRP)).thenReturn(null);
|
||||
|
||||
Object result = filter.doPostFilter(GRP, ADPT, body("404"), prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
assertEquals(body("404"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-4. 상태코드 필드값이 숫자가 아니면 로그만 남기고 상태코드를 변경하지 않는다")
|
||||
void testPostFilter_nonNumericValue_noStatusChange() throws Exception {
|
||||
Object result = filter.doPostFilter(GRP, ADPT, body("E0001"), prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
assertEquals(body("E0001"), result, "파싱 실패해도 원 메시지는 그대로 반환되어야 한다");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-5. 업무결과코드 0000은 유효한 상태코드가 아니므로 설정하지 않는다")
|
||||
void testPostFilter_businessCode0000_noStatusChange() throws Exception {
|
||||
filter.doPostFilter(GRP, ADPT, body("0000"), prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-6. HTTP 상태코드 범위(100~599)를 벗어난 값은 설정하지 않는다")
|
||||
void testPostFilter_outOfRangeStatus_noStatusChange() throws Exception {
|
||||
for (String value : new String[] { "0", "99", "600", "9999", "-200" }) {
|
||||
reset(mockResponse);
|
||||
|
||||
filter.doPostFilter(GRP, ADPT, body(value), prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-7. JSON 배열 응답이면 상태코드를 변경하지 않는다")
|
||||
void testPostFilter_jsonArray_noStatusChange() throws Exception {
|
||||
filter.doPostFilter(GRP, ADPT, "[{\"" + FIELD + "\":\"404\"}]", prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2-8. 필드값이 JSON null이면 상태코드를 변경하지 않는다")
|
||||
void testPostFilter_jsonNullValue_noStatusChange() throws Exception {
|
||||
filter.doPostFilter(GRP, ADPT, "{\"" + FIELD + "\":null}", prop, mockRequest, mockResponse);
|
||||
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 3. 비정상 입력에서도 예외를 던지지 않는다 (거래 실패 방지)
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("3-1. JSON 형식이 아닌 응답이어도 예외 없이 통과한다")
|
||||
void testPostFilter_nonJsonBody_noException() throws Exception {
|
||||
String xml = "<xml><rslt>0000</rslt></xml>";
|
||||
|
||||
Object result = assertDoesNotThrow(
|
||||
() -> filter.doPostFilter(GRP, ADPT, xml, prop, mockRequest, mockResponse));
|
||||
|
||||
assertSame(xml, result);
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3-2. 깨진 JSON 응답이어도 예외 없이 통과한다")
|
||||
void testPostFilter_malformedJson_noException() {
|
||||
String broken = "{\"" + FIELD + "\":\"404\"";
|
||||
|
||||
assertDoesNotThrow(() -> filter.doPostFilter(GRP, ADPT, broken, prop, mockRequest, mockResponse));
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3-3. null 응답이어도 예외 없이 null을 그대로 반환한다")
|
||||
void testPostFilter_nullMessage_noException() {
|
||||
Object result = assertDoesNotThrow(
|
||||
() -> filter.doPostFilter(GRP, ADPT, null, prop, mockRequest, mockResponse));
|
||||
|
||||
assertNull(result);
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3-4. 빈 문자열 응답이어도 예외 없이 통과한다")
|
||||
void testPostFilter_emptyBody_noException() {
|
||||
assertDoesNotThrow(() -> filter.doPostFilter(GRP, ADPT, "", prop, mockRequest, mockResponse));
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("3-5. 프로퍼티 그룹 미등록(PropManager가 null 반환)이어도 예외 없이 통과한다")
|
||||
void testPostFilter_propGroupMissing_noException() {
|
||||
when(mockPropManager.getProperty(anyString(), anyString())).thenReturn(null);
|
||||
|
||||
assertDoesNotThrow(() -> filter.doPostFilter(GRP, ADPT, body("404"), prop, mockRequest, mockResponse));
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 4. doPreFilter / 현재 동작 고정 (개선 검토 대상)
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
@DisplayName("4-1. doPreFilter는 아무 것도 하지 않고 요청 메시지를 그대로 반환한다")
|
||||
void testPreFilter_doesNothing() throws Exception {
|
||||
String message = body("404");
|
||||
|
||||
Object result = filter.doPreFilter(GRP, ADPT, message, prop, mockRequest, mockResponse);
|
||||
|
||||
assertSame(message, result);
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
verifyNoInteractions(mockPropManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("4-2. [확인필요] byte[] 응답은 JSON으로 파싱되지 않아 상태코드가 설정되지 않는다")
|
||||
void testPostFilter_byteArray_notSupported() throws Exception {
|
||||
byte[] msg = body("404").getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
Object result = filter.doPostFilter(GRP, ADPT, msg, prop, mockRequest, mockResponse);
|
||||
|
||||
// JsonPathUtil.toTree 가 byte[] 를 toString() 처리하므로 "[B@..." 가 되어 파싱에 실패한다.
|
||||
verify(mockResponse, never()).setStatus(anyInt());
|
||||
assertSame(msg, result);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user