diff --git a/src/main/java/com/eactive/eai/adapter/service/DJBApiAdapterService.java b/src/main/java/com/eactive/eai/adapter/service/DJBApiAdapterService.java index c9e1e39..8e27f86 100644 --- a/src/main/java/com/eactive/eai/adapter/service/DJBApiAdapterService.java +++ b/src/main/java/com/eactive/eai/adapter/service/DJBApiAdapterService.java @@ -2,7 +2,9 @@ package com.eactive.eai.adapter.service; import java.io.IOException; import java.io.StringWriter; +import java.io.UnsupportedEncodingException; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; @@ -10,6 +12,7 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Properties; import javax.servlet.ServletInputStream; @@ -18,6 +21,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.StopWatch; +import org.apache.hc.core5.http.ContentType; import org.apache.mina.common.ByteBuffer; import org.dom4j.Document; import org.dom4j.DocumentException; @@ -28,7 +32,7 @@ import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.json.simple.JSONValue; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.util.AntPathMatcher; @@ -40,10 +44,13 @@ import com.eactive.eai.adapter.http.HttpMemoryLogger; import com.eactive.eai.adapter.http.HttpMethodType; import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport; import com.eactive.eai.adapter.http.dynamic.filter.ApiKeyExtractFilter; +import com.eactive.eai.adapter.http.dynamic.filter.FilterException; +import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter; import com.eactive.eai.adapter.http.filter.AbstractCryptoFilter; import com.eactive.eai.common.context.ElinkTransactionContext; import com.eactive.eai.common.exception.ExceptionUtil; import com.eactive.eai.common.message.MessageType; +import com.eactive.eai.common.stdmessage.STDMessageManager; import com.eactive.eai.common.util.CommonLib; import com.eactive.eai.common.util.JacksonUtil; import com.eactive.eai.common.util.Logger; @@ -52,8 +59,9 @@ import com.eactive.eai.common.util.XMLUtils; import com.eactive.eai.inbound.action.ActionFactory; import com.eactive.eai.inbound.action.RequestAction; import com.eactive.eai.inbound.processor.Processor; -import com.eactive.eai.message.StandardMessageUtil; -import com.eactive.eai.util.JsonPathUtil; +import com.eactive.eai.message.StandardMessage; +import com.eactive.eai.message.manager.StandardMessageManager; +import com.eactive.eai.util.QueryStringUtils; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -61,6 +69,11 @@ import com.fasterxml.jackson.databind.node.ObjectNode; @Service public class DJBApiAdapterService extends HttpAdapterServiceSupport { + + public static final String STD_MESSAGE_KEY = "STD_MESSAGE_KEY"; + public static final String FINAL_STD_MESSAGE_KEY = "FINAL_STD_MESSAGE_KEY"; + public static final String API_SERVICE_CODE = "API_SERVICE_CODE"; + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER); @@ -90,7 +103,6 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport { String relayRequestHeaderKeys = httpProp.getProperty(HEADER_KEYS); String headerGroupName = httpProp.getProperty(HEADER_GROUP); - boolean isParameterType = false; String message = null; String paramValue = null; @@ -126,12 +138,6 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport { transactionProp.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, "")); transactionProp.put("BLOCK_IP", httpProp.getProperty("BLOCK_IP", "")); - //djerp bypass - Map pathVariables = assignPathVariables(request, adptGrpName, adptName, null, transactionProp); - if (pathVariables != null) { - transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables); - } - transactionProp.put(ENC_PATHS, httpProp.getProperty(ENC_PATHS, "")); transactionProp.put(ENCRYPT_ALGORITHM, httpProp.getProperty(ENCRYPT_ALGORITHM, "")); //jwhong @@ -170,74 +176,8 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport { 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 paramMap = assignParameterMap(request, adptGrpName, adptName, null, transactionProp); - int i = 0; - for (Map.Entry 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) { + String recvBody = ""; + if (request.getContentLength() > 0) { ServletInputStream sis = request.getInputStream(); ByteBuffer bb = ByteBuffer.allocate(1024).setAutoExpand(true); int i = 0; @@ -257,43 +197,68 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport { String bodyEncode = encode; String contentTypeHeader = request.getContentType(); if (StringUtils.isNotBlank(contentTypeHeader)) { - try { - MediaType mediaType = MediaType.parseMediaType(contentTypeHeader); - if (mediaType.getCharset() != null) { - bodyEncode = mediaType.getCharset().name(); + try { + MediaType mediaType = MediaType.parseMediaType(contentTypeHeader); + if (mediaType.getCharset() != null) { + bodyEncode = mediaType.getCharset().name(); + } + } catch (Exception ignored) { } - } catch (Exception ignored) {} } - paramValue = new String(data, bodyEncode); + recvBody = new String(data, bodyEncode); if (traceLevel >= 3) { HttpMemoryLogger.txlog(adptGrpName + adptName, - "RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(data)); + "RECV " + "[" + recvBody + "]" + CommonLib.getDumpMessage(data)); } if (logger.isDebug()) { - logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n" + logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + recvBody + "]\n" + CommonLib.getDumpMessage(data)); } - } + } + // 순수한 Body값을 저장을 위해 위치 변경. + transactionProp.put(INBOUND_REQUEST_MESSAGE, recvBody); + + // 요청 URL 에서 서비스키(STD_MESSAGE_KEY/FINAL_STD_MESSAGE_KEY/API_SERVICE_CODE)를 확정한다. + assignApiKeys(adptGrpName, adptName, transactionProp.get(INBOUND_REQUEST_MESSAGE), transactionProp); + + // 확정된 서비스키로 PathVariable 을 추출한다. djerp bypass 의 Outbound URL 치환에도 사용된다. + Map pathVariables = extractPathVariables(transactionProp.getProperty(STD_MESSAGE_KEY), + transactionProp.getProperty(FINAL_STD_MESSAGE_KEY)); + transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables); + + + boolean isParameterType = isParameterType(HttpMethodType.getValue(request.getMethod()), + request.getContentType()); + if (isParameterType) { + Map paramMap = assignParameterMap(request, adptGrpName, adptName, recvBody, + transactionProp, urlDecodeYn, pathVariables); + boolean bUrlDecode = "Y".equals(urlDecodeYn); + paramValue = QueryStringUtils.makeJson(paramMap, bUrlDecode); + + if (logger.isDebug()) { + logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]"); + } + } else { + Map paramMap = convertArrayStringValue(pathVariables); + boolean bUrlDecode = "Y".equals(urlDecodeYn); + paramValue = mergeParamsToJsonBody(recvBody, paramMap, bUrlDecode); } 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 { +// if ("Y".equals(urlDecodeYn) && isParameterType) { +// message = URLDecoder.decode(paramValue); +// } else { message = paramValue; - } +// } TxFileLogger.logTxFile(transactionProp, message, "[IN_RECV]"); @@ -314,9 +279,6 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport { // 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동. // transactionProp.put(INBOUND_REQUEST_MESSAGE, message); - ApiKeyExtractFilter apiKeyExtractor = new ApiKeyExtractFilter(); - apiKeyExtractor.doPreFilter(adptGrpName, adptName, transactionProp.get(INBOUND_REQUEST_MESSAGE), transactionProp, request, response); - Object result = service(adptGrpName, adptName, reqObject, transactionProp, request, response); // bypass만 필요 @@ -612,71 +574,231 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport { return (String)resultMessage; } + + public static boolean isParameterType(HttpMethodType method, String contentType) { + boolean isParameterType = true; + switch (method) { + case GET: + case DELETE: + isParameterType = true; + break; + case POST: + case PUT: + case PATCH: + if (StringUtils.contains(contentType, "application/x-www-form-urlencoded")) { + isParameterType = true; + } else { + isParameterType = false; + } + break; + default: + break; + } + return isParameterType; + } + + private Map assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName, + Object reqMessage, Properties prop, String urlDecode, Map variablesMap) throws UnsupportedEncodingException { + Map pathMap = convertArrayStringValue(variablesMap); + + // param encoding 추가 + String encoding = null; + String reqContentType = request.getContentType(); + try { + ContentType oContentType = ContentType.parse(reqContentType); + if (oContentType != null && oContentType.getCharset() != null) + encoding = oContentType.getCharset().displayName(); + } catch (Exception e) { + // 지원하지 않는 charset(UnsupportedCharsetException)이 헤더로 들어와도 500 이 나가지 않도록 한다. + logger.warn("HttpAdapterServiceRest] invalid Content-Type charset. [" + reqContentType + "]"); + } - private Map 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]; + boolean bUrlDecode = StringUtils.equalsIgnoreCase(urlDecode, "Y"); + if (encoding == null) { + // Content-Type 에 charset 이 없을 때(GET 등)의 기본값은 처리 경로에 따라 다르다. + // - %인코딩 복원(URLDecoder) : HTML5/WHATWG 표준이 UTF-8 이므로 UTF-8. + // ISO-8859-1 로 복원하면 %ED%95%9C%EA%B8%80 이 '한글' 로 깨진다. + // - 그 외 : 컨테이너가 디코딩한 문자열의 원본 바이트를 되찾는 용도(byte latch)이므로 + // 기존 동작인 ISO-8859-1 을 유지한다. + encoding = bUrlDecode ? StandardCharsets.UTF_8.name() : "ISO-8859-1"; + } - // PathVariable 지원 추가 - String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName); - if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) { - Map paramMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath, - requestPath); - if (paramMap != null && paramMap.size() > 0) { - Map returnMap = new HashMap<>(); - for (String key : paramMap.keySet()) { - if (StringUtils.equalsIgnoreCase(key, "method")) { - continue; - } - returnMap.put(key, new String[] { paramMap.get(key) }); - } + // POST 방식의 form data + if (reqMessage instanceof String) { + String formData = (String) reqMessage; + Map formDataParamMap = QueryStringUtils.parseQueryString(formData, encoding, bUrlDecode); + pathMap.putAll(formDataParamMap); + } - return returnMap; - } - } - } catch (Exception e) { - logger.error(e.getMessage()); - } - } + // GET 방식의 query string + String queryString = request.getQueryString(); + Map paramMap = QueryStringUtils.parseQueryString(queryString, encoding, bUrlDecode); + pathMap.putAll(paramMap); - return request.getParameterMap(); - } + return pathMap; + } + + + private Map convertArrayStringValue(Map variablesMap) { + Map pathMap = new HashMap<>(); + + for (String key : variablesMap.keySet()) { + if (StringUtils.equalsIgnoreCase(key, "method")) { + continue; + } + pathMap.put(key, new String[] { variablesMap.get(key) }); + } + return pathMap; + } + + + /** + * JSON Body 요청에 PathVariable(및 추가 파라미터)을 병합한다. + * + *
    + *
  • 추가할 파라미터가 없으면 Body 를 그대로 반환한다.
  • + *
  • Body 가 비어있으면 파라미터만으로 JSON 오브젝트를 만든다.
  • + *
  • Body 가 JSON 오브젝트({...})면 항목을 추가한다. 빈 오브젝트({})도 유효한 JSON 으로 병합한다.
  • + *
  • XML / JSON 배열 등 오브젝트가 아닌 Body 는 훼손하지 않고 그대로 반환한다. + * (PathVariable 은 INBOUND_PATH_VARIABLES 로 Outbound 에 전달된다)
  • + *
+ */ + private String mergeParamsToJsonBody(String body, Map paramMap, boolean bUrlDecode) + throws UnsupportedEncodingException { + if (paramMap == null || paramMap.isEmpty()) { + return body; + } + + StringBuilder addJson = new StringBuilder(); + for (Entry entry : paramMap.entrySet()) { + if (addJson.length() > 0) + addJson.append(","); + + addJson.append("\"").append(JSONValue.escape(entry.getKey())).append("\":"); + + String[] values = entry.getValue(); + if (values.length > 1) { + addJson.append("["); + for (int j = 0; j < values.length; j++) { + if (j > 0) { + addJson.append(","); + } + addJson.append("\"").append(JSONValue.escape(decodeParamValue(values[j], bUrlDecode))).append("\""); + } + addJson.append("]"); + } else { + addJson.append("\"").append(JSONValue.escape(decodeParamValue(values[0], bUrlDecode))).append("\""); + } + } + + String trimmedBody = StringUtils.trimToEmpty(body); + if (trimmedBody.isEmpty()) { + return "{" + addJson + "}"; + } + + if (!StringUtils.startsWith(trimmedBody, "{") || !StringUtils.endsWith(trimmedBody, "}")) { + // JSON 오브젝트가 아니면 Body 를 덮어쓰지 않는다. + logger.warn("HttpAdapterServiceRest] body is not a JSON object. skip pathVariable merge."); + return body; + } + + String innerBody = StringUtils.substring(trimmedBody, 1, trimmedBody.length() - 1); + String mergedJson; + if (StringUtils.isBlank(innerBody)) { + mergedJson = "{" + addJson + "}"; + } else { + mergedJson = "{" + innerBody + "," + addJson + "}"; + } + logger.debug("HttpAdapterServiceRest] add pathVariable : JSON =[" + mergedJson + "] "); + return mergedJson; + } + + private String decodeParamValue(String value, boolean bUrlDecode) throws UnsupportedEncodingException { + return bUrlDecode ? URLDecoder.decode(value, StandardCharsets.UTF_8.name()) : value; + } private String getRewritePath(String extUri, String basePath) { return StringUtils.removeStart(extUri, StringUtils.removeEnd(basePath, "/")); } - private Map assignPathVariables(HttpServletRequest request, String adptGrpName, String adptName, - Object requestBytes, Properties prop) { - Map variablesMap = null; - // QueryString 있을때는 체크(X) - if (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]; + /** + * 요청 URL 로부터 서비스키를 확정해 tx prop 에 세팅한다. + * (기존 {@link ApiKeyExtractFilter#doPreFilter} 가 하던 일) + * + *
    + *
  • {@code STD_MESSAGE_KEY} : Action 이 만들어낸 요청 경로 (ex. {@code GET/api/v1/users/123})
  • + *
  • {@code FINAL_STD_MESSAGE_KEY} : 등록된 서비스키 (ex. {@code GET/api/v1/users/{userId}})
  • + *
  • {@code API_SERVICE_CODE} : 서비스키에 매핑된 EAI 서비스 코드
  • + *
+ * + *

기존에는 이 필터와 PathVariable 추출이 각각 Action 을 생성해 {@code perform()} 을 호출하고 + * 서비스키 매칭까지 중복 수행했다. Action 호출은 요청 1건당 한 번이면 충분하므로 여기서만 수행하고, + * PathVariable 추출은 여기서 확정한 서비스키를 {@link #extractPathVariables(String, String)} 에 + * 넘겨 처리한다. + */ + private void assignApiKeys(String adptGrpName, String adptName, Object reqMessage, Properties prop) + throws Exception { + String actionName = prop.getProperty(Processor.REQUEST_ACTION); + RequestAction action = ActionFactory.createAction(actionName); + action.setAdapterInfo(adptGrpName, adptName, prop); + String[] keys = action.perform(reqMessage); + String requestPath = keys[0]; - // PathVariable 지원 추가 - String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName); - if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) { - variablesMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath, requestPath); - } - } catch (Exception e) { - logger.error(e.getMessage()); - } + prop.setProperty(STD_MESSAGE_KEY, requestPath); // action class 통해서 생성 + + // PathVariable 지원 추가 + // ex) /api/bank/account/12345 --> /api/bank/account/{accountNo} + String ruledPath = ApiKeyExtractFilter.getMatchedKey(requestPath); + if (StringUtils.isBlank(ruledPath)) { + throw new FilterException("path not found - " + requestPath, HttpAdapterFilter.ERROR_PRE_FAIL, + HttpStatus.FORBIDDEN.value()); + } + prop.setProperty(FINAL_STD_MESSAGE_KEY, ruledPath); + + String apiSvcCode = getEaiSvcCode(ruledPath); + if (StringUtils.isBlank(apiSvcCode)) { + // Properties 는 null 값을 허용하지 않아 그대로 put 하면 NPE 로 500 이 나간다. + logger.warn("HttpAdapterServiceRest] eaiSvcCode not found. apiId=[" + ruledPath + "]"); + } + prop.put(API_SERVICE_CODE, StringUtils.defaultString(apiSvcCode)); + } + + private String getEaiSvcCode(String apiId) { + StandardMessage standardMessage = STDMessageManager.getInstance().getSTDMessage(apiId); + return StandardMessageManager.getInstance().getMapper().getEaiSvcCode(standardMessage); + } + + /** + * 요청 경로와 매칭된 서비스키를 비교해 PathVariable 을 추출한다. + * ex) {@code GET/api/v1/users/123} + {@code GET/api/v1/users/{userId}} → {@code {userId=123}} + * + *

QueryString 유무와 무관하게 추출한다. Outbound(HttpClient5AdapterServiceRest/Bypass)의 + * URL 치환에 사용되므로 QueryString 이 있다고 건너뛰면 치환이 불가하거나 NPE 가 발생한다. + * + * @param requestPath 실제 요청 경로 ({@code STD_MESSAGE_KEY}) + * @param ruledPath 매칭된 서비스키 ({@code FINAL_STD_MESSAGE_KEY}) + * @return PathVariable Map. 없으면 빈 Map (null 아님) + */ + private Map extractPathVariables(String requestPath, String ruledPath) { + Map pathMap = new HashMap<>(); + + if (StringUtils.equals(requestPath, ruledPath) || !StringUtils.contains(ruledPath, "{")) { + return pathMap; } - return variablesMap; + Map variablesMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath, requestPath); + if (variablesMap == null) { + return pathMap; + } + + for (Entry entry : variablesMap.entrySet()) { + // {method} 는 서비스키를 구성하는 요소일 뿐 업무 파라미터가 아니다. + if (StringUtils.equalsIgnoreCase(entry.getKey(), "method")) { + continue; + } + pathMap.put(entry.getKey(), entry.getValue()); + } + return pathMap; } private Properties getHeaders(HttpServletRequest request) { @@ -746,34 +868,4 @@ public class DJBApiAdapterService extends HttpAdapterServiceSupport { return ipAddress; } - private String assignApiId(String adptGrpName, String adptName, Object message, Properties prop, - HttpServletRequest request) { - String apiId = null; - try { - String actionName = prop.getProperty(Processor.REQUEST_ACTION); - RequestAction action = ActionFactory.createAction(actionName); - action.setAdapterInfo(adptGrpName, adptName, prop); - String[] keys = action.perform(message); - apiId = keys[0]; - - // PathVariable 지원 추가 - apiId = StandardMessageUtil.getMatchedKey(apiId, actionName); - } catch (Exception e) { - logger.error(e.getMessage()); - } - -// // header 에서 확보 -// String apiId = request.getHeader(HEADER_NAME_API_CODE); -// if (StringUtils.isBlank(apiId)) { -// // url에서 확보 -// // /ONLWeb/api/v1/public/getUserInfo.svc/ -// apiId = request.getRequestURI(); -// // /ONLWeb/api/v1/public/getUserInfo.svc -// apiId = StringUtils.removeEnd(apiId, "/"); -// // getUserInfo.svc -// apiId = StringUtils.substringAfterLast(apiId, "/"); -// } - - return apiId; - } } diff --git a/src/test/java/com/eactive/eai/adapter/service/DJBApiAdapterServiceTest.java b/src/test/java/com/eactive/eai/adapter/service/DJBApiAdapterServiceTest.java new file mode 100644 index 0000000..527be79 --- /dev/null +++ b/src/test/java/com/eactive/eai/adapter/service/DJBApiAdapterServiceTest.java @@ -0,0 +1,694 @@ +package com.eactive.eai.adapter.service; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang3.StringUtils; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.springframework.http.HttpStatus; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.util.AntPathMatcher; + +import com.eactive.eai.adapter.AdapterGroupVO; +import com.eactive.eai.adapter.AdapterVO; +import com.eactive.eai.adapter.Keys; +import com.eactive.eai.adapter.http.HttpMethodType; +import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey; +import com.eactive.eai.adapter.http.dynamic.filter.FilterException; +import com.eactive.eai.common.errorcode.ErrorCodeManager; +import com.eactive.eai.common.message.MessageType; +import com.eactive.eai.common.stdmessage.STDMessageManager; +import com.eactive.eai.common.util.ApplicationContextProvider; +import com.eactive.eai.inbound.action.ActionException; +import com.eactive.eai.inbound.action.RequestAction; +import com.eactive.eai.inbound.processor.Processor; +import com.eactive.eai.message.StandardMessage; +import com.eactive.eai.message.manager.StandardMessageManager; +import com.eactive.eai.message.service.InterfaceMapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * DJBApiAdapterService : Parameter(QueryString/FormData) + PathVariable 동시 처리 검증 + * + *

검증 대상 (2026-08 수정분) + *

    + *
  • {@code isParameterType(HttpMethodType, String)} : 파라미터형 요청 판정
  • + *
  • {@code assignParameterMap(...)} : PathVariable + FormData + QueryString 병합
  • + *
  • {@code assignApiKeys(...)} : 서비스키 확정 (Action 1회 수행)
  • + *
  • {@code extractPathVariables(...)} : 확정된 서비스키로 PathVariable 추출
  • + *
  • {@code callApi(...)} : JSON Body 요청에 PathVariable 을 병합해 만드는 최종 전문
  • + *
+ * + *

STDMessageManager / StandardMessageManager 는 실제 DB 로딩 대신 Mock 으로 대체하고, + * 게이트웨이 본 처리({@code service(...)})는 테스트 서브클래스에서 가로채 전달 전문만 캡처한다. + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class DJBApiAdapterServiceTest { + + /** StandardMessageUtil.REST_URL_ACTION2 - PathVariable 매칭이 허용되는 action */ + private static final String ACTION = "com.eactive.eai.inbound.action.RestUrlParseRequestAction"; + + private static final String GRP = "TESTGRP"; + private static final String ADP = "TESTADP"; + + /** STDMessageManager 에 등록되어 있다고 가정하는 서비스 키 목록 */ + private static final String[] STD_KEYS = { + "GET/api/v1/users/{userId}", + "DELETE/api/v1/users/{userId}", + "POST/api/v1/users/{userId}/orders/{orderId}", + "PUT/api/v1/users/{userId}", + "PATCH/api/v1/users/{userId}", + "POST/api/v1/plain", + "{method}/api/v2/users/{userId}" + }; + + private final ObjectMapper json = new ObjectMapper(); + + // ================================================================ + // 공통 setup + // ================================================================ + + @BeforeAll + void setUpAll() throws Exception { + STDMessageManager stdManager = Mockito.mock(STDMessageManager.class); + Mockito.when(stdManager.getAllSTDMessageKeys()).thenReturn(STD_KEYS); + Mockito.when(stdManager.getMatchedPathVariable(anyString())).thenAnswer(inv -> { + String key = inv.getArgument(0); + AntPathMatcher matcher = new AntPathMatcher(); + for (String candidate : STD_KEYS) { + if (matcher.match(candidate, key)) { + return candidate; + } + } + return null; + }); + Mockito.when(stdManager.getSTDMessage(anyString())).thenReturn(Mockito.mock(StandardMessage.class)); + + // logger.isDebug() 경로에서 호출되는 ExceptionUtil.make() 대응 + ErrorCodeManager errorCodeManager = Mockito.mock(ErrorCodeManager.class); + Mockito.when(errorCodeManager.getMessage(anyString())).thenReturn("[{1}] [{2}]"); + + ApplicationContext ctx = Mockito.mock(ApplicationContext.class); + Mockito.when(ctx.getBean(STDMessageManager.class)).thenReturn(stdManager); + Mockito.when(ctx.getBean(ErrorCodeManager.class)).thenReturn(errorCodeManager); + + Field ctxField = ApplicationContextProvider.class.getDeclaredField("context"); + ctxField.setAccessible(true); + ctxField.set(null, ctx); + + // ApiKeyExtractFilter.getEaiSvcCode() 대응 + InterfaceMapper mapper = Mockito.mock(InterfaceMapper.class); + Mockito.when(mapper.getEaiSvcCode(any())).thenReturn("TESTSVC"); + StandardMessageManager.getInstance().setMapper(mapper); + } + + // ================================================================ + // 1. isParameterType : 파라미터형 요청 판정 + // ================================================================ + + @Test + @DisplayName("GET/DELETE 는 Content-Type 과 무관하게 파라미터형") + void isParameterType_GET_DELETE() { + assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.GET, null)); + assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.GET, "application/json")); + assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.DELETE, "application/json")); + } + + @Test + @DisplayName("POST/PUT/PATCH + form-urlencoded 는 파라미터형") + void isParameterType_form() { + String form = "application/x-www-form-urlencoded;charset=UTF-8"; + assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.POST, form)); + assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.PUT, form)); + assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.PATCH, form)); + } + + @Test + @DisplayName("POST/PUT/PATCH + JSON 은 Body 형(=파라미터형 아님)") + void isParameterType_json() { + String ct = "application/json;charset=UTF-8"; + assertFalse(DJBApiAdapterService.isParameterType(HttpMethodType.POST, ct)); + assertFalse(DJBApiAdapterService.isParameterType(HttpMethodType.PUT, ct)); + assertFalse(DJBApiAdapterService.isParameterType(HttpMethodType.PATCH, ct)); + // Content-Type 미지정 POST 도 Body 형으로 취급 + assertFalse(DJBApiAdapterService.isParameterType(HttpMethodType.POST, null)); + } + + @Test + @DisplayName("정의되지 않은 메서드(HEAD/OPTIONS 등)는 파라미터형으로 취급된다") + void isParameterType_unknown() { + // 수정 전에는 지역변수 초기값이 false 라 Body 형이었으나, 현재는 true 로 바뀌었다. + assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.getValue("OPTIONS"), null)); + assertTrue(DJBApiAdapterService.isParameterType(HttpMethodType.UNKNOWN, "application/json")); + } + + // ================================================================ + // 2. assignParameterMap : PathVariable + FormData + QueryString 병합 + // ================================================================ + + @Test + @DisplayName("GET : QueryString 과 PathVariable 이 동시에 병합된다") + void assignParameterMap_query_and_pathVariable() throws Exception { + MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123"); + req.setQueryString("page=2&size=10"); + Properties prop = newProp("GET", "/api/v1/users/123"); + + Map map = assignParameterMap(req, "", prop, "N"); + + assertEquals("123", single(map, "userId"), "PathVariable 이 누락됨"); + assertEquals("2", single(map, "page")); + assertEquals("10", single(map, "size")); + assertEquals(3, map.size()); + } + + @Test + @DisplayName("GET : QueryString 이 없어도 PathVariable 은 추출된다") + void assignParameterMap_pathVariable_only() throws Exception { + MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123"); + Properties prop = newProp("GET", "/api/v1/users/123"); + + Map map = assignParameterMap(req, "", prop, "N"); + + assertEquals(1, map.size()); + assertEquals("123", single(map, "userId")); + } + + @Test + @DisplayName("이름이 겹치면 QueryString 값이 PathVariable 을 덮어쓴다") + void assignParameterMap_query_overrides_pathVariable() throws Exception { + MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123"); + req.setQueryString("userId=999"); + Properties prop = newProp("GET", "/api/v1/users/123"); + + Map map = assignParameterMap(req, "", prop, "N"); + + assertEquals("999", single(map, "userId")); + } + + @Test + @DisplayName("동일 파라미터 다중 값은 배열로 유지된다") + void assignParameterMap_multiValue() throws Exception { + MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123"); + req.setQueryString("code=A&code=B"); + Properties prop = newProp("GET", "/api/v1/users/123"); + + Map map = assignParameterMap(req, "", prop, "N"); + + assertEquals(2, map.get("code").length); + assertEquals("A", map.get("code")[0]); + assertEquals("B", map.get("code")[1]); + } + + @Test + @DisplayName("POST form-urlencoded : Body(form) + QueryString + PathVariable 이 모두 병합된다") + void assignParameterMap_formData() throws Exception { + MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9"); + req.setContentType("application/x-www-form-urlencoded;charset=UTF-8"); + req.setQueryString("trace=on"); + Properties prop = newProp("POST", "/api/v1/users/123/orders/9"); + + Map map = assignParameterMap(req, "amount=1000&memo=hello", prop, "N"); + + assertEquals("123", single(map, "userId")); + assertEquals("9", single(map, "orderId")); + assertEquals("1000", single(map, "amount")); + assertEquals("hello", single(map, "memo")); + assertEquals("on", single(map, "trace")); + } + + @Test + @DisplayName("Content-Type 이 없어도(GET 등) 예외 없이 처리된다") + void assignParameterMap_nullContentType() throws Exception { + MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123"); + req.setQueryString("page=1"); + req.setContentType(null); + Properties prop = newProp("GET", "/api/v1/users/123"); + + Map map = assertDoesNotThrow(() -> assignParameterMap(req, "", prop, "N")); + assertEquals("1", single(map, "page")); + } + + @Test + @DisplayName("잘못된 charset 이 담긴 Content-Type 도 예외로 전파되지 않는다") + void assignParameterMap_invalidCharset() throws Exception { + MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9"); + req.setContentType("application/x-www-form-urlencoded;charset=NO_SUCH_CHARSET"); + Properties prop = newProp("POST", "/api/v1/users/123/orders/9"); + + Map map = assertDoesNotThrow(() -> assignParameterMap(req, "amount=1000", prop, "N")); + assertEquals("1000", single(map, "amount")); + assertEquals("123", single(map, "userId")); + } + + @Test + @DisplayName("URL_DECODE_YN=Y : %인코딩된 한글 파라미터가 UTF-8 로 복원된다") + void assignParameterMap_urlDecode_hangul() throws Exception { + MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123"); + // "한글" == %ED%95%9C%EA%B8%80 (UTF-8) + req.setQueryString("name=%ED%95%9C%EA%B8%80"); + Properties prop = newProp("GET", "/api/v1/users/123"); + + Map map = assignParameterMap(req, "", prop, "Y"); + + assertEquals("한글", single(map, "name"), "%인코딩 복원 기본 charset 이 UTF-8 이 아니면 깨진다"); + } + + @Test + @DisplayName("URL_DECODE_YN=Y : Content-Type 의 charset 이 %인코딩 복원에 우선한다") + void assignParameterMap_urlDecode_contentTypeCharset() throws Exception { + MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9"); + req.setContentType("application/x-www-form-urlencoded;charset=EUC-KR"); + Properties prop = newProp("POST", "/api/v1/users/123/orders/9"); + // "한글" == %C7%D1%B1%DB (EUC-KR) + Map map = assignParameterMap(req, "name=%C7%D1%B1%DB", prop, "Y"); + + assertEquals("한글", single(map, "name")); + } + + @Test + @DisplayName("URL_DECODE_YN=N : 기존 ISO-8859-1 byte latch 동작을 유지한다") + void assignParameterMap_noUrlDecode_keepsLatin1Latch() throws Exception { + MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123"); + // 컨테이너가 URIEncoding=ISO-8859-1 로 디코딩해 넘겨준 상태를 재현한다. + String latin1Decoded = new String("한글".getBytes("UTF-8"), "ISO-8859-1"); + req.setQueryString("name=" + latin1Decoded); + Properties prop = newProp("GET", "/api/v1/users/123"); + + Map map = assignParameterMap(req, "", prop, "N"); + + // ISO-8859-1 로 원본 바이트를 되찾은 뒤 플랫폼 기본 charset 으로 디코딩하는 기존 동작. + String expected = new String("한글".getBytes("UTF-8")); + assertEquals(expected, single(map, "name"), "URL_DECODE_YN=N 경로의 기존 동작이 변경됨"); + } + + // ================================================================ + // 3-1. assignApiKeys : 서비스키 확정 (기존 ApiKeyExtractFilter.doPreFilter) + // ================================================================ + + @Test + @DisplayName("서비스키 3종(STD/FINAL/API_SERVICE_CODE)을 tx prop 에 세팅한다") + void assignApiKeys_setsServiceKeys() throws Exception { + Properties prop = newProp("GET", "/api/v1/users/123"); + + assignApiKeys("", prop); + + assertEquals("GET/api/v1/users/123", prop.getProperty(DJBApiAdapterService.STD_MESSAGE_KEY)); + assertEquals("GET/api/v1/users/{userId}", prop.getProperty(DJBApiAdapterService.FINAL_STD_MESSAGE_KEY)); + assertEquals("TESTSVC", prop.getProperty(DJBApiAdapterService.API_SERVICE_CODE)); + } + + @Test + @DisplayName("PathVariable 없이 정확히 일치하는 서비스키도 세팅된다") + void assignApiKeys_exactKey() throws Exception { + Properties prop = newProp("POST", "/api/v1/plain"); + + assignApiKeys("", prop); + + assertEquals("POST/api/v1/plain", prop.getProperty(DJBApiAdapterService.STD_MESSAGE_KEY)); + assertEquals("POST/api/v1/plain", prop.getProperty(DJBApiAdapterService.FINAL_STD_MESSAGE_KEY)); + } + + @Test + @DisplayName("등록되지 않은 경로는 403 FilterException 으로 차단한다") + void assignApiKeys_unknownPath() throws Exception { + Properties prop = newProp("GET", "/api/v1/unknown/path"); + + FilterException e = assertThrows(FilterException.class, () -> assignApiKeys("", prop)); + assertEquals(HttpStatus.FORBIDDEN.value(), e.getStatus()); + } + + @Test + @DisplayName("Action 생성 실패는 예외로 전파된다") + void assignApiKeys_actionFailure() throws Exception { + Properties prop = newProp("GET", "/api/v1/users/123"); + prop.setProperty(Processor.REQUEST_ACTION, "com.eactive.eai.NoSuchAction"); + + assertThrows(ActionException.class, () -> assignApiKeys("", prop)); + } + + @Test + @DisplayName("요청 1건당 Action 은 한 번만 생성/수행된다 (중복 제거 검증)") + void assignApiKeys_actionPerformedOnce() throws Exception { + CapturingAdapterService svc = new CapturingAdapterService(); + MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123"); + req.setQueryString("page=2"); + + CountingRequestAction.COUNT.set(0); + callApi(svc, req, CountingRequestAction.class.getName()); + + assertEquals(1, CountingRequestAction.COUNT.get(), + "서비스키 확정과 PathVariable 추출이 각각 Action 을 호출하면 2 가 된다"); + } + + // ================================================================ + // 3-2. extractPathVariables : 서비스키 대비 PathVariable 추출 (순수 함수) + // ================================================================ + + @Test + @DisplayName("PathVariable 이 없는 서비스키는 빈 Map 을 반환한다(null 아님)") + void extractPathVariables_noTemplate() throws Exception { + Map map = extractPathVariables("POST/api/v1/plain", "POST/api/v1/plain"); + + assertNotNull(map); + assertTrue(map.isEmpty()); + } + + @Test + @DisplayName("서비스키 템플릿에서 PathVariable 을 추출한다") + void extractPathVariables_extract() throws Exception { + Map map = extractPathVariables("POST/api/v1/users/123/orders/9", + "POST/api/v1/users/{userId}/orders/{orderId}"); + + assertEquals("123", map.get("userId")); + assertEquals("9", map.get("orderId")); + assertEquals(2, map.size()); + } + + @Test + @DisplayName("{method} 는 파라미터로 포함하지 않는다") + void extractPathVariables_skipMethod() throws Exception { + Map map = extractPathVariables("GET/api/v2/users/777", "{method}/api/v2/users/{userId}"); + + assertFalse(map.containsKey("method"), "{method} 는 제외되어야 함"); + assertEquals("777", map.get("userId")); + assertEquals(1, map.size()); + } + + @Test + @DisplayName("QueryString 유무는 PathVariable 추출에 영향을 주지 않는다") + void extractPathVariables_independentOfQueryString() throws Exception { + // 서비스키는 QueryString 을 포함하지 않으므로 동일 입력 → 동일 결과여야 한다. + Map map = extractPathVariables("GET/api/v1/users/123", "GET/api/v1/users/{userId}"); + + assertEquals("123", map.get("userId"), "QueryString 존재 시 PathVariable 추출이 생략되면 안 됨"); + } + + // ================================================================ + // 4. callApi : JSON Body + PathVariable 병합 (end-to-end) + // ================================================================ + + @Test + @DisplayName("POST JSON : Body 에 PathVariable 이 추가된다") + void callApi_jsonBody_with_pathVariables() throws Exception { + CapturingAdapterService svc = new CapturingAdapterService(); + MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9"); + req.setContentType("application/json;charset=UTF-8"); + req.setContent("{\"amount\":\"1000\"}".getBytes("UTF-8")); + + callApi(svc, req); + + JsonNode node = json.readTree((String) svc.captured); + assertEquals("1000", node.path("amount").asText()); + assertEquals("123", node.path("userId").asText(), "PathVariable userId 누락"); + assertEquals("9", node.path("orderId").asText(), "PathVariable orderId 누락"); + } + + @Test + @DisplayName("POST JSON : PathVariable 이 없으면 Body 를 그대로 전달한다") + void callApi_jsonBody_without_pathVariables() throws Exception { + CapturingAdapterService svc = new CapturingAdapterService(); + MockHttpServletRequest req = newRequest("POST", "/api/v1/plain"); + req.setContentType("application/json;charset=UTF-8"); + req.setContent("{\"amount\":\"1000\"}".getBytes("UTF-8")); + + callApi(svc, req); + + assertEquals("{\"amount\":\"1000\"}", svc.captured); + } + + @Test + @DisplayName("POST JSON : 빈 오브젝트 Body({}) 에 PathVariable 을 넣어도 유효한 JSON") + void callApi_emptyJsonBody() throws Exception { + CapturingAdapterService svc = new CapturingAdapterService(); + MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9"); + req.setContentType("application/json;charset=UTF-8"); + req.setContent("{}".getBytes("UTF-8")); + + callApi(svc, req); + + JsonNode node = json.readTree((String) svc.captured); // {,"userId":..} 이면 파싱 실패 + assertEquals("123", node.path("userId").asText()); + assertEquals("9", node.path("orderId").asText()); + } + + @Test + @DisplayName("POST JSON : Body 가 없으면 PathVariable 만으로 JSON 을 만든다") + void callApi_noBody() throws Exception { + CapturingAdapterService svc = new CapturingAdapterService(); + MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9"); + req.setContentType("application/json;charset=UTF-8"); + + callApi(svc, req); + + JsonNode node = json.readTree((String) svc.captured); + assertEquals("123", node.path("userId").asText()); + assertEquals("9", node.path("orderId").asText()); + } + + @Test + @DisplayName("POST JSON : Body 끝에 개행/공백이 있어도 Body 가 유실되지 않는다") + void callApi_jsonBody_trailingNewline() throws Exception { + CapturingAdapterService svc = new CapturingAdapterService(); + MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9"); + req.setContentType("application/json;charset=UTF-8"); + req.setContent("{\"amount\":\"1000\"}\n".getBytes("UTF-8")); + + callApi(svc, req); + + JsonNode node = json.readTree((String) svc.captured); + assertEquals("1000", node.path("amount").asText(), "Body 가 PathVariable 로 덮어써짐"); + assertEquals("123", node.path("userId").asText()); + } + + @Test + @DisplayName("POST XML : JSON 이 아닌 Body 는 PathVariable 병합으로 유실되면 안 된다") + void callApi_xmlBody_must_not_be_dropped() throws Exception { + CapturingAdapterService svc = new CapturingAdapterService(); + MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9"); + req.setContentType("application/xml;charset=UTF-8"); + req.setContent("1000".getBytes("UTF-8")); + + callApi(svc, req); + + assertTrue(((String) svc.captured).contains("1000"), + "XML Body 가 PathVariable JSON 으로 덮어써짐 : " + svc.captured); + } + + @Test + @DisplayName("PathVariable 값에 특수문자가 있어도 JSON 이 깨지지 않는다") + void callApi_pathVariable_escaping() throws Exception { + CapturingAdapterService svc = new CapturingAdapterService(); + MockHttpServletRequest req = newRequest("POST", "/api/v1/users/a\"b/orders/9"); + req.setContentType("application/json;charset=UTF-8"); + req.setContent("{\"amount\":\"1000\"}".getBytes("UTF-8")); + + callApi(svc, req); + + JsonNode node = json.readTree((String) svc.captured); // escape 누락이면 파싱 실패 + assertEquals("a\"b", node.path("userId").asText()); + } + + @Test + @DisplayName("GET : QueryString + PathVariable 이 하나의 JSON 전문으로 전달된다") + void callApi_get_query_and_pathVariable() throws Exception { + CapturingAdapterService svc = new CapturingAdapterService(); + MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123"); + req.setQueryString("page=2&size=10"); + + callApi(svc, req); + + JsonNode node = json.readTree((String) svc.captured); + assertEquals("123", node.path("userId").asText()); + assertEquals("2", node.path("page").asText()); + assertEquals("10", node.path("size").asText()); + } + + @Test + @DisplayName("QueryString 이 있어도 INBOUND_PATH_VARIABLES 가 채워진다(Outbound URL 치환용)") + void callApi_inboundPathVariables_with_queryString() throws Exception { + CapturingAdapterService svc = new CapturingAdapterService(); + MockHttpServletRequest req = newRequest("GET", "/api/v1/users/123"); + req.setQueryString("page=2"); + + callApi(svc, req); + + @SuppressWarnings("unchecked") + Map pathVariables = (Map) svc.capturedProp + .get(HttpAdapterServiceKey.INBOUND_PATH_VARIABLES); + assertNotNull(pathVariables, "QueryString 존재 시 INBOUND_PATH_VARIABLES 미설정 → Outbound 치환 불가/NPE"); + assertEquals("123", pathVariables.get("userId")); + } + + @Test + @DisplayName("[현재 동작] POST JSON + QueryString : QueryString 은 전문에 병합되지 않는다") + void callApi_jsonBody_with_queryString_currentBehavior() throws Exception { + CapturingAdapterService svc = new CapturingAdapterService(); + MockHttpServletRequest req = newRequest("POST", "/api/v1/users/123/orders/9"); + req.setContentType("application/json;charset=UTF-8"); + req.setQueryString("trace=on"); + req.setContent("{\"amount\":\"1000\"}".getBytes("UTF-8")); + + callApi(svc, req); + + JsonNode node = json.readTree((String) svc.captured); + assertEquals("1000", node.path("amount").asText()); + assertEquals("123", node.path("userId").asText()); + assertTrue(node.path("trace").isMissingNode(), + "현재 사양: JSON Body 요청의 QueryString 은 전문에 포함되지 않음"); + // QueryString 자체는 필터 검증용으로 보존된다. + assertEquals("trace=on", svc.capturedProp.getProperty(HttpAdapterServiceKey.INBOUND_QUERY_STRING)); + } + + // ================================================================ + // helper + // ================================================================ + + /** 게이트웨이 본 처리를 가로채 전달 전문/컨텍스트만 캡처하는 테스트용 서브클래스 */ + static class CapturingAdapterService extends DJBApiAdapterService { + Object captured; + Properties capturedProp; + + @Override + public Object service(String adptGrpName, String adptName, Object message, Properties prop, + HttpServletRequest request, HttpServletResponse response) { + this.captured = message; + this.capturedProp = prop; + return "{\"result\":\"ok\"}"; + } + } + + private MockHttpServletRequest newRequest(String method, String uri) { + MockHttpServletRequest req = new MockHttpServletRequest(method, uri); + req.setContextPath(""); + return req; + } + + /** RestUrlParseRequestAction 이 서비스키를 만들기 위해 필요한 최소 컨텍스트 */ + private Properties newProp(String method, String extUri) { + Properties prop = new Properties(); + prop.setProperty(Processor.REQUEST_ACTION, ACTION); + prop.setProperty(DJBApiAdapterService.PROPERTIES_NAME_HTTP_REQUEST_METHOD, method); + prop.setProperty(HttpAdapterServiceKey.INBOUND_EXTURI, extUri); + return prop; + } + + private String callApi(CapturingAdapterService svc, MockHttpServletRequest req) throws Exception { + return callApi(svc, req, ACTION); + } + + private String callApi(CapturingAdapterService svc, MockHttpServletRequest req, String actionName) + throws Exception { + AdapterGroupVO group = new AdapterGroupVO(); + group.setName(GRP); + group.setType(Keys.TYPE_REST); + group.setMessageType(MessageType.JSON); + group.setMessageEncode("UTF-8"); + group.setRefClass(actionName); + + AdapterVO adapter = new AdapterVO(); + adapter.setName(ADP); + adapter.setAdapterGroupVO(group); + + Properties httpProp = new Properties(); + httpProp.setProperty(HttpAdapterServiceKey.URL_DECODE_YN, "N"); + httpProp.setProperty(DJBApiAdapterService.HEADER_GROUP, ""); + httpProp.setProperty(DJBApiAdapterService.HEADER_KEYS, ""); + + return svc.callApi(req, new MockHttpServletResponse(), httpProp, group, adapter, new Properties()); + } + + /** 운영 흐름(callApi)과 동일하게 assignApiKeys → extractPathVariables 결과를 넘겨 호출한다. */ + @SuppressWarnings("unchecked") + private Map assignParameterMap(HttpServletRequest req, Object reqMessage, Properties prop, + String urlDecode) throws Exception { + assignApiKeys(reqMessage, prop); + Map variablesMap = extractPathVariables( + prop.getProperty(DJBApiAdapterService.STD_MESSAGE_KEY), + prop.getProperty(DJBApiAdapterService.FINAL_STD_MESSAGE_KEY)); + Method m = DJBApiAdapterService.class.getDeclaredMethod("assignParameterMap", HttpServletRequest.class, + String.class, String.class, Object.class, Properties.class, String.class, Map.class); + m.setAccessible(true); + try { + return (Map) m.invoke(new DJBApiAdapterService(), req, GRP, ADP, reqMessage, prop, + urlDecode, variablesMap); + } catch (java.lang.reflect.InvocationTargetException e) { + throw (Exception) e.getCause(); + } + } + + private void assignApiKeys(Object reqMessage, Properties prop) throws Exception { + Method m = DJBApiAdapterService.class.getDeclaredMethod("assignApiKeys", String.class, String.class, + Object.class, Properties.class); + m.setAccessible(true); + try { + m.invoke(new DJBApiAdapterService(), GRP, ADP, reqMessage, prop); + } catch (java.lang.reflect.InvocationTargetException e) { + throw (Exception) e.getCause(); + } + } + + @SuppressWarnings("unchecked") + private Map extractPathVariables(String requestPath, String ruledPath) throws Exception { + Method m = DJBApiAdapterService.class.getDeclaredMethod("extractPathVariables", String.class, String.class); + m.setAccessible(true); + try { + return (Map) m.invoke(new DJBApiAdapterService(), requestPath, ruledPath); + } catch (java.lang.reflect.InvocationTargetException e) { + throw (Exception) e.getCause(); + } + } + + /** Action 이 요청당 몇 번 수행되는지 세기 위한 테스트용 RequestAction */ + public static class CountingRequestAction implements RequestAction { + static final AtomicInteger COUNT = new AtomicInteger(); + + private Properties prop; + + @Override + public void setAdapterInfo(String adapterGroupName, String adapterName, Properties prop) { + this.prop = prop; + } + + @Override + public String[] perform(Object message) { + COUNT.incrementAndGet(); + String method = prop.getProperty(DJBApiAdapterService.PROPERTIES_NAME_HTTP_REQUEST_METHOD); + String extUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI); + return new String[] { method + "/" + StringUtils.removeStart(extUri, "/") }; + } + + @Override + public String getDescription() { + return "counting test action"; + } + } + + private String single(Map map, String key) { + String[] values = map.get(key); + assertNotNull(values, "key 없음 : " + key); + assertEquals(1, values.length, "단일 값이 아님 : " + key); + return values[0]; + } +}