Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 91f91c18ca | |||
| 840136b8ca | |||
| efcc7fe208 | |||
| 8bcbee7e52 | |||
| 04aa0df977 | |||
| 2eeee58d35 | |||
| 5f24bacd48 | |||
| 21c3bcbc6a | |||
| aff3ed6658 | |||
| 8947fc248f | |||
| 58f659a179 | |||
| 745df6d073 | |||
| 4a41398f03 | |||
| 3a578b3c70 | |||
| 4d479e4fd6 | |||
| 780b9bd934 | |||
| 42f52a4974 | |||
| 1a79c39e76 |
@@ -20,7 +20,12 @@
|
|||||||
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
|
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
|
||||||
">
|
">
|
||||||
|
|
||||||
<context:component-scan base-package="com.eactive.eai" />
|
<context:component-scan base-package="com.eactive.eai">
|
||||||
|
<context:exclude-filter type="annotation"
|
||||||
|
expression="org.springframework.stereotype.Controller"/>
|
||||||
|
<context:exclude-filter type="annotation"
|
||||||
|
expression="org.springframework.web.bind.annotation.RestController"/>
|
||||||
|
</context:component-scan>
|
||||||
|
|
||||||
<bean id="entityManagerFactory" primary="true"
|
<bean id="entityManagerFactory" primary="true"
|
||||||
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
|
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
|
||||||
|
|||||||
@@ -17,6 +17,10 @@
|
|||||||
http://www.springframework.org/schema/mvc
|
http://www.springframework.org/schema/mvc
|
||||||
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
|
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
|
||||||
|
|
||||||
|
<context:property-placeholder
|
||||||
|
location="/WEB-INF/properties/*.${eai.systemmode}.properties"
|
||||||
|
ignore-unresolvable="true" />
|
||||||
|
|
||||||
<context:component-scan
|
<context:component-scan
|
||||||
base-package="com.eactive.eai.authserver" />
|
base-package="com.eactive.eai.authserver" />
|
||||||
<context:component-scan
|
<context:component-scan
|
||||||
@@ -31,4 +35,8 @@
|
|||||||
<mvc:interceptors>
|
<mvc:interceptors>
|
||||||
<bean class="com.eactive.eai.adapter.interceptor.HttpResponseLoggingInterceptor"/>
|
<bean class="com.eactive.eai.adapter.interceptor.HttpResponseLoggingInterceptor"/>
|
||||||
</mvc:interceptors>
|
</mvc:interceptors>
|
||||||
|
|
||||||
|
<bean class="com.eactive.eai.adapter.controller.DJErpAdapterMappingRegistrar">
|
||||||
|
<property name="paths" value="${dj.erp.adapter.paths}" />
|
||||||
|
</bean>
|
||||||
</beans>
|
</beans>
|
||||||
@@ -20,3 +20,6 @@ eai.systemmode=D
|
|||||||
eai.systemtype=API
|
eai.systemtype=API
|
||||||
eai.tableowner=AGWADM
|
eai.tableowner=AGWADM
|
||||||
eai.server.extractor=[0,2],[0,2],[-2]
|
eai.server.extractor=[0,2],[0,2],[-2]
|
||||||
|
|
||||||
|
# DJErp API Adapter request mapping paths (comma-separated)
|
||||||
|
dj.erp.adapter.paths=/dj/{path:^(?!oauth).*$},/dj/{path:^(?!oauth).*$}/**
|
||||||
|
|||||||
@@ -12,3 +12,6 @@ hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
|
|||||||
eai.systemtype=API
|
eai.systemtype=API
|
||||||
eai.server.extractor=[0,2],[0,2],[-2]
|
eai.server.extractor=[0,2],[0,2],[-2]
|
||||||
|
|
||||||
|
# DJErp API Adapter request mapping paths (comma-separated)
|
||||||
|
dj.erp.adapter.paths=/dj/{path:^(?!oauth).*$},/dj/{path:^(?!oauth).*$}/**
|
||||||
|
|
||||||
|
|||||||
@@ -18,3 +18,6 @@ eai.systemmode=D
|
|||||||
eai.systemtype=API
|
eai.systemtype=API
|
||||||
eai.tableowner=dapigw
|
eai.tableowner=dapigw
|
||||||
eai.server.extractor=[0,2],[0,2],[-2]
|
eai.server.extractor=[0,2],[0,2],[-2]
|
||||||
|
|
||||||
|
# DJErp API Adapter request mapping paths (comma-separated)
|
||||||
|
dj.erp.adapter.paths=/dj/{path:^(?!oauth).*$},/dj/{path:^(?!oauth).*$}/**
|
||||||
|
|||||||
+1
-1
Submodule elink-online-common updated: d81aeeef67...8f70451477
@@ -0,0 +1,91 @@
|
|||||||
|
package com.eactive.eai.adapter.controller;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.ApplicationListener;
|
||||||
|
import org.springframework.context.event.ContextRefreshedEvent;
|
||||||
|
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.util.Logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* properties 파일의 dj.erp.adapter.paths 값을 읽어
|
||||||
|
* DJErpApiAdapterController 의 callApi 메서드를 동적으로 URL에 등록한다.
|
||||||
|
*
|
||||||
|
* 경로는 쉼표로 구분하여 여러 개를 지정할 수 있다.
|
||||||
|
* 예) /dj/{path:^(?!oauth).*$},/dj/{path:^(?!oauth).*$}/**
|
||||||
|
*/
|
||||||
|
public class DJErpAdapterMappingRegistrar implements ApplicationListener<ContextRefreshedEvent> {
|
||||||
|
|
||||||
|
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private DJErpApiAdapterController djErpApiAdapterController;
|
||||||
|
|
||||||
|
private String paths;
|
||||||
|
|
||||||
|
private boolean registered = false;
|
||||||
|
|
||||||
|
public void setPaths(String paths) {
|
||||||
|
this.paths = paths;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onApplicationEvent(ContextRefreshedEvent event) {
|
||||||
|
if (registered) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StringUtils.isBlank(paths)) {
|
||||||
|
logger.warn("DJErpAdapterMappingRegistrar] dj.erp.adapter.paths 가 설정되지 않았습니다.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// OAuth2의 FrameworkEndpointHandlerMapping 을 제외하고 MVC 기본 매핑만 선택
|
||||||
|
Map<String, RequestMappingHandlerMapping> candidates =
|
||||||
|
event.getApplicationContext().getBeansOfType(RequestMappingHandlerMapping.class);
|
||||||
|
|
||||||
|
RequestMappingHandlerMapping requestMappingHandlerMapping = candidates.values().stream()
|
||||||
|
.filter(m -> m.getClass() == RequestMappingHandlerMapping.class)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (requestMappingHandlerMapping == null) {
|
||||||
|
logger.warn("DJErpAdapterMappingRegistrar] RequestMappingHandlerMapping 을 찾을 수 없습니다.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Method callApi = DJErpApiAdapterController.class.getDeclaredMethod(
|
||||||
|
"callApi", HttpServletRequest.class, HttpServletResponse.class);
|
||||||
|
|
||||||
|
RequestMappingInfo.BuilderConfiguration options = new RequestMappingInfo.BuilderConfiguration();
|
||||||
|
options.setPatternParser(requestMappingHandlerMapping.getPatternParser());
|
||||||
|
|
||||||
|
for (String path : paths.split(",")) {
|
||||||
|
path = path.trim();
|
||||||
|
if (path.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
RequestMappingInfo mappingInfo = RequestMappingInfo
|
||||||
|
.paths(path)
|
||||||
|
.options(options)
|
||||||
|
.build();
|
||||||
|
requestMappingHandlerMapping.registerMapping(mappingInfo, djErpApiAdapterController, callApi);
|
||||||
|
logger.warn("DJErpAdapterMappingRegistrar] 등록 완료: " + path);
|
||||||
|
}
|
||||||
|
|
||||||
|
registered = true;
|
||||||
|
|
||||||
|
} catch (NoSuchMethodException e) {
|
||||||
|
logger.error("DJErpAdapterMappingRegistrar] callApi 메서드를 찾을 수 없습니다.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,7 +16,6 @@ import org.springframework.http.HttpStatus;
|
|||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.util.AntPathMatcher;
|
import org.springframework.util.AntPathMatcher;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||||
@@ -57,7 +56,6 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
* @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
|
* @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer
|
||||||
* endpoints)
|
* endpoints)
|
||||||
*/
|
*/
|
||||||
@RequestMapping(value = { "/dj/{path:^(?!oauth).*$}", "/dj/{path:^(?!oauth).*$}/**" })
|
|
||||||
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
|
||||||
throws Exception {
|
throws Exception {
|
||||||
// /ONLWeb/api/v1/public/getUserInfo.svc
|
// /ONLWeb/api/v1/public/getUserInfo.svc
|
||||||
@@ -144,50 +142,14 @@ public class DJErpApiAdapterController implements HttpAdapterServiceKey {
|
|||||||
try {
|
try {
|
||||||
String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO,
|
||||||
transactionProp);
|
transactionProp);
|
||||||
// if (RESPONSE_TYPE_ASYNC.equals(responseType)) { // table의 값이 ASYNC 로 들어가 있는데
|
servletResponse.addHeader("traceId",
|
||||||
// response_type_async는 ASYN 로 되어 있어 아래처럼 비교함 jwhong 2025
|
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
||||||
if ("ASYNC".equals(responseType)) {
|
int httpStatus = servletResponse.getStatus();
|
||||||
// responseEntity = ResponseEntity.ok("dummy"); // comment by jwhong
|
if (httpStatus != 200) {
|
||||||
// servletResponse.addHeader("traceId", responseData); // uuid를 response header에
|
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||||
servletResponse.addHeader("traceId",
|
|
||||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
|
||||||
int httpStatus = servletResponse.getStatus();
|
|
||||||
if (httpStatus == 200) {
|
|
||||||
// 업체별 aync response message 가 다르다.
|
|
||||||
String asyncMsgStyle = httpProp.getProperty("ASYNC_RTNMSG_TYPE", "");
|
|
||||||
String responseBody = "";
|
|
||||||
boolean encryptAsyncAckApply = StringUtils
|
|
||||||
.equalsIgnoreCase(httpProp.getProperty("ASYNC_ENCRYPT_ACK", "N"), "Y");
|
|
||||||
|
|
||||||
if (asyncMsgStyle == null || asyncMsgStyle.trim().isEmpty()) {
|
|
||||||
responseBody = makeResponseBodyMsg();
|
|
||||||
} else {
|
|
||||||
responseBody = asyncMsgStyle;
|
|
||||||
}
|
|
||||||
if (encryptAsyncAckApply) {
|
|
||||||
responseBody = service.doPostEncryption(responseBody, transactionProp, servletRequest);
|
|
||||||
}
|
|
||||||
|
|
||||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseBody);
|
|
||||||
// jwhong
|
|
||||||
} else {
|
|
||||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||||
// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
|
|
||||||
// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
|
|
||||||
|
|
||||||
servletResponse.addHeader("traceId",
|
|
||||||
transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID)); // uuid를 response header에
|
|
||||||
int httpStatus = servletResponse.getStatus();
|
|
||||||
if (httpStatus != 200) {
|
|
||||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
|
||||||
} else {
|
|
||||||
responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,38 @@
|
|||||||
package com.eactive.eai.adapter.service;
|
package com.eactive.eai.adapter.service;
|
||||||
|
|
||||||
|
import java.net.URLDecoder;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import javax.servlet.ServletInputStream;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.apache.commons.lang3.time.StopWatch;
|
||||||
|
import org.apache.mina.common.ByteBuffer;
|
||||||
|
import org.json.simple.JSONObject;
|
||||||
|
import org.json.simple.JSONValue;
|
||||||
|
import org.springframework.context.annotation.Primary;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.util.AntPathMatcher;
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||||
import com.eactive.eai.adapter.AdapterPropManager;
|
|
||||||
import com.eactive.eai.adapter.AdapterVO;
|
import com.eactive.eai.adapter.AdapterVO;
|
||||||
import com.eactive.eai.adapter.Keys;
|
import com.eactive.eai.adapter.Keys;
|
||||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthFilter;
|
import com.eactive.eai.common.context.ElinkTransactionContext;
|
||||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||||
import com.eactive.eai.common.message.MessageType;
|
import com.eactive.eai.common.message.MessageType;
|
||||||
import com.eactive.eai.common.util.CommonLib;
|
import com.eactive.eai.common.util.CommonLib;
|
||||||
@@ -20,61 +45,19 @@ import com.fasterxml.jackson.databind.JsonNode;
|
|||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
@Primary
|
||||||
import org.apache.commons.lang3.time.StopWatch;
|
|
||||||
import org.apache.mina.common.ByteBuffer;
|
|
||||||
import org.json.simple.JSONObject;
|
|
||||||
import org.json.simple.JSONValue;
|
|
||||||
import org.json.simple.parser.JSONParser;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.http.HttpMethod;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.util.AntPathMatcher;
|
|
||||||
|
|
||||||
import javax.servlet.ServletInputStream;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
import java.net.URLDecoder;
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
//for encrypt/decrypt jwhong
|
|
||||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
|
||||||
import com.kjbank.encrypt.exchange.crypto.AES256Cipher;
|
|
||||||
import com.kjbank.encrypt.exchange.crypto.AESCipher;
|
|
||||||
import com.kjbank.encrypt.exchange.crypto.AES256GCMCipher;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.io.ByteArrayInputStream;
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.ObjectOutputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.ObjectInputStream;
|
|
||||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
|
||||||
import com.nimbusds.jwt.SignedJWT;
|
|
||||||
import com.eactive.eai.common.context.ElinkTransactionContext;
|
|
||||||
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||||
|
|
||||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||||
public static final String HTTP_STATUS = "HTTP_STATUS"; // jwhong
|
public static final String HTTP_STATUS = "HTTP_STATUS";
|
||||||
// HEADER_GROUP JSON에 추가할 항목 정의, 없으면 전체 header 추가
|
|
||||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||||
public static final String PROPERTIES_NAME_HTTP_REQUEST_METHOD = "httpRequestMethod";
|
public static final String PROPERTIES_NAME_HTTP_REQUEST_METHOD = "httpRequestMethod";
|
||||||
|
|
||||||
private static final String JSON_CONTENT_TYPE = "application/json";
|
|
||||||
private static final String JSON_FIELD_NAME = "json-body";
|
|
||||||
private static final String FILE_GROUP_NAME = "image-file";
|
|
||||||
private static final String UPLOAD_ROOT_PATH = "UPLOAD_ROOT_PATH";
|
|
||||||
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id"; // jwhong
|
|
||||||
private boolean encryptResponseApply; // inbound에 대한 응답 암호화 여부 flag
|
|
||||||
|
|
||||||
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp, AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
|
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp, AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
|
||||||
int traceLevel = 0;
|
int traceLevel = 0;
|
||||||
|
|
||||||
AdapterPropManager manager = null;
|
|
||||||
String adptGrpName = adapterGroupVO.getName();
|
String adptGrpName = adapterGroupVO.getName();
|
||||||
String adptName = adapterVO.getName();
|
String adptName = adapterVO.getName();
|
||||||
|
|
||||||
@@ -90,61 +73,56 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
|
|
||||||
String paramValue = null;
|
String paramValue = null;
|
||||||
String adptMsgType = null;
|
String adptMsgType = null;
|
||||||
|
|
||||||
transactionProp.put(INBOUND_METHOD, request.getMethod());
|
transactionProp.put(INBOUND_METHOD, request.getMethod());
|
||||||
transactionProp.put(INBOUND_URI, request.getRequestURI());
|
transactionProp.put(INBOUND_URI, request.getRequestURI());
|
||||||
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(request.getQueryString()));
|
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(request.getQueryString()));
|
||||||
transactionProp.put(INBOUND_HEADER, getHeaders(request));
|
transactionProp.put(INBOUND_HEADER, getHeaders(request));
|
||||||
transactionProp.put(INBOUND_EXTPARAMS, StringUtils.defaultString(request.getQueryString()));
|
transactionProp.put(INBOUND_EXTPARAMS, StringUtils.defaultString(request.getQueryString()));
|
||||||
if (StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_REST)
|
if (StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_REST)
|
||||||
|| StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_HTTP_CUSTOM)) {
|
|| StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_HTTP_CUSTOM)) {
|
||||||
// /api/v1/public/getUserInfo.svc
|
// /api/v1/public/getUserInfo.svc
|
||||||
String extUrl = StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
|
String extUrl = StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
|
||||||
transactionProp.put(INBOUND_EXTURI, extUrl);
|
transactionProp.put(INBOUND_EXTURI, extUrl);
|
||||||
} else {
|
} else {
|
||||||
transactionProp.put(INBOUND_EXTURI, getExtUri(request));
|
transactionProp.put(INBOUND_EXTURI, getExtUri(request));
|
||||||
}
|
}
|
||||||
transactionProp.put(INBOUND_CLIENT_IP, getClientIp(request)); // Client IP 추가
|
transactionProp.put(INBOUND_CLIENT_IP, getClientIp(request));
|
||||||
transactionProp.put(Processor.REQUEST_ACTION, adapterVO.getAdapterGroupVO().getRefClass());
|
transactionProp.put(Processor.REQUEST_ACTION, adapterVO.getAdapterGroupVO().getRefClass());
|
||||||
transactionProp.put(API_PATH, httpProp.getProperty(API_PATH, ""));
|
transactionProp.put(API_PATH, httpProp.getProperty(API_PATH, ""));
|
||||||
|
|
||||||
//djerp bypass
|
|
||||||
transactionProp.put(INBOUND_REWRITE_PATH,
|
transactionProp.put(INBOUND_REWRITE_PATH,
|
||||||
getRewritePath(transactionProp.getProperty(INBOUND_EXTURI), transactionProp.getProperty(API_PATH)));
|
getRewritePath(transactionProp.getProperty(INBOUND_EXTURI), transactionProp.getProperty(API_PATH)));
|
||||||
transactionProp.put(INBOUND_REMOTE_ADDR, request.getRemoteAddr());
|
transactionProp.put(INBOUND_REMOTE_ADDR, request.getRemoteAddr());
|
||||||
transactionProp.put(INBOUND_SCHEME, request.getScheme());
|
transactionProp.put(INBOUND_SCHEME, request.getScheme());
|
||||||
|
|
||||||
transactionProp.put(PRE_FILTERS, httpProp.getProperty(PRE_FILTERS, ""));
|
transactionProp.put(PRE_FILTERS, httpProp.getProperty(PRE_FILTERS, ""));
|
||||||
transactionProp.put(POST_FILTERS, httpProp.getProperty(POST_FILTERS, ""));
|
transactionProp.put(POST_FILTERS, httpProp.getProperty(POST_FILTERS, ""));
|
||||||
transactionProp.put(PROPERTIES_NAME_HTTP_REQUEST_METHOD, request.getMethod());
|
transactionProp.put(PROPERTIES_NAME_HTTP_REQUEST_METHOD, request.getMethod());
|
||||||
transactionProp.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
|
transactionProp.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
|
||||||
transactionProp.put("BLOCK_IP", httpProp.getProperty("BLOCK_IP", ""));
|
transactionProp.put("BLOCK_IP", httpProp.getProperty("BLOCK_IP", ""));
|
||||||
|
|
||||||
//djerp bypass
|
|
||||||
Map<String, String> pathVariables = assignPathVariables(request, adptGrpName, adptName, null, transactionProp);
|
Map<String, String> pathVariables = assignPathVariables(request, adptGrpName, adptName, null, transactionProp);
|
||||||
if (pathVariables != null) {
|
if (pathVariables != null) {
|
||||||
transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
transactionProp.put(INBOUND_PATH_VARIABLES, pathVariables);
|
||||||
}
|
}
|
||||||
|
|
||||||
transactionProp.put(ENC_PATHS, httpProp.getProperty(ENC_PATHS, ""));
|
transactionProp.put(ENC_PATHS, httpProp.getProperty(ENC_PATHS, ""));
|
||||||
|
|
||||||
transactionProp.put(ENCRYPT_ALGORITHM, httpProp.getProperty(ENCRYPT_ALGORITHM, "")); //jwhong
|
transactionProp.put(ENCRYPT_ALGORITHM, httpProp.getProperty(ENCRYPT_ALGORITHM, ""));
|
||||||
if (getHeaders(request).get(HEADER_NAME_CLIENT_ID) != null) { // jwhong
|
if (getHeaders(request).get(HEADER_NAME_CLIENT_ID) != null) {
|
||||||
transactionProp.put(HEADER_NAME_CLIENT_ID, getHeaders(request).get(HEADER_NAME_CLIENT_ID));
|
transactionProp.put(HEADER_NAME_CLIENT_ID, getHeaders(request).get(HEADER_NAME_CLIENT_ID));
|
||||||
}
|
}
|
||||||
transactionProp.put(ENCRYPT_BASE_TYPE, httpProp.getProperty(ENCRYPT_BASE_TYPE, "")); //jwhong
|
transactionProp.put(ENCRYPT_BASE_TYPE, httpProp.getProperty(ENCRYPT_BASE_TYPE, ""));
|
||||||
// //transactionProp.put(INBOUND_TOKEN, getHeaders(request).get(INBOUND_TOKEN)); // jwhong
|
|
||||||
// transactionProp.put(INBOUND_TOKEN, getHeaders(request).get(INBOUND_TOKEN) != null ? getHeaders(request).get(INBOUND_TOKEN) : ""); //jwhong , null 이면 default로 "" put
|
|
||||||
String inboundToken = getHeaders(request).getOrDefault(INBOUND_TOKEN, "").toString();
|
String inboundToken = getHeaders(request).getOrDefault(INBOUND_TOKEN, "").toString();
|
||||||
if (StringUtils.isNotBlank(inboundToken) && StringUtils.startsWith(inboundToken, "Bearer ")) {
|
if (StringUtils.isNotBlank(inboundToken) && StringUtils.startsWith(inboundToken, "Bearer ")) {
|
||||||
inboundToken = inboundToken.substring(7);
|
inboundToken = inboundToken.substring(7);
|
||||||
}
|
}
|
||||||
transactionProp.put(INBOUND_TOKEN, inboundToken);
|
transactionProp.put(INBOUND_TOKEN, inboundToken);
|
||||||
transactionProp.put(ENCRYPT_AES256_IV, httpProp.getProperty(ENCRYPT_AES256_IV, "")); //jwhong
|
transactionProp.put(ENCRYPT_AES256_IV, httpProp.getProperty(ENCRYPT_AES256_IV, ""));
|
||||||
transactionProp.put(ENCRYPT_AES256_KEY, httpProp.getProperty(ENCRYPT_AES256_KEY, "")); //jwhong
|
transactionProp.put(ENCRYPT_AES256_KEY, httpProp.getProperty(ENCRYPT_AES256_KEY, ""));
|
||||||
|
|
||||||
|
// SEED 컬럼암호화 시 Key로 사용함
|
||||||
// SEED 컬럼암호하 시 Key로 사용함
|
|
||||||
String seedkey = getHeaders(request).getOrDefault("x-obp-partnercode", "").toString();
|
String seedkey = getHeaders(request).getOrDefault("x-obp-partnercode", "").toString();
|
||||||
ElinkTransactionContext.setSeedKey(seedkey);
|
ElinkTransactionContext.setSeedKey(seedkey);
|
||||||
|
|
||||||
@@ -168,7 +146,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
case PUT:
|
case PUT:
|
||||||
if (StringUtils.contains(request.getContentType(), "application/x-www-form-urlencoded")) {
|
if (StringUtils.contains(request.getContentType(), "application/x-www-form-urlencoded")) {
|
||||||
isParameterType = true;
|
isParameterType = true;
|
||||||
} else if ( StringUtils.isNoneBlank(request.getQueryString()) ) { // jwhong
|
} else if (StringUtils.isNoneBlank(request.getQueryString())) {
|
||||||
isParameterType = true;
|
isParameterType = true;
|
||||||
} else {
|
} else {
|
||||||
isParameterType = false;
|
isParameterType = false;
|
||||||
@@ -180,7 +158,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
|
|
||||||
if (isParameterType) {
|
if (isParameterType) {
|
||||||
paramValue = request.getQueryString();
|
paramValue = request.getQueryString();
|
||||||
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(paramValue)); // Filter에서 QueryString 검증을 위해 저장
|
transactionProp.put(INBOUND_QUERY_STRING, StringUtils.defaultString(paramValue));
|
||||||
if (paramValue == null)
|
if (paramValue == null)
|
||||||
paramValue = "";
|
paramValue = "";
|
||||||
if (traceLevel >= 3) {
|
if (traceLevel >= 3) {
|
||||||
@@ -219,7 +197,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
sb.append("}");
|
sb.append("}");
|
||||||
|
|
||||||
paramValue = sb.toString();
|
paramValue = sb.toString();
|
||||||
|
|
||||||
if (logger.isDebug()) {
|
if (logger.isDebug()) {
|
||||||
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
||||||
+ CommonLib.getDumpMessage(paramValue.getBytes(encode)));
|
+ CommonLib.getDumpMessage(paramValue.getBytes(encode)));
|
||||||
@@ -266,17 +244,11 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (paramValue == null) { // parameter가 없는 경우때문에 처리
|
if (paramValue == null) {
|
||||||
paramValue = "";
|
paramValue = "";
|
||||||
}
|
}
|
||||||
// 순수한 Body값을 저장을 위해 위치 변경.
|
|
||||||
transactionProp.put(INBOUND_REQUEST_MESSAGE, paramValue);
|
transactionProp.put(INBOUND_REQUEST_MESSAGE, paramValue);
|
||||||
|
|
||||||
// paramValue가 null이 아닌 빈문자열(""," ")인 경우에 대비하여 조건 수정.
|
|
||||||
// if (StringUtils.isNotBlank(paramValue)) { // jwhong decrypt
|
|
||||||
// paramValue = doPreDecryption(paramValue, transactionProp, request);
|
|
||||||
// }
|
|
||||||
|
|
||||||
if ("Y".equals(urlDecodeYn) && isParameterType) {
|
if ("Y".equals(urlDecodeYn) && isParameterType) {
|
||||||
message = URLDecoder.decode(paramValue);
|
message = URLDecoder.decode(paramValue);
|
||||||
} else {
|
} else {
|
||||||
@@ -291,11 +263,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
logger.debug(resMsg);
|
logger.debug(resMsg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||||
// HttpHeaders responseHeaders = new HttpHeaders();
|
|
||||||
// responseHeaders.setContentType(MediaType.valueOf("application/json;charset=" + encode));
|
|
||||||
|
|
||||||
|
|
||||||
// HEADER_GROUP 셋팅
|
// HEADER_GROUP 셋팅
|
||||||
if (MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)
|
if (MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)
|
||||||
@@ -318,7 +286,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (headerJson.size() > 0) {
|
if (headerJson.size() > 0) {
|
||||||
jsonMessage.put(headerGroupName, headerJson);
|
jsonMessage.put(headerGroupName, headerJson);
|
||||||
message = jsonMessage.toJSONString();
|
message = jsonMessage.toJSONString();
|
||||||
@@ -329,9 +297,6 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
message = "";
|
message = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
// 위치변경 : 가공되지 않은 Body값을 저장하기 위하여 위쪽으로 이동.
|
|
||||||
// transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
|
|
||||||
// 로컬 서비스 호출 ,encoding 처리 추가
|
|
||||||
String result = (String) service(adptGrpName, adptName, message, transactionProp, request, response);
|
String result = (String) service(adptGrpName, adptName, message, transactionProp, request, response);
|
||||||
|
|
||||||
applyOutboundResponseHeaders(transactionProp, response);
|
applyOutboundResponseHeaders(transactionProp, response);
|
||||||
@@ -358,17 +323,11 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
result = mapper.writeValueAsString(rootNode);
|
result = mapper.writeValueAsString(rootNode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// KJBank는 요청에 대한 응답 (Sync응답, Aync 에 대한 Ack응답) 에 대하여 암호화 하지 않는다. 무조건 안한다. 따라서 아래부분은 구현은 했지만 사용하지 않는다.
|
|
||||||
// 위 2가지 경우 암호화 하는걸로 요청 변경되어 아래 암호화 수행하도록 수정함
|
|
||||||
// encryptResponseApply = StringUtils.equalsIgnoreCase(httpProp.getProperty("ENCRYPT_RESPONSE_APPLY", "N"), "Y");
|
|
||||||
// if ( encryptResponseApply) {
|
|
||||||
// result = doPostEncryption(result, transactionProp, request); // jwhong Encrypt
|
|
||||||
// }
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HttpClientAdapterServiceBypass.assignRelayDataToInbound() 에서
|
* HttpClientAdapterServiceBypass.assignRelayDataToInbound() 에서
|
||||||
* transactionProp에 저장한 OUTBOUND_RESPONSE_HEADERS를 response에 적용한다.
|
* transactionProp에 저장한 OUTBOUND_RESPONSE_HEADERS를 response에 적용한다.
|
||||||
@@ -411,411 +370,6 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// jwhong decrypt
|
|
||||||
|
|
||||||
private String doPreDecryption(String eaiBody, Properties transactionProp, HttpServletRequest request) throws Exception {
|
|
||||||
String decryptAlgorithm = transactionProp.getProperty(ENCRYPT_ALGORITHM, "");
|
|
||||||
String xElinkClientId = transactionProp.getProperty(HEADER_NAME_CLIENT_ID, ""); // 이 값이 OAuth의 client id 값이다 . http header 에 포함되어 온다. jwhong
|
|
||||||
String encryptBaseKeyType = transactionProp.getProperty(ENCRYPT_BASE_TYPE);
|
|
||||||
//String inboundToken2 = transactionProp.getProperty(INBOUND_TOKEN, ""); // 이건 token 값이 아니고 authorization 값이다
|
|
||||||
String inboundToken = "";
|
|
||||||
|
|
||||||
String secretAES256Iv = transactionProp.getProperty("ENCRYPT_AES256_IV");
|
|
||||||
String secretAES256Key = transactionProp.getProperty("ENCRYPT_AES256_KEY");
|
|
||||||
|
|
||||||
if ( decryptAlgorithm == "" ) { // 복호화 대상이 아님
|
|
||||||
return eaiBody;
|
|
||||||
}
|
|
||||||
|
|
||||||
inboundToken = JwtTokenExtractor(request);
|
|
||||||
xElinkClientId = JwtClientIdExtractor(inboundToken); // token에서 client id를 추출함
|
|
||||||
|
|
||||||
// 암호화 key를 token 내용으로 할지 client secret 내용으로 할지 결정함. adapter property에 정의함
|
|
||||||
// ENCRYPT_ALGORITHM 을 설정했는데 ENCRYPT_BASE_TYPE을 설정안하면 Decrypt 수행시 Exception 발생함
|
|
||||||
String clientSecret = "";
|
|
||||||
if ("TOKEN".equalsIgnoreCase(encryptBaseKeyType)) {
|
|
||||||
clientSecret = inboundToken;
|
|
||||||
} else if ( "SECRETKEY".equalsIgnoreCase(encryptBaseKeyType)) {
|
|
||||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
|
||||||
ClientDetails clientDetail = manager.getClientDeatilsStore().get(xElinkClientId);
|
|
||||||
|
|
||||||
if ( clientDetail != null ) { // 여기서 not null 이라는 것은 apim oauth server에서 발급된 token 임.
|
|
||||||
// 즉 KJBank 에서 요청이 들어온 것이다.
|
|
||||||
clientSecret = clientDetail.getClientSecret();
|
|
||||||
} // 그럼 업체에서 요청이 들어오면?? 업체도 apim oauth server에서 발급된 token을 사용하는것이다.
|
|
||||||
}
|
|
||||||
|
|
||||||
byte[] decryptedMessage = null;
|
|
||||||
decryptedMessage = doInboundPreDecrypt(eaiBody, decryptAlgorithm,clientSecret,secretAES256Iv, secretAES256Key );
|
|
||||||
|
|
||||||
if (decryptedMessage == null) {
|
|
||||||
throw new Exception("[ApiAdapterService] Decrypt Error : Invalid encrypted message");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
String resultMessage = new String(decryptedMessage, StandardCharsets.UTF_8 );
|
|
||||||
return resultMessage;
|
|
||||||
//return new String(decryptedMessage, StandardCharsets.UTF_8 );
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// jwhong encrypt
|
|
||||||
public String doPostEncryption(String eaiBody, Properties transactionProp, HttpServletRequest request) throws Exception {
|
|
||||||
|
|
||||||
String decryptAlgorithm = transactionProp.getProperty(ENCRYPT_ALGORITHM, "");
|
|
||||||
String xElinkClientId = transactionProp.getProperty(HEADER_NAME_CLIENT_ID, ""); // 이 값이 OAuth의 client id 값이다 . http header 에 포함되어 온다. jwhong
|
|
||||||
String encryptBaseKeyType = transactionProp.getProperty(ENCRYPT_BASE_TYPE);
|
|
||||||
String inboundToken = "";
|
|
||||||
|
|
||||||
String secretAES256Iv = transactionProp.getProperty("ENCRYPT_AES256_IV");
|
|
||||||
String secretAES256Key = transactionProp.getProperty("ENCRYPT_AES256_KEY");
|
|
||||||
|
|
||||||
if ( decryptAlgorithm == "" ) { // 복호화 대상이 아님
|
|
||||||
return eaiBody;
|
|
||||||
}
|
|
||||||
|
|
||||||
inboundToken = JwtTokenExtractor(request);
|
|
||||||
xElinkClientId = JwtClientIdExtractor(inboundToken); // token에서 client id를 추출함
|
|
||||||
|
|
||||||
// 암호화 key를 token 내용으로 할지 client secret 내용으로 할지 결정함. adapter property에 정의함
|
|
||||||
// ENCRYPT_ALGORITHM 을 설정했는데 ENCRYPT_BASE_TYPE을 설정안하면 Decrypt 수행시 Exception 발생함
|
|
||||||
String clientSecret = "";
|
|
||||||
if ("TOKEN".equalsIgnoreCase(encryptBaseKeyType)) {
|
|
||||||
clientSecret = inboundToken;
|
|
||||||
} else if ( "SECRETKEY".equalsIgnoreCase(encryptBaseKeyType)) {
|
|
||||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
|
||||||
ClientDetails clientDetail = manager.getClientDeatilsStore().get(xElinkClientId);
|
|
||||||
|
|
||||||
if ( clientDetail != null ) {
|
|
||||||
clientSecret = clientDetail.getClientSecret();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String encryptedMessage = null;
|
|
||||||
encryptedMessage = doInboundPostEncrypt(eaiBody, decryptAlgorithm,clientSecret,secretAES256Iv, secretAES256Key );
|
|
||||||
|
|
||||||
if (encryptedMessage == null) {
|
|
||||||
throw new Exception("[ApiAdapterService] Encrypt Error : Invalid PlainText message");
|
|
||||||
}
|
|
||||||
|
|
||||||
return encryptedMessage;
|
|
||||||
//String resultMessage = new String(encryptedMessage, StandardCharsets.UTF_8 );
|
|
||||||
//return resultMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private byte[] convertObjectToBytes(Object obj) throws IOException {
|
|
||||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
|
||||||
ObjectOutputStream oos = new ObjectOutputStream(bos);
|
|
||||||
oos.writeObject(obj);
|
|
||||||
oos.flush();
|
|
||||||
return bos.toByteArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
private byte[] convertObjectToBase64Bytes(Object obj) throws IOException {
|
|
||||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
|
||||||
ObjectOutputStream oos = new ObjectOutputStream(bos);
|
|
||||||
oos.writeObject(obj);
|
|
||||||
oos.flush();
|
|
||||||
oos.close();
|
|
||||||
|
|
||||||
// 직렬화된 byte[] → Base64 문자열 → 다시 byte[]로 변환
|
|
||||||
String base64String = Base64.getEncoder().encodeToString(bos.toByteArray());
|
|
||||||
return base64String.getBytes(StandardCharsets.UTF_8);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Object convertBytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
|
|
||||||
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
|
|
||||||
ObjectInputStream ois = new ObjectInputStream(bis)) {
|
|
||||||
return ois.readObject();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private byte[] doInboundPreDecrypt(String eaiStringBody, String decryptAlgorithm, String clientSecretKey, String secretAES256Iv, String secretAES256Key) throws Exception {
|
|
||||||
|
|
||||||
byte[] decryptedMessage = null;
|
|
||||||
//String eaiStringBody = new String(eaiBody, StandardCharsets.UTF_8);
|
|
||||||
|
|
||||||
eaiStringBody = extractBodyMsg(decryptAlgorithm, eaiStringBody);
|
|
||||||
|
|
||||||
if (eaiStringBody == null) {
|
|
||||||
throw new Exception("[ApiAdapterService] Cannot decrypt Error : input is plain text");
|
|
||||||
}
|
|
||||||
|
|
||||||
//test source
|
|
||||||
logger.debug("Base64 문자열: " + eaiStringBody);
|
|
||||||
logger.debug("Base64 문자열 길이: " + eaiStringBody.length());
|
|
||||||
logger.debug("Base64 문자열 끝: " + eaiStringBody.substring(eaiStringBody.length() - 10));
|
|
||||||
|
|
||||||
// Base64 디코딩 테스트
|
|
||||||
try {
|
|
||||||
byte[] decoded = Base64.getDecoder().decode(eaiStringBody);
|
|
||||||
logger.debug("디코딩 성공, 길이: " + decoded.length);
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
logger.debug("Base64 디코딩 실패: " + e.getMessage());
|
|
||||||
}
|
|
||||||
// end test source
|
|
||||||
|
|
||||||
switch (decryptAlgorithm) {
|
|
||||||
case "AES128":
|
|
||||||
case "AES128-TOSS":
|
|
||||||
try {
|
|
||||||
String key128 = clientSecretKey.substring(22,38); //togetherEncoder 경우는 substring(44,60) 이네??
|
|
||||||
//String decryptedStrMessage = AESCipher.decrypt(eaiStringBody, key128);
|
|
||||||
String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
|
|
||||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "AES128-TOGETHER":
|
|
||||||
try {
|
|
||||||
String key128 = clientSecretKey.substring(44,60); //togetherEncoder 경우는 substring(44,60) 이네??
|
|
||||||
//String decryptedStrMessage = AESCipher.decrypt(eaiStringBody, key128);
|
|
||||||
String decryptedStrMessage = AESCipher.decryptExistException(eaiStringBody, key128);
|
|
||||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES128 Decryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "AES256":
|
|
||||||
try {
|
|
||||||
String key = clientSecretKey.substring(10,42);
|
|
||||||
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, key);
|
|
||||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "AES256-KAKAO":
|
|
||||||
try {
|
|
||||||
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
|
||||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "AES256-TOSS":
|
|
||||||
try {
|
|
||||||
String decryptedStrMessage = AES256Cipher.decrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
|
||||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES256 Decryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "AES256GCM":
|
|
||||||
try {
|
|
||||||
byte[] key = AES256GCMCipher.generateKey();
|
|
||||||
AES256GCMCipher cipher = new AES256GCMCipher(key);
|
|
||||||
byte[] aad = "metadata".getBytes();
|
|
||||||
|
|
||||||
String decryptedStrMessage = cipher.decrypt(eaiStringBody , aad);
|
|
||||||
decryptedMessage = decryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
try {
|
|
||||||
decryptedMessage = eaiStringBody.getBytes();
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] doOutboundPostFilter Array copy error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
return decryptedMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String extractBodyMsg(String decryptAlgorithm, String eaiStringBody) {
|
|
||||||
|
|
||||||
String decryptedJsonKey = "";
|
|
||||||
String decryptedBodyMessage = "";
|
|
||||||
|
|
||||||
decryptedJsonKey = getJsonKey(decryptAlgorithm);
|
|
||||||
|
|
||||||
try {
|
|
||||||
JSONParser parser = new JSONParser();
|
|
||||||
JSONObject jsonObject = (JSONObject) parser.parse(eaiStringBody);
|
|
||||||
decryptedBodyMessage = (String) jsonObject.get(decryptedJsonKey);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClient5AdapterServiceRest] extractBodyMsg error : " + e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return decryptedBodyMessage;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getJsonKey(String Algorithm) {
|
|
||||||
|
|
||||||
String jsonKey = "";
|
|
||||||
|
|
||||||
switch (Algorithm) {
|
|
||||||
case "AES128":
|
|
||||||
case "AES128-TOSS":
|
|
||||||
jsonKey = "preScreeningRequest";
|
|
||||||
break;
|
|
||||||
case "AES128-TOGETHER":
|
|
||||||
jsonKey = "obpTxData";
|
|
||||||
break;
|
|
||||||
case "AES256":
|
|
||||||
jsonKey = "preScreeningRequest";
|
|
||||||
break;
|
|
||||||
case "AES256-KAKAO":
|
|
||||||
jsonKey = "encrypted_data";
|
|
||||||
break;
|
|
||||||
case "AES256-TOSS":
|
|
||||||
jsonKey = "encryptedData";
|
|
||||||
break;
|
|
||||||
case "AES256-NICEON":
|
|
||||||
jsonKey = "enc_data";
|
|
||||||
break;
|
|
||||||
case "AES256GCM":
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
return jsonKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String doInboundPostEncrypt(String eaiStringBody, String encryptAlgorithm, String clientSecretKey, String secretAES256Iv, String secretAES256Key) {
|
|
||||||
|
|
||||||
//byte[] encryptedMessage = null;
|
|
||||||
String encryptedStrMessage = null;
|
|
||||||
String encryptedJsonKey = "";
|
|
||||||
|
|
||||||
encryptedJsonKey = getJsonKey(encryptAlgorithm);
|
|
||||||
|
|
||||||
switch (encryptAlgorithm) {
|
|
||||||
case "AES128":
|
|
||||||
case "AES128-TOSS":
|
|
||||||
try {
|
|
||||||
String key128 = clientSecretKey.substring(22,38); //togetherEncoder 경우는 substring(44,60) 이네??
|
|
||||||
encryptedStrMessage = AESCipher.encrypt(eaiStringBody, key128);
|
|
||||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "AES128-TOGETHER":
|
|
||||||
try {
|
|
||||||
String key128 = clientSecretKey.substring(44,60); //togetherEncoder 경우는 substring(44,60) 이네??
|
|
||||||
encryptedStrMessage = AESCipher.encrypt(eaiStringBody, key128);
|
|
||||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES128 Encryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "AES256":
|
|
||||||
try {
|
|
||||||
String key = clientSecretKey.substring(10,42);
|
|
||||||
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, key);
|
|
||||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "AES256-KAKAO":
|
|
||||||
try {
|
|
||||||
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
|
||||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case "AES256-TOSS":
|
|
||||||
try {
|
|
||||||
encryptedStrMessage = AES256Cipher.encrypt(eaiStringBody, secretAES256Iv, secretAES256Key);
|
|
||||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES256 Encryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "AES256GCM":
|
|
||||||
try {
|
|
||||||
byte[] key = AES256GCMCipher.generateKey();
|
|
||||||
AES256GCMCipher cipher = new AES256GCMCipher(key);
|
|
||||||
byte[] aad = "metadata".getBytes();
|
|
||||||
|
|
||||||
encryptedStrMessage = cipher.encrypt(eaiStringBody , aad);
|
|
||||||
//encryptedMessage = encryptedStrMessage.getBytes(StandardCharsets.UTF_8);
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] AES256GCM Encryption error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
try {
|
|
||||||
encryptedStrMessage = eaiStringBody;
|
|
||||||
//encryptedMessage = eaiStringBody.getBytes();
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
logger.error("HttpClientAdapterServiceRest] doOutboundPostFilter Array copy error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
Map<String, Object> map = new HashMap<>();
|
|
||||||
map.put(encryptedJsonKey, encryptedStrMessage);
|
|
||||||
JSONObject json = new JSONObject();
|
|
||||||
json.putAll(map);
|
|
||||||
return json.toJSONString();
|
|
||||||
//return encryptedMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private String JwtTokenExtractor(HttpServletRequest request) {
|
|
||||||
|
|
||||||
String Token = "";
|
|
||||||
try {
|
|
||||||
Token = JwtAuthFilter.extractJWTToken(request);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.debug("Token is: " + Token);
|
|
||||||
return Token;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private String JwtClientIdExtractor(String inboundToken) {
|
|
||||||
|
|
||||||
String tokenClientId ="";
|
|
||||||
try {
|
|
||||||
SignedJWT signedJWT = SignedJWT.parse(inboundToken);
|
|
||||||
tokenClientId = (String) signedJWT.getJWTClaimsSet().getClaim(PAYLOAD_PARAM_NAME_CLIENT_ID);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
tokenClientId = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.debug("Token Client ID: " + tokenClientId);
|
|
||||||
return tokenClientId;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// jwhong until here
|
|
||||||
|
|
||||||
|
|
||||||
private Map<String, String[]> assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName,
|
private Map<String, String[]> assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName,
|
||||||
Object requestBytes, Properties prop) {
|
Object requestBytes, Properties prop) {
|
||||||
// PathVariable 체크
|
// PathVariable 체크
|
||||||
@@ -852,11 +406,11 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
|
|
||||||
return request.getParameterMap();
|
return request.getParameterMap();
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getRewritePath(String extUri, String basePath) {
|
private String getRewritePath(String extUri, String basePath) {
|
||||||
return StringUtils.removeStart(extUri, StringUtils.removeEnd(basePath, "/"));
|
return StringUtils.removeStart(extUri, StringUtils.removeEnd(basePath, "/"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<String, String> assignPathVariables(HttpServletRequest request, String adptGrpName, String adptName,
|
private Map<String, String> assignPathVariables(HttpServletRequest request, String adptGrpName, String adptName,
|
||||||
Object requestBytes, Properties prop) {
|
Object requestBytes, Properties prop) {
|
||||||
Map<String, String> variablesMap = null;
|
Map<String, String> variablesMap = null;
|
||||||
@@ -881,7 +435,7 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
|
|
||||||
return variablesMap;
|
return variablesMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Properties getHeaders(HttpServletRequest request) {
|
private Properties getHeaders(HttpServletRequest request) {
|
||||||
Properties prop = new Properties();
|
Properties prop = new Properties();
|
||||||
|
|
||||||
@@ -924,11 +478,6 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* HTTP 요청에서 클라이언트 IP를 추출합니다.
|
|
||||||
* X-Forwarded-For 헤더가 있는 경우 이를 우선적으로 사용하고,
|
|
||||||
* 없는 경우 remoteAddr을 사용합니다.
|
|
||||||
*/
|
|
||||||
private String getClientIp(HttpServletRequest request) {
|
private String getClientIp(HttpServletRequest request) {
|
||||||
String ipAddress = request.getHeader("X-Forwarded-For");
|
String ipAddress = request.getHeader("X-Forwarded-For");
|
||||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||||
@@ -948,35 +497,4 @@ public class DJErpApiAdapterService extends HttpAdapterServiceSupport {
|
|||||||
}
|
}
|
||||||
return ipAddress;
|
return ipAddress;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String assignApiId(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request) {
|
|
||||||
String apiId = null;
|
|
||||||
try {
|
|
||||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
|
||||||
RequestAction action = ActionFactory.createAction(actionName);
|
|
||||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
|
||||||
String[] keys = action.perform(message);
|
|
||||||
apiId = keys[0];
|
|
||||||
|
|
||||||
// PathVariable 지원 추가
|
|
||||||
apiId = StandardMessageUtil.getMatchedKey(apiId, actionName);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
// // header 에서 확보
|
|
||||||
// String apiId = request.getHeader(HEADER_NAME_API_CODE);
|
|
||||||
// if (StringUtils.isBlank(apiId)) {
|
|
||||||
// // url에서 확보
|
|
||||||
// // /ONLWeb/api/v1/public/getUserInfo.svc/
|
|
||||||
// apiId = request.getRequestURI();
|
|
||||||
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
|
||||||
// apiId = StringUtils.removeEnd(apiId, "/");
|
|
||||||
// // getUserInfo.svc
|
|
||||||
// apiId = StringUtils.substringAfterLast(apiId, "/");
|
|
||||||
// }
|
|
||||||
|
|
||||||
return apiId;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
package com.eactive.eai.authserver.custom;
|
package com.eactive.eai.authserver.custom;
|
||||||
|
|
||||||
|
import java.security.Principal;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
@@ -28,6 +30,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
|||||||
import org.springframework.web.bind.annotation.RequestParam;
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
import org.springframework.web.bind.annotation.ResponseBody;
|
import org.springframework.web.bind.annotation.ResponseBody;
|
||||||
|
|
||||||
|
import com.eactive.eai.adapter.http.dynamic.UnkownMessageLogUtils;
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||||
import com.eactive.eai.authserver.config.RequestContextData;
|
import com.eactive.eai.authserver.config.RequestContextData;
|
||||||
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
||||||
@@ -42,8 +45,6 @@ import com.eactive.eai.common.util.UUID;
|
|||||||
import com.eactive.eai.data.entity.onl.authserver.TokenIssuanceLog;
|
import com.eactive.eai.data.entity.onl.authserver.TokenIssuanceLog;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
import java.security.Principal;
|
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
public class DJErpOAuth2Controller {
|
public class DJErpOAuth2Controller {
|
||||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||||
@@ -160,6 +161,12 @@ public class DJErpOAuth2Controller {
|
|||||||
clientId, grantType, scopes);
|
clientId, grantType, scopes);
|
||||||
logger.error(e.getMessage());
|
logger.error(e.getMessage());
|
||||||
logTokenIssuance(false, false, e.getMessage(), null);
|
logTokenIssuance(false, false, e.getMessage(), null);
|
||||||
|
|
||||||
|
Properties logProp = new Properties();
|
||||||
|
logProp.put("clientId", clientId);
|
||||||
|
UnkownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
|
||||||
|
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
|
||||||
|
|
||||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage());
|
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage());
|
||||||
int statusCode = NumberUtils.toInt(StringUtils.left(e.getCode(), 3), HttpStatus.UNAUTHORIZED.value());
|
int statusCode = NumberUtils.toInt(StringUtils.left(e.getCode(), 3), HttpStatus.UNAUTHORIZED.value());
|
||||||
return ResponseEntity.status(statusCode).body(errorJson);
|
return ResponseEntity.status(statusCode).body(errorJson);
|
||||||
@@ -169,6 +176,12 @@ public class DJErpOAuth2Controller {
|
|||||||
clientId, grantType, scopes);
|
clientId, grantType, scopes);
|
||||||
logger.error(e.getMessage());
|
logger.error(e.getMessage());
|
||||||
logTokenIssuance(false, false, e.getMessage(), null);
|
logTokenIssuance(false, false, e.getMessage(), null);
|
||||||
|
|
||||||
|
Properties logProp = new Properties();
|
||||||
|
logProp.put("clientId", clientId);
|
||||||
|
UnkownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
|
||||||
|
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
|
||||||
|
|
||||||
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, "Unauthorized. [Unknown]");
|
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, "Unauthorized. [Unknown]");
|
||||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorJson);
|
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorJson);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
public class GroupMetricDTO {
|
||||||
|
private String groupId;
|
||||||
|
private String groupName;
|
||||||
|
private boolean activate;
|
||||||
|
private long allowed;
|
||||||
|
private long rejectedPerSecond;
|
||||||
|
private long rejectedThreshold;
|
||||||
|
private long totalRequests;
|
||||||
|
private double rejectRatio;
|
||||||
|
private long lastResetTime;
|
||||||
|
|
||||||
|
public String getGroupId() { return groupId; }
|
||||||
|
public void setGroupId(String groupId) { this.groupId = groupId; }
|
||||||
|
|
||||||
|
public String getGroupName() { return groupName; }
|
||||||
|
public void setGroupName(String groupName) { this.groupName = groupName; }
|
||||||
|
|
||||||
|
public boolean isActivate() { return activate; }
|
||||||
|
public void setActivate(boolean activate) { this.activate = activate; }
|
||||||
|
|
||||||
|
public long getAllowed() { return allowed; }
|
||||||
|
public void setAllowed(long allowed) { this.allowed = allowed; }
|
||||||
|
|
||||||
|
public long getRejectedPerSecond() { return rejectedPerSecond; }
|
||||||
|
public void setRejectedPerSecond(long rejectedPerSecond) { this.rejectedPerSecond = rejectedPerSecond; }
|
||||||
|
|
||||||
|
public long getRejectedThreshold() { return rejectedThreshold; }
|
||||||
|
public void setRejectedThreshold(long rejectedThreshold) { this.rejectedThreshold = rejectedThreshold; }
|
||||||
|
|
||||||
|
public long getTotalRequests() { return totalRequests; }
|
||||||
|
public void setTotalRequests(long totalRequests) { this.totalRequests = totalRequests; }
|
||||||
|
|
||||||
|
public double getRejectRatio() { return rejectRatio; }
|
||||||
|
public void setRejectRatio(double rejectRatio) { this.rejectRatio = rejectRatio; }
|
||||||
|
|
||||||
|
public long getLastResetTime() { return lastResetTime; }
|
||||||
|
public void setLastResetTime(long lastResetTime) { this.lastResetTime = lastResetTime; }
|
||||||
|
}
|
||||||
@@ -1,21 +1,20 @@
|
|||||||
package com.eactive.eai.manage.inflow;
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
|
||||||
import com.eactive.eai.common.inflow.CustomGroupBucket;
|
import com.eactive.eai.common.inflow.CustomGroupBucket;
|
||||||
import com.eactive.eai.common.inflow.InflowControlManager;
|
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||||
import com.eactive.eai.common.inflow.InflowGroupVO;
|
import com.eactive.eai.common.inflow.InflowGroupVO;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class InflowGroupBucketService {
|
public class InflowGroupBucketService {
|
||||||
|
|
||||||
public GroupBucketStatusDTO getGroupBucketStatus(String groupId) {
|
public GroupBucketStatusDTO getGroupBucketStatus(String groupId) {
|
||||||
InflowControlManager manager = InflowControlManager.getInstance();
|
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
|
||||||
|
|
||||||
InflowGroupVO groupVo = manager.getGroupInflowThreshold(groupId);
|
InflowGroupVO groupVo = manager.getGroupInflowThreshold(groupId);
|
||||||
if (groupVo == null) {
|
if (groupVo == null) {
|
||||||
@@ -72,25 +71,12 @@ public class InflowGroupBucketService {
|
|||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 그룹 버킷 조회 (리플렉션 사용)
|
|
||||||
*/
|
|
||||||
public CustomGroupBucket getCustomGroupBucket(String groupId) {
|
public CustomGroupBucket getCustomGroupBucket(String groupId) {
|
||||||
try {
|
return InflowControlUtil.getInflowControlManager().getGroupBucket(groupId);
|
||||||
InflowControlManager manager = InflowControlManager.getInstance();
|
|
||||||
Field field = InflowControlManager.class.getDeclaredField("groupBucketList");
|
|
||||||
field.setAccessible(true);
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
Map<String, CustomGroupBucket> groupBucketList =
|
|
||||||
(Map<String, CustomGroupBucket>) field.get(manager);
|
|
||||||
return groupBucketList.get(groupId);
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<GroupBucketStatusDTO> getAllGroupBucketStatus() {
|
public List<GroupBucketStatusDTO> getAllGroupBucketStatus() {
|
||||||
InflowControlManager manager = InflowControlManager.getInstance();
|
AbstractInflowControlManager manager = InflowControlUtil.getInflowControlManager();
|
||||||
String[] groupIds = manager.getGroupAllKeys();
|
String[] groupIds = manager.getGroupAllKeys();
|
||||||
|
|
||||||
List<GroupBucketStatusDTO> result = new ArrayList<>();
|
List<GroupBucketStatusDTO> result = new ArrayList<>();
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/manage/inflow/group")
|
||||||
|
public class InflowGroupMetricController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private InflowGroupMetricService metricService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 특정 그룹의 메트릭 조회
|
||||||
|
* GET /manage/inflow/group/{groupId}/metric
|
||||||
|
*/
|
||||||
|
@GetMapping("/{groupId}/metric")
|
||||||
|
public ResponseEntity<?> getGroupMetric(@PathVariable String groupId) {
|
||||||
|
GroupMetricDTO metric = metricService.getGroupMetric(groupId);
|
||||||
|
|
||||||
|
if (metric == null) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "그룹을 찾을 수 없습니다: " + groupId);
|
||||||
|
return ResponseEntity.ok(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", metric);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모든 그룹의 메트릭 조회
|
||||||
|
* GET /manage/inflow/group/metric
|
||||||
|
*/
|
||||||
|
@GetMapping("/metric")
|
||||||
|
public ResponseEntity<?> getAllGroupMetrics() {
|
||||||
|
List<GroupMetricDTO> list = metricService.getAllGroupMetrics();
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", list);
|
||||||
|
result.put("count", list.size());
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 특정 그룹의 메트릭 초기화
|
||||||
|
* POST /manage/inflow/group/{groupId}/metric/reset
|
||||||
|
*/
|
||||||
|
@PostMapping("/{groupId}/metric/reset")
|
||||||
|
public ResponseEntity<?> resetGroupMetric(@PathVariable String groupId) {
|
||||||
|
boolean ok = metricService.resetGroupMetric(groupId);
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", ok);
|
||||||
|
result.put("message", ok ? "초기화 완료: " + groupId : "그룹을 찾을 수 없습니다: " + groupId);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 전체 그룹 메트릭 초기화
|
||||||
|
* POST /manage/inflow/group/metric/reset
|
||||||
|
*/
|
||||||
|
@PostMapping("/metric/reset")
|
||||||
|
public ResponseEntity<?> resetAllGroupMetrics() {
|
||||||
|
metricService.resetAllGroupMetrics();
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("message", "전체 그룹 메트릭 초기화 완료");
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.inflow.Bucket;
|
||||||
|
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||||
|
import com.eactive.eai.common.inflow.InflowGroupVO;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class InflowGroupMetricService {
|
||||||
|
|
||||||
|
public GroupMetricDTO getGroupMetric(String groupId) {
|
||||||
|
DualInflowControlManager manager = getManager();
|
||||||
|
if (manager == null) return null;
|
||||||
|
|
||||||
|
InflowGroupVO groupVo = manager.getGroupInflowThreshold(groupId);
|
||||||
|
if (groupVo == null) return null;
|
||||||
|
|
||||||
|
return buildDTO(groupId, groupVo, manager.getGroupMetrics(groupId));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<GroupMetricDTO> getAllGroupMetrics() {
|
||||||
|
DualInflowControlManager manager = getManager();
|
||||||
|
if (manager == null) return new ArrayList<>();
|
||||||
|
|
||||||
|
List<GroupMetricDTO> result = new ArrayList<>();
|
||||||
|
for (String groupId : manager.getGroupAllKeys()) {
|
||||||
|
GroupMetricDTO dto = getGroupMetric(groupId);
|
||||||
|
if (dto != null) result.add(dto);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean resetGroupMetric(String groupId) {
|
||||||
|
DualInflowControlManager manager = getManager();
|
||||||
|
if (manager == null) return false;
|
||||||
|
if (manager.getGroupInflowThreshold(groupId) == null) return false;
|
||||||
|
manager.resetGroupMetrics(groupId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void resetAllGroupMetrics() {
|
||||||
|
DualInflowControlManager manager = getManager();
|
||||||
|
if (manager != null) manager.resetAllGroupMetrics();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected DualInflowControlManager getManager() {
|
||||||
|
Bucket bucket = InflowControlUtil.getBucket();
|
||||||
|
return (bucket instanceof DualInflowControlManager)
|
||||||
|
? (DualInflowControlManager) bucket
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private GroupMetricDTO buildDTO(String groupId, InflowGroupVO groupVo,
|
||||||
|
DualInflowControlManager.TargetMetrics m) {
|
||||||
|
GroupMetricDTO dto = new GroupMetricDTO();
|
||||||
|
dto.setGroupId(groupId);
|
||||||
|
dto.setGroupName(groupVo.getGroupName());
|
||||||
|
dto.setActivate(groupVo.isActivate());
|
||||||
|
|
||||||
|
if (m != null) {
|
||||||
|
long allowed = m.allowed.get();
|
||||||
|
long rejPs = m.rejectedPerSecond.get();
|
||||||
|
long rejTh = m.rejectedThreshold.get();
|
||||||
|
long total = allowed + rejPs + rejTh;
|
||||||
|
dto.setAllowed(allowed);
|
||||||
|
dto.setRejectedPerSecond(rejPs);
|
||||||
|
dto.setRejectedThreshold(rejTh);
|
||||||
|
dto.setTotalRequests(total);
|
||||||
|
dto.setRejectRatio(total > 0
|
||||||
|
? Math.round((double)(rejPs + rejTh) / total * 10000) / 100.0
|
||||||
|
: 0.0);
|
||||||
|
dto.setLastResetTime(m.lastResetTime);
|
||||||
|
}
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 어댑터/인터페이스/클라이언트 버킷 상태 모니터링 API.
|
||||||
|
*
|
||||||
|
* DualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
|
||||||
|
* 비활성화 환경에서는 success=false 또는 빈 목록을 반환한다.
|
||||||
|
*
|
||||||
|
* GET /manage/inflow/adapter/bucket-status → 전체 어댑터 버킷 상태
|
||||||
|
* GET /manage/inflow/adapter/{adapterId}/bucket-status → 특정 어댑터 버킷 상태
|
||||||
|
* GET /manage/inflow/interface/bucket-status → 전체 인터페이스 버킷 상태
|
||||||
|
* GET /manage/inflow/interface/{interfaceId}/bucket-status → 특정 인터페이스 버킷 상태
|
||||||
|
* GET /manage/inflow/client/bucket-status → 전체 클라이언트 버킷 상태
|
||||||
|
* GET /manage/inflow/client/{clientId}/bucket-status → 특정 클라이언트 버킷 상태
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/manage/inflow")
|
||||||
|
public class InflowTargetBucketController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private InflowTargetBucketService bucketService;
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 어댑터
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@GetMapping("/adapter/bucket-status")
|
||||||
|
public ResponseEntity<?> getAllAdapterBucketStatus() {
|
||||||
|
List<TargetBucketStatusDTO> list = bucketService.getAllAdapterBucketStatus();
|
||||||
|
return ok(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/adapter/{adapterId}/bucket-status")
|
||||||
|
public ResponseEntity<?> getAdapterBucketStatus(@PathVariable String adapterId) {
|
||||||
|
TargetBucketStatusDTO dto = bucketService.getAdapterBucketStatus(adapterId);
|
||||||
|
return single(dto, "어댑터를 찾을 수 없습니다: " + adapterId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 인터페이스
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@GetMapping("/interface/bucket-status")
|
||||||
|
public ResponseEntity<?> getAllInterfaceBucketStatus() {
|
||||||
|
List<TargetBucketStatusDTO> list = bucketService.getAllInterfaceBucketStatus();
|
||||||
|
return ok(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/interface/{interfaceId}/bucket-status")
|
||||||
|
public ResponseEntity<?> getInterfaceBucketStatus(@PathVariable String interfaceId) {
|
||||||
|
TargetBucketStatusDTO dto = bucketService.getInterfaceBucketStatus(interfaceId);
|
||||||
|
return single(dto, "인터페이스를 찾을 수 없습니다: " + interfaceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 클라이언트
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@GetMapping("/client/bucket-status")
|
||||||
|
public ResponseEntity<?> getAllClientBucketStatus() {
|
||||||
|
List<TargetBucketStatusDTO> list = bucketService.getAllClientBucketStatus();
|
||||||
|
return ok(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/client/{clientId}/bucket-status")
|
||||||
|
public ResponseEntity<?> getClientBucketStatus(@PathVariable String clientId) {
|
||||||
|
TargetBucketStatusDTO dto = bucketService.getClientBucketStatus(clientId);
|
||||||
|
return single(dto, "클라이언트를 찾을 수 없습니다: " + clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Helpers
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
private ResponseEntity<?> ok(List<TargetBucketStatusDTO> list) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", list);
|
||||||
|
result.put("count", list.size());
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<?> single(TargetBucketStatusDTO dto, String notFoundMsg) {
|
||||||
|
if (dto == null) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", notFoundMsg);
|
||||||
|
return ResponseEntity.ok(error);
|
||||||
|
}
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", dto);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
|
||||||
|
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||||
|
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 어댑터/인터페이스/클라이언트 버킷 상태 조회 서비스.
|
||||||
|
*
|
||||||
|
* DualInflowControlManager 가 활성화된 경우에만 동작한다.
|
||||||
|
* InflowControlManager 가 기본 구현체인 경우 빈 목록 또는 null 을 반환한다.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class InflowTargetBucketService {
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 어댑터
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public TargetBucketStatusDTO getAdapterBucketStatus(String adapterId) {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return null;
|
||||||
|
DualCustomBucket bucket = manager.getAdapterBucket(adapterId);
|
||||||
|
if (bucket == null) return null;
|
||||||
|
return toDto(adapterId, "ADAPTER", bucket);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TargetBucketStatusDTO> getAllAdapterBucketStatus() {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return new ArrayList<>();
|
||||||
|
return toDtoList("ADAPTER", manager.getAdapterBucketMap());
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 인터페이스
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public TargetBucketStatusDTO getInterfaceBucketStatus(String interfaceId) {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return null;
|
||||||
|
DualCustomBucket bucket = manager.getInterfaceBucket(interfaceId);
|
||||||
|
if (bucket == null) return null;
|
||||||
|
return toDto(interfaceId, "INTERFACE", bucket);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TargetBucketStatusDTO> getAllInterfaceBucketStatus() {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return new ArrayList<>();
|
||||||
|
return toDtoList("INTERFACE", manager.getInterfaceBucketMap());
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 클라이언트
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public TargetBucketStatusDTO getClientBucketStatus(String clientId) {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return null;
|
||||||
|
DualCustomBucket bucket = manager.getClientBucket(clientId);
|
||||||
|
if (bucket == null) return null;
|
||||||
|
return toDto(clientId, "CLIENT", bucket);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TargetBucketStatusDTO> getAllClientBucketStatus() {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return new ArrayList<>();
|
||||||
|
return toDtoList("CLIENT", manager.getClientBucketMap());
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Private helpers
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
protected DualInflowControlManager getDualManager() {
|
||||||
|
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
|
||||||
|
return (base instanceof DualInflowControlManager) ? (DualInflowControlManager) base : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private TargetBucketStatusDTO toDto(String targetId, String targetType, DualCustomBucket bucket) {
|
||||||
|
InflowTargetVO vo = bucket.getInflowTargetVo();
|
||||||
|
List<GroupBucketStatusDTO.BucketInfo> buckets = new ArrayList<>();
|
||||||
|
|
||||||
|
if (vo.getThresholdPerSecond() > 0) {
|
||||||
|
long capacity = vo.getThresholdPerSecond();
|
||||||
|
long available = bucket.getPerSecondAvailableTokens();
|
||||||
|
if (available < 0) available = capacity;
|
||||||
|
buckets.add(new GroupBucketStatusDTO.BucketInfo(
|
||||||
|
"perSecond", capacity, Math.min(available, capacity), "SEC"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vo.getThreshold() > 0) {
|
||||||
|
long capacity = vo.getThreshold();
|
||||||
|
long available = bucket.getThresholdAvailableTokens();
|
||||||
|
if (available < 0) available = capacity;
|
||||||
|
buckets.add(new GroupBucketStatusDTO.BucketInfo(
|
||||||
|
"threshold", capacity, Math.min(available, capacity), vo.getThresholdTimeUnit()));
|
||||||
|
}
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = new TargetBucketStatusDTO();
|
||||||
|
dto.setTargetId(targetId);
|
||||||
|
dto.setTargetType(targetType);
|
||||||
|
dto.setActivate(vo.isActivate());
|
||||||
|
dto.setBuckets(buckets);
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<TargetBucketStatusDTO> toDtoList(String targetType, Map<String, DualCustomBucket> bucketMap) {
|
||||||
|
List<TargetBucketStatusDTO> result = new ArrayList<>();
|
||||||
|
for (Map.Entry<String, DualCustomBucket> entry : bucketMap.entrySet()) {
|
||||||
|
result.add(toDto(entry.getKey(), targetType, entry.getValue()));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 어댑터/인터페이스/클라이언트 유량제어 메트릭 API.
|
||||||
|
*
|
||||||
|
* DualInflowControlManager 가 활성화된 환경에서만 정상 응답한다.
|
||||||
|
*
|
||||||
|
* GET /manage/inflow/adapter/metric → 전체 어댑터 메트릭
|
||||||
|
* GET /manage/inflow/adapter/{adapterId}/metric → 특정 어댑터 메트릭
|
||||||
|
* POST /manage/inflow/adapter/metric/reset → 전체 어댑터 메트릭 초기화
|
||||||
|
* POST /manage/inflow/adapter/{adapterId}/metric/reset → 특정 어댑터 메트릭 초기화
|
||||||
|
*
|
||||||
|
* GET /manage/inflow/interface/metric → 전체 인터페이스 메트릭
|
||||||
|
* GET /manage/inflow/interface/{interfaceId}/metric → 특정 인터페이스 메트릭
|
||||||
|
* POST /manage/inflow/interface/metric/reset → 전체 인터페이스 메트릭 초기화
|
||||||
|
* POST /manage/inflow/interface/{interfaceId}/metric/reset → 특정 인터페이스 메트릭 초기화
|
||||||
|
*
|
||||||
|
* GET /manage/inflow/client/metric → 전체 클라이언트 메트릭
|
||||||
|
* GET /manage/inflow/client/{clientId}/metric → 특정 클라이언트 메트릭
|
||||||
|
* POST /manage/inflow/client/metric/reset → 전체 클라이언트 메트릭 초기화
|
||||||
|
* POST /manage/inflow/client/{clientId}/metric/reset → 특정 클라이언트 메트릭 초기화
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/manage/inflow")
|
||||||
|
public class InflowTargetMetricController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private InflowTargetMetricService metricService;
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 어댑터
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@GetMapping("/adapter/metric")
|
||||||
|
public ResponseEntity<?> getAllAdapterMetrics() {
|
||||||
|
List<TargetMetricDTO> list = metricService.getAllAdapterMetrics();
|
||||||
|
return okList(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/adapter/{adapterId}/metric")
|
||||||
|
public ResponseEntity<?> getAdapterMetric(@PathVariable String adapterId) {
|
||||||
|
TargetMetricDTO dto = metricService.getAdapterMetric(adapterId);
|
||||||
|
return okSingle(dto, "어댑터를 찾을 수 없습니다: " + adapterId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/adapter/metric/reset")
|
||||||
|
public ResponseEntity<?> resetAllAdapterMetrics() {
|
||||||
|
metricService.resetAllAdapterMetrics();
|
||||||
|
return okReset("전체 어댑터 메트릭 초기화 완료");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/adapter/{adapterId}/metric/reset")
|
||||||
|
public ResponseEntity<?> resetAdapterMetric(@PathVariable String adapterId) {
|
||||||
|
boolean ok = metricService.resetAdapterMetric(adapterId);
|
||||||
|
return okResetSingle(ok, adapterId, "어댑터");
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 인터페이스
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@GetMapping("/interface/metric")
|
||||||
|
public ResponseEntity<?> getAllInterfaceMetrics() {
|
||||||
|
List<TargetMetricDTO> list = metricService.getAllInterfaceMetrics();
|
||||||
|
return okList(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/interface/{interfaceId}/metric")
|
||||||
|
public ResponseEntity<?> getInterfaceMetric(@PathVariable String interfaceId) {
|
||||||
|
TargetMetricDTO dto = metricService.getInterfaceMetric(interfaceId);
|
||||||
|
return okSingle(dto, "인터페이스를 찾을 수 없습니다: " + interfaceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/interface/metric/reset")
|
||||||
|
public ResponseEntity<?> resetAllInterfaceMetrics() {
|
||||||
|
metricService.resetAllInterfaceMetrics();
|
||||||
|
return okReset("전체 인터페이스 메트릭 초기화 완료");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/interface/{interfaceId}/metric/reset")
|
||||||
|
public ResponseEntity<?> resetInterfaceMetric(@PathVariable String interfaceId) {
|
||||||
|
boolean ok = metricService.resetInterfaceMetric(interfaceId);
|
||||||
|
return okResetSingle(ok, interfaceId, "인터페이스");
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 클라이언트
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@GetMapping("/client/metric")
|
||||||
|
public ResponseEntity<?> getAllClientMetrics() {
|
||||||
|
List<TargetMetricDTO> list = metricService.getAllClientMetrics();
|
||||||
|
return okList(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/client/{clientId}/metric")
|
||||||
|
public ResponseEntity<?> getClientMetric(@PathVariable String clientId) {
|
||||||
|
TargetMetricDTO dto = metricService.getClientMetric(clientId);
|
||||||
|
return okSingle(dto, "클라이언트를 찾을 수 없습니다: " + clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/client/metric/reset")
|
||||||
|
public ResponseEntity<?> resetAllClientMetrics() {
|
||||||
|
metricService.resetAllClientMetrics();
|
||||||
|
return okReset("전체 클라이언트 메트릭 초기화 완료");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/client/{clientId}/metric/reset")
|
||||||
|
public ResponseEntity<?> resetClientMetric(@PathVariable String clientId) {
|
||||||
|
boolean ok = metricService.resetClientMetric(clientId);
|
||||||
|
return okResetSingle(ok, clientId, "클라이언트");
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Helpers
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
private ResponseEntity<?> okList(List<TargetMetricDTO> list) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", list);
|
||||||
|
result.put("count", list.size());
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<?> okSingle(TargetMetricDTO dto, String notFoundMsg) {
|
||||||
|
if (dto == null) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", notFoundMsg);
|
||||||
|
return ResponseEntity.ok(error);
|
||||||
|
}
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("data", dto);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<?> okReset(String message) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", true);
|
||||||
|
result.put("message", message);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<?> okResetSingle(boolean ok, String targetId, String targetLabel) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("success", ok);
|
||||||
|
result.put("message", ok
|
||||||
|
? "초기화 완료: " + targetId
|
||||||
|
: targetLabel + "를 찾을 수 없습니다: " + targetId);
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.inflow.AbstractInflowControlManager;
|
||||||
|
import com.eactive.eai.common.inflow.InflowControlUtil;
|
||||||
|
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class InflowTargetMetricService {
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 어댑터
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public TargetMetricDTO getAdapterMetric(String adapterId) {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return null;
|
||||||
|
InflowTargetVO vo = manager.getAdapterInflowThreashold(adapterId);
|
||||||
|
if (vo == null) return null;
|
||||||
|
return buildDTO(adapterId, "ADAPTER", vo, manager.getAdapterMetrics(adapterId));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TargetMetricDTO> getAllAdapterMetrics() {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return new ArrayList<>();
|
||||||
|
List<TargetMetricDTO> result = new ArrayList<>();
|
||||||
|
for (String id : manager.getAdapterAllKeys()) {
|
||||||
|
TargetMetricDTO dto = getAdapterMetric(id);
|
||||||
|
if (dto != null) result.add(dto);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean resetAdapterMetric(String adapterId) {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return false;
|
||||||
|
if (manager.getAdapterInflowThreashold(adapterId) == null) return false;
|
||||||
|
manager.resetAdapterMetrics(adapterId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void resetAllAdapterMetrics() {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager != null) manager.resetAllAdapterMetrics();
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 인터페이스
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public TargetMetricDTO getInterfaceMetric(String interfaceId) {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return null;
|
||||||
|
InflowTargetVO vo = manager.getInterfaceInflowThreashold(interfaceId);
|
||||||
|
if (vo == null) return null;
|
||||||
|
return buildDTO(interfaceId, "INTERFACE", vo, manager.getInterfaceMetrics(interfaceId));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TargetMetricDTO> getAllInterfaceMetrics() {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return new ArrayList<>();
|
||||||
|
List<TargetMetricDTO> result = new ArrayList<>();
|
||||||
|
for (String id : manager.getInterfaceAllKeys()) {
|
||||||
|
TargetMetricDTO dto = getInterfaceMetric(id);
|
||||||
|
if (dto != null) result.add(dto);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean resetInterfaceMetric(String interfaceId) {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return false;
|
||||||
|
if (manager.getInterfaceInflowThreashold(interfaceId) == null) return false;
|
||||||
|
manager.resetInterfaceMetrics(interfaceId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void resetAllInterfaceMetrics() {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager != null) manager.resetAllInterfaceMetrics();
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 클라이언트
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public TargetMetricDTO getClientMetric(String clientId) {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return null;
|
||||||
|
InflowTargetVO vo = manager.getClientInflowThreshold(clientId);
|
||||||
|
if (vo == null) return null;
|
||||||
|
return buildDTO(clientId, "CLIENT", vo, manager.getClientMetrics(clientId));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TargetMetricDTO> getAllClientMetrics() {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return new ArrayList<>();
|
||||||
|
List<TargetMetricDTO> result = new ArrayList<>();
|
||||||
|
for (String id : manager.getClientBucketMap().keySet()) {
|
||||||
|
TargetMetricDTO dto = getClientMetric(id);
|
||||||
|
if (dto != null) result.add(dto);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean resetClientMetric(String clientId) {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager == null) return false;
|
||||||
|
if (manager.getClientInflowThreshold(clientId) == null) return false;
|
||||||
|
manager.resetClientMetrics(clientId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void resetAllClientMetrics() {
|
||||||
|
DualInflowControlManager manager = getDualManager();
|
||||||
|
if (manager != null) manager.resetAllClientMetrics();
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Private helpers
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
protected DualInflowControlManager getDualManager() {
|
||||||
|
AbstractInflowControlManager base = InflowControlUtil.getInflowControlManager();
|
||||||
|
return (base instanceof DualInflowControlManager) ? (DualInflowControlManager) base : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private TargetMetricDTO buildDTO(String targetId, String targetType,
|
||||||
|
InflowTargetVO vo,
|
||||||
|
DualInflowControlManager.TargetMetrics m) {
|
||||||
|
TargetMetricDTO dto = new TargetMetricDTO();
|
||||||
|
dto.setTargetId(targetId);
|
||||||
|
dto.setTargetType(targetType);
|
||||||
|
dto.setActivate(vo.isActivate());
|
||||||
|
|
||||||
|
if (m != null) {
|
||||||
|
long allowed = m.allowed.get();
|
||||||
|
long rejPs = m.rejectedPerSecond.get();
|
||||||
|
long rejTh = m.rejectedThreshold.get();
|
||||||
|
long total = allowed + rejPs + rejTh;
|
||||||
|
dto.setAllowed(allowed);
|
||||||
|
dto.setRejectedPerSecond(rejPs);
|
||||||
|
dto.setRejectedThreshold(rejTh);
|
||||||
|
dto.setTotalRequests(total);
|
||||||
|
dto.setRejectRatio(total > 0
|
||||||
|
? Math.round((double)(rejPs + rejTh) / total * 10000) / 100.0
|
||||||
|
: 0.0);
|
||||||
|
dto.setLastResetTime(m.lastResetTime);
|
||||||
|
}
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 어댑터/인터페이스/클라이언트 버킷 상태 DTO.
|
||||||
|
* {@link GroupBucketStatusDTO}와 동일한 BucketInfo 구조를 공유한다.
|
||||||
|
*/
|
||||||
|
public class TargetBucketStatusDTO {
|
||||||
|
|
||||||
|
private String targetId; // 어댑터명 | 인터페이스ID | 클라이언트ID
|
||||||
|
private String targetType; // "ADAPTER" | "INTERFACE" | "CLIENT"
|
||||||
|
private boolean activate;
|
||||||
|
private List<GroupBucketStatusDTO.BucketInfo> buckets;
|
||||||
|
|
||||||
|
public String getTargetId() { return targetId; }
|
||||||
|
public void setTargetId(String targetId) { this.targetId = targetId; }
|
||||||
|
|
||||||
|
public String getTargetType() { return targetType; }
|
||||||
|
public void setTargetType(String targetType) { this.targetType = targetType; }
|
||||||
|
|
||||||
|
public boolean isActivate() { return activate; }
|
||||||
|
public void setActivate(boolean activate) { this.activate = activate; }
|
||||||
|
|
||||||
|
public List<GroupBucketStatusDTO.BucketInfo> getBuckets() { return buckets; }
|
||||||
|
public void setBuckets(List<GroupBucketStatusDTO.BucketInfo> buckets) { this.buckets = buckets; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 어댑터/인터페이스/클라이언트 메트릭 DTO.
|
||||||
|
*/
|
||||||
|
public class TargetMetricDTO {
|
||||||
|
|
||||||
|
private String targetId;
|
||||||
|
private String targetType; // "ADAPTER" | "INTERFACE" | "CLIENT"
|
||||||
|
private boolean activate;
|
||||||
|
private long allowed;
|
||||||
|
private long rejectedPerSecond;
|
||||||
|
private long rejectedThreshold;
|
||||||
|
private long totalRequests;
|
||||||
|
private double rejectRatio;
|
||||||
|
private long lastResetTime;
|
||||||
|
|
||||||
|
public String getTargetId() { return targetId; }
|
||||||
|
public void setTargetId(String targetId) { this.targetId = targetId; }
|
||||||
|
|
||||||
|
public String getTargetType() { return targetType; }
|
||||||
|
public void setTargetType(String targetType) { this.targetType = targetType; }
|
||||||
|
|
||||||
|
public boolean isActivate() { return activate; }
|
||||||
|
public void setActivate(boolean activate) { this.activate = activate; }
|
||||||
|
|
||||||
|
public long getAllowed() { return allowed; }
|
||||||
|
public void setAllowed(long allowed) { this.allowed = allowed; }
|
||||||
|
|
||||||
|
public long getRejectedPerSecond() { return rejectedPerSecond; }
|
||||||
|
public void setRejectedPerSecond(long rejectedPerSecond) { this.rejectedPerSecond = rejectedPerSecond; }
|
||||||
|
|
||||||
|
public long getRejectedThreshold() { return rejectedThreshold; }
|
||||||
|
public void setRejectedThreshold(long rejectedThreshold) { this.rejectedThreshold = rejectedThreshold; }
|
||||||
|
|
||||||
|
public long getTotalRequests() { return totalRequests; }
|
||||||
|
public void setTotalRequests(long totalRequests) { this.totalRequests = totalRequests; }
|
||||||
|
|
||||||
|
public double getRejectRatio() { return rejectRatio; }
|
||||||
|
public void setRejectRatio(double rejectRatio) { this.rejectRatio = rejectRatio; }
|
||||||
|
|
||||||
|
public long getLastResetTime() { return lastResetTime; }
|
||||||
|
public void setLastResetTime(long lastResetTime) { this.lastResetTime = lastResetTime; }
|
||||||
|
}
|
||||||
@@ -8,7 +8,7 @@ mapper.definition=standard-message-mapping-config-djb.properties
|
|||||||
# StandardMessage Coordinator implementation
|
# StandardMessage Coordinator implementation
|
||||||
message.coordinator.class=com.eactive.eai.custom.message.StandardMessageCoordinatorDJB
|
message.coordinator.class=com.eactive.eai.custom.message.StandardMessageCoordinatorDJB
|
||||||
# RequestProcessor implementation
|
# RequestProcessor implementation
|
||||||
#requestProcessor.class=com.eactive.eai.inbound.processor.RequestProcessor
|
requestProcessor.class=com.eactive.eai.inbound.processor.DualRequestProcessor
|
||||||
# reader : parsing input data to StandardMessage
|
# reader : parsing input data to StandardMessage
|
||||||
reader.JSON=com.eactive.eai.message.parser.JsonReader
|
reader.JSON=com.eactive.eai.message.parser.JsonReader
|
||||||
reader.JSN=com.eactive.eai.message.parser.JsonReader
|
reader.JSN=com.eactive.eai.message.parser.JsonReader
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* InflowGroupMetricController 단위 테스트.
|
||||||
|
*
|
||||||
|
* <p>Spring MVC를 기동하지 않고 컨트롤러를 직접 인스턴스화하여
|
||||||
|
* 응답 구조(success, data, count, message)를 검증한다.
|
||||||
|
*/
|
||||||
|
class InflowGroupMetricControllerTest {
|
||||||
|
|
||||||
|
private InflowGroupMetricController controller;
|
||||||
|
private InflowGroupMetricService mockService;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
controller = new InflowGroupMetricController();
|
||||||
|
mockService = mock(InflowGroupMetricService.class);
|
||||||
|
ReflectionTestUtils.setField(controller, "metricService", mockService);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Helper
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private GroupMetricDTO makeDTO(String groupId, String groupName,
|
||||||
|
long allowed, long rejPs, long rejTh) {
|
||||||
|
GroupMetricDTO dto = new GroupMetricDTO();
|
||||||
|
dto.setGroupId(groupId);
|
||||||
|
dto.setGroupName(groupName);
|
||||||
|
dto.setActivate(true);
|
||||||
|
dto.setAllowed(allowed);
|
||||||
|
dto.setRejectedPerSecond(rejPs);
|
||||||
|
dto.setRejectedThreshold(rejTh);
|
||||||
|
long total = allowed + rejPs + rejTh;
|
||||||
|
dto.setTotalRequests(total);
|
||||||
|
dto.setRejectRatio(total > 0 ? (double)(rejPs + rejTh) / total * 100 : 0.0);
|
||||||
|
dto.setLastResetTime(System.currentTimeMillis());
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> body(ResponseEntity<?> response) {
|
||||||
|
return (Map<String, Object>) response.getBody();
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// GET /{groupId}/metric
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getGroupMetric_found_successTrueAndDataPresent() {
|
||||||
|
GroupMetricDTO dto = makeDTO("G1", "결제그룹", 900, 60, 40);
|
||||||
|
when(mockService.getGroupMetric("G1")).thenReturn(dto);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getGroupMetric("G1");
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(200, response.getStatusCodeValue());
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(dto, body.get("data"));
|
||||||
|
assertFalse(body.containsKey("message"), "성공 응답에 message 필드는 없어야 합니다");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getGroupMetric_notFound_successFalseWithMessage() {
|
||||||
|
when(mockService.getGroupMetric("GHOST")).thenReturn(null);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getGroupMetric("GHOST");
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(200, response.getStatusCodeValue());
|
||||||
|
assertEquals(Boolean.FALSE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("GHOST"),
|
||||||
|
"오류 메시지에 groupId가 포함되어야 합니다");
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// GET /metric
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllGroupMetrics_returnsListAndCount() {
|
||||||
|
List<GroupMetricDTO> list = Arrays.asList(
|
||||||
|
makeDTO("G1", "그룹1", 100, 5, 0),
|
||||||
|
makeDTO("G2", "그룹2", 200, 0, 10)
|
||||||
|
);
|
||||||
|
when(mockService.getAllGroupMetrics()).thenReturn(list);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getAllGroupMetrics();
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(list, body.get("data"));
|
||||||
|
assertEquals(2, body.get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllGroupMetrics_emptyList_countZero() {
|
||||||
|
when(mockService.getAllGroupMetrics()).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getAllGroupMetrics();
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertEquals(0, body.get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// POST /{groupId}/metric/reset
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetGroupMetric_success_successTrueWithGroupId() {
|
||||||
|
when(mockService.resetGroupMetric("G1")).thenReturn(true);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.resetGroupMetric("G1");
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("G1"),
|
||||||
|
"성공 메시지에 groupId가 포함되어야 합니다");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetGroupMetric_notFound_successFalseWithGroupId() {
|
||||||
|
when(mockService.resetGroupMetric("GHOST")).thenReturn(false);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.resetGroupMetric("GHOST");
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(Boolean.FALSE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("GHOST"),
|
||||||
|
"오류 메시지에 groupId가 포함되어야 합니다");
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// POST /metric/reset
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAllGroupMetrics_alwaysSuccessTrue() {
|
||||||
|
doNothing().when(mockService).resetAllGroupMetrics();
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.resetAllGroupMetrics();
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertNotNull(body.get("message"));
|
||||||
|
verify(mockService).resetAllGroupMetrics();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAllGroupMetrics_callsDelegateOnce() {
|
||||||
|
doNothing().when(mockService).resetAllGroupMetrics();
|
||||||
|
|
||||||
|
controller.resetAllGroupMetrics();
|
||||||
|
|
||||||
|
verify(mockService, times(1)).resetAllGroupMetrics();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.inflow.InflowGroupVO;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* InflowGroupMetricService 단위 테스트.
|
||||||
|
*
|
||||||
|
* <p>getManager()를 protected로 오버라이드하는 내부 테스트 서브클래스를 사용하여
|
||||||
|
* mockito-inline(static mock) 없이 DualInflowControlManager 의존성을 주입한다.
|
||||||
|
*/
|
||||||
|
class InflowGroupMetricServiceTest {
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 테스트용 서브클래스 — getManager()를 오버라이드하여 mock 주입
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static InflowGroupMetricService serviceWith(DualInflowControlManager manager) {
|
||||||
|
return new InflowGroupMetricService() {
|
||||||
|
@Override
|
||||||
|
protected DualInflowControlManager getManager() {
|
||||||
|
return manager;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Helpers
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private InflowGroupVO makeGroupVO(String groupId, String groupName) {
|
||||||
|
InflowGroupVO vo = new InflowGroupVO();
|
||||||
|
vo.setGroupId(groupId);
|
||||||
|
vo.setGroupName(groupName);
|
||||||
|
vo.setActivate(true);
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private DualInflowControlManager.TargetMetrics makeMetrics(long allowed, long rejPs, long rejTh) {
|
||||||
|
DualInflowControlManager.TargetMetrics m = new DualInflowControlManager.TargetMetrics();
|
||||||
|
m.allowed.set(allowed);
|
||||||
|
m.rejectedPerSecond.set(rejPs);
|
||||||
|
m.rejectedThreshold.set(rejTh);
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// getGroupMetric
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getGroupMetric_managerIsNull_returnsNull() {
|
||||||
|
assertNull(serviceWith(null).getGroupMetric("G1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getGroupMetric_groupNotFound_returnsNull() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getGroupInflowThreshold("G1")).thenReturn(null);
|
||||||
|
|
||||||
|
assertNull(serviceWith(manager).getGroupMetric("G1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getGroupMetric_noMetricsYet_returnsZeroCounters() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "결제그룹"));
|
||||||
|
when(manager.getGroupMetrics("G1")).thenReturn(null);
|
||||||
|
|
||||||
|
GroupMetricDTO dto = serviceWith(manager).getGroupMetric("G1");
|
||||||
|
|
||||||
|
assertNotNull(dto);
|
||||||
|
assertEquals("G1", dto.getGroupId());
|
||||||
|
assertEquals("결제그룹", dto.getGroupName());
|
||||||
|
assertTrue(dto.isActivate());
|
||||||
|
assertEquals(0, dto.getAllowed());
|
||||||
|
assertEquals(0, dto.getRejectedPerSecond());
|
||||||
|
assertEquals(0, dto.getRejectedThreshold());
|
||||||
|
assertEquals(0, dto.getTotalRequests());
|
||||||
|
assertEquals(0.0, dto.getRejectRatio());
|
||||||
|
assertEquals(0, dto.getLastResetTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getGroupMetric_withMetrics_returnsCorrectValues() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "결제그룹"));
|
||||||
|
when(manager.getGroupMetrics("G1")).thenReturn(makeMetrics(900, 60, 40));
|
||||||
|
|
||||||
|
GroupMetricDTO dto = serviceWith(manager).getGroupMetric("G1");
|
||||||
|
|
||||||
|
assertEquals(900, dto.getAllowed());
|
||||||
|
assertEquals(60, dto.getRejectedPerSecond());
|
||||||
|
assertEquals(40, dto.getRejectedThreshold());
|
||||||
|
assertEquals(1000, dto.getTotalRequests());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getGroupMetric_rejectRatioCalculation() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "G1"));
|
||||||
|
// allowed=90, rejPs=5, rejTh=5 → reject=10/100 = 10.00%
|
||||||
|
when(manager.getGroupMetrics("G1")).thenReturn(makeMetrics(90, 5, 5));
|
||||||
|
|
||||||
|
GroupMetricDTO dto = serviceWith(manager).getGroupMetric("G1");
|
||||||
|
|
||||||
|
assertEquals(10.0, dto.getRejectRatio(), 0.01);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getGroupMetric_zeroTotal_rejectRatioIsZero() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "G1"));
|
||||||
|
when(manager.getGroupMetrics("G1")).thenReturn(makeMetrics(0, 0, 0));
|
||||||
|
|
||||||
|
GroupMetricDTO dto = serviceWith(manager).getGroupMetric("G1");
|
||||||
|
|
||||||
|
assertEquals(0.0, dto.getRejectRatio(), 0.0001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getGroupMetric_lastResetTimeIsPropagated() {
|
||||||
|
DualInflowControlManager.TargetMetrics m = makeMetrics(10, 0, 0);
|
||||||
|
m.lastResetTime = 1234567890L;
|
||||||
|
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "G1"));
|
||||||
|
when(manager.getGroupMetrics("G1")).thenReturn(m);
|
||||||
|
|
||||||
|
GroupMetricDTO dto = serviceWith(manager).getGroupMetric("G1");
|
||||||
|
|
||||||
|
assertEquals(1234567890L, dto.getLastResetTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// getAllGroupMetrics
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllGroupMetrics_managerIsNull_returnsEmptyList() {
|
||||||
|
List<GroupMetricDTO> result = serviceWith(null).getAllGroupMetrics();
|
||||||
|
|
||||||
|
assertNotNull(result);
|
||||||
|
assertTrue(result.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllGroupMetrics_noGroups_returnsEmptyList() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getGroupAllKeys()).thenReturn(new String[]{});
|
||||||
|
|
||||||
|
assertTrue(serviceWith(manager).getAllGroupMetrics().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllGroupMetrics_twoGroups_returnsBoth() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getGroupAllKeys()).thenReturn(new String[]{"G1", "G2"});
|
||||||
|
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "그룹1"));
|
||||||
|
when(manager.getGroupInflowThreshold("G2")).thenReturn(makeGroupVO("G2", "그룹2"));
|
||||||
|
when(manager.getGroupMetrics("G1")).thenReturn(makeMetrics(10, 0, 0));
|
||||||
|
when(manager.getGroupMetrics("G2")).thenReturn(makeMetrics(20, 5, 0));
|
||||||
|
|
||||||
|
List<GroupMetricDTO> result = serviceWith(manager).getAllGroupMetrics();
|
||||||
|
|
||||||
|
assertEquals(2, result.size());
|
||||||
|
assertEquals("G1", result.get(0).getGroupId());
|
||||||
|
assertEquals("G2", result.get(1).getGroupId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllGroupMetrics_groupNotFoundIsSkipped() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getGroupAllKeys()).thenReturn(new String[]{"G1", "GHOST"});
|
||||||
|
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "그룹1"));
|
||||||
|
when(manager.getGroupInflowThreshold("GHOST")).thenReturn(null);
|
||||||
|
when(manager.getGroupMetrics("G1")).thenReturn(makeMetrics(5, 0, 0));
|
||||||
|
|
||||||
|
List<GroupMetricDTO> result = serviceWith(manager).getAllGroupMetrics();
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
assertEquals("G1", result.get(0).getGroupId());
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// resetGroupMetric
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetGroupMetric_managerIsNull_returnsFalse() {
|
||||||
|
assertFalse(serviceWith(null).resetGroupMetric("G1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetGroupMetric_groupNotFound_returnsFalse() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getGroupInflowThreshold("G1")).thenReturn(null);
|
||||||
|
|
||||||
|
assertFalse(serviceWith(manager).resetGroupMetric("G1"));
|
||||||
|
verify(manager, never()).resetGroupMetrics(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetGroupMetric_success_returnsTrueAndCallsManager() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getGroupInflowThreshold("G1")).thenReturn(makeGroupVO("G1", "그룹1"));
|
||||||
|
|
||||||
|
assertTrue(serviceWith(manager).resetGroupMetric("G1"));
|
||||||
|
verify(manager).resetGroupMetrics("G1");
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// resetAllGroupMetrics
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAllGroupMetrics_managerIsNull_noException() {
|
||||||
|
assertDoesNotThrow(() -> serviceWith(null).resetAllGroupMetrics());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAllGroupMetrics_callsManagerReset() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
|
||||||
|
serviceWith(manager).resetAllGroupMetrics();
|
||||||
|
|
||||||
|
verify(manager).resetAllGroupMetrics();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* InflowTargetBucketController 단위 테스트.
|
||||||
|
*
|
||||||
|
* <p>Spring MVC를 기동하지 않고 컨트롤러를 직접 인스턴스화하여
|
||||||
|
* 응답 구조(success, data, count, message)를 검증한다.
|
||||||
|
*/
|
||||||
|
class InflowTargetBucketControllerTest {
|
||||||
|
|
||||||
|
private InflowTargetBucketController controller;
|
||||||
|
private InflowTargetBucketService mockService;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
controller = new InflowTargetBucketController();
|
||||||
|
mockService = mock(InflowTargetBucketService.class);
|
||||||
|
ReflectionTestUtils.setField(controller, "bucketService", mockService);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Helper
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private TargetBucketStatusDTO makeDTO(String id, String type) {
|
||||||
|
TargetBucketStatusDTO dto = new TargetBucketStatusDTO();
|
||||||
|
dto.setTargetId(id);
|
||||||
|
dto.setTargetType(type);
|
||||||
|
dto.setActivate(true);
|
||||||
|
dto.setBuckets(Collections.emptyList());
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> body(ResponseEntity<?> response) {
|
||||||
|
return (Map<String, Object>) response.getBody();
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 어댑터 — 단일 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterBucketStatus_found_successTrueAndDataPresent() {
|
||||||
|
TargetBucketStatusDTO dto = makeDTO("ADAPTER_A", "ADAPTER");
|
||||||
|
when(mockService.getAdapterBucketStatus("ADAPTER_A")).thenReturn(dto);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getAdapterBucketStatus("ADAPTER_A");
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(200, response.getStatusCodeValue());
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(dto, body.get("data"));
|
||||||
|
assertFalse(body.containsKey("message"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterBucketStatus_notFound_successFalseWithAdapterId() {
|
||||||
|
when(mockService.getAdapterBucketStatus("GHOST")).thenReturn(null);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getAdapterBucketStatus("GHOST");
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(Boolean.FALSE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 어댑터 — 전체 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllAdapterBucketStatus_returnsListAndCount() {
|
||||||
|
List<TargetBucketStatusDTO> list = Arrays.asList(
|
||||||
|
makeDTO("A1", "ADAPTER"),
|
||||||
|
makeDTO("A2", "ADAPTER")
|
||||||
|
);
|
||||||
|
when(mockService.getAllAdapterBucketStatus()).thenReturn(list);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getAllAdapterBucketStatus();
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(list, body.get("data"));
|
||||||
|
assertEquals(2, body.get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllAdapterBucketStatus_emptyList_countZero() {
|
||||||
|
when(mockService.getAllAdapterBucketStatus()).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getAllAdapterBucketStatus());
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertEquals(0, body.get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 인터페이스 — 단일 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getInterfaceBucketStatus_found_successTrue() {
|
||||||
|
TargetBucketStatusDTO dto = makeDTO("IF_001", "INTERFACE");
|
||||||
|
when(mockService.getInterfaceBucketStatus("IF_001")).thenReturn(dto);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getInterfaceBucketStatus("IF_001");
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(dto, body.get("data"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getInterfaceBucketStatus_notFound_successFalseWithInterfaceId() {
|
||||||
|
when(mockService.getInterfaceBucketStatus("GHOST")).thenReturn(null);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getInterfaceBucketStatus("GHOST"));
|
||||||
|
|
||||||
|
assertEquals(Boolean.FALSE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 인터페이스 — 전체 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllInterfaceBucketStatus_returnsListAndCount() {
|
||||||
|
List<TargetBucketStatusDTO> list = Collections.singletonList(makeDTO("IF_001", "INTERFACE"));
|
||||||
|
when(mockService.getAllInterfaceBucketStatus()).thenReturn(list);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getAllInterfaceBucketStatus());
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertEquals(1, body.get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 클라이언트 — 단일 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getClientBucketStatus_found_successTrueAndDataPresent() {
|
||||||
|
TargetBucketStatusDTO dto = makeDTO("CLIENT_A", "CLIENT");
|
||||||
|
when(mockService.getClientBucketStatus("CLIENT_A")).thenReturn(dto);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getClientBucketStatus("CLIENT_A");
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(200, response.getStatusCodeValue());
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(dto, body.get("data"));
|
||||||
|
assertFalse(body.containsKey("message"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getClientBucketStatus_notFound_successFalseWithClientId() {
|
||||||
|
when(mockService.getClientBucketStatus("CLIENT_X")).thenReturn(null);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getClientBucketStatus("CLIENT_X");
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(Boolean.FALSE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("CLIENT_X"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 클라이언트 — 전체 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllClientBucketStatus_returnsListAndCount() {
|
||||||
|
List<TargetBucketStatusDTO> list = Arrays.asList(
|
||||||
|
makeDTO("CLIENT_A", "CLIENT"),
|
||||||
|
makeDTO("CLIENT_B", "CLIENT"),
|
||||||
|
makeDTO("CLIENT_C", "CLIENT")
|
||||||
|
);
|
||||||
|
when(mockService.getAllClientBucketStatus()).thenReturn(list);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getAllClientBucketStatus();
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(list, body.get("data"));
|
||||||
|
assertEquals(3, body.get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllClientBucketStatus_emptyList_countZero() {
|
||||||
|
when(mockService.getAllClientBucketStatus()).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getAllClientBucketStatus());
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertEquals(0, body.get("count"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualCustomBucket;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||||
|
|
||||||
|
import io.github.bucket4j.Bandwidth;
|
||||||
|
import io.github.bucket4j.Bucket4j;
|
||||||
|
import io.github.bucket4j.local.LocalBucket;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* InflowTargetBucketService 단위 테스트.
|
||||||
|
*
|
||||||
|
* <p>getDualManager()를 protected로 오버라이드하는 내부 테스트 서브클래스를 사용하여
|
||||||
|
* DualInflowControlManager 의존성을 주입한다.
|
||||||
|
*/
|
||||||
|
class InflowTargetBucketServiceTest {
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 테스트용 서브클래스
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static InflowTargetBucketService serviceWith(DualInflowControlManager manager) {
|
||||||
|
return new InflowTargetBucketService() {
|
||||||
|
@Override
|
||||||
|
protected DualInflowControlManager getDualManager() {
|
||||||
|
return manager;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Helpers
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private InflowTargetVO makeVO(String name, long perSec, long threshold, String unit, boolean activate) {
|
||||||
|
InflowTargetVO vo = new InflowTargetVO();
|
||||||
|
vo.setName(name);
|
||||||
|
vo.setThresholdPerSecond(perSec);
|
||||||
|
vo.setThreshold(threshold);
|
||||||
|
vo.setThresholdTimeUnit(unit);
|
||||||
|
vo.setActivate(activate);
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LocalBucket freshBucket(long capacity) {
|
||||||
|
return Bucket4j.builder()
|
||||||
|
.addLimit(Bandwidth.simple(capacity, Duration.ofSeconds(1)))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private LocalBucket exhaustedBucket(long capacity) {
|
||||||
|
LocalBucket b = freshBucket(capacity);
|
||||||
|
b.tryConsume(capacity);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
private DualCustomBucket makeDualBucket(String name, long perSec, long threshold) {
|
||||||
|
return new DualCustomBucket(freshBucket(perSec), freshBucket(threshold),
|
||||||
|
makeVO(name, perSec, threshold, "DAY", true));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// DualManager null (비활성 환경)
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterBucketStatus_managerIsNull_returnsNull() {
|
||||||
|
assertNull(serviceWith(null).getAdapterBucketStatus("ADAPTER_A"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllAdapterBucketStatus_managerIsNull_returnsEmptyList() {
|
||||||
|
List<TargetBucketStatusDTO> result = serviceWith(null).getAllAdapterBucketStatus();
|
||||||
|
assertNotNull(result);
|
||||||
|
assertTrue(result.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getInterfaceBucketStatus_managerIsNull_returnsNull() {
|
||||||
|
assertNull(serviceWith(null).getInterfaceBucketStatus("IF_001"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllInterfaceBucketStatus_managerIsNull_returnsEmptyList() {
|
||||||
|
assertTrue(serviceWith(null).getAllInterfaceBucketStatus().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getClientBucketStatus_managerIsNull_returnsNull() {
|
||||||
|
assertNull(serviceWith(null).getClientBucketStatus("CLIENT_A"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllClientBucketStatus_managerIsNull_returnsEmptyList() {
|
||||||
|
assertTrue(serviceWith(null).getAllClientBucketStatus().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 버킷 미존재
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterBucketStatus_notFound_returnsNull() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterBucket("ADAPTER_A")).thenReturn(null);
|
||||||
|
|
||||||
|
assertNull(serviceWith(manager).getAdapterBucketStatus("ADAPTER_A"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getInterfaceBucketStatus_notFound_returnsNull() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getInterfaceBucket("IF_001")).thenReturn(null);
|
||||||
|
|
||||||
|
assertNull(serviceWith(manager).getInterfaceBucketStatus("IF_001"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getClientBucketStatus_notFound_returnsNull() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getClientBucket("CLIENT_A")).thenReturn(null);
|
||||||
|
|
||||||
|
assertNull(serviceWith(manager).getClientBucketStatus("CLIENT_A"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 단일 조회 — targetType, targetId 매핑
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterBucketStatus_found_mapsAdapterType() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterBucket("ADAPTER_A")).thenReturn(makeDualBucket("ADAPTER_A", 10, 1000));
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = serviceWith(manager).getAdapterBucketStatus("ADAPTER_A");
|
||||||
|
|
||||||
|
assertNotNull(dto);
|
||||||
|
assertEquals("ADAPTER_A", dto.getTargetId());
|
||||||
|
assertEquals("ADAPTER", dto.getTargetType());
|
||||||
|
assertTrue(dto.isActivate());
|
||||||
|
assertEquals(2, dto.getBuckets().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getInterfaceBucketStatus_found_mapsInterfaceType() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getInterfaceBucket("IF_001")).thenReturn(makeDualBucket("IF_001", 20, 2000));
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = serviceWith(manager).getInterfaceBucketStatus("IF_001");
|
||||||
|
|
||||||
|
assertNotNull(dto);
|
||||||
|
assertEquals("IF_001", dto.getTargetId());
|
||||||
|
assertEquals("INTERFACE", dto.getTargetType());
|
||||||
|
assertTrue(dto.isActivate());
|
||||||
|
assertEquals(2, dto.getBuckets().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getClientBucketStatus_found_mapsClientType() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getClientBucket("CLIENT_A")).thenReturn(makeDualBucket("CLIENT_A", 50, 5000));
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("CLIENT_A");
|
||||||
|
|
||||||
|
assertNotNull(dto);
|
||||||
|
assertEquals("CLIENT_A", dto.getTargetId());
|
||||||
|
assertEquals("CLIENT", dto.getTargetType());
|
||||||
|
assertTrue(dto.isActivate());
|
||||||
|
assertEquals(2, dto.getBuckets().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// BucketInfo 타입별 포함 여부
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void toDto_onlyThreshold_bucketInfoHasOneThresholdEntry() {
|
||||||
|
InflowTargetVO vo = makeVO("C1", 0, 1000, "DAY", true);
|
||||||
|
DualCustomBucket bucket = new DualCustomBucket(null, freshBucket(1000), vo);
|
||||||
|
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getClientBucket("C1")).thenReturn(bucket);
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C1");
|
||||||
|
|
||||||
|
assertEquals(1, dto.getBuckets().size());
|
||||||
|
assertEquals("threshold", dto.getBuckets().get(0).getType());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void toDto_onlyPerSecond_bucketInfoHasOnePerSecondEntry() {
|
||||||
|
InflowTargetVO vo = makeVO("C2", 100, 0, "SEC", true);
|
||||||
|
DualCustomBucket bucket = new DualCustomBucket(freshBucket(100), null, vo);
|
||||||
|
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getClientBucket("C2")).thenReturn(bucket);
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C2");
|
||||||
|
|
||||||
|
assertEquals(1, dto.getBuckets().size());
|
||||||
|
assertEquals("perSecond", dto.getBuckets().get(0).getType());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void toDto_bothBuckets_bucketInfoHasTwoEntries() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getClientBucket("C3")).thenReturn(makeDualBucket("C3", 100, 5000));
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C3");
|
||||||
|
|
||||||
|
assertEquals(2, dto.getBuckets().size());
|
||||||
|
assertEquals("perSecond", dto.getBuckets().get(0).getType());
|
||||||
|
assertEquals("threshold", dto.getBuckets().get(1).getType());
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 사용률 계산
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void toDto_exhaustedThreshold_usagePercentIs100() {
|
||||||
|
InflowTargetVO vo = makeVO("C4", 0, 100, "DAY", true);
|
||||||
|
DualCustomBucket bucket = new DualCustomBucket(null, exhaustedBucket(100), vo);
|
||||||
|
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getClientBucket("C4")).thenReturn(bucket);
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C4");
|
||||||
|
|
||||||
|
GroupBucketStatusDTO.BucketInfo info = dto.getBuckets().get(0);
|
||||||
|
assertEquals(0, info.getAvailableTokens());
|
||||||
|
assertEquals(100.0, info.getUsagePercent(), 0.01);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void toDto_freshBucket_usagePercentIsZero() {
|
||||||
|
InflowTargetVO vo = makeVO("C5", 0, 100, "DAY", true);
|
||||||
|
DualCustomBucket bucket = new DualCustomBucket(null, freshBucket(100), vo);
|
||||||
|
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getClientBucket("C5")).thenReturn(bucket);
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = serviceWith(manager).getClientBucketStatus("C5");
|
||||||
|
|
||||||
|
GroupBucketStatusDTO.BucketInfo info = dto.getBuckets().get(0);
|
||||||
|
assertEquals(100, info.getAvailableTokens());
|
||||||
|
assertEquals(0.0, info.getUsagePercent(), 0.01);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void toDto_capacity_perSecondBucketInfoCapacityMatchesVO() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterBucket("A1")).thenReturn(makeDualBucket("A1", 30, 3000));
|
||||||
|
|
||||||
|
TargetBucketStatusDTO dto = serviceWith(manager).getAdapterBucketStatus("A1");
|
||||||
|
|
||||||
|
GroupBucketStatusDTO.BucketInfo ps = dto.getBuckets().get(0);
|
||||||
|
assertEquals(30, ps.getCapacity());
|
||||||
|
assertEquals("SEC", ps.getTimeUnit());
|
||||||
|
|
||||||
|
GroupBucketStatusDTO.BucketInfo th = dto.getBuckets().get(1);
|
||||||
|
assertEquals(3000, th.getCapacity());
|
||||||
|
assertEquals("DAY", th.getTimeUnit());
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 전체 목록 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllClientBucketStatus_twoEntries_returnsBoth() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
|
||||||
|
map.put("CLIENT_A", makeDualBucket("CLIENT_A", 10, 1000));
|
||||||
|
map.put("CLIENT_B", makeDualBucket("CLIENT_B", 20, 2000));
|
||||||
|
when(manager.getClientBucketMap()).thenReturn(map);
|
||||||
|
|
||||||
|
List<TargetBucketStatusDTO> result = serviceWith(manager).getAllClientBucketStatus();
|
||||||
|
|
||||||
|
assertEquals(2, result.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllAdapterBucketStatus_emptyMap_returnsEmptyList() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterBucketMap()).thenReturn(new ConcurrentHashMap<>());
|
||||||
|
|
||||||
|
assertTrue(serviceWith(manager).getAllAdapterBucketStatus().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllInterfaceBucketStatus_oneEntry_targetTypeIsInterface() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
Map<String, DualCustomBucket> map = new ConcurrentHashMap<>();
|
||||||
|
map.put("IF_001", makeDualBucket("IF_001", 10, 1000));
|
||||||
|
when(manager.getInterfaceBucketMap()).thenReturn(map);
|
||||||
|
|
||||||
|
List<TargetBucketStatusDTO> result = serviceWith(manager).getAllInterfaceBucketStatus();
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
assertEquals("INTERFACE", result.get(0).getTargetType());
|
||||||
|
assertEquals("IF_001", result.get(0).getTargetId());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,301 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* InflowTargetMetricController 단위 테스트.
|
||||||
|
*
|
||||||
|
* <p>Spring MVC를 기동하지 않고 컨트롤러를 직접 인스턴스화하여
|
||||||
|
* 응답 구조(success, data, count, message)를 검증한다.
|
||||||
|
*/
|
||||||
|
class InflowTargetMetricControllerTest {
|
||||||
|
|
||||||
|
private InflowTargetMetricController controller;
|
||||||
|
private InflowTargetMetricService mockService;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
controller = new InflowTargetMetricController();
|
||||||
|
mockService = mock(InflowTargetMetricService.class);
|
||||||
|
ReflectionTestUtils.setField(controller, "metricService", mockService);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Helper
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private TargetMetricDTO makeDTO(String targetId, String targetType,
|
||||||
|
long allowed, long rejPs, long rejTh) {
|
||||||
|
TargetMetricDTO dto = new TargetMetricDTO();
|
||||||
|
dto.setTargetId(targetId);
|
||||||
|
dto.setTargetType(targetType);
|
||||||
|
dto.setActivate(true);
|
||||||
|
dto.setAllowed(allowed);
|
||||||
|
dto.setRejectedPerSecond(rejPs);
|
||||||
|
dto.setRejectedThreshold(rejTh);
|
||||||
|
long total = allowed + rejPs + rejTh;
|
||||||
|
dto.setTotalRequests(total);
|
||||||
|
dto.setRejectRatio(total > 0 ? (double)(rejPs + rejTh) / total * 100 : 0.0);
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> body(ResponseEntity<?> response) {
|
||||||
|
return (Map<String, Object>) response.getBody();
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 어댑터 — 단일 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterMetric_found_successTrueAndDataPresent() {
|
||||||
|
TargetMetricDTO dto = makeDTO("A1", "ADAPTER", 900, 60, 40);
|
||||||
|
when(mockService.getAdapterMetric("A1")).thenReturn(dto);
|
||||||
|
|
||||||
|
ResponseEntity<?> response = controller.getAdapterMetric("A1");
|
||||||
|
Map<String, Object> body = body(response);
|
||||||
|
|
||||||
|
assertEquals(200, response.getStatusCodeValue());
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(dto, body.get("data"));
|
||||||
|
assertFalse(body.containsKey("message"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterMetric_notFound_successFalseWithMessage() {
|
||||||
|
when(mockService.getAdapterMetric("GHOST")).thenReturn(null);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getAdapterMetric("GHOST"));
|
||||||
|
|
||||||
|
assertEquals(Boolean.FALSE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 어댑터 — 전체 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllAdapterMetrics_returnsListAndCount() {
|
||||||
|
List<TargetMetricDTO> list = Arrays.asList(
|
||||||
|
makeDTO("A1", "ADAPTER", 100, 5, 0),
|
||||||
|
makeDTO("A2", "ADAPTER", 200, 0, 10)
|
||||||
|
);
|
||||||
|
when(mockService.getAllAdapterMetrics()).thenReturn(list);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getAllAdapterMetrics());
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(list, body.get("data"));
|
||||||
|
assertEquals(2, body.get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllAdapterMetrics_emptyList_countZero() {
|
||||||
|
when(mockService.getAllAdapterMetrics()).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getAllAdapterMetrics());
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertEquals(0, body.get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 어댑터 — reset
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAdapterMetric_success_successTrueWithTargetId() {
|
||||||
|
when(mockService.resetAdapterMetric("A1")).thenReturn(true);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.resetAdapterMetric("A1"));
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("A1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAdapterMetric_notFound_successFalseWithTargetId() {
|
||||||
|
when(mockService.resetAdapterMetric("GHOST")).thenReturn(false);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.resetAdapterMetric("GHOST"));
|
||||||
|
|
||||||
|
assertEquals(Boolean.FALSE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAllAdapterMetrics_alwaysSuccessTrue() {
|
||||||
|
doNothing().when(mockService).resetAllAdapterMetrics();
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.resetAllAdapterMetrics());
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertNotNull(body.get("message"));
|
||||||
|
verify(mockService).resetAllAdapterMetrics();
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 인터페이스 — 단일 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getInterfaceMetric_found_successTrueAndDataPresent() {
|
||||||
|
TargetMetricDTO dto = makeDTO("IF1", "INTERFACE", 500, 20, 10);
|
||||||
|
when(mockService.getInterfaceMetric("IF1")).thenReturn(dto);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getInterfaceMetric("IF1"));
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(dto, body.get("data"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getInterfaceMetric_notFound_successFalseWithMessage() {
|
||||||
|
when(mockService.getInterfaceMetric("GHOST")).thenReturn(null);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getInterfaceMetric("GHOST"));
|
||||||
|
|
||||||
|
assertEquals(Boolean.FALSE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 인터페이스 — 전체 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllInterfaceMetrics_returnsListAndCount() {
|
||||||
|
List<TargetMetricDTO> list = Collections.singletonList(
|
||||||
|
makeDTO("IF1", "INTERFACE", 100, 0, 0));
|
||||||
|
when(mockService.getAllInterfaceMetrics()).thenReturn(list);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getAllInterfaceMetrics());
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertEquals(1, body.get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 인터페이스 — reset
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetInterfaceMetric_success_successTrue() {
|
||||||
|
when(mockService.resetInterfaceMetric("IF1")).thenReturn(true);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.resetInterfaceMetric("IF1"));
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("IF1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAllInterfaceMetrics_callsDelegateOnce() {
|
||||||
|
doNothing().when(mockService).resetAllInterfaceMetrics();
|
||||||
|
|
||||||
|
controller.resetAllInterfaceMetrics();
|
||||||
|
|
||||||
|
verify(mockService, times(1)).resetAllInterfaceMetrics();
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 클라이언트 — 단일 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getClientMetric_found_successTrueAndDataPresent() {
|
||||||
|
TargetMetricDTO dto = makeDTO("C1", "CLIENT", 300, 50, 20);
|
||||||
|
when(mockService.getClientMetric("C1")).thenReturn(dto);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getClientMetric("C1"));
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(dto, body.get("data"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getClientMetric_notFound_successFalseWithMessage() {
|
||||||
|
when(mockService.getClientMetric("GHOST")).thenReturn(null);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getClientMetric("GHOST"));
|
||||||
|
|
||||||
|
assertEquals(Boolean.FALSE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 클라이언트 — 전체 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllClientMetrics_returnsListAndCount() {
|
||||||
|
List<TargetMetricDTO> list = Arrays.asList(
|
||||||
|
makeDTO("C1", "CLIENT", 100, 5, 5),
|
||||||
|
makeDTO("C2", "CLIENT", 200, 0, 0),
|
||||||
|
makeDTO("C3", "CLIENT", 50, 10, 0)
|
||||||
|
);
|
||||||
|
when(mockService.getAllClientMetrics()).thenReturn(list);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getAllClientMetrics());
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertSame(list, body.get("data"));
|
||||||
|
assertEquals(3, body.get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllClientMetrics_emptyList_countZero() {
|
||||||
|
when(mockService.getAllClientMetrics()).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.getAllClientMetrics());
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertEquals(0, body.get("count"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 클라이언트 — reset
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetClientMetric_success_successTrue() {
|
||||||
|
when(mockService.resetClientMetric("C1")).thenReturn(true);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.resetClientMetric("C1"));
|
||||||
|
|
||||||
|
assertEquals(Boolean.TRUE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("C1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetClientMetric_notFound_successFalse() {
|
||||||
|
when(mockService.resetClientMetric("GHOST")).thenReturn(false);
|
||||||
|
|
||||||
|
Map<String, Object> body = body(controller.resetClientMetric("GHOST"));
|
||||||
|
|
||||||
|
assertEquals(Boolean.FALSE, body.get("success"));
|
||||||
|
assertTrue(body.get("message").toString().contains("GHOST"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAllClientMetrics_callsDelegateOnce() {
|
||||||
|
doNothing().when(mockService).resetAllClientMetrics();
|
||||||
|
|
||||||
|
controller.resetAllClientMetrics();
|
||||||
|
|
||||||
|
verify(mockService, times(1)).resetAllClientMetrics();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
package com.eactive.eai.manage.inflow;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||||
|
import com.eactive.eai.common.inflow.dual.DualInflowControlManager;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* InflowTargetMetricService 단위 테스트.
|
||||||
|
*
|
||||||
|
* <p>getDualManager()를 오버라이드하여 DualInflowControlManager 의존성을 주입한다.
|
||||||
|
*/
|
||||||
|
class InflowTargetMetricServiceTest {
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// 테스트용 서브클래스
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static InflowTargetMetricService serviceWith(DualInflowControlManager manager) {
|
||||||
|
return new InflowTargetMetricService() {
|
||||||
|
@Override
|
||||||
|
protected DualInflowControlManager getDualManager() { return manager; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Helpers
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private InflowTargetVO makeVO(String name) {
|
||||||
|
InflowTargetVO vo = new InflowTargetVO();
|
||||||
|
vo.setName(name);
|
||||||
|
vo.setActivate(true);
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private DualInflowControlManager.TargetMetrics makeMetrics(long allowed, long rejPs, long rejTh) {
|
||||||
|
DualInflowControlManager.TargetMetrics m = new DualInflowControlManager.TargetMetrics();
|
||||||
|
m.allowed.set(allowed);
|
||||||
|
m.rejectedPerSecond.set(rejPs);
|
||||||
|
m.rejectedThreshold.set(rejTh);
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// DualManager null (비활성 환경)
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterMetric_managerIsNull_returnsNull() {
|
||||||
|
assertNull(serviceWith(null).getAdapterMetric("A1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllAdapterMetrics_managerIsNull_returnsEmptyList() {
|
||||||
|
assertTrue(serviceWith(null).getAllAdapterMetrics().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAdapterMetric_managerIsNull_returnsFalse() {
|
||||||
|
assertFalse(serviceWith(null).resetAdapterMetric("A1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAllAdapterMetrics_managerIsNull_noException() {
|
||||||
|
assertDoesNotThrow(() -> serviceWith(null).resetAllAdapterMetrics());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getInterfaceMetric_managerIsNull_returnsNull() {
|
||||||
|
assertNull(serviceWith(null).getInterfaceMetric("IF1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getClientMetric_managerIsNull_returnsNull() {
|
||||||
|
assertNull(serviceWith(null).getClientMetric("C1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 어댑터 — 단일 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterMetric_notRegistered_returnsNull() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterInflowThreashold("A1")).thenReturn(null);
|
||||||
|
|
||||||
|
assertNull(serviceWith(manager).getAdapterMetric("A1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterMetric_found_mapsFields() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||||
|
when(manager.getAdapterMetrics("A1")).thenReturn(makeMetrics(900, 60, 40));
|
||||||
|
|
||||||
|
TargetMetricDTO dto = serviceWith(manager).getAdapterMetric("A1");
|
||||||
|
|
||||||
|
assertNotNull(dto);
|
||||||
|
assertEquals("A1", dto.getTargetId());
|
||||||
|
assertEquals("ADAPTER", dto.getTargetType());
|
||||||
|
assertTrue(dto.isActivate());
|
||||||
|
assertEquals(900, dto.getAllowed());
|
||||||
|
assertEquals(60, dto.getRejectedPerSecond());
|
||||||
|
assertEquals(40, dto.getRejectedThreshold());
|
||||||
|
assertEquals(1000, dto.getTotalRequests());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterMetric_noMetricsYet_returnsZeroCounters() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||||
|
when(manager.getAdapterMetrics("A1")).thenReturn(null);
|
||||||
|
|
||||||
|
TargetMetricDTO dto = serviceWith(manager).getAdapterMetric("A1");
|
||||||
|
|
||||||
|
assertNotNull(dto);
|
||||||
|
assertEquals(0, dto.getAllowed());
|
||||||
|
assertEquals(0, dto.getTotalRequests());
|
||||||
|
assertEquals(0.0, dto.getRejectRatio(), 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterMetric_rejectRatioCalculation() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||||
|
// allowed=90, rejPs=5, rejTh=5 → reject=10/100 = 10.00%
|
||||||
|
when(manager.getAdapterMetrics("A1")).thenReturn(makeMetrics(90, 5, 5));
|
||||||
|
|
||||||
|
TargetMetricDTO dto = serviceWith(manager).getAdapterMetric("A1");
|
||||||
|
|
||||||
|
assertEquals(10.0, dto.getRejectRatio(), 0.01);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAdapterMetric_zeroTotal_rejectRatioIsZero() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||||
|
when(manager.getAdapterMetrics("A1")).thenReturn(makeMetrics(0, 0, 0));
|
||||||
|
|
||||||
|
TargetMetricDTO dto = serviceWith(manager).getAdapterMetric("A1");
|
||||||
|
|
||||||
|
assertEquals(0.0, dto.getRejectRatio(), 0.0001);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 어댑터 — 전체 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllAdapterMetrics_twoEntries_returnsBoth() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterAllKeys()).thenReturn(new String[]{"A1", "A2"});
|
||||||
|
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||||
|
when(manager.getAdapterInflowThreashold("A2")).thenReturn(makeVO("A2"));
|
||||||
|
when(manager.getAdapterMetrics("A1")).thenReturn(makeMetrics(10, 0, 0));
|
||||||
|
when(manager.getAdapterMetrics("A2")).thenReturn(makeMetrics(20, 5, 0));
|
||||||
|
|
||||||
|
List<TargetMetricDTO> result = serviceWith(manager).getAllAdapterMetrics();
|
||||||
|
|
||||||
|
assertEquals(2, result.size());
|
||||||
|
assertEquals("A1", result.get(0).getTargetId());
|
||||||
|
assertEquals("A2", result.get(1).getTargetId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllAdapterMetrics_noKeys_returnsEmptyList() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterAllKeys()).thenReturn(new String[]{});
|
||||||
|
|
||||||
|
assertTrue(serviceWith(manager).getAllAdapterMetrics().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllAdapterMetrics_notRegisteredSkipped() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterAllKeys()).thenReturn(new String[]{"A1", "GHOST"});
|
||||||
|
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||||
|
when(manager.getAdapterInflowThreashold("GHOST")).thenReturn(null);
|
||||||
|
when(manager.getAdapterMetrics("A1")).thenReturn(null);
|
||||||
|
|
||||||
|
List<TargetMetricDTO> result = serviceWith(manager).getAllAdapterMetrics();
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
assertEquals("A1", result.get(0).getTargetId());
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 어댑터 — reset
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAdapterMetric_notRegistered_returnsFalse() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterInflowThreashold("A1")).thenReturn(null);
|
||||||
|
|
||||||
|
assertFalse(serviceWith(manager).resetAdapterMetric("A1"));
|
||||||
|
verify(manager, never()).resetAdapterMetrics(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAdapterMetric_success_returnsTrueAndCallsManager() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getAdapterInflowThreashold("A1")).thenReturn(makeVO("A1"));
|
||||||
|
|
||||||
|
assertTrue(serviceWith(manager).resetAdapterMetric("A1"));
|
||||||
|
verify(manager).resetAdapterMetrics("A1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAllAdapterMetrics_callsManager() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
|
||||||
|
serviceWith(manager).resetAllAdapterMetrics();
|
||||||
|
|
||||||
|
verify(manager).resetAllAdapterMetrics();
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 인터페이스 — 단일 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getInterfaceMetric_found_mapsFields() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getInterfaceInflowThreashold("IF1")).thenReturn(makeVO("IF1"));
|
||||||
|
when(manager.getInterfaceMetrics("IF1")).thenReturn(makeMetrics(50, 10, 5));
|
||||||
|
|
||||||
|
TargetMetricDTO dto = serviceWith(manager).getInterfaceMetric("IF1");
|
||||||
|
|
||||||
|
assertNotNull(dto);
|
||||||
|
assertEquals("IF1", dto.getTargetId());
|
||||||
|
assertEquals("INTERFACE", dto.getTargetType());
|
||||||
|
assertEquals(50, dto.getAllowed());
|
||||||
|
assertEquals(65, dto.getTotalRequests());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getInterfaceMetric_notRegistered_returnsNull() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getInterfaceInflowThreashold("IF1")).thenReturn(null);
|
||||||
|
|
||||||
|
assertNull(serviceWith(manager).getInterfaceMetric("IF1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetInterfaceMetric_success_returnsTrueAndCallsManager() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getInterfaceInflowThreashold("IF1")).thenReturn(makeVO("IF1"));
|
||||||
|
|
||||||
|
assertTrue(serviceWith(manager).resetInterfaceMetric("IF1"));
|
||||||
|
verify(manager).resetInterfaceMetrics("IF1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetInterfaceMetric_notRegistered_returnsFalse() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getInterfaceInflowThreashold("IF1")).thenReturn(null);
|
||||||
|
|
||||||
|
assertFalse(serviceWith(manager).resetInterfaceMetric("IF1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAllInterfaceMetrics_callsManager() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
serviceWith(manager).resetAllInterfaceMetrics();
|
||||||
|
verify(manager).resetAllInterfaceMetrics();
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 클라이언트 — 단일 조회
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getClientMetric_found_mapsFields() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
|
||||||
|
when(manager.getClientMetrics("C1")).thenReturn(makeMetrics(200, 30, 20));
|
||||||
|
|
||||||
|
TargetMetricDTO dto = serviceWith(manager).getClientMetric("C1");
|
||||||
|
|
||||||
|
assertNotNull(dto);
|
||||||
|
assertEquals("C1", dto.getTargetId());
|
||||||
|
assertEquals("CLIENT", dto.getTargetType());
|
||||||
|
assertEquals(200, dto.getAllowed());
|
||||||
|
assertEquals(250, dto.getTotalRequests());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getClientMetric_notRegistered_returnsNull() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getClientInflowThreshold("C1")).thenReturn(null);
|
||||||
|
|
||||||
|
assertNull(serviceWith(manager).getClientMetric("C1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetClientMetric_success_returnsTrueAndCallsManager() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getClientInflowThreshold("C1")).thenReturn(makeVO("C1"));
|
||||||
|
|
||||||
|
assertTrue(serviceWith(manager).resetClientMetric("C1"));
|
||||||
|
verify(manager).resetClientMetrics("C1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetClientMetric_notRegistered_returnsFalse() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
when(manager.getClientInflowThreshold("C1")).thenReturn(null);
|
||||||
|
|
||||||
|
assertFalse(serviceWith(manager).resetClientMetric("C1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resetAllClientMetrics_callsManager() {
|
||||||
|
DualInflowControlManager manager = mock(DualInflowControlManager.class);
|
||||||
|
serviceWith(manager).resetAllClientMetrics();
|
||||||
|
verify(manager).resetAllClientMetrics();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user