init
This commit is contained in:
@@ -0,0 +1,388 @@
|
||||
package com.eactive.eai;
|
||||
|
||||
import com.eactive.eai.common.EAITable;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import org.json.simple.JSONValue;
|
||||
|
||||
/**
|
||||
* 테스트용 메시지 키 검증 클래스
|
||||
*/
|
||||
public class MessageKeyTest {
|
||||
|
||||
|
||||
/**
|
||||
* XML 또는 JSON 메시지의 성공 여부를 검증하는 테스트용 메소드
|
||||
* 추출된 값을 배열로 반환
|
||||
*/
|
||||
public static TestResult isSuccessMessageTest(String messageType, Object message, String path, String expectedValue) {
|
||||
try {
|
||||
String extractedValue = "";
|
||||
|
||||
if(EAITable.XML_TYPE.equals(messageType)) {
|
||||
if(message instanceof byte[]) {
|
||||
extractedValue = extractXmlValue(new String((byte[])message), path);
|
||||
} else if(message instanceof String) {
|
||||
extractedValue = extractXmlValue((String)message, path);
|
||||
}
|
||||
}
|
||||
else if(EAITable.JSON_TYPE.equals(messageType)) {
|
||||
Object json = JSONValue.parse((String)message);
|
||||
extractedValue = extractJsonValue(json, path);
|
||||
}
|
||||
|
||||
if(extractedValue == null) extractedValue = "";
|
||||
boolean result = compareMessageValue(extractedValue, expectedValue);
|
||||
|
||||
return new TestResult(result, extractedValue);
|
||||
|
||||
} catch(Exception e) {
|
||||
e.printStackTrace();
|
||||
return new TestResult(false, "오류 발생: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// 테스트 결과를 담는 클래스
|
||||
static class TestResult {
|
||||
boolean success;
|
||||
String extractedValue;
|
||||
|
||||
TestResult(boolean success, String extractedValue) {
|
||||
this.success = success;
|
||||
this.extractedValue = extractedValue;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 메시지 값 비교를 수행하는 메소드
|
||||
*/
|
||||
private static boolean compareMessageValue(String actualValue, String expectedValue) {
|
||||
if(actualValue == null) actualValue = "";
|
||||
if(expectedValue == null) return false;
|
||||
|
||||
// 예약어로 시작하는 경우
|
||||
if(expectedValue.startsWith("@")) {
|
||||
return compareWithReservedWord(actualValue, expectedValue);
|
||||
}
|
||||
|
||||
// 일반 equals 비교
|
||||
return actualValue.equals(expectedValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 예약어를 포함한 값 비교 처리
|
||||
*/
|
||||
private static boolean compareWithReservedWord(String actualValue, String definition) {
|
||||
if (actualValue == null) actualValue = "";
|
||||
if (definition == null) return false;
|
||||
|
||||
try {
|
||||
// 1. 기본 비교
|
||||
if (definition.startsWith("@eq:")) {
|
||||
return actualValue.equals(definition.substring(4));
|
||||
}
|
||||
if (definition.startsWith("@ne:")) {
|
||||
return !actualValue.equals(definition.substring(4));
|
||||
}
|
||||
if ("@null".equals(definition)) {
|
||||
return actualValue.isEmpty();
|
||||
}
|
||||
if ("@!null".equals(definition)) {
|
||||
return !actualValue.isEmpty();
|
||||
}
|
||||
|
||||
// 2. 문자열 패턴
|
||||
if (definition.startsWith("@contains:")) {
|
||||
String[] values = definition.substring(10).split(",");
|
||||
for (String value : values) {
|
||||
if (actualValue.equals(value.trim())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (definition.startsWith("@!contains:")) {
|
||||
String[] values = definition.substring(11).split(",");
|
||||
for (String value : values) {
|
||||
if (actualValue.equals(value.trim())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (definition.startsWith("@starts:")) {
|
||||
return actualValue.startsWith(definition.substring(8));
|
||||
}
|
||||
if (definition.startsWith("@ends:")) {
|
||||
return actualValue.endsWith(definition.substring(6));
|
||||
}
|
||||
|
||||
// 3. 숫자 비교
|
||||
if (definition.startsWith("@gt:") ||
|
||||
definition.startsWith("@lt:") ||
|
||||
definition.startsWith("@ge:") ||
|
||||
definition.startsWith("@le:")) {
|
||||
|
||||
double actualNum = Double.parseDouble(actualValue);
|
||||
if (definition.startsWith("@gt:")) {
|
||||
double defNum = Double.parseDouble(definition.substring(4));
|
||||
return actualNum > defNum;
|
||||
}
|
||||
if (definition.startsWith("@lt:")) {
|
||||
double defNum = Double.parseDouble(definition.substring(4));
|
||||
return actualNum < defNum;
|
||||
}
|
||||
if (definition.startsWith("@ge:")) {
|
||||
double defNum = Double.parseDouble(definition.substring(4));
|
||||
return actualNum >= defNum;
|
||||
}
|
||||
if (definition.startsWith("@le:")) {
|
||||
double defNum = Double.parseDouble(definition.substring(4));
|
||||
return actualNum <= defNum;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* XML 값 추출 메소드
|
||||
*/
|
||||
private static String extractXmlValue(String xmlMessage, String path) {
|
||||
if(path == null) return "";
|
||||
|
||||
// XPath 형식인 경우
|
||||
if(path.startsWith("//") || path.startsWith("/")) {
|
||||
return MessageUtil.getXmlFldByXPath(xmlMessage, path);
|
||||
}
|
||||
|
||||
// 단순 태그명인 경우
|
||||
return MessageUtil.getXmlFld(xmlMessage, path);
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 값 추출 메소드
|
||||
*/
|
||||
private static String extractJsonValue(Object json, String path) {
|
||||
if(path == null) return "";
|
||||
|
||||
// JSONPath 형식인 경우
|
||||
if(path.startsWith("$.")) {
|
||||
return MessageUtil.getJSONValueByPath(json, path);
|
||||
}
|
||||
|
||||
// 단순 키인 경우
|
||||
return MessageUtil.getJSONValue(json, path);
|
||||
}
|
||||
|
||||
private static void testXml() {
|
||||
System.out.println("\n=== XML 테스트 ===");
|
||||
|
||||
// 단순 경로 테스트
|
||||
String xml1 = "<root><status>SUCCESS</status></root>";
|
||||
test("XML 단순 경로",
|
||||
EAITable.XML_TYPE,
|
||||
xml1,
|
||||
"status",
|
||||
"SUCCESS");
|
||||
|
||||
// 중첩 경로 테스트 (일반 방식)
|
||||
String xml2 = "<root><response><header><resultCode>0000</resultCode></header></response></root>";
|
||||
test("XML 중첩 경로 (일반)",
|
||||
EAITable.XML_TYPE,
|
||||
xml2,
|
||||
"resultCode",
|
||||
"0000");
|
||||
|
||||
// 중첩 경로 테스트 (XPath 방식)
|
||||
test("XML 중첩 경로 (XPath)",
|
||||
EAITable.XML_TYPE,
|
||||
xml2,
|
||||
"//response/header/resultCode",
|
||||
"0000");
|
||||
|
||||
// 네임스페이스가 있는 XML
|
||||
String xml3 = "<ns:root xmlns:ns=\"http://test.com\"><ns:status>OK</ns:status></ns:root>";
|
||||
test("XML 네임스페이스",
|
||||
EAITable.XML_TYPE,
|
||||
xml3,
|
||||
"//ns:status",
|
||||
"OK");
|
||||
|
||||
// 실패 케이스
|
||||
test("XML 실패 케이스",
|
||||
EAITable.XML_TYPE,
|
||||
xml1,
|
||||
"status",
|
||||
"FAIL");
|
||||
|
||||
// 존재하지 않는 경로
|
||||
test("XML 없는 경로",
|
||||
EAITable.XML_TYPE,
|
||||
xml1,
|
||||
"nonexistent",
|
||||
"SUCCESS");
|
||||
}
|
||||
|
||||
private static void testJson() {
|
||||
System.out.println("\n=== JSON 테스트 ===");
|
||||
|
||||
// 단순 경로 테스트
|
||||
String json1 = "{\"status\":\"success\"}";
|
||||
test("JSON 단순 경로",
|
||||
EAITable.JSON_TYPE,
|
||||
json1,
|
||||
"status",
|
||||
"success");
|
||||
|
||||
// 중첩 경로 테스트 (일반 방식)
|
||||
String json2 = "{\"response\":{\"header\":{\"resultCode\":\"0000\"}}}";
|
||||
test("JSON 중첩 경로 (일반)",
|
||||
EAITable.JSON_TYPE,
|
||||
json2,
|
||||
"resultCode",
|
||||
"0000");
|
||||
|
||||
// 중첩 경로 테스트 (JSONPath 방식)
|
||||
test("JSON 중첩 경로 (JSONPath)",
|
||||
EAITable.JSON_TYPE,
|
||||
json2,
|
||||
"$.response.header.resultCode",
|
||||
"0000");
|
||||
|
||||
// 배열이 포함된 JSON
|
||||
String json3 = "{\"responses\":[{\"status\":\"success\"},{\"status\":\"pending\"}]}";
|
||||
test("JSON 배열 경로",
|
||||
EAITable.JSON_TYPE,
|
||||
json3,
|
||||
"$.responses[0].status",
|
||||
"success");
|
||||
|
||||
// 실패 케이스
|
||||
test("JSON 실패 케이스",
|
||||
EAITable.JSON_TYPE,
|
||||
json1,
|
||||
"status",
|
||||
"failure");
|
||||
|
||||
// 존재하지 않는 경로
|
||||
test("JSON 없는 경로",
|
||||
EAITable.JSON_TYPE,
|
||||
json1,
|
||||
"nonexistent",
|
||||
"success");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
testXml();
|
||||
testJson();
|
||||
testReservedWords();
|
||||
}
|
||||
|
||||
private static void testReservedWords() {
|
||||
System.out.println("\n=== 예약어 테스트 ===");
|
||||
|
||||
// 1. 기본 비교 테스트
|
||||
test("예약어 - eq",
|
||||
EAITable.XML_TYPE,
|
||||
"<root><code>SUCCESS</code></root>",
|
||||
"code",
|
||||
"@eq:SUCCESS");
|
||||
|
||||
test("예약어 - ne",
|
||||
EAITable.XML_TYPE,
|
||||
"<root><code>SUCCESS</code></root>",
|
||||
"code",
|
||||
"@ne:FAIL");
|
||||
|
||||
test("예약어 - null",
|
||||
EAITable.XML_TYPE,
|
||||
"<root><code></code></root>",
|
||||
"code",
|
||||
"@null");
|
||||
|
||||
test("예약어 - !null",
|
||||
EAITable.XML_TYPE,
|
||||
"<root><code>SUCCESS</code></root>",
|
||||
"code",
|
||||
"@!null");
|
||||
|
||||
// 2. 문자열 패턴 테스트
|
||||
test("예약어 - contains",
|
||||
EAITable.JSON_TYPE,
|
||||
"{\"status\":\"success\"}",
|
||||
"status",
|
||||
"@contains:success,ok,done");
|
||||
|
||||
test("예약어 - !contains",
|
||||
EAITable.JSON_TYPE,
|
||||
"{\"status\":\"success\"}",
|
||||
"status",
|
||||
"@!contains:fail,error,invalid");
|
||||
|
||||
test("예약어 - starts",
|
||||
EAITable.JSON_TYPE,
|
||||
"{\"code\":\"SUCCESS_001\"}",
|
||||
"code",
|
||||
"@starts:SUCCESS");
|
||||
|
||||
test("예약어 - ends",
|
||||
EAITable.JSON_TYPE,
|
||||
"{\"code\":\"ERR_001\"}",
|
||||
"code",
|
||||
"@ends:001");
|
||||
|
||||
// 3. 숫자 비교 테스트
|
||||
test("예약어 - gt",
|
||||
EAITable.JSON_TYPE,
|
||||
"{\"value\":\"100\"}",
|
||||
"value",
|
||||
"@gt:50");
|
||||
|
||||
test("예약어 - lt",
|
||||
EAITable.JSON_TYPE,
|
||||
"{\"value\":\"100\"}",
|
||||
"value",
|
||||
"@lt:150");
|
||||
|
||||
test("예약어 - ge",
|
||||
EAITable.JSON_TYPE,
|
||||
"{\"value\":\"100\"}",
|
||||
"value",
|
||||
"@ge:100");
|
||||
|
||||
test("예약어 - le",
|
||||
EAITable.JSON_TYPE,
|
||||
"{\"value\":\"100\"}",
|
||||
"value",
|
||||
"@le:100");
|
||||
|
||||
// 4. 실패 케이스
|
||||
test("예약어 - 잘못된 숫자",
|
||||
EAITable.JSON_TYPE,
|
||||
"{\"value\":\"invalid\"}",
|
||||
"value",
|
||||
"@gt:50");
|
||||
|
||||
test("예약어 - 잘못된 패턴",
|
||||
EAITable.JSON_TYPE,
|
||||
"{\"status\":\"success\"}",
|
||||
"status",
|
||||
"@invalid:pattern");
|
||||
}
|
||||
|
||||
private static void test(String testName, String type, String message, String path, String expected) {
|
||||
TestResult result = isSuccessMessageTest(type, message, path, expected);
|
||||
System.out.println(String.format(
|
||||
"테스트: %s\n결과: %s\n메시지: %s\n경로: %s\n기대값: %s\n추출된 값: [%s]\n",
|
||||
testName,
|
||||
result.success ? "성공" : "실패",
|
||||
message,
|
||||
path,
|
||||
expected,
|
||||
result.extractedValue
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package com.eactive.eai.adapter.controller;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Properties;
|
||||
|
||||
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.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpDynamicInAdapterUri;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.adapter.service.ApiAdapterService;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.common.util.InboundErrorLogger;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.common.util.UUIDGenerator;
|
||||
import com.eactive.eai.inbound.error.InboundErrorInfoVO;
|
||||
|
||||
@RestController
|
||||
public class ApiAdapterController implements HttpAdapterServiceKey {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
@Autowired
|
||||
ApiAdapterService service;
|
||||
|
||||
/**
|
||||
* KBANK 요구사항으로 /api/v1/oauth/token 과 같은 형태로 토큰 발급거래를 수행해야해서 예외처리함
|
||||
* @See com.eactive.eai.authserver.config.AuthorizationServerConfig.configure(AuthorizationServerEndpointsConfigurer endpoints)
|
||||
*/
|
||||
@RequestMapping(value = {"/api/*", "/api/*/{path:^(?!.*oauth).*$}/**"})
|
||||
// @RequestMapping(value = {"/api/**"})
|
||||
public ResponseEntity<String> callApi(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception {
|
||||
// /ONLWeb/api/v1/public/getUserInfo.svc
|
||||
String apiUri = servletRequest.getRequestURI();
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
apiUri = StringUtils.removeStart(apiUri, servletRequest.getContextPath());
|
||||
apiUri = StringUtils.removeEnd(apiUri, "/");
|
||||
HttpDynamicInAdapterUri adptUri = findAdptUri(apiUri, HttpDynamicInAdapterManager.getInstance());
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("ApiAdapterController] service request uri : " + servletRequest.getRequestURI());
|
||||
}
|
||||
|
||||
if (adptUri == null) {
|
||||
logError(servletRequest);
|
||||
// throw new Exception("can not find Adapter Uri");
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("can not find Adapter Uri");
|
||||
}
|
||||
|
||||
|
||||
String adapterGroupName = adptUri.getAdptGrpName();
|
||||
String adapterName = adptUri.getAdptName();
|
||||
AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(adapterGroupName);
|
||||
AdapterVO adapterVO = AdapterManager.getInstance().getAdapterVO(adapterGroupName, adapterName);
|
||||
if (adapterVO == null) {
|
||||
// throw new Exception("Adapter not found error");
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Adapter not found error");
|
||||
}
|
||||
|
||||
Properties httpProp = AdapterPropManager.getInstance().getProperties(adapterVO.getPropGroupName());
|
||||
|
||||
String adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||
MediaType mediaType = MediaType.valueOf("application/json;charset=" + encode);
|
||||
String errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||
|
||||
String responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
|
||||
ResponseEntity responseEntity = null;
|
||||
Properties transactionProp = new Properties();
|
||||
try {
|
||||
String responseData = service.callApi(servletRequest, servletResponse, httpProp, adapterGroupVO, adapterVO, transactionProp);
|
||||
if (RESPONSE_TYPE_ASYNC.equals(responseType)) {
|
||||
responseEntity = ResponseEntity.ok("dummy");
|
||||
} else {
|
||||
// responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
// 버즈빌 포인트 적립 처리하기 위하여 정상응답이더라도 응답코드(apiRsltCd) 값이 200이 아닌 경우 처리를 위하여 수정
|
||||
// Filter에서 설정한 response status값을 responseEntity 생성시 적용 modify by lwk 2025.03.24
|
||||
int httpStatus = servletResponse.getStatus();
|
||||
if (httpStatus != 200) {
|
||||
responseEntity = ResponseEntity.status(httpStatus).contentType(mediaType).body(responseData);
|
||||
} else {
|
||||
responseEntity = ResponseEntity.ok().contentType(mediaType).body(responseData);
|
||||
}
|
||||
}
|
||||
} catch (HttpStatusException e) {
|
||||
logger.warn("ApiAdapterController] " + adapterGroupName + "-" + adapterName + ">>" + e.getMessage());
|
||||
String errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode, e.getCode(),
|
||||
e.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(e.getStatus()).contentType(mediaType).body(errorMsg);
|
||||
} catch (JwtAuthException e) {
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
String errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode, e.getCode(),
|
||||
e.getMessage(), errorResponseFormat);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(mediaType).body(errorMsg);
|
||||
} catch (Exception e) {
|
||||
logger.error(adapterGroupName + "-" + adapterName + ">>" + e.getMessage(), e);
|
||||
responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(mediaType).body(e);
|
||||
} finally {
|
||||
/**
|
||||
* 로깅 인터셉터에 데이터를 전달하기 위한 처리
|
||||
* 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
|
||||
* 추후 더 좋은방법이 생길경우 개선 요망
|
||||
*/
|
||||
servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
|
||||
}
|
||||
return responseEntity;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* url에서 뒤쪽 /이후를 제거하면서 찾는다.<br>
|
||||
* /api/v1/public/getUserInfo.svc
|
||||
*
|
||||
* @param apiUri
|
||||
* @return
|
||||
*/
|
||||
private HttpDynamicInAdapterUri findAdptUri(String apiUri, HttpDynamicInAdapterManager manager) {
|
||||
if (StringUtils.isBlank(apiUri)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
HttpDynamicInAdapterUri adptUri = manager.getAdptUri(apiUri);
|
||||
if (adptUri != null) {
|
||||
return adptUri;
|
||||
}
|
||||
|
||||
// /api/v1/public
|
||||
apiUri = StringUtils.substringBeforeLast(apiUri, "/");
|
||||
if (apiUri.length() < 4) { // /api
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void logError(HttpServletRequest request) {
|
||||
InboundErrorInfoVO errorInfoVO = new InboundErrorInfoVO();
|
||||
|
||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||
String serverName = eaiServerManager.getLocalServerName();
|
||||
String uuid = null;
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
String instanceid1 = serverName.substring(0, 2);
|
||||
String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||
String instid = instanceid1 + instanceid2;
|
||||
uuid = instid + UUIDGenerator.getUUID();
|
||||
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = request.getRequestURI();
|
||||
|
||||
String errorCode = "RECEAIIRP010";
|
||||
String errorMsg = ExceptionUtil.make(new Exception("cat not find uri"), errorCode, msgArgs);
|
||||
|
||||
errorInfoVO.setEaiSvcSno(uuid); // EAI서비스일련번호
|
||||
errorInfoVO.setAdptBwkGrpNm("HTTP_IN_NO_URI"); // 어댑터업무그룹명
|
||||
errorInfoVO.setErrCd(errorCode); // 에러코드
|
||||
errorInfoVO.setErrTxt(errorMsg); // 에러내용
|
||||
errorInfoVO.setErrTm(DatetimeUtil.getCurrentTime(new Date().getTime())); // 에러발생시각
|
||||
errorInfoVO.setErrDstcd(" ");
|
||||
sb.append("Remote Addr : ").append(request.getRemoteAddr()).append("\n").append("Request URI : ")
|
||||
.append(request.getRequestURI());
|
||||
errorInfoVO.setBwkDataTxt(sb.toString()); // 업무데이터내용
|
||||
errorInfoVO.setEaiSvrInstNm(serverName); // EAI서버인스턴스명
|
||||
|
||||
InboundErrorLogger.error(errorInfoVO);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.eactive.eai.adapter.controller;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
|
||||
@Controller
|
||||
public class TokenRedirectController {
|
||||
|
||||
@PostMapping("/sample/v1/oauth/token")
|
||||
public void redirectPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
// 포워딩할 URL을 지정
|
||||
String targetUrl = "/api/v1/oauth/token";
|
||||
// 요청과 응답을 다른 URL로 포워딩
|
||||
request.getRequestDispatcher(targetUrl).forward(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.eactive.eai.adapter.interceptor;
|
||||
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
|
||||
Properties transactionProp = (Properties) request.getAttribute(TransactionContextKeys.TRANSACTION_PROP);
|
||||
if(transactionProp == null || "ASYN".equals(transactionProp.getProperty(HttpAdapterServiceKey.INBOUND_SYNC_ASYNC_TYPE))){
|
||||
return;
|
||||
}
|
||||
|
||||
String uuid = transactionProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
String adapterGroupName = transactionProp.getProperty(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME);
|
||||
String adapterName = transactionProp.getProperty(HttpClientAdapterServiceKey.ADAPTER_NAME);
|
||||
String url = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
|
||||
String method = transactionProp.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
|
||||
|
||||
if(StringUtils.isBlank(uuid) || StringUtils.isBlank(adapterGroupName)){
|
||||
return;
|
||||
}
|
||||
|
||||
Map<Object, Object> headerMap = new HashMap<>();
|
||||
// 응답 헤더 로깅
|
||||
for (String headerName : response.getHeaderNames()) {
|
||||
String headerValue = response.getHeader(headerName);
|
||||
headerMap.put(headerName, headerValue);
|
||||
}
|
||||
|
||||
int httpStatusCode = response.getStatus();
|
||||
HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName, adapterName, headerMap, url, method, httpStatusCode);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
package com.eactive.eai.adapter.service;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.Keys;
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.inbound.action.ActionFactory;
|
||||
import com.eactive.eai.inbound.action.RequestAction;
|
||||
import com.eactive.eai.inbound.processor.Processor;
|
||||
import com.eactive.eai.message.StandardMessageUtil;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.mina.common.ByteBuffer;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.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.*;
|
||||
|
||||
@Service
|
||||
public class ApiAdapterService extends HttpAdapterServiceSupport {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||
// HEADER_GROUP JSON에 추가할 항목 정의, 없으면 전체 header 추가
|
||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||
public static final String PROPERTIES_NAME_HTTP_REQUEST_METHOD = "httpRequestMethod";
|
||||
|
||||
private static final String JSON_CONTENT_TYPE = "application/json";
|
||||
private static final String JSON_FIELD_NAME = "json-body";
|
||||
private static final String FILE_GROUP_NAME = "image-file";
|
||||
private static final String UPLOAD_ROOT_PATH = "UPLOAD_ROOT_PATH";
|
||||
|
||||
public String callApi(HttpServletRequest request, HttpServletResponse response, Properties httpProp, AdapterGroupVO adapterGroupVO, AdapterVO adapterVO, Properties transactionProp) throws Exception {
|
||||
int traceLevel = 0;
|
||||
|
||||
AdapterPropManager manager = null;
|
||||
String adptGrpName = adapterGroupVO.getName();
|
||||
String adptName = adapterVO.getName();
|
||||
|
||||
|
||||
String urlDecodeYn = httpProp.getProperty(URL_DECODE_YN, "N");
|
||||
String encode = StringUtils.defaultIfBlank(adapterGroupVO.getMessageEncode(), "UTF-8");
|
||||
|
||||
String traceLevelTemp = httpProp.getProperty(TRACE_LEVEL, "0");
|
||||
String relayRequestHeaderKeys = httpProp.getProperty(HEADER_KEYS);
|
||||
String headerGroupName = httpProp.getProperty(HEADER_GROUP);
|
||||
|
||||
boolean isParameterType = false;
|
||||
String message = null;
|
||||
|
||||
String paramValue = null;
|
||||
String adptMsgType = null;
|
||||
|
||||
transactionProp.put(INBOUND_METHOD, request.getMethod());
|
||||
transactionProp.put(INBOUND_URI, request.getRequestURI());
|
||||
transactionProp.put(INBOUND_HEADER, getHeaders(request));
|
||||
if (StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_REST)
|
||||
|| StringUtils.equals(adapterVO.getAdapterGroupVO().getType(), Keys.TYPE_HTTP_CUSTOM)) {
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
String extUrl = StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
|
||||
transactionProp.put(INBOUND_EXTURI, extUrl);
|
||||
} else {
|
||||
transactionProp.put(INBOUND_EXTURI, getExtUri(request));
|
||||
}
|
||||
transactionProp.put(INBOUND_CLIENT_IP, getClientIp(request)); // Client IP 추가
|
||||
transactionProp.put(Processor.REQUEST_ACTION, adapterVO.getAdapterGroupVO().getRefClass());
|
||||
transactionProp.put(API_PATH, httpProp.getProperty(API_PATH, ""));
|
||||
transactionProp.put(PRE_FILTERS, httpProp.getProperty(PRE_FILTERS, ""));
|
||||
transactionProp.put(POST_FILTERS, httpProp.getProperty(POST_FILTERS, ""));
|
||||
transactionProp.put(PROPERTIES_NAME_HTTP_REQUEST_METHOD, request.getMethod());
|
||||
transactionProp.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
|
||||
|
||||
transactionProp.put(ENC_PATHS, httpProp.getProperty(ENC_PATHS, ""));
|
||||
|
||||
try {
|
||||
traceLevel = Integer.parseInt(traceLevelTemp);
|
||||
} catch (Exception e) {
|
||||
traceLevel = 0;
|
||||
}
|
||||
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
logger.debug("시작 >> encode = [" + encode + "]");
|
||||
|
||||
switch (HttpMethodType.getValue(request.getMethod())) {
|
||||
case GET:
|
||||
case DELETE:
|
||||
isParameterType = true;
|
||||
break;
|
||||
case POST:
|
||||
case PUT:
|
||||
if (StringUtils.contains(request.getContentType(), "application/x-www-form-urlencoded")) {
|
||||
isParameterType = true;
|
||||
} else {
|
||||
isParameterType = false;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (isParameterType) {
|
||||
paramValue = request.getQueryString();
|
||||
if (paramValue == null)
|
||||
paramValue = "";
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(paramValue));
|
||||
}
|
||||
|
||||
// json으로 변환
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("{");
|
||||
Map<String, String[]> paramMap = assignParameterMap(request, adptGrpName, adptName, null, transactionProp);
|
||||
int i = 0;
|
||||
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
|
||||
if (i > 0) {
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append("\"").append(entry.getKey()).append("\":");
|
||||
String[] values = entry.getValue();
|
||||
if (values.length > 1) {
|
||||
// ["111", "222"]
|
||||
sb.append("[");
|
||||
for (int j = 0; j < values.length; j++) {
|
||||
if (j > 0) {
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append("\"").append(JSONValue.escape(values[j])).append("\"");
|
||||
}
|
||||
sb.append("]");
|
||||
} else {
|
||||
sb.append("\"").append(JSONValue.escape(values[0])).append("\"");
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
sb.append("}");
|
||||
|
||||
paramValue = sb.toString();
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
||||
+ CommonLib.getDumpMessage(paramValue.getBytes(encode)));
|
||||
}
|
||||
} else {
|
||||
ServletInputStream sis = request.getInputStream();
|
||||
ByteBuffer bb = ByteBuffer.allocate(1024).setAutoExpand(true);
|
||||
int i = 0;
|
||||
byte[] cbuf = new byte[1024];
|
||||
while ((i = sis.read(cbuf, 0, 1024)) != -1) {
|
||||
if (i == 1024) {
|
||||
bb.put(cbuf);
|
||||
} else {
|
||||
byte[] tail = new byte[i];
|
||||
System.arraycopy(cbuf, 0, tail, 0, i);
|
||||
bb.put(tail);
|
||||
}
|
||||
}
|
||||
byte[] data = new byte[bb.position()];
|
||||
bb.position(0);
|
||||
bb.get(data);
|
||||
paramValue = new String(data, encode);
|
||||
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(data));
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
||||
+ CommonLib.getDumpMessage(data));
|
||||
}
|
||||
}
|
||||
|
||||
if (paramValue == null) { // parameter가 없는 경우때문에 처리
|
||||
paramValue = "";
|
||||
}
|
||||
|
||||
if ("Y".equals(urlDecodeYn) && isParameterType) {
|
||||
message = URLDecoder.decode(paramValue);
|
||||
} else {
|
||||
message = paramValue;
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
String[] msgArgs = new String[2];
|
||||
msgArgs[0] = adptGrpName;
|
||||
msgArgs[1] = message;
|
||||
String resMsg = ExceptionUtil.make("RICEAIAHA005", msgArgs);
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
|
||||
|
||||
adptMsgType = adapterVO.getAdapterGroupVO().getMessageType();
|
||||
// HttpHeaders responseHeaders = new HttpHeaders();
|
||||
// responseHeaders.setContentType(MediaType.valueOf("application/json;charset=" + encode));
|
||||
|
||||
|
||||
// HEADER_GROUP 셋팅
|
||||
if (MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)
|
||||
&& StringUtils.isNotBlank(relayRequestHeaderKeys)) {
|
||||
JSONObject jsonMessage = (JSONObject) JSONValue.parse(message);
|
||||
JSONObject headerJson = new JSONObject();
|
||||
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements(); ) {
|
||||
String key = e.nextElement();
|
||||
headerJson.put(key, request.getHeader(key));
|
||||
}
|
||||
} else {
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils
|
||||
.tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
||||
|
||||
for (String key : relayKeyArr) {
|
||||
String headerValue = request.getHeader(key);
|
||||
if (StringUtils.isNotBlank(headerValue)) {
|
||||
headerJson.put(key, headerValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (headerJson.size() > 0) {
|
||||
jsonMessage.put(headerGroupName, headerJson);
|
||||
message = jsonMessage.toJSONString();
|
||||
}
|
||||
}
|
||||
|
||||
if (message == null) {
|
||||
message = "";
|
||||
}
|
||||
|
||||
transactionProp.put(INBOUND_REQUEST_MESSAGE, message);
|
||||
// 로컬 서비스 호출 ,encoding 처리 추가
|
||||
String result = (String) service(adptGrpName, adptName, message, transactionProp, request, response);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] result " + encode + " (" + adptGrpName + ") = [" + result + "]");
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
String syncAsyncType = transactionProp.getProperty(INBOUND_SYNC_ASYNC_TYPE);
|
||||
if (!"ASYN".equals(syncAsyncType) && MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode rootNode = (ObjectNode) mapper.readTree(result);
|
||||
JsonNode headerGroup = rootNode.get(headerGroupName);
|
||||
if(headerGroup != null) {
|
||||
for(Iterator<String> it = headerGroup.fieldNames(); it.hasNext();) {
|
||||
String name = it.next();
|
||||
String value = headerGroup.get(name).asText();
|
||||
response.addHeader(name, value);
|
||||
}
|
||||
rootNode.remove(headerGroupName);
|
||||
result = mapper.writeValueAsString(rootNode);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
private Map<String, String[]> assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName,
|
||||
Object requestBytes, Properties prop) {
|
||||
// PathVariable 체크
|
||||
if (StringUtils.equalsAnyIgnoreCase(request.getMethod(), HttpMethod.GET.name(), HttpMethod.DELETE.name())
|
||||
&& StringUtils.isBlank(request.getQueryString())) {
|
||||
try {
|
||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||
RequestAction action = ActionFactory.createAction(actionName);
|
||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||
String[] keys = action.perform(requestBytes);
|
||||
String requestPath = keys[0];
|
||||
|
||||
// PathVariable 지원 추가
|
||||
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
||||
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
||||
Map<String, String> paramMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath,
|
||||
requestPath);
|
||||
if (paramMap != null && paramMap.size() > 0) {
|
||||
Map<String, String[]> returnMap = new HashMap<>();
|
||||
for (String key : paramMap.keySet()) {
|
||||
if (StringUtils.equalsIgnoreCase(key, "method")) {
|
||||
continue;
|
||||
}
|
||||
returnMap.put(key, new String[] { paramMap.get(key) });
|
||||
}
|
||||
|
||||
return returnMap;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
return request.getParameterMap();
|
||||
}
|
||||
|
||||
private Properties getHeaders(HttpServletRequest request) {
|
||||
Properties prop = new Properties();
|
||||
|
||||
Enumeration<String> headerNames = request.getHeaderNames();
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String key = headerNames.nextElement();
|
||||
String value = request.getHeader(key);
|
||||
prop.setProperty(key, value);
|
||||
}
|
||||
|
||||
return prop;
|
||||
}
|
||||
|
||||
private String getExtUri(HttpServletRequest request) {
|
||||
String orgUri = request.getRequestURI().replaceAll(request.getContextPath(), "");
|
||||
String uri = getExtUri(orgUri, 3);
|
||||
if (uri != null && uri.trim().length() > 0) {
|
||||
return "/" + uri;
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static String getExtUri(String url, int length) {
|
||||
String[] urls = url.split("/");
|
||||
List<String> newUrls = new ArrayList<>();
|
||||
Collections.addAll(newUrls, urls);
|
||||
return StringUtils.join(newUrls.subList(length, urls.length).toArray(), "/");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Deprecated
|
||||
public void service(String adptGrpName, String adptName, HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP 요청에서 클라이언트 IP를 추출합니다.
|
||||
* X-Forwarded-For 헤더가 있는 경우 이를 우선적으로 사용하고,
|
||||
* 없는 경우 remoteAddr을 사용합니다.
|
||||
*/
|
||||
private String getClientIp(HttpServletRequest request) {
|
||||
String ipAddress = request.getHeader("X-Forwarded-For");
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getRemoteAddr();
|
||||
}
|
||||
return ipAddress;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package com.eactive.eai.authserver.config;
|
||||
|
||||
import java.security.KeyPair;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.vo.ClientVO;
|
||||
import com.eactive.eai.common.logger.EAIDBLogControl;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
|
||||
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
|
||||
import org.springframework.security.oauth2.provider.ClientDetailsService;
|
||||
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
|
||||
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
|
||||
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
|
||||
|
||||
import com.eactive.eai.authserver.provider.ElinkJdbcTokenStore;
|
||||
import com.eactive.eai.common.dao.Keys;
|
||||
import com.eactive.eai.common.property.PropGroupVO;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.ServiceLocator;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.data.entity.onl.authserver.TokenIssuanceLog;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetails;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
@Configuration
|
||||
@EnableAuthorizationServer
|
||||
@Order(6)
|
||||
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
public static final String PROP_GROUP_AUTH_SERVER = "OAuthServer";
|
||||
public static final String PROP_KEYSTORE_PATH = "certification.keystorePath";
|
||||
public static final String PROP_KEYSTORE_PW = "certification.keystorePassword";
|
||||
public static final String PROP_KEY_ALIAS = "certification.keyAlias";
|
||||
public static final String PROP_KEY_PW = "certification.keyPassword";
|
||||
public static final String PROP_TOKEN_TYPE = "oauth2.tokenType";
|
||||
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Autowired
|
||||
private TokenIssuanceLogDAO tokenIssuanceLogDAO;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("eLinkClientDetailsService")
|
||||
private ClientDetailsService clientDetailsService;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("eLinkUserDetailsService")
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
@Override
|
||||
public void configure(final AuthorizationServerSecurityConfigurer security) throws Exception {
|
||||
security.tokenKeyAccess("permitAll()") // /oauth/token_key
|
||||
.checkTokenAccess("permitAll()") // /oauth/check_token
|
||||
.allowFormAuthenticationForClients();
|
||||
|
||||
security.addTokenEndpointAuthenticationFilter(new OAuthRequestLoggingFilter());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
|
||||
clients.withClientDetails(clientDetailsService);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
|
||||
super.configure(endpoints);
|
||||
|
||||
PropGroupVO vo = PropManager.getInstance().getPropGroupVO(PROP_GROUP_AUTH_SERVER);
|
||||
String tokenType = "JWT";
|
||||
if (vo != null) {
|
||||
tokenType = vo.getProperty(PROP_TOKEN_TYPE, "JWT");
|
||||
}
|
||||
|
||||
endpoints.pathMapping("/oauth/token", "/api/v1/oauth/token");
|
||||
endpoints.authenticationManager(authenticationManager);
|
||||
endpoints.userDetailsService(userDetailsService);
|
||||
|
||||
// JWT 토큰을 사용하는 경우
|
||||
JwtAccessTokenConverter converter = jwtAccessTokenConverter();
|
||||
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
|
||||
// JWT 변환 후에 로깅하도록 순서 변경
|
||||
tokenEnhancerChain.setTokenEnhancers(
|
||||
Arrays.asList(converter, new TokenIssuanceLogEnhancer())
|
||||
);
|
||||
|
||||
endpoints
|
||||
.tokenStore(new JwtTokenStore(converter))
|
||||
.accessTokenConverter(converter)
|
||||
.tokenEnhancer(tokenEnhancerChain);
|
||||
|
||||
endpoints.exceptionTranslator(new CustomWebResponseExceptionTranslator());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtAccessTokenConverter jwtAccessTokenConverter() {
|
||||
PropGroupVO vo = PropManager.getInstance().getPropGroupVO(PROP_GROUP_AUTH_SERVER);
|
||||
String keystorePath = "/certificate/elink-oauth-dev.jks";
|
||||
String keystorePassword = "elink1234";
|
||||
String keyAlias = "elink-oauth";
|
||||
String keyPassword = "elink1234";
|
||||
if (vo != null) {
|
||||
keystorePath = vo.getProperty(PROP_KEYSTORE_PATH);
|
||||
keystorePassword = vo.getProperty(PROP_KEYSTORE_PW);
|
||||
keyAlias = vo.getProperty(PROP_KEY_ALIAS);
|
||||
keyPassword = vo.getProperty(PROP_KEY_PW);
|
||||
} else {
|
||||
logger.warn("The properties has not been set.[" + PROP_GROUP_AUTH_SERVER + "]");
|
||||
}
|
||||
|
||||
Resource keystore = new ClassPathResource(keystorePath);
|
||||
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(keystore, keystorePassword.toCharArray());
|
||||
KeyPair keyPair = keyStoreKeyFactory.getKeyPair(keyAlias, keyPassword.toCharArray());
|
||||
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
|
||||
converter.setKeyPair(keyPair);
|
||||
return converter;
|
||||
}
|
||||
|
||||
|
||||
private DataSource getDataSource() {
|
||||
try {
|
||||
ServiceLocator sl = ServiceLocator.getInstance();
|
||||
DataSource dataSource = sl.getDataSource(Keys.EAI_DATASOURCE);
|
||||
return dataSource;
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed get [" + Keys.EAI_DATASOURCE + "]");
|
||||
logger.error(e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {
|
||||
@Override
|
||||
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
|
||||
OAuth2Exception oAuth2Exception;
|
||||
boolean isRestrictionExempt = false;
|
||||
if (e instanceof OAuth2Exception) {
|
||||
oAuth2Exception = (OAuth2Exception) e;
|
||||
if(e instanceof IssueLimitOAuth2Exception){
|
||||
isRestrictionExempt = true;
|
||||
}
|
||||
} else {
|
||||
oAuth2Exception = new OAuth2Exception("Server error", e);
|
||||
}
|
||||
|
||||
// 토큰 발급 실패 로깅
|
||||
logTokenIssuance(false, isRestrictionExempt, oAuth2Exception.getMessage(), null);
|
||||
|
||||
return ResponseEntity
|
||||
.status(oAuth2Exception.getHttpErrorCode())
|
||||
.body(oAuth2Exception);
|
||||
}
|
||||
}
|
||||
|
||||
private class TokenIssuanceLogEnhancer implements TokenEnhancer {
|
||||
@Override
|
||||
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
|
||||
if (!EAIDBLogControl.isEnable()) {
|
||||
logger.warn("DB logging is disabled. Skipping token issuance logging.");
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
String clientId = authentication.getOAuth2Request().getClientId();
|
||||
LocalDateTime startDateTime = LocalDateTime.now().minusHours(24);
|
||||
|
||||
int recentTokenCount = tokenIssuanceLogDAO.findRecentLogsForRestrictionCount(clientId, startDateTime);
|
||||
|
||||
try {
|
||||
ClientVO clientVO = OAuth2Manager.getInstance().getClientInfo(clientId);
|
||||
int dailyTokenLimit = clientVO.getDailyTokenLimit();
|
||||
if (dailyTokenLimit > 0 && recentTokenCount >= dailyTokenLimit) {
|
||||
throw new IssueLimitOAuth2Exception("Token issuance limit exceeded for this client");
|
||||
}
|
||||
|
||||
// JWT 변환 이후의 최종 토큰 값 로깅
|
||||
logTokenIssuance(true, false, "Token issued successfully", accessToken.getValue());
|
||||
} catch (DAOException e) {
|
||||
logger.warn("cannot find clientVo - " + clientId);
|
||||
}
|
||||
return accessToken;
|
||||
}
|
||||
}
|
||||
|
||||
private void logTokenIssuance(boolean isSuccess, boolean isRestrictionExempt, String resultMessage, String accessToken) {
|
||||
try {
|
||||
if (!EAIDBLogControl.isEnable()) {
|
||||
logger.warn("DB logging is disabled. Skipping token issuance logging.");
|
||||
return;
|
||||
}
|
||||
RequestContextData data = RequestContextData.ThreadLocalRequestContext.get();
|
||||
OAuth2Manager.getInstance();
|
||||
|
||||
TokenIssuanceLog log = new TokenIssuanceLog();
|
||||
String clientId = data.getClientId();
|
||||
log.setClientId(clientId);
|
||||
|
||||
if(StringUtils.isNotBlank(clientId)) {
|
||||
ClientVO clientVO = OAuth2Manager.getInstance().getClientInfo(clientId);
|
||||
log.setAppName(clientVO.getClientName());
|
||||
log.setOrgId(clientVO.getOrgId());
|
||||
log.setOrgName(clientVO.getOrgName());
|
||||
}
|
||||
|
||||
log.setGrantType(data.getGrantType());
|
||||
log.setScope(data.getScope());
|
||||
log.setIpAddress(data.getIpAddress());
|
||||
log.setSuccessYn(isSuccess ? "Y" : "N");
|
||||
log.setIssuanceDateTime(LocalDateTime.now());
|
||||
log.setRestrictionExemptYn(isRestrictionExempt ? "Y" : "N");
|
||||
log.setResultMessage(resultMessage);
|
||||
log.setAccessToken(accessToken); // Add access token value to the log
|
||||
|
||||
tokenIssuanceLogDAO.saveTokenIssuanceLog(log);
|
||||
} catch (Throwable th) {
|
||||
logger.error("Error while logging token issuance: " + th.getMessage(), th);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.eactive.eai.authserver.config;
|
||||
|
||||
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
|
||||
|
||||
public class IssueLimitOAuth2Exception extends OAuth2Exception {
|
||||
public IssueLimitOAuth2Exception(String msg, Throwable t) {
|
||||
super(msg, t);
|
||||
}
|
||||
|
||||
public IssueLimitOAuth2Exception(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.eactive.eai.authserver.config;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
|
||||
public class OAuthRequestLoggingFilter extends OncePerRequestFilter {
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
try {
|
||||
RequestContextData data = new RequestContextData();
|
||||
data.setClientId(request.getParameter("client_id"));
|
||||
data.setIpAddress(extractIpAddress(request));
|
||||
data.setGrantType(request.getParameter("grant_type"));
|
||||
data.setScope(request.getParameter("scope"));
|
||||
data.setUsername(request.getParameter("username"));
|
||||
|
||||
RequestContextData.ThreadLocalRequestContext.set(data);
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
RequestContextData.ThreadLocalRequestContext.clear();
|
||||
}
|
||||
}
|
||||
private String extractIpAddress(HttpServletRequest request) {
|
||||
String ipAddress = request.getHeader("X-Forwarded-For");
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getRemoteAddr();
|
||||
}
|
||||
return ipAddress;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.eactive.eai.authserver.config;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class RequestContextData {
|
||||
private String clientId;
|
||||
private String ipAddress;
|
||||
private String grantType;
|
||||
private String scope;
|
||||
private String username;
|
||||
|
||||
// Getters and setters
|
||||
|
||||
public static class ThreadLocalRequestContext {
|
||||
private static final ThreadLocal<RequestContextData> contextHolder = new ThreadLocal<>();
|
||||
|
||||
public static void set(RequestContextData data) {
|
||||
contextHolder.set(data);
|
||||
}
|
||||
|
||||
public static RequestContextData get() {
|
||||
return contextHolder.get();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
contextHolder.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.eactive.eai.authserver.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@Order(1)
|
||||
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("eLinkUserDetailsService")
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.csrf().disable()
|
||||
.headers().frameOptions().disable()
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/**").permitAll()
|
||||
.and()
|
||||
.formLogin();
|
||||
// .and()
|
||||
// .httpBasic();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Override
|
||||
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public BCryptPasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class SnapOAuth2AccessTokenRequest implements Serializable {
|
||||
private String grantType;
|
||||
private String authCode;
|
||||
private String refreshToken;
|
||||
private Object additionalInfo;
|
||||
|
||||
public String getGrantType() {
|
||||
return grantType;
|
||||
}
|
||||
|
||||
public void setGrantType(String grantType) {
|
||||
this.grantType = grantType;
|
||||
}
|
||||
|
||||
public String getAuthCode() {
|
||||
return authCode;
|
||||
}
|
||||
|
||||
public void setAuthCode(String authCode) {
|
||||
this.authCode = authCode;
|
||||
}
|
||||
|
||||
public String getRefreshToken() {
|
||||
return refreshToken;
|
||||
}
|
||||
|
||||
public void setRefreshToken(String refreshToken) {
|
||||
this.refreshToken = refreshToken;
|
||||
}
|
||||
|
||||
public Object getAdditionalInfo() {
|
||||
return additionalInfo;
|
||||
}
|
||||
|
||||
public void setAdditionalInfo(Object additionalInfo) {
|
||||
this.additionalInfo = additionalInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SnapOAuth2AccessTokenRequest [grantType=" + grantType + ", authCode=" + authCode + ", refreshToken="
|
||||
+ refreshToken + ", additionalInfo=" + additionalInfo + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
@JsonInclude(Include.NON_NULL)
|
||||
public class SnapOAuth2AccessTokenResponse implements Serializable {
|
||||
private String responseCode;
|
||||
private String responseMessage;
|
||||
private String accessToken;
|
||||
private String tokenType;
|
||||
private String expiresIn;
|
||||
private Object additionalInfo;
|
||||
|
||||
public String getResponseCode() {
|
||||
return responseCode;
|
||||
}
|
||||
|
||||
public void setResponseCode(String responseCode) {
|
||||
this.responseCode = responseCode;
|
||||
}
|
||||
|
||||
public String getResponseMessage() {
|
||||
return responseMessage;
|
||||
}
|
||||
|
||||
public void setResponseMessage(String responseMessage) {
|
||||
this.responseMessage = responseMessage;
|
||||
}
|
||||
|
||||
public String getAccessToken() {
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
public void setAccessToken(String accessToken) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
|
||||
public String getTokenType() {
|
||||
return tokenType;
|
||||
}
|
||||
|
||||
public void setTokenType(String tokenType) {
|
||||
this.tokenType = tokenType;
|
||||
}
|
||||
|
||||
public String getExpiresIn() {
|
||||
return expiresIn;
|
||||
}
|
||||
|
||||
public void setExpiresIn(String expiresIn) {
|
||||
this.expiresIn = expiresIn;
|
||||
}
|
||||
|
||||
public Object getAdditionalInfo() {
|
||||
return additionalInfo;
|
||||
}
|
||||
|
||||
public void setAdditionalInfo(Object additionalInfo) {
|
||||
this.additionalInfo = additionalInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SnapOAuth2AccessTokenResponse [responseCode=" + responseCode + ", responseMessage=" + responseMessage
|
||||
+ ", accessToken=" + accessToken + ", tokenType=" + tokenType + ", expiresIn=" + expiresIn
|
||||
+ ", additionalInfo=" + additionalInfo + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.eactive.eai.authserver.custom;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.Principal;
|
||||
import java.security.PublicKey;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Signature;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.util.OAuth2Utils;
|
||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Request;
|
||||
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.util.BeanUtils;
|
||||
import com.eactive.eai.authserver.vo.ClientVO;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
@Controller
|
||||
public class SnapOAuth2Controller {
|
||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
private static final String HEADER_TIMESTAMP = "X-TIMESTAMP";
|
||||
private static final String HEADER_CLIENT_ID = "X-CLIENT-KEY";
|
||||
private static final String HEADER_SIGNATURE = "X-SIGNATURE";
|
||||
|
||||
private static final String SERVICE_CODE_ACCESS_TOKEN = "00"; // 임시설정
|
||||
|
||||
@RequestMapping(value = "/bukopin_snap_api/v1.0/access-token/b2b", method = RequestMethod.POST, produces = "application/json; charset=\"UTF-8\"")
|
||||
@ResponseBody
|
||||
public SnapOAuth2AccessTokenResponse token(@RequestBody SnapOAuth2AccessTokenRequest tokenRequest,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(tokenRequest.toString());
|
||||
}
|
||||
|
||||
SnapOAuth2AccessTokenResponse responseToken = new SnapOAuth2AccessTokenResponse();
|
||||
try {
|
||||
if (!StringUtils.equals(tokenRequest.getGrantType(), "client_credentials")) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {grantType}");
|
||||
}
|
||||
|
||||
String timeStamp = request.getHeader(HEADER_TIMESTAMP);
|
||||
String clientId = request.getHeader(HEADER_CLIENT_ID);
|
||||
String signature = request.getHeader(HEADER_SIGNATURE);
|
||||
|
||||
ClientDetails clientDetails = OAuth2Manager.getInstance().getClientDeatilsStore().get(clientId);
|
||||
verifyClient(clientDetails, timeStamp, clientId, signature);
|
||||
|
||||
response.setHeader(HEADER_TIMESTAMP, timeStamp);
|
||||
response.setHeader(HEADER_CLIENT_ID, clientId);
|
||||
|
||||
HashMap<String, String> authorizationParameters = new HashMap<String, String>();
|
||||
authorizationParameters.put(OAuth2Utils.GRANT_TYPE, tokenRequest.getGrantType());
|
||||
authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
|
||||
authorizationParameters.put("client_secret", clientDetails.getClientSecret());
|
||||
|
||||
Set<String> responseType = new HashSet<String>();
|
||||
responseType.add(tokenRequest.getGrantType());
|
||||
|
||||
OAuth2Request authorizationRequest = new OAuth2Request(authorizationParameters, clientId, null, true, null,
|
||||
null, "", responseType, null);
|
||||
|
||||
Principal principal = new OAuth2Authentication(authorizationRequest, null);
|
||||
ResponseEntity<OAuth2AccessToken> result = tokenEndpoint().postAccessToken(principal,
|
||||
authorizationParameters);
|
||||
OAuth2AccessToken token = result.getBody();
|
||||
responseToken.setAccessToken(token.getValue());
|
||||
responseToken.setExpiresIn(String.valueOf(token.getExpiresIn()));
|
||||
responseToken.setTokenType(token.getTokenType());
|
||||
} catch (JwtAuthException e) {
|
||||
response.setStatus(NumberUtils.toInt(StringUtils.left(e.getCode(), 3), HttpStatus.UNAUTHORIZED.value()));
|
||||
responseToken.setResponseCode(e.getCode());
|
||||
responseToken.setResponseMessage(e.getMessage());
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
responseToken.setResponseCode(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"));
|
||||
responseToken.setResponseMessage("Unauthorized. [Unknown]");
|
||||
}
|
||||
|
||||
return responseToken;
|
||||
}
|
||||
|
||||
private void verifyClient(ClientDetails clientDetails, String timeStamp, String clientId, String signatureStr)
|
||||
throws JwtAuthException {
|
||||
if (StringUtils.isBlank(timeStamp)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {" + HEADER_TIMESTAMP + "}");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(clientId)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {" + HEADER_CLIENT_ID + "}");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(signatureStr)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.BAD_REQUEST.value(), SERVICE_CODE_ACCESS_TOKEN, "02"),
|
||||
"Invalid Mandatory Field {" + HEADER_SIGNATURE + "}");
|
||||
}
|
||||
|
||||
if (clientDetails == null) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [client not found]");
|
||||
}
|
||||
|
||||
String publicKeyStr = ((ClientVO) clientDetails).getSecurityKey();
|
||||
if (StringUtils.isBlank(publicKeyStr)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [public key not found]");
|
||||
}
|
||||
|
||||
try {
|
||||
String message = clientId + "|" + timeStamp;
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyStr));
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
PublicKey publicKey = keyFactory.generatePublic(keySpec);
|
||||
|
||||
Signature signature = Signature.getInstance("SHA256withRSA");
|
||||
signature.initVerify(publicKey);
|
||||
signature.update(message.getBytes(StandardCharsets.UTF_8));
|
||||
if (!signature.verify(Base64.getDecoder().decode(signatureStr))) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [Signature not matched]");
|
||||
}
|
||||
} catch (JwtAuthException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_ACCESS_TOKEN, "00"),
|
||||
"Unauthorized. [Signature fail]");
|
||||
}
|
||||
}
|
||||
|
||||
private TokenEndpoint tokenEndpoint() {
|
||||
return BeanUtils.getBean("tokenEndpoint", TokenEndpoint.class);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// First generate a public/private key pair
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
// generator.initialize(512, new SecureRandom());
|
||||
//generator.initialize(1024, new SecureRandom());
|
||||
generator.initialize(2048, new SecureRandom());
|
||||
KeyPair pair = generator.generateKeyPair();
|
||||
|
||||
// The private key can be used to sign (not encrypt!) a message. The public key
|
||||
// holder can then verify the message.
|
||||
|
||||
String message = "sSGJDwlJsel5WeXodzd3J3MQ20KYCZpL|2022-12-21T14:36:19+07:00";
|
||||
|
||||
// Let's sign our message
|
||||
Signature privateSignature = Signature.getInstance("SHA256withRSA");
|
||||
privateSignature.initSign(pair.getPrivate());
|
||||
privateSignature.update(message.getBytes(StandardCharsets.UTF_8));
|
||||
System.out.println(
|
||||
"private key=" + Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));
|
||||
|
||||
byte[] signature = privateSignature.sign();
|
||||
//System.out.println("signature=" + new String(signature, StandardCharsets.UTF_8));
|
||||
System.out.println("signature=" + Base64.getEncoder().encodeToString(signature));
|
||||
|
||||
// Let's check the signature
|
||||
Signature publicSignature = Signature.getInstance("SHA256withRSA");
|
||||
publicSignature.initVerify(pair.getPublic());
|
||||
publicSignature.update(message.getBytes(StandardCharsets.UTF_8));
|
||||
boolean isCorrect = publicSignature.verify(signature);
|
||||
System.out.println("public key=" + Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()));
|
||||
|
||||
System.out.println("Signature correct: " + isCorrect);
|
||||
|
||||
// The public key can be used to encrypt a message, the private key can be used
|
||||
// to decrypt it.
|
||||
// Encrypt the message
|
||||
Cipher encryptCipher = Cipher.getInstance("RSA");
|
||||
encryptCipher.init(Cipher.ENCRYPT_MODE, pair.getPublic());
|
||||
|
||||
byte[] cipherText = encryptCipher.doFinal(message.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// Now decrypt it
|
||||
Cipher decriptCipher = Cipher.getInstance("RSA");
|
||||
decriptCipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());
|
||||
|
||||
String decipheredMessage = new String(decriptCipher.doFinal(cipherText), StandardCharsets.UTF_8);
|
||||
|
||||
System.out.println(decipheredMessage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.eactive.eai.authserver.provider;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
|
||||
|
||||
/**
|
||||
* ** Oracle DDL
|
||||
* @formatter:off
|
||||
* CRATE TABLE tseaiau05 (
|
||||
* TOKEN_ID VARCHAR(255),
|
||||
* TOKEN BLOB,
|
||||
* AUTHENTICATION_ID VARCHAR(255) PRIMARY KEY,
|
||||
* USER_NAME VARCHAR(255),
|
||||
* CLIENT_ID VARCHAR(255),
|
||||
* AUTHENTICATION BLOB,
|
||||
* REFRESH_TOKEN VARCHAR(255),
|
||||
* CREATE_TIME timestamp default systimestamp
|
||||
* );
|
||||
*
|
||||
* CREATE TABLE tseaiau06 (
|
||||
* TOKEN_ID VARCHAR(255),
|
||||
* TOKEN BLOB,
|
||||
* AUTHENTICATION BLOB,
|
||||
* CREATE_TIME timestamp default systimestamp
|
||||
* );
|
||||
*
|
||||
* CREATE INDEX IX_TSEAIAU05_01 ON TSEAIAU05 (CREATE_TIME);
|
||||
* CREATE INDEX IX_TSEAIAU06_01 ON TSEAIAU06 (CREATE_TIME);
|
||||
* @formatter:on
|
||||
*/
|
||||
public class ElinkJdbcTokenStore extends JdbcTokenStore {
|
||||
private static final String ELINK_ACCESS_TOKEN_INSERT_STATEMENT = "insert into tseaiau05 (token_id, token, authentication_id, user_name, client_id, authentication, refresh_token) values (?, ?, ?, ?, ?, ?, ?)";
|
||||
private static final String ELINK_ACCESS_TOKEN_SELECT_STATEMENT = "select token_id, token from tseaiau05 where token_id = ?";
|
||||
private static final String ELINK_ACCESS_TOKEN_AUTHENTICATION_SELECT_STATEMENT = "select token_id, authentication from tseaiau05 where token_id = ?";
|
||||
private static final String ELINK_ACCESS_TOKEN_FROM_AUTHENTICATION_SELECT_STATEMENT = "select token_id, token from tseaiau05 where authentication_id = ?";
|
||||
private static final String ELINK_ACCESS_TOKENS_FROM_USERNAME_AND_CLIENT_SELECT_STATEMENT = "select token_id, token from tseaiau05 where user_name = ? and client_id = ?";
|
||||
private static final String ELINK_ACCESS_TOKENS_FROM_USERNAME_SELECT_STATEMENT = "select token_id, token from tseaiau05 where user_name = ?";
|
||||
private static final String ELINK_ACCESS_TOKENS_FROM_CLIENTID_SELECT_STATEMENT = "select token_id, token from tseaiau05 where client_id = ?";
|
||||
private static final String ELINK_ACCESS_TOKEN_DELETE_STATEMENT = "delete from tseaiau05 where token_id = ?";
|
||||
private static final String ELINK_ACCESS_TOKEN_DELETE_FROM_REFRESH_TOKEN_STATEMENT = "delete from tseaiau05 where refresh_token = ?";
|
||||
private static final String ELINK_REFRESH_TOKEN_INSERT_STATEMENT = "insert into tseaiau06 (token_id, token, authentication) values (?, ?, ?)";
|
||||
private static final String ELINK_REFRESH_TOKEN_SELECT_STATEMENT = "select token_id, token from tseaiau06 where token_id = ?";
|
||||
private static final String ELINK_REFRESH_TOKEN_AUTHENTICATION_SELECT_STATEMENT = "select token_id, authentication from tseaiau06 where token_id = ?";
|
||||
private static final String ELINK_REFRESH_TOKEN_DELETE_STATEMENT = "delete from tseaiau06 where token_id = ?";
|
||||
private String insertAccessTokenSql = ELINK_ACCESS_TOKEN_INSERT_STATEMENT;
|
||||
private String selectAccessTokenSql = ELINK_ACCESS_TOKEN_SELECT_STATEMENT;
|
||||
private String selectAccessTokenAuthenticationSql = ELINK_ACCESS_TOKEN_AUTHENTICATION_SELECT_STATEMENT;
|
||||
private String selectAccessTokenFromAuthenticationSql = ELINK_ACCESS_TOKEN_FROM_AUTHENTICATION_SELECT_STATEMENT;
|
||||
private String selectAccessTokensFromUserNameAndClientIdSql = ELINK_ACCESS_TOKENS_FROM_USERNAME_AND_CLIENT_SELECT_STATEMENT;
|
||||
private String selectAccessTokensFromUserNameSql = ELINK_ACCESS_TOKENS_FROM_USERNAME_SELECT_STATEMENT;
|
||||
private String selectAccessTokensFromClientIdSql = ELINK_ACCESS_TOKENS_FROM_CLIENTID_SELECT_STATEMENT;
|
||||
private String deleteAccessTokenSql = ELINK_ACCESS_TOKEN_DELETE_STATEMENT;
|
||||
private String insertRefreshTokenSql = ELINK_REFRESH_TOKEN_INSERT_STATEMENT;
|
||||
private String selectRefreshTokenSql = ELINK_REFRESH_TOKEN_SELECT_STATEMENT;
|
||||
private String selectRefreshTokenAuthenticationSql = ELINK_REFRESH_TOKEN_AUTHENTICATION_SELECT_STATEMENT;
|
||||
private String deleteRefreshTokenSql = ELINK_REFRESH_TOKEN_DELETE_STATEMENT;
|
||||
private String deleteAccessTokenFromRefreshTokenSql = ELINK_ACCESS_TOKEN_DELETE_FROM_REFRESH_TOKEN_STATEMENT;
|
||||
|
||||
public ElinkJdbcTokenStore(DataSource dataSource) {
|
||||
super(dataSource);
|
||||
|
||||
super.setInsertAccessTokenSql(insertAccessTokenSql);
|
||||
super.setSelectAccessTokenSql(selectAccessTokenSql);
|
||||
super.setDeleteAccessTokenSql(deleteAccessTokenSql);
|
||||
super.setInsertRefreshTokenSql(insertRefreshTokenSql);
|
||||
super.setSelectRefreshTokenSql(selectRefreshTokenSql);
|
||||
super.setDeleteRefreshTokenSql(deleteRefreshTokenSql);
|
||||
super.setSelectAccessTokenAuthenticationSql(selectAccessTokenAuthenticationSql);
|
||||
super.setSelectRefreshTokenAuthenticationSql(selectRefreshTokenAuthenticationSql);
|
||||
super.setSelectAccessTokenFromAuthenticationSql(selectAccessTokenFromAuthenticationSql);
|
||||
super.setDeleteAccessTokenFromRefreshTokenSql(deleteAccessTokenFromRefreshTokenSql);
|
||||
super.setSelectAccessTokensFromUserNameSql(selectAccessTokensFromUserNameSql);
|
||||
super.setSelectAccessTokensFromUserNameAndClientIdSql(selectAccessTokensFromUserNameAndClientIdSql);
|
||||
super.setSelectAccessTokensFromClientIdSql(selectAccessTokensFromClientIdSql);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.eactive.eai.custom;
|
||||
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.transformer.message.ISO8583MessageFactory;
|
||||
|
||||
/**
|
||||
* 이곳에서 Custermizing 대상 class 및 변수의 초기화 작업을 수행한다.
|
||||
*/
|
||||
public class CustomizingAppInitializer implements InitializingBean {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
public static final String MESSAGE_TYPE_H2H = "H2H";
|
||||
public static final String LAYOUT_TYPE_H2H = "ISO8583H2H";
|
||||
public static final String ISO8583_H2H_CLASS_NAME = "com.eactive.eai.custom.transformer.message.ISO8583H2HMessage";
|
||||
|
||||
public static final String MESSAGE_TYPE_SVL = "SVL";
|
||||
public static final String LAYOUT_TYPE_SVL = "ISO8583SVL";
|
||||
public static final String ISO8583_SVL_CLASS_NAME = "com.eactive.eai.custom.transformer.message.ISO8583SilverlakeMessage";
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
/*
|
||||
* @formatter:off
|
||||
* Custom ISO8583 메시지 추가시
|
||||
* - ONLWeb: Custom Mesaage java 추가, 아래 맵에 추가
|
||||
* - EMSWeb: Custom Mesaage java 추가, 아래 맵에 추가(로그조회시 parsing 위해)
|
||||
* @formatter:on
|
||||
*/
|
||||
ISO8583MessageFactory.ISO8583_MESSAGE_TYPE_CLASS_MAP.put(MESSAGE_TYPE_H2H, ISO8583_H2H_CLASS_NAME);
|
||||
ISO8583MessageFactory.ISO8583_MESSAGE_TYPE_CLASS_MAP.put(MESSAGE_TYPE_SVL, ISO8583_SVL_CLASS_NAME);
|
||||
ISO8583MessageFactory.ISO8583_LAYOUT_TYPE_CLASS_MAP.put(LAYOUT_TYPE_H2H, ISO8583_H2H_CLASS_NAME);
|
||||
ISO8583MessageFactory.ISO8583_LAYOUT_TYPE_CLASS_MAP.put(LAYOUT_TYPE_SVL, ISO8583_SVL_CLASS_NAME);
|
||||
logger.info("ISO8583MessageFactory registered - {} = {}", MESSAGE_TYPE_H2H, ISO8583_H2H_CLASS_NAME);
|
||||
logger.info("ISO8583MessageFactory registered - {} = {}", MESSAGE_TYPE_SVL, ISO8583_SVL_CLASS_NAME);
|
||||
logger.info("ISO8583MessageFactory registered - {} = {}", LAYOUT_TYPE_H2H, ISO8583_H2H_CLASS_NAME);
|
||||
logger.info("ISO8583MessageFactory registered - {} = {}", LAYOUT_TYPE_SVL, ISO8583_SVL_CLASS_NAME);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.eactive.eai.custom.adapter.handler;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.handler.AdapterErrorMessageHandler;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
public class LonErrorMsgHandler implements AdapterErrorMessageHandler {
|
||||
|
||||
@Override
|
||||
public Object generateNonStandardErrorResponseMessage(String inboudnAdapterGroupName, String inboudnAdapterName,
|
||||
Properties callProp, Object outboundRequestData, StandardMessage resStandardMessage) throws Exception{
|
||||
|
||||
if(resStandardMessage != null && isErrorMessage(resStandardMessage)) {
|
||||
AdapterGroupVO adapterGroupVO = AdapterManager.getInstance().getAdapterGroupVO(inboudnAdapterGroupName);
|
||||
if(MessageType.JSON.equals(adapterGroupVO.getMessageType())) {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
String requestMessage = (String) outboundRequestData;
|
||||
JsonNode requestJson = objectMapper.readTree(requestMessage);
|
||||
String alncInstCd = requestJson.get("dataCmn").get("alncInstCd").asText();
|
||||
|
||||
ObjectNode responseJson = objectMapper.createObjectNode();
|
||||
ObjectNode dataCmnNode = objectMapper.createObjectNode();
|
||||
responseJson.set("dataCmn", dataCmnNode);
|
||||
dataCmnNode.put("fnclInstCd", "KBK");
|
||||
dataCmnNode.put("alncInstCd", alncInstCd);
|
||||
dataCmnNode.put("tlgrRspnsCd", "0210");
|
||||
|
||||
return responseJson.toString();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
private boolean isErrorMessage(StandardMessage standardMessage) {
|
||||
InterfaceMapper mapper = StandardMessageManager.getInstance().getMapper();
|
||||
String responseType = mapper.getResponseType(standardMessage);
|
||||
return STDMessageKeys.RESPONSE_TYPE_CODE_E.equals(responseType);
|
||||
}
|
||||
|
||||
}
|
||||
+888
@@ -0,0 +1,888 @@
|
||||
package com.eactive.eai.custom.adapter.http.client.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.NameValuePair;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.message.BasicNameValuePair;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.net.URIBuilder;
|
||||
import org.dom4j.Document;
|
||||
import org.dom4j.Element;
|
||||
import org.dom4j.io.SAXReader;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.authoutbound.AccessTokenManagerByDB;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
|
||||
public class HttpClient5AdapterServiceKbank extends HttpClient5AdapterServiceSupport
|
||||
implements HttpClientAdapterServiceKey {
|
||||
|
||||
public static final String TYPE_VARIABLE_URL_REQUEST = "variableUrlRequest";
|
||||
public static final String TYPE_SIMPLE_REQUEST = "simpleRequest";
|
||||
public static final String REST_OPTION = "REST_OPTION";
|
||||
//public static final String HEADER_CONTENT_TYPE = "Content-Type";
|
||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||
public static final String HTTP_STATUS = "HTTP_STATUS";
|
||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||
public static final String AUTH_TOKEN = "AUTH_TOKEN";
|
||||
|
||||
/**
|
||||
* 1. 기능 : REST API 통신에 사용 <br>
|
||||
* 2. 처리 개요 : - 속성 정보를 설정 하고 수동 시스템 서비스를 호출 한다. <br>
|
||||
* 3. 주의사항 <br>
|
||||
*
|
||||
* @param prop Http Adapter 속성 정보
|
||||
* @return 반환 된 Object
|
||||
* @exception Exception 수동 시스템 간 통신 중 발생
|
||||
**/
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
||||
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
String bizCode = "";
|
||||
String authToken = "";
|
||||
try {
|
||||
Properties authProp = PropManager.getInstance().getProperties(AUTH_TOKEN); //Authorization
|
||||
bizCode = vo.getAdapterGroupName().substring(1, 4);
|
||||
authToken = authProp.getProperty(bizCode, "");
|
||||
} catch (Exception e) {
|
||||
logger.debug("Property Group AUTH_TOKEN is not Exist !!");
|
||||
}
|
||||
|
||||
logger.debug("authToken :::::::::::::::::::::::::::::::::::" + authToken);
|
||||
|
||||
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
||||
String relayResponseHeaderKeys = prop.getProperty(HEADER_KEYS, "");
|
||||
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
||||
|
||||
boolean useForwardProxy = StringUtils.equalsIgnoreCase(prop.getProperty("FORWARD_PROXY_USE_YN", "N"), "Y");
|
||||
String forwardProxyUrl = prop.getProperty("FORWARD_PROXY_URL");
|
||||
|
||||
// ex) $.dataHeader.GW_RSLT_CD
|
||||
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
||||
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
||||
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
||||
|
||||
// 레이아웃 메시지 타입 REST URL 추출 시 활용. Default JSON
|
||||
String messageType = prop.getProperty("MESSAGE_TYPE", MessageType.JSON);
|
||||
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
||||
* - type : simpleRequest, variableUrlRequest
|
||||
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
||||
* - method : get, delete, post, put
|
||||
* - contentType: application/json(default), application/x-www-form-urlencoded
|
||||
* - adapterTokenUseYn: Y, N(default)
|
||||
* ex)
|
||||
* {"type":"simpleRequest","extraPath":"v2.0/accout/balance","method":"post"}
|
||||
* @formatter:on
|
||||
*/
|
||||
|
||||
String restOptionData = tempProp.getProperty(REST_OPTION);
|
||||
|
||||
JSONObject restOptionObject = parseJson(restOptionData);
|
||||
if (restOptionObject == null) {
|
||||
throw new Exception("OptionData parsing result is NULL");
|
||||
}
|
||||
|
||||
String rmethod = (String) restOptionObject.getOrDefault("method", inboundMethod);
|
||||
String contentType = (String) restOptionObject.getOrDefault("contentType", "application/json");
|
||||
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
||||
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
||||
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
||||
}
|
||||
|
||||
HttpClient mclient = this.client;
|
||||
String sendData = "";
|
||||
if (data instanceof String) {
|
||||
sendData = (String) data;
|
||||
} else if (data instanceof byte[]) {
|
||||
sendData = new String((byte[]) data, vo.getEncode());
|
||||
}
|
||||
|
||||
////mclient.getParams().setContentCharset(vo.getEncode());
|
||||
|
||||
JSONObject dataObject = null;
|
||||
|
||||
Object httpHeader = null;
|
||||
Object dataContent = null;
|
||||
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
|
||||
Object parsed = parseJsonGeneric(sendData);
|
||||
|
||||
if(parsed instanceof JSONObject) {
|
||||
dataObject = parseJson(sendData);
|
||||
if (dataObject != null && StringUtils.isNotBlank(headerGroupName)) {
|
||||
httpHeader = dataObject.get(headerGroupName);
|
||||
dataObject.remove(headerGroupName);
|
||||
}
|
||||
|
||||
dataContent = dataObject;
|
||||
if (dataObject.containsKey("innerList")) {
|
||||
JSONArray innerList = (JSONArray) dataObject.get("innerList");
|
||||
dataContent = innerList;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("HttpClientAdapterServiceRest] dataObject1 = [" + dataObject + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] dataContent = [" + dataContent + "]");
|
||||
|
||||
// interface 에 설정된게 우선한다.
|
||||
String uri = null;
|
||||
if (dataObject == null) {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, sendData);
|
||||
} else {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, dataObject);
|
||||
}
|
||||
|
||||
// ////if (vo.getConnectionTimeout() != 0) {
|
||||
// mclient.getHttpConnectionManager().getParams().setConnectionTimeout(vo.getConnectionTimeout());
|
||||
// }
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL=[" + vo.getUrl() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") PARAMETER_NAME=[" + vo.getParameterName() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") ENCODE=[" + vo.getEncode() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") RESPONSE_TYPE=[" + vo.getResponseType() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL_ENCODE_YN=[" + vo.getUrlEncodeYn() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") CONNECTION_TIMEOUT=[" + vo.getConnectionTimeout() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") REST_OPTION=[" + restOptionData + "] ");
|
||||
}
|
||||
|
||||
HttpUriRequestBase method = null;
|
||||
|
||||
// 메소드 타입에 따라 HttpRequestBase 인스턴스 생성
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
case DELETE:
|
||||
method = new HttpDelete(uri);
|
||||
break;
|
||||
case POST:
|
||||
method = new HttpPost(uri);
|
||||
break;
|
||||
case PUT:
|
||||
method = new HttpPut(uri);
|
||||
break;
|
||||
default:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
}
|
||||
|
||||
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
|
||||
|
||||
if(useForwardProxy) {
|
||||
java.net.URL url = new java.net.URL(forwardProxyUrl);
|
||||
|
||||
// 프로토콜, 호스트, 포트 추출
|
||||
String protocol = url.getProtocol();
|
||||
String host = url.getHost();
|
||||
int port = url.getPort();
|
||||
HttpHost proxy = new HttpHost(protocol,host, port);
|
||||
requestConfigBuilder.setProxy(proxy);
|
||||
}
|
||||
|
||||
configureHttpClient(requestConfigBuilder, vo, method);
|
||||
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
case DELETE:
|
||||
HashMap<String, String> h = getParameters(dataObject);
|
||||
URIBuilder uriBuilder = new URIBuilder(uri);
|
||||
for (Map.Entry<String, String> entry : h.entrySet()) {
|
||||
uriBuilder.addParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
URI fullUri = uriBuilder.build();
|
||||
if (method instanceof HttpGet) {
|
||||
((HttpGet) method).setUri(fullUri);
|
||||
} else if (method instanceof HttpDelete) {
|
||||
((HttpDelete) method).setUri(fullUri);
|
||||
}
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] (get Method) QueryString = [" + fullUri.getQuery() + "]");
|
||||
}
|
||||
break;
|
||||
case PUT:
|
||||
case POST:
|
||||
//assignPostBody(dataObject, contentType, vo.getEncode(), method);
|
||||
assignPostBody(dataContent, contentType, vo.getEncode(), method);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") method.getParams()=["
|
||||
+ method.getEntity() + "] ");
|
||||
}
|
||||
|
||||
OAuth2AccessTokenVO accessToken = null;
|
||||
if (useAdapterToken) {
|
||||
AccessTokenManagerByDB tokenManager = AccessTokenManagerByDB.getInstance();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
||||
|
||||
// 토큰이 없거나 만료 됐으면 재발급
|
||||
if (accessToken == null || accessToken.isExpired()) {
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
||||
oldToken);
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
||||
+ accessToken + "]");
|
||||
}
|
||||
|
||||
setAuthHeaders(method, accessToken);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RequestHeader [Authorization=" + method.getHeader("Authorization") + "]");
|
||||
}
|
||||
}
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
if(!StringUtils.isBlank(authToken)) {
|
||||
setAuthHeaders(method, authToken);
|
||||
}
|
||||
|
||||
// 전달 header 셋팅
|
||||
// Adapter 레벨 header 보다 data로 넘어온 httpHeader를 우선 적용(header명이 같다면 덮어씀)
|
||||
assignRequestHeaders(method, httpHeader);
|
||||
|
||||
int status = -1;
|
||||
|
||||
try {
|
||||
byte[] responseMessage = null;
|
||||
Header[] responseHeaders;
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
if (dataContent != null) { //dataObject
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = ["
|
||||
+ dataContent.toString() + "]"); //dataObject.toJSONString()
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(dataContent.toString())); //dataObject.toJSONString()
|
||||
} else {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = [" + sendData
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
}
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"SEND [" + sendData + "]" + CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
|
||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
HttpContext context = new BasicHttpContext();
|
||||
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
||||
Integer logProcessNo = (Integer) tempProp.get(HttpClientAdapterServiceKey.LOG_PROCESS_NO);
|
||||
if (logProcessNo != null && logProcessNo > 0) {
|
||||
context.setAttribute(HttpClientAdapterServiceKey.LOG_PROCESS_NO, logProcessNo);
|
||||
}
|
||||
|
||||
try {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[method getName]" + method.getMethod());
|
||||
logger.debug("[method getEntity]" + method.getEntity());
|
||||
logger.debug("[method getRequestHeaders]" + method.getHeaders().toString());
|
||||
logger.debug("[method getURI]" + method.getPath());
|
||||
}
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = response.getCode();
|
||||
|
||||
if (status >= 200 && status <= 207) {
|
||||
status = 200;
|
||||
}
|
||||
|
||||
// if (status == 404) {
|
||||
// status = 200;
|
||||
// }
|
||||
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
responseHeaders = response.getHeaders();
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + responseMessage + "]");
|
||||
}
|
||||
}
|
||||
} catch (ConnectException e) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
}
|
||||
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
||||
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
||||
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
||||
*
|
||||
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
||||
* __ex) $.dataHeader.resultCode
|
||||
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
||||
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
||||
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
||||
* @formatter:on
|
||||
*/
|
||||
boolean needReissue = false;
|
||||
|
||||
Properties responseHeaderProp = assignRelayDataToInbound(tempProp, responseHeaders);
|
||||
String responseString = new String(responseMessage, vo.getEncode());
|
||||
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
tempProp.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, responseHeaderProp);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_MESSAGE, responseString);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_STATUS, status);
|
||||
|
||||
if (status >= 200 && status <= 207) {
|
||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
} else if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseString);
|
||||
// logger.error(errMsg);
|
||||
|
||||
if (status >= 400 && status < 500) {
|
||||
if (useAdapterToken) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
|
||||
// if (!needReissue) {
|
||||
// throw new Exception(errMsg);
|
||||
// }
|
||||
} else {
|
||||
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV " + vo.getEncode() + "(" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV MS949 (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "MS949") + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV euc-kr (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "euc-kr") + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = " + CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
if (useAdapterToken) {
|
||||
if (responseMessage == null) {
|
||||
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
||||
}
|
||||
|
||||
// OAuth 토큰 재요청 코드 확인
|
||||
if (needReissue) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] retry access token response code = ["
|
||||
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
}
|
||||
|
||||
// 토큰 재발급
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
OAuth2AccessTokenVO newaccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||
method.setHeader("Authorization", newaccessToken.getAuthorization());
|
||||
|
||||
setAuthHeaders(method, newaccessToken);
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RETRY TOKEN = [" + newaccessToken + "]");
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method)) {
|
||||
status = response.getCode();
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
||||
}
|
||||
}catch (IOException e){
|
||||
throw new Exception("retry excuteMethod Exceptioin = " + e.getMessage());
|
||||
}
|
||||
|
||||
|
||||
if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV " + vo.getEncode() + "("
|
||||
+ vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
// ----------------------------------------------------------
|
||||
}
|
||||
}
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"RECV [" + new String(responseMessage, vo.getEncode()) + "]"
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
|
||||
return assignResponseHeaders(method, responseMessage, headerGroupName, vo.getEncode(), messageType,
|
||||
relayResponseHeaderKeys, status, responseHeaderProp);
|
||||
} catch (SocketTimeoutException ste) { // Read Timeout :: HttpClient 3.1일 경우
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(),
|
||||
ste);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(), ste);
|
||||
throw ste;
|
||||
} catch (ConnectException ce) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(),
|
||||
ce);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(), ce);
|
||||
throw ce;
|
||||
} catch (Exception e) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
||||
e);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status != HttpStatus.SC_OK) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = String.valueOf(status);
|
||||
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Properties assignRelayDataToInbound(Properties prop, Header[] responseHeaders) {
|
||||
Properties headerProp = new Properties();
|
||||
if (responseHeaders == null || responseHeaders.length == 0) {
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
for (Header header : responseHeaders) {
|
||||
headerProp.put(header.getName(), header.getValue());
|
||||
}
|
||||
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 1단계 레이아웃에만 적용되도록 구현됨.
|
||||
*
|
||||
* @param method
|
||||
* @param responseMessage
|
||||
* @param headerGroupName
|
||||
* @param encode
|
||||
* @param messageType
|
||||
* @param relayHeaderKeys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private String assignResponseHeaders(HttpUriRequestBase method, byte[] responseMessage, String headerGroupName,
|
||||
String encode, String messageType, String relayHeaderKeys, int status, Properties responseHeaderProp) throws Exception {
|
||||
if (!MessageType.JSON.equals(messageType) || StringUtils.isBlank(headerGroupName)
|
||||
|| StringUtils.isBlank(relayHeaderKeys)) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils.tokenizeToStringArray(relayHeaderKeys, ",");
|
||||
JSONObject headerJson = new JSONObject();
|
||||
for (String key : relayKeyArr) {
|
||||
String value = responseHeaderProp.getProperty(key);
|
||||
if (StringUtils.isNotBlank(value)) {
|
||||
headerJson.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
headerJson.put(HTTP_STATUS, String.valueOf(status));
|
||||
|
||||
if (headerJson.size() <= 0) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
JSONObject message = null;
|
||||
if (responseMessage == null || responseMessage.length == 0) {
|
||||
message = new JSONObject();
|
||||
} else {
|
||||
message = parseJson(new String(responseMessage, encode));
|
||||
if (message == null) {
|
||||
message = new JSONObject();
|
||||
message.put("Malformed_Response_Message", new String(responseMessage, encode));
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(headerGroupName) && message != null)
|
||||
message.put(headerGroupName, headerJson);
|
||||
|
||||
logger.info("------------- message --------------- : {} ", message);
|
||||
|
||||
return message.toJSONString();
|
||||
}
|
||||
|
||||
// 2025.04.09 Authorization 헤더값을 프로퍼티(AUTH_TOKEN)에서 지정하여 설정할 수 있도록 수정
|
||||
private void setAuthHeaders(HttpUriRequestBase method, String authorization) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s", authorization));
|
||||
}
|
||||
|
||||
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||
String encode) {
|
||||
if (responseMessage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
||||
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
||||
if (StringUtils.isBlank(responseCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
||||
return ArrayUtils.contains(arr, responseCode);
|
||||
} catch (Exception e) {
|
||||
logger.error("HttpClientAdapterServiceRest] checkTokenRetry error=" + e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void assignRequestHeaders(HttpUriRequestBase method, Object httpHeader) {
|
||||
if (httpHeader == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (httpHeader instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) httpHeader;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
method.setHeader((String) key, (String) obj);
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request Header :" + (String) key + "=[" + (String) obj + "]");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private void assignPostBody(Object eaiBody, String contentType, String charset, HttpUriRequestBase method) {
|
||||
if (eaiBody == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(contentType, "application/x-www-form-urlencoded")) {
|
||||
if (eaiBody instanceof JSONObject) {
|
||||
List<NameValuePair> params = new ArrayList<>();
|
||||
JSONObject jsonObject = (JSONObject) eaiBody;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
params.add(new BasicNameValuePair((String) key, (String) jsonObject.get(key)));
|
||||
}
|
||||
|
||||
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
|
||||
method.setEntity(entity);
|
||||
}
|
||||
|
||||
} else {
|
||||
ContentType contentTypeObj = ContentType.create(contentType, charset);
|
||||
|
||||
// 요청 본문을 StringEntity 객체로 생성
|
||||
StringEntity entity = new StringEntity(eaiBody.toString(), contentTypeObj);
|
||||
|
||||
// 요청에 본문 추가
|
||||
method.setEntity(entity);
|
||||
}
|
||||
}
|
||||
|
||||
private HashMap<String, String> getParameters(Object message) throws Exception {
|
||||
|
||||
HashMap<String, String> result = new HashMap<String, String>();
|
||||
|
||||
if (message != null) {
|
||||
if (message instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) message;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
result.put((String) key, getStringValue(obj));
|
||||
}
|
||||
} else {
|
||||
String[] messages = ((String) message).split("&");
|
||||
String[] data = null;
|
||||
|
||||
for (int i = 0; i < messages.length; i++) {
|
||||
data = messages[i].split("=", 2);
|
||||
if (data.length == 2) {
|
||||
result.put(data[0], data[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getStringValue(Object obj) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (obj instanceof String) {
|
||||
return (String) obj;
|
||||
} else if (obj instanceof Long) {
|
||||
return Long.toString((Long) obj);
|
||||
} else if (obj instanceof BigDecimal) {
|
||||
return ((BigDecimal) obj).toPlainString();
|
||||
} else {
|
||||
return (String) obj;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object parseJsonGeneric(String jsonData) {
|
||||
if (StringUtils.isBlank(jsonData)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
JSONParser parser = new JSONParser();
|
||||
Object parsedObj = parser.parse(jsonData);
|
||||
return parsedObj;
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private JSONObject parseJson(String message) throws Exception {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (JSONObject) JSONValue.parse(message);
|
||||
}
|
||||
|
||||
private Document convertXmlDocument(String message) throws Exception {
|
||||
SAXReader builder = new SAXReader();
|
||||
Document document = builder.read(new StringReader(message));
|
||||
return document;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private String changeUrl(String messageType, String url, String restOption, Object sendData) {
|
||||
if ((MessageType.JSON.equals(messageType) || MessageType.XML.equals(messageType))) {
|
||||
try {
|
||||
if (StringUtils.isBlank(restOption)) {
|
||||
return url;
|
||||
}
|
||||
List<String> urlVariableList = new ArrayList<String>();
|
||||
JSONObject restOptionObject = parseJson(restOption);
|
||||
|
||||
if (restOptionObject == null)
|
||||
throw new Exception("restOption is NULL");
|
||||
|
||||
String type = (String) restOptionObject.get("type");
|
||||
String requestExtraPath = (String) restOptionObject.get("extraPath");
|
||||
url = getUrl(url, requestExtraPath);
|
||||
if (TYPE_VARIABLE_URL_REQUEST.equals(type)) {
|
||||
Pattern p = Pattern.compile("\\{(.*?)\\}");
|
||||
Matcher m = p.matcher(requestExtraPath);
|
||||
List<String> uriVariables = new ArrayList<>();
|
||||
while(m.find()) {
|
||||
String fieldName = m.group(1);
|
||||
uriVariables.add(fieldName);
|
||||
}
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
JSONObject jsonObject;
|
||||
if (sendData instanceof JSONObject) {
|
||||
jsonObject = (JSONObject) sendData;
|
||||
} else {
|
||||
jsonObject = (JSONObject) JSONValue.parse((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
String uriVariable = (String) jsonObject.get(urlVaribleId);
|
||||
urlVariableList.add(uriVariable);
|
||||
jsonObject.remove(urlVaribleId);
|
||||
}
|
||||
} else if (MessageType.XML.equals(messageType)) {
|
||||
Document doc;
|
||||
if (sendData instanceof Document) {
|
||||
doc = (Document) sendData;
|
||||
} else {
|
||||
doc = convertXmlDocument((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
Element element = (Element) doc.selectSingleNode("//" + urlVaribleId);
|
||||
urlVariableList.add(element.getText());
|
||||
if (doc.getRootElement() == element) {
|
||||
doc = null;
|
||||
} else {
|
||||
element.getParent().remove(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (urlVariableList.size() > 0) {
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
||||
Object[] urls = urlVariableList.toArray();
|
||||
url = uriComponents.expand(urls).toUriString();
|
||||
logger.debug("HttpClientAdapterServiceRest] after extand url=[" + url + "] ");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to change url", e);
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
private String getUrl(String baseUrl, String extraPath) {
|
||||
if (StringUtils.isBlank(extraPath)) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
||||
return extraPath;
|
||||
}
|
||||
|
||||
String targetUrl = baseUrl;
|
||||
if (!targetUrl.endsWith("/")) {
|
||||
targetUrl += "/";
|
||||
}
|
||||
if (extraPath.startsWith("/")) {
|
||||
targetUrl += extraPath.substring(1);
|
||||
} else {
|
||||
targetUrl += extraPath;
|
||||
}
|
||||
|
||||
logger.debug("HttpClientAdapterServiceRest] after concatenate url=[" + targetUrl + "] ");
|
||||
return targetUrl;
|
||||
}
|
||||
|
||||
}
|
||||
+867
@@ -0,0 +1,867 @@
|
||||
package com.eactive.eai.custom.adapter.http.client.impl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.httpclient.HttpStatus;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpHost;
|
||||
import org.apache.hc.core5.http.NameValuePair;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.message.BasicNameValuePair;
|
||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.net.URIBuilder;
|
||||
import org.dom4j.Document;
|
||||
import org.dom4j.Element;
|
||||
import org.dom4j.io.SAXReader;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.vo.ClientVO;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.authoutbound.AccessTokenManagerByDB;
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.eactive.eai.custom.adapter.http.util.VirtualAccountTransform;
|
||||
import com.jayway.jsonpath.DocumentContext;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
|
||||
// Kbank 가상계좌 OUTBOUND
|
||||
public class HttpClient5AdapterServiceVirtualAccount extends HttpClient5AdapterServiceSupport
|
||||
implements HttpClientAdapterServiceKey {
|
||||
public static final String TYPE_VARIABLE_URL_REQUEST = "variableUrlRequest";
|
||||
public static final String TYPE_SIMPLE_REQUEST = "simpleRequest";
|
||||
|
||||
public static final String REST_OPTION = "REST_OPTION";
|
||||
|
||||
////public static final String HEADER_CONTENT_TYPE = "Content-Type";
|
||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||
public static final String HTTP_STATUS = "HTTP_STATUS";
|
||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||
|
||||
private String getSecurityKey(String adapterGroupName) throws DAOException {
|
||||
String clientId = null;
|
||||
String aesKey = null;
|
||||
AdapterGroupVO adapterGroup = null;;
|
||||
adapterGroup = AdapterManager.getInstance().getAdapterGroup(adapterGroupName);
|
||||
|
||||
clientId = adapterGroup.getClientId();
|
||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||
try {
|
||||
ClientVO client = manager.getClientInfo(clientId);
|
||||
aesKey = client.getSecurityKey();
|
||||
return aesKey;
|
||||
} catch (DAOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
||||
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
||||
|
||||
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
||||
String relayResponseHeaderKeys = prop.getProperty(HEADER_KEYS, "");
|
||||
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
||||
|
||||
boolean useForwardProxy = StringUtils.equalsIgnoreCase(prop.getProperty("FORWARD_PROXY_USE_YN", "N"), "Y");
|
||||
String forwardProxyUrl = prop.getProperty("FORWARD_PROXY_URL");
|
||||
|
||||
// ex) $.dataHeader.GW_RSLT_CD
|
||||
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
||||
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
||||
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
||||
|
||||
// 레이아웃 메시지 타입 REST URL 추출 시 활용. Default JSON
|
||||
String messageType = prop.getProperty("MESSAGE_TYPE", MessageType.JSON);
|
||||
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
||||
* - type : simpleRequest, variableUrlRequest
|
||||
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
||||
* - method : get, delete, post, put
|
||||
* - contentType: application/json(default), application/x-www-form-urlencoded
|
||||
* - adapterTokenUseYn: Y, N(default)
|
||||
* ex)
|
||||
* {"type":"simpleRequest","extraPath":"v2.0/accout/balance","method":"post"}
|
||||
* @formatter:on
|
||||
*/
|
||||
|
||||
String restOptionData = tempProp.getProperty(REST_OPTION);
|
||||
|
||||
JSONObject restOptionObject = parseJson(restOptionData);
|
||||
if (restOptionObject == null) {
|
||||
throw new Exception("OptionData parsing result is NULL");
|
||||
}
|
||||
|
||||
String rmethod = (String) restOptionObject.getOrDefault("method", inboundMethod);
|
||||
String contentType = (String) restOptionObject.getOrDefault("contentType", "application/json");
|
||||
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
||||
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
||||
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
||||
}
|
||||
|
||||
HttpClient mclient = this.client;
|
||||
String sendData = "";
|
||||
if (data instanceof String) {
|
||||
sendData = (String) data;
|
||||
} else if (data instanceof byte[]) {
|
||||
sendData = new String((byte[]) data, vo.getEncode());
|
||||
}
|
||||
|
||||
// 필드암복호화 처리 (dec CubeOne -> enc AES)
|
||||
String encPaths = prop.getProperty("ENC_PATHS");
|
||||
List<String> encFieldList = null;
|
||||
String aesKey = getSecurityKey(vo.getAdapterGroupName());
|
||||
if (logger.isDebug()) logger.debug("HttpClientAdapterServiceRest] ENC AdapterGroupName[" + vo.getAdapterGroupName()+ "], aesKey["+aesKey+"]");
|
||||
if(StringUtils.isNotBlank(aesKey) && StringUtils.isNotBlank(encPaths)) {
|
||||
String[] items = encPaths.split(",");
|
||||
encFieldList = Arrays.asList(items);
|
||||
sendData = VirtualAccountTransform.toAES(aesKey, encFieldList, sendData);
|
||||
if (logger.isDebug()) logger.debug("HttpClientAdapterServiceRest] after toAES = [" + sendData + "]");
|
||||
}
|
||||
|
||||
////mclient.getParams().setContentCharset(vo.getEncode());
|
||||
|
||||
JSONObject dataObject = null;
|
||||
Object httpHeader = null;
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
dataObject = parseJson(sendData);
|
||||
if (dataObject != null && StringUtils.isNotBlank(headerGroupName)) {
|
||||
httpHeader = dataObject.get(headerGroupName);
|
||||
dataObject.remove(headerGroupName);
|
||||
}
|
||||
if (logger.isDebug()) logger.debug("HttpClientAdapterServiceRest] dataObject1 = [" + dataObject + "]");
|
||||
}
|
||||
else {
|
||||
if (logger.isDebug()) logger.debug("HttpClientAdapterServiceRest] sendData = [" + sendData + "]");
|
||||
}
|
||||
|
||||
|
||||
// interface 에 설정된게 우선한다.
|
||||
String uri = null;
|
||||
if (dataObject == null) {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, sendData);
|
||||
} else {
|
||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, dataObject);
|
||||
}
|
||||
|
||||
if (logger.isDebug()) logger.debug("HttpClientAdapterServiceRest] dataObject2 = [" + dataObject + "]");
|
||||
|
||||
//////if (vo.getConnectionTimeout() != 0) {
|
||||
// mclient.getHttpConnectionManager().getParams().setConnectionTimeout(vo.getConnectionTimeout());
|
||||
//}
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug(
|
||||
"HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL=[" + vo.getUrl() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") PARAMETER_NAME=["
|
||||
+ vo.getParameterName() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") ENCODE=["
|
||||
+ vo.getEncode() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") RESPONSE_TYPE=["
|
||||
+ vo.getResponseType() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL_ENCODE_YN=["
|
||||
+ vo.getUrlEncodeYn() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") CONNECTION_TIMEOUT=["
|
||||
+ vo.getConnectionTimeout() + "] ");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") REST_OPTION=["
|
||||
+ restOptionData + "] ");
|
||||
}
|
||||
|
||||
HttpUriRequestBase method = null;
|
||||
|
||||
// 메소드 타입에 따라 HttpRequestBase 인스턴스 생성
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
case DELETE:
|
||||
method = new HttpDelete(uri);
|
||||
break;
|
||||
case POST:
|
||||
method = new HttpPost(uri);
|
||||
break;
|
||||
case PUT:
|
||||
method = new HttpPut(uri);
|
||||
break;
|
||||
default:
|
||||
method = new HttpGet(uri);
|
||||
break;
|
||||
}
|
||||
|
||||
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
|
||||
|
||||
if (useForwardProxy) {
|
||||
java.net.URL url = new java.net.URL(forwardProxyUrl);
|
||||
|
||||
// 프로토콜, 호스트, 포트 추출
|
||||
String protocol = url.getProtocol();
|
||||
String host = url.getHost();
|
||||
int port = url.getPort();
|
||||
HttpHost proxy = new HttpHost(protocol, host, port);
|
||||
requestConfigBuilder.setProxy(proxy);
|
||||
}
|
||||
|
||||
configureHttpClient(requestConfigBuilder, vo, method);
|
||||
|
||||
switch (HttpMethodType.getValue(rmethod)) {
|
||||
case GET:
|
||||
case DELETE:
|
||||
HashMap<String, String> h = getParameters(dataObject);
|
||||
URIBuilder uriBuilder = new URIBuilder(uri);
|
||||
for (Map.Entry<String, String> entry : h.entrySet()) {
|
||||
uriBuilder.addParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
URI fullUri = uriBuilder.build();
|
||||
if (method instanceof HttpGet) {
|
||||
((HttpGet) method).setUri(fullUri);
|
||||
} else if (method instanceof HttpDelete) {
|
||||
((HttpDelete) method).setUri(fullUri);
|
||||
}
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] (get Method) QueryString = [" + fullUri.getQuery() + "]");
|
||||
}
|
||||
break;
|
||||
case PUT:
|
||||
case POST:
|
||||
assignPostBody(dataObject, contentType, vo.getEncode(), method);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") method.getParams()=["
|
||||
+ method.getEntity() + "] ");
|
||||
}
|
||||
|
||||
OAuth2AccessTokenVO accessToken = null;
|
||||
if (useAdapterToken) {
|
||||
AccessTokenManagerByDB tokenManager = AccessTokenManagerByDB.getInstance();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
||||
|
||||
// 토큰이 없거나 만료 됐으면 재발급
|
||||
if (accessToken == null || accessToken.isExpired()) {
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
||||
oldToken);
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
||||
+ accessToken + "]");
|
||||
}
|
||||
|
||||
setAuthHeaders(method, accessToken);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RequestHeader [Authorization=" + method.getHeader("Authorization") + "]");
|
||||
}
|
||||
}
|
||||
|
||||
// 전달 header 셋팅
|
||||
// Adapter 레벨 header 보다 data로 넘어온 httpHeader를 우선 적용(header명이 같다면 덮어씀)
|
||||
assignRequestHeaders(method, httpHeader);
|
||||
|
||||
int status = -1;
|
||||
|
||||
try {
|
||||
byte[] responseMessage = null;
|
||||
Header[] responseHeaders;
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
if (dataObject != null) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = ["
|
||||
+ dataObject.toJSONString() + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(dataObject.toJSONString()));
|
||||
} else {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = [" + sendData
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
}
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"SEND [" + sendData + "]" + CommonLib.getDumpMessage(sendData));
|
||||
}
|
||||
|
||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
HttpContext context = new BasicHttpContext();
|
||||
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
||||
|
||||
try {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[method getName]" + method.getMethod());
|
||||
logger.debug("[method getEntity]" + method.getEntity());
|
||||
logger.debug("[method getRequestHeaders]" + method.getHeaders().toString());
|
||||
logger.debug("[method getURI]" + method.getPath());
|
||||
}
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
||||
status = response.getCode();
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
responseHeaders = response.getHeaders();
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = ["
|
||||
+ responseMessage + "]");
|
||||
}
|
||||
}
|
||||
} catch (ConnectException e) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
}
|
||||
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
||||
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
||||
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
||||
*
|
||||
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
||||
* __ex) $.dataHeader.resultCode
|
||||
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
||||
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
||||
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
||||
* @formatter:on
|
||||
*/
|
||||
boolean needReissue = false;
|
||||
|
||||
Properties responseHeaderProp = assignRelayDataToInbound(tempProp, responseHeaders);
|
||||
String responseString = new String(responseMessage, vo.getEncode());
|
||||
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
tempProp.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, responseHeaderProp);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_MESSAGE, responseString);
|
||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_STATUS, status);
|
||||
|
||||
if (status == 200) {
|
||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
} else if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseString);
|
||||
// logger.error(errMsg);
|
||||
|
||||
if (status >= 400 && status < 500) {
|
||||
if (useAdapterToken) {
|
||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
||||
vo.getEncode());
|
||||
}
|
||||
|
||||
if (!needReissue) {
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
} else {
|
||||
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV " + vo.getEncode() + "(" + vo.getAdapterGroupName()
|
||||
+ ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV MS949 (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "MS949") + "]");
|
||||
// logger.debug("HttpClientAdapterServiceRest] RECV euc-kr (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "euc-kr") + "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
if (useAdapterToken) {
|
||||
if (responseMessage == null) {
|
||||
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
||||
}
|
||||
|
||||
// OAuth 토큰 재요청 코드 확인
|
||||
if (needReissue) {
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] retry access token response code = ["
|
||||
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
}
|
||||
|
||||
// 토큰 재발급
|
||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
||||
OAuth2AccessTokenVO newaccessToken = (OAuth2AccessTokenVO) tokenManager
|
||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
||||
method.setHeader("Authorization", newaccessToken.getAuthorization());
|
||||
|
||||
setAuthHeaders(method, newaccessToken);
|
||||
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
||||
+ ") RETRY TOKEN = [" + newaccessToken + "]");
|
||||
}
|
||||
|
||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method)) {
|
||||
status = response.getCode();
|
||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("[received status]" + status);
|
||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = ["
|
||||
+ new String(responseMessage, vo.getEncode()) + "]");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new Exception("retry excuteMethod Exceptioin = " + e.getMessage());
|
||||
}
|
||||
|
||||
if (status == 302) {
|
||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
||||
relayResponseHeaderKeys += ",Location";
|
||||
}
|
||||
} else {
|
||||
String errMsg = String.format(
|
||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseMessage);
|
||||
throw new Exception(errMsg);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------
|
||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY responseType =" + vo.getResponseType());
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV " + vo.getEncode() + "("
|
||||
+ vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode())
|
||||
+ "]");
|
||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
// ----------------------------------------------------------
|
||||
}
|
||||
}
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"RECV [" + new String(responseMessage, vo.getEncode()) + "]"
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
|
||||
// TODO : toCubeOne
|
||||
if(StringUtils.isNotBlank(aesKey) && encFieldList != null) {
|
||||
responseMessage = VirtualAccountTransform.toCubeOne(aesKey, encFieldList, responseMessage);
|
||||
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"RECV ENC[" + new String(responseMessage, vo.getEncode()) + "]"
|
||||
+ CommonLib.getDumpMessage(responseMessage));
|
||||
}
|
||||
}
|
||||
|
||||
return assignResponseHeaders(method, responseMessage, headerGroupName, vo.getEncode(), messageType,
|
||||
relayResponseHeaderKeys, status, responseHeaderProp);
|
||||
} catch (SocketTimeoutException ste) { // Read Timeout :: HttpClient 3.1일 경우
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(),
|
||||
ste);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ste.toString(), ste);
|
||||
throw ste;
|
||||
} catch (ConnectException ce) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
||||
"HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(),
|
||||
ce);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
||||
+ ce.toString(), ce);
|
||||
throw ce;
|
||||
} catch (Exception e) {
|
||||
if (vo.getTraceLevel() >= 3) {
|
||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
||||
}
|
||||
logger.error("HttpClientAdapterServiceRest] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
||||
e);
|
||||
throw e;
|
||||
} finally {
|
||||
if (status != HttpStatus.SC_OK) {
|
||||
String[] msgArgs = new String[1];
|
||||
msgArgs[0] = String.valueOf(status);
|
||||
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(resMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Properties assignRelayDataToInbound(Properties prop, Header[] responseHeaders) {
|
||||
Properties headerProp = new Properties();
|
||||
if (responseHeaders == null || responseHeaders.length == 0) {
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
for (Header header : responseHeaders) {
|
||||
headerProp.put(header.getName(), header.getValue());
|
||||
}
|
||||
|
||||
return headerProp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 1단계 레이아웃에만 적용되도록 구현됨.
|
||||
*
|
||||
* @param method
|
||||
* @param responseMessage
|
||||
* @param headerGroupName
|
||||
* @param encode
|
||||
* @param messageType
|
||||
* @param relayHeaderKeys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private String assignResponseHeaders(HttpUriRequestBase method, byte[] responseMessage, String headerGroupName,
|
||||
String encode, String messageType, String relayHeaderKeys, int status, Properties responseHeaderProp)
|
||||
throws Exception {
|
||||
if (!MessageType.JSON.equals(messageType) || StringUtils.isBlank(headerGroupName)
|
||||
|| StringUtils.isBlank(relayHeaderKeys)) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils.tokenizeToStringArray(relayHeaderKeys, ",");
|
||||
JSONObject headerJson = new JSONObject();
|
||||
for (String key : relayKeyArr) {
|
||||
String value = responseHeaderProp.getProperty(key);
|
||||
if (StringUtils.isNotBlank(value)) {
|
||||
headerJson.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
headerJson.put(HTTP_STATUS, String.valueOf(status));
|
||||
|
||||
if (headerJson.size() <= 0) {
|
||||
return new String(responseMessage, encode);
|
||||
}
|
||||
|
||||
JSONObject message = null;
|
||||
if (responseMessage == null || responseMessage.length == 0) {
|
||||
message = new JSONObject();
|
||||
} else {
|
||||
message = parseJson(new String(responseMessage, encode));
|
||||
if (message == null) {
|
||||
message = new JSONObject();
|
||||
message.put("Malformed_Response_Message", new String(responseMessage, encode));
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(headerGroupName) && message != null)
|
||||
message.put(headerGroupName, headerJson);
|
||||
return message.toJSONString();
|
||||
}
|
||||
|
||||
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
||||
method.setHeader("Authorization",
|
||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
||||
String encode) {
|
||||
if (responseMessage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
||||
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
||||
if (StringUtils.isBlank(responseCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
||||
return ArrayUtils.contains(arr, responseCode);
|
||||
} catch (Exception e) {
|
||||
logger.error("HttpClientAdapterServiceRest] checkTokenRetry error=" + e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void assignRequestHeaders(HttpUriRequestBase method, Object httpHeader) {
|
||||
if (httpHeader == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (httpHeader instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) httpHeader;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
method.setHeader((String) key, (String) obj);
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Request Header :" + (String) key + "=[" + (String) obj + "]");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private void assignPostBody(Object eaiBody, String contentType, String charset, HttpUriRequestBase method) {
|
||||
if (eaiBody == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(contentType, "application/x-www-form-urlencoded")) {
|
||||
if (eaiBody instanceof JSONObject) {
|
||||
List<NameValuePair> params = new ArrayList<>();
|
||||
JSONObject jsonObject = (JSONObject) eaiBody;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
params.add(new BasicNameValuePair((String) key, (String) jsonObject.get(key)));
|
||||
}
|
||||
|
||||
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
|
||||
method.setEntity(entity);
|
||||
}
|
||||
|
||||
} else {
|
||||
ContentType contentTypeObj = ContentType.create(contentType, charset);
|
||||
|
||||
// 요청 본문을 StringEntity 객체로 생성
|
||||
StringEntity entity = new StringEntity(eaiBody.toString(), contentTypeObj);
|
||||
|
||||
// 요청에 본문 추가
|
||||
method.setEntity(entity);
|
||||
}
|
||||
}
|
||||
|
||||
private HashMap<String, String> getParameters(Object message) throws Exception {
|
||||
|
||||
HashMap<String, String> result = new HashMap<String, String>();
|
||||
|
||||
if (message != null) {
|
||||
if (message instanceof JSONObject) {
|
||||
JSONObject jsonObject = (JSONObject) message;
|
||||
for (Object key : jsonObject.keySet()) {
|
||||
Object obj = jsonObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
result.put((String) key, getStringValue(obj));
|
||||
}
|
||||
} else {
|
||||
String[] messages = ((String) message).split("&");
|
||||
String[] data = null;
|
||||
|
||||
for (int i = 0; i < messages.length; i++) {
|
||||
data = messages[i].split("=", 2);
|
||||
if (data.length == 2) {
|
||||
result.put(data[0], data[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getStringValue(Object obj) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (obj instanceof String) {
|
||||
return (String) obj;
|
||||
} else if (obj instanceof Long) {
|
||||
return Long.toString((Long) obj);
|
||||
} else if (obj instanceof BigDecimal) {
|
||||
return ((BigDecimal) obj).toPlainString();
|
||||
} else {
|
||||
return (String) obj;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private JSONObject parseJson(String message) throws Exception {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (JSONObject) JSONValue.parse(message);
|
||||
}
|
||||
|
||||
private Document convertXmlDocument(String message) throws Exception {
|
||||
SAXReader builder = new SAXReader();
|
||||
Document document = builder.read(new StringReader(message));
|
||||
return document;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private String changeUrl(String messageType, String url, String restOption, Object sendData) {
|
||||
if ((MessageType.JSON.equals(messageType) || MessageType.XML.equals(messageType))) {
|
||||
try {
|
||||
if (StringUtils.isBlank(restOption)) {
|
||||
return url;
|
||||
}
|
||||
List<String> urlVariableList = new ArrayList<String>();
|
||||
JSONObject restOptionObject = parseJson(restOption);
|
||||
|
||||
if (restOptionObject == null)
|
||||
throw new Exception("restOption is NULL");
|
||||
|
||||
String type = (String) restOptionObject.get("type");
|
||||
String requestExtraPath = (String) restOptionObject.get("extraPath");
|
||||
url = getUrl(url, requestExtraPath);
|
||||
if (TYPE_VARIABLE_URL_REQUEST.equals(type)) {
|
||||
Pattern p = Pattern.compile("\\{(.*?)\\}");
|
||||
Matcher m = p.matcher(requestExtraPath);
|
||||
List<String> uriVariables = new ArrayList<>();
|
||||
while (m.find()) {
|
||||
String fieldName = m.group(1);
|
||||
uriVariables.add(fieldName);
|
||||
}
|
||||
if (MessageType.JSON.equals(messageType)) {
|
||||
JSONObject jsonObject;
|
||||
if (sendData instanceof JSONObject) {
|
||||
jsonObject = (JSONObject) sendData;
|
||||
} else {
|
||||
jsonObject = (JSONObject) JSONValue.parse((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
String uriVariable = (String) jsonObject.get(urlVaribleId);
|
||||
urlVariableList.add(uriVariable);
|
||||
jsonObject.remove(urlVaribleId);
|
||||
}
|
||||
} else if (MessageType.XML.equals(messageType)) {
|
||||
Document doc;
|
||||
if (sendData instanceof Document) {
|
||||
doc = (Document) sendData;
|
||||
} else {
|
||||
doc = convertXmlDocument((String) sendData);
|
||||
}
|
||||
for (Object tempObject : uriVariables) {
|
||||
String urlVaribleId = (String) tempObject;
|
||||
Element element = (Element) doc.selectSingleNode("//" + urlVaribleId);
|
||||
urlVariableList.add(element.getText());
|
||||
if (doc.getRootElement() == element) {
|
||||
doc = null;
|
||||
} else {
|
||||
element.getParent().remove(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (urlVariableList.size() > 0) {
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
||||
Object[] urls = urlVariableList.toArray();
|
||||
url = uriComponents.expand(urls).toUriString();
|
||||
logger.debug("HttpClientAdapterServiceRest] after extand url=[" + url + "] ");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to change url", e);
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
private String getUrl(String baseUrl, String extraPath) {
|
||||
if (StringUtils.isBlank(extraPath)) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
||||
return extraPath;
|
||||
}
|
||||
|
||||
String targetUrl = baseUrl;
|
||||
if (!targetUrl.endsWith("/")) {
|
||||
targetUrl += "/";
|
||||
}
|
||||
if (extraPath.startsWith("/")) {
|
||||
targetUrl += extraPath.substring(1);
|
||||
} else {
|
||||
targetUrl += extraPath;
|
||||
}
|
||||
|
||||
logger.debug("HttpClientAdapterServiceRest] after concatenate url=[" + targetUrl + "] ");
|
||||
return targetUrl;
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class JsonToSetStatusFilter implements HttpAdapterFilter {
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
||||
|
||||
int httpStatus = 200;
|
||||
|
||||
if (rootNode.has("apiRsltCd") && !rootNode.get("apiRsltCd").asText().isEmpty()) {
|
||||
try {
|
||||
String statusParam = rootNode.get("apiRsltCd").asText();
|
||||
httpStatus = Integer.parseInt(statusParam);
|
||||
} catch (NumberFormatException e) {
|
||||
httpStatus = 400; // 잘못된 입력일 경우 400 Bad Request 반환
|
||||
}
|
||||
// HTTP 상태 코드 설정
|
||||
response.setStatus(httpStatus);
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, resultMessage);
|
||||
int httpStatus = 200;
|
||||
|
||||
if (rootNode.has("apiRsltCd") && !rootNode.get("apiRsltCd").asText().isEmpty()) {
|
||||
try {
|
||||
String statusParam = rootNode.get("apiRsltCd").asText();
|
||||
httpStatus = Integer.parseInt(statusParam);
|
||||
} catch (NumberFormatException e) {
|
||||
httpStatus = 400; // 잘못된 입력일 경우 400 Bad Request 반환
|
||||
}
|
||||
// HTTP 상태 코드 설정
|
||||
response.setStatus(httpStatus);
|
||||
}
|
||||
return resultMessage;
|
||||
}
|
||||
|
||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException, JsonProcessingException {
|
||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
||||
String orgMessageString;
|
||||
if(message instanceof byte[]) {
|
||||
orgMessageString = new String((byte[])message, charset);
|
||||
} else {
|
||||
orgMessageString = (String) message;
|
||||
}
|
||||
|
||||
return mapper.readTree(orgMessageString);
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
public class JsonToStdConverterFilter implements HttpAdapterFilter {
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
||||
|
||||
if (rootNode.has("header_part")) {
|
||||
JsonNode headerPart = rootNode.path("header_part");
|
||||
if (!headerPart.has("eaiIntfId") || headerPart.get("eaiIntfId").asText().isEmpty()) {
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
String inboundUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
|
||||
String apiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH) + "/";
|
||||
|
||||
// getUserInfo.svc
|
||||
String eaiIntfId = org.apache.commons.lang.StringUtils.removeStart(inboundUri, apiPath);
|
||||
|
||||
// header_part 아래 eaiIntfId가 추가 또는 수정
|
||||
if (headerPart instanceof ObjectNode) {
|
||||
((ObjectNode) headerPart).put("eaiIntfId", eaiIntfId);
|
||||
// 요청 응답 구분코드 강제 설정 -> API명 찾아갈때 필요
|
||||
if (!headerPart.has("reqRspnsDscd")) {
|
||||
((ObjectNode) headerPart).put("reqRspnsDscd", "S");
|
||||
}
|
||||
|
||||
// GUID 강제 설정
|
||||
String orgnlTx = "";
|
||||
if (headerPart.has("orgnlTx") && !headerPart.get("orgnlTx").asText().isEmpty()) {
|
||||
orgnlTx = headerPart.get("orgnlTx").asText();
|
||||
}
|
||||
if (!headerPart.has("tlgrWrtnDt")) {
|
||||
((ObjectNode) headerPart).put("tlgrWrtnDt", orgnlTx);
|
||||
}
|
||||
if (!headerPart.has("tlgrCrtnSysNm")) {
|
||||
((ObjectNode) headerPart).put("tlgrCrtnSysNm", "");
|
||||
}
|
||||
if (!headerPart.has("tlgrSrlNo")) {
|
||||
((ObjectNode) headerPart).put("tlgrSrlNo", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return message;
|
||||
}
|
||||
return rootNode.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, resultMessage);
|
||||
|
||||
if (rootNode.has("header_part")) {
|
||||
JsonNode headerPart = rootNode.path("header_part");
|
||||
if (!headerPart.has("eaiIntfId") || headerPart.get("eaiIntfId").asText().isEmpty()) {
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
String inboundUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
|
||||
String apiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH) + "/";
|
||||
|
||||
// getUserInfo.svc
|
||||
String eaiIntfId = org.apache.commons.lang.StringUtils.removeStart(inboundUri, apiPath);
|
||||
|
||||
// header_part 아래 eaiIntfId가 추가 또는 수정
|
||||
if (headerPart instanceof ObjectNode) {
|
||||
((ObjectNode) headerPart).put("eaiIntfId", eaiIntfId);
|
||||
// 요청 응답 구분코드 강제 설정 -> API명 찾아갈때 필요
|
||||
((ObjectNode) headerPart).put("reqRspnsDscd", "S");
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return resultMessage;
|
||||
}
|
||||
return rootNode.toString();
|
||||
}
|
||||
|
||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException, JsonProcessingException {
|
||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
||||
String orgMessageString;
|
||||
if(message instanceof byte[]) {
|
||||
orgMessageString = new String((byte[])message, charset);
|
||||
} else {
|
||||
orgMessageString = (String) message;
|
||||
}
|
||||
|
||||
return mapper.readTree(orgMessageString);
|
||||
}
|
||||
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Iterator;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
public class KbankEaiJsonParseFilter implements HttpAdapterFilter {
|
||||
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
||||
|
||||
ObjectNode replacedJson = mapper.createObjectNode();
|
||||
for(Iterator<String> it = rootNode.fieldNames(); it.hasNext();) {
|
||||
String fieldName = it.next();
|
||||
String value = rootNode.get(fieldName).asText();
|
||||
JsonNode jsonNode = mapper.readTree(value);
|
||||
replacedJson.set(fieldName, jsonNode);
|
||||
}
|
||||
|
||||
return replacedJson.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
JsonNode rootNode = parseJson(adptGrpName, resultMessage);
|
||||
|
||||
ObjectNode replacedJson = mapper.createObjectNode();
|
||||
for(Iterator<String> it = rootNode.fieldNames(); it.hasNext();) {
|
||||
String fieldName = it.next();
|
||||
JsonNode childNode = rootNode.get(fieldName);
|
||||
String childString = mapper.writeValueAsString(childNode);
|
||||
replacedJson.put(fieldName, childString);
|
||||
}
|
||||
|
||||
return replacedJson.toString();
|
||||
}
|
||||
|
||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException, JsonProcessingException {
|
||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
||||
String orgMessageString;
|
||||
if(message instanceof byte[]) {
|
||||
orgMessageString = new String((byte[])message, charset);
|
||||
} else {
|
||||
orgMessageString = (String) message;
|
||||
}
|
||||
|
||||
return mapper.readTree(orgMessageString);
|
||||
}
|
||||
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Properties;
|
||||
import java.util.Date;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Iterator;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.Mac;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.apache.commons.net.util.Base64;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.common.server.Keys;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class KbankHmacSha256VerifyFilter implements HttpAdapterFilter {
|
||||
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
||||
private static final int TIMESTAMP_EXPIRATION_SECONDS = 60*10*1000;
|
||||
private static final String GROUP_NAME = "HMAC_INFO";
|
||||
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
|
||||
try {
|
||||
|
||||
String hmacSignature = getHeaderCaseInsensitive(request, "hmac_signature");
|
||||
String hmacTimestamp = getHeaderCaseInsensitive(request, "hmac_timestamp");
|
||||
|
||||
if(StringUtils.isBlank(hmacSignature) || StringUtils.isBlank(hmacTimestamp)) {
|
||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Can not find hmac info");
|
||||
}
|
||||
|
||||
long inputTime = new SimpleDateFormat("yyyyMMddHHmmss").parse(hmacTimestamp).getTime();
|
||||
long currentTime = new Date().getTime();
|
||||
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
|
||||
|
||||
logger.debug("### inputTime :"+inputTime);
|
||||
logger.debug("### currentTime :"+currentTime);
|
||||
logger.debug("### timeStamp :"+timeStamp);
|
||||
|
||||
String systemMode = System.getProperty(Keys.EAI_SYSTEMMODE);
|
||||
|
||||
if(currentTime - inputTime > TIMESTAMP_EXPIRATION_SECONDS) {
|
||||
|
||||
logger.debug("### systemMode:" + systemMode);
|
||||
logger.debug("### currentTime - inputTime:" + (currentTime - inputTime));
|
||||
|
||||
if("P".equals(systemMode)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN,"00"), "Signature verifying failed");
|
||||
}
|
||||
}
|
||||
|
||||
String sMessage = (String)message;
|
||||
|
||||
sMessage = sMessage.replace(" ","");
|
||||
sMessage = sMessage.replace("\n","");
|
||||
sMessage = sMessage.replace("\r","");
|
||||
|
||||
sMessage = sMessage + hmacTimestamp;
|
||||
|
||||
logger.info("### sMessage:"+sMessage);
|
||||
|
||||
String alCoId = "AL2021012901001";
|
||||
|
||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
||||
|
||||
for(Iterator<String> it = rootNode.fieldNames(); it.hasNext();){
|
||||
String fieldName = it.next();
|
||||
if(fieldName.equals("ALCO_ID")) alCoId = rootNode.get(fieldName).asText();
|
||||
}
|
||||
|
||||
logger.info("### alCoId:"+alCoId);
|
||||
|
||||
Properties hmacProp = PropManager.getInstance().getProperties(GROUP_NAME);
|
||||
|
||||
String hmacKey = hmacProp.getProperty(alCoId+"-hmack-key","");
|
||||
String hmacKek = hmacProp.getProperty(alCoId+"-hmack-kek","");
|
||||
String hmacIvForKey = hmacProp.getProperty(alCoId+"-hmack-iv-for-key","");
|
||||
|
||||
logger.debug("### hmacKey:"+hmacKey);
|
||||
logger.debug("### hmacIvForKey:"+hmacIvForKey);
|
||||
logger.debug("### hmacKek:"+hmacKek);
|
||||
|
||||
//kbank.payment.hmac-key
|
||||
int hmacKeyLen = hmacKey.length();
|
||||
byte[] hmacKeyData = new byte[hmacKeyLen/2];
|
||||
for(int i=0;i<hmacKeyLen;i+=2){
|
||||
hmacKeyData[i/2] = (byte)((Character.digit(hmacKey.charAt(i), 16) << 4) + Character.digit(hmacKey.charAt(i+1), 16));
|
||||
}
|
||||
|
||||
//kbank.payment.hmac-kek
|
||||
int hmacKekLen = hmacKek.length();
|
||||
byte[] hmacKekData = new byte[hmacKekLen/2];
|
||||
for(int i=0;i<hmacKekLen;i+=2){
|
||||
hmacKekData[i/2] = (byte)((Character.digit(hmacKek.charAt(i),16) << 4) + Character.digit(hmacKek.charAt(i+1), 16));
|
||||
}
|
||||
|
||||
//kbank.payment.hmac-iv-for-key
|
||||
int hmacIvForKeyLen = hmacIvForKey.length();
|
||||
byte[] hmacIvForKeyData = new byte[hmacIvForKeyLen/2];
|
||||
for(int i=0;i<hmacIvForKeyLen;i+=2){
|
||||
hmacIvForKeyData[i/2] = (byte)((Character.digit(hmacIvForKey.charAt(i),16) << 4) + Character.digit(hmacIvForKey.charAt(i+1), 16));
|
||||
}
|
||||
|
||||
byte[] decrypedHmacKey = null;
|
||||
|
||||
try{
|
||||
Cipher cp = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
cp.init(Cipher.DECRYPT_MODE, new SecretKeySpec(hmacIvForKeyData,"AES"), new IvParameterSpec(hmacIvForKeyData));
|
||||
decrypedHmacKey = cp.doFinal(hmacKeyData);
|
||||
} catch (Exception e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed");
|
||||
}
|
||||
|
||||
SecretKeySpec secretKey = new SecretKeySpec(decrypedHmacKey, "HmacSHA256");
|
||||
String madeSignature = "";
|
||||
|
||||
logger.info("### secretKey:"+secretKey);
|
||||
|
||||
try{
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(secretKey);
|
||||
madeSignature= Base64.encodeBase64String(mac.doFinal(sMessage.getBytes()));
|
||||
} catch (Exception e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed");
|
||||
}
|
||||
|
||||
logger.info("### madeSignature:"+madeSignature);
|
||||
|
||||
if(!StringUtils.equals(hmacSignature, madeSignature)){
|
||||
logger.info("### hmacSignature:"+hmacSignature);
|
||||
logger.info("### madeSignature:"+madeSignature);
|
||||
|
||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed" );
|
||||
}
|
||||
|
||||
} catch (JwtAuthException e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed(Unknown)" );
|
||||
}
|
||||
|
||||
logger.info("### pass: "+"success");
|
||||
|
||||
return message;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 대소문자 구분 없이 HTTP 헤더 값을 가져오는 메소드
|
||||
* @param request HTTP 요청 객체
|
||||
* @param headerName 찾고자 하는 헤더 이름
|
||||
* @return 헤더 값 또는 null
|
||||
*/
|
||||
public static String getHeaderCaseInsensitive(HttpServletRequest request, String headerName) {
|
||||
Enumeration<String> headerNames = request.getHeaderNames();
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String header = headerNames.nextElement();
|
||||
if (header != null && header.equalsIgnoreCase(headerName)) {
|
||||
return request.getHeader(header);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException,JsonProcessingException {
|
||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
||||
String orgMessageString;
|
||||
|
||||
if(message instanceof byte[]) {
|
||||
orgMessageString = new String((byte[])message, charset);
|
||||
} else {
|
||||
orgMessageString = (String) message;
|
||||
}
|
||||
|
||||
return mapper.readTree(orgMessageString);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return resultMessage;
|
||||
}
|
||||
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.apache.commons.codec.digest.HmacAlgorithms;
|
||||
import org.apache.commons.codec.digest.HmacUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.vo.ClientVO;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class SnapHmacSha512VerifyFilter implements HttpAdapterFilter {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
||||
private static final int X_TIMESTAMP_EXPIRATION_SECONDS = 60 * 5;
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
// @formatter:off
|
||||
/*
|
||||
* HMAC_SHA512 (clientSecret, stringToSign)
|
||||
*
|
||||
* stringToSign = HTTPMethod:EndpointUrl:AccessToken
|
||||
* :Lowercase(HexEncode(SHA-256(minify(RequestBody)))):TimeStamp
|
||||
*/
|
||||
try {
|
||||
String xSignature = request.getHeader("X-SIGNATURE");
|
||||
if (StringUtils.isBlank(xSignature)) {
|
||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Can not find X-SIGNATURE");
|
||||
}
|
||||
|
||||
String clientSecret = assignClientSecret(prop, request);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(request.getMethod())
|
||||
.append(":")
|
||||
.append(getEndpointUrl(request))
|
||||
.append(":")
|
||||
.append(SnapSimpleOauth2Filter.extractToken(request))
|
||||
.append(":")
|
||||
.append(getRequestBody((String)message))
|
||||
.append(":")
|
||||
.append(getTimeStamp(request));
|
||||
// @formatter:on
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug(sb.toString());
|
||||
}
|
||||
|
||||
String hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_512, clientSecret).hmacHex(sb.toString());
|
||||
|
||||
if (!StringUtils.equals(xSignature, hmac)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Signature verifying failed");
|
||||
}
|
||||
} catch (JwtAuthException e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Signature verifying failed(unkown)");
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private String assignClientSecret(Properties prop, HttpServletRequest request) throws Exception {
|
||||
String clientId = assignClientId(prop, request);
|
||||
if (StringUtils.isBlank(clientId)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Can not find clientId info");
|
||||
}
|
||||
|
||||
ClientVO client = (ClientVO) OAuth2Manager.getInstance().getClientDeatilsStore().get(clientId);
|
||||
if (client == null) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Can not find client info");
|
||||
}
|
||||
|
||||
return client.getClientSecret();
|
||||
}
|
||||
|
||||
private String assignClientId(Properties prop, HttpServletRequest request) {
|
||||
String clientId = null;
|
||||
try {
|
||||
// 이전 filter에서 셋팅한 clientId 확보
|
||||
clientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
||||
|
||||
// 이전 filter에서 셋팅한 값이 없다면 header 정보에서 확보
|
||||
if (StringUtils.isBlank(clientId)) {
|
||||
clientId = request.getHeader(HttpAdapterServiceSupport.HEADER_NAME_CLIENT_ID);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
return clientId;
|
||||
}
|
||||
|
||||
private String getEndpointUrl(HttpServletRequest request) {
|
||||
String servletPath = request.getServletPath();
|
||||
String pathInfo = request.getPathInfo();
|
||||
String queryString = request.getQueryString();
|
||||
|
||||
StringBuilder url = new StringBuilder();
|
||||
url.append(servletPath);
|
||||
|
||||
if (pathInfo != null) {
|
||||
url.append(pathInfo);
|
||||
}
|
||||
|
||||
if (queryString != null) {
|
||||
url.append("?").append(queryString);
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
private String getRequestBody(String message) throws Exception {
|
||||
if (StringUtils.isEmpty(message)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// Lowercase(HexEncode(SHA-256(minify(RequestBody))))
|
||||
String body = minifyJson(message);
|
||||
try {
|
||||
body = DigestUtils.sha256Hex(body);
|
||||
} catch (Exception e) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"SHA-256 digest error");
|
||||
}
|
||||
return body.toLowerCase();
|
||||
}
|
||||
|
||||
private String minifyJson(String json) {
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode jsonNode = objectMapper.readValue(json, JsonNode.class);
|
||||
return jsonNode.toString();
|
||||
} catch (Exception e) {
|
||||
// json이 아닐경우
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
private String getTimeStamp(HttpServletRequest request) throws Exception {
|
||||
String timeStamp = request.getHeader("X-TIMESTAMP");
|
||||
if (StringUtils.isBlank(timeStamp)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Can not find X-TIMESTAMP");
|
||||
}
|
||||
|
||||
// 2020-12-23T09:10:11+07:00(현재시간이랑 비교로직 추가-보안)
|
||||
ZonedDateTime xTimeStamp = ZonedDateTime.parse(timeStamp, DateTimeFormatter.ISO_DATE_TIME);
|
||||
xTimeStamp = xTimeStamp.plusSeconds(X_TIMESTAMP_EXPIRATION_SECONDS);
|
||||
ZonedDateTime now = ZonedDateTime.now();
|
||||
if (xTimeStamp.isBefore(now.withZoneSameInstant(xTimeStamp.getZone()))) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Too old X-TIMESTAMP");
|
||||
}
|
||||
|
||||
return timeStamp;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return resultMessage;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String str = "POST:/api/test/aaa/type02/555:"
|
||||
+ "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJzbmFwIl0sImV4cCI6MTY3NjUyNDI1MSwianRpIjoiNzI0MWMyZGUtZjJhNi00NTFmLWExMjQtZGM3NmI0ZGY1OThjIiwiY2xpZW50X2lkIjoic1NHSkR3bEpzZWw1V2VYb2R6ZDNKM01RMjBLWUNacEwifQ.Obe8t8IwuQ3P7i4yCSASYze-9DLmVwXe0g_gBYlwv_Jzc7V8-ooTwp6SVnaNsM6pp1GV-9lxMpAzQO_CRHQq_hdMeiPI_CXHh3gETvjQThn57QGEGdCNp_lUEVYtMPUxi5u3X6Of07o0_OB83WI7rA1zD0DaP8V67pgfq-jMRe_3IXztOYu_nwMgREbGvs9tqcsjxppRKkEHcK1S8Eq4HzaLwjwyHJAhIlTba27yd4T8ELC7IpFphJBfEPF_t0ZpYW15lOrg5pHPjy1xpTV0Kgipog5wycTZlFUeCWWjfxTrpVmt_1XlEOlZH9X6xAefWrH93_fpbt3OcxwP4u9KhA"
|
||||
+ ":424058b889b9d860d13b79d90df52ddcbefba2fc9d27607e999c7c3c4d61d9c8:" + "2023-02-16T09:47:07+07:00";
|
||||
|
||||
String hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_512,
|
||||
"o3Hre3voTrHbLueDrHC0LYM5effHQZILI8t23htbD12TKD5QJUMONqFqv4494iQS46bzHS0xW1fBC5LHo3D0SzhZvQcPUaJZw0iQ79NnzYFUCTrEsoFJRL300dp3Ql4y")
|
||||
.hmacHex(str);
|
||||
|
||||
System.out.println(hmac);
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.text.ParseException;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthFilter;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.common.property.PropGroupVO;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.inbound.action.ActionFactory;
|
||||
import com.eactive.eai.inbound.action.RequestAction;
|
||||
import com.eactive.eai.inbound.processor.Processor;
|
||||
import com.eactive.eai.message.StandardMessageUtil;
|
||||
import com.nimbusds.jose.JWSVerifier;
|
||||
import com.nimbusds.jose.crypto.RSASSAVerifier;
|
||||
import com.nimbusds.jose.util.IOUtils;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
|
||||
public class SnapJwtAuthFilter implements HttpAdapterFilter {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
public static final String PROP_GROUP_AUTH_SERVER = "OAuthServer";
|
||||
public static final String PROP_KEYSTORE_PATH = "certification.publicKeyPath";
|
||||
|
||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
||||
|
||||
public static final String PAYLOAD_PARAM_NAME_SCOPE = "scope";
|
||||
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id";
|
||||
|
||||
private JWSVerifier jwsVerifier;
|
||||
|
||||
public SnapJwtAuthFilter() {
|
||||
super();
|
||||
|
||||
PropGroupVO vo = PropManager.getInstance().getPropGroupVO(PROP_GROUP_AUTH_SERVER);
|
||||
String publicKeyPath = "/certificate/elink-oauth-dev.pub";
|
||||
if (vo != null) {
|
||||
publicKeyPath = vo.getProperty(PROP_KEYSTORE_PATH);
|
||||
} else {
|
||||
logger.warn("The properties has not been set.[" + PROP_GROUP_AUTH_SERVER + "]");
|
||||
}
|
||||
|
||||
Resource resource = new ClassPathResource(publicKeyPath);
|
||||
String publicKey = null;
|
||||
try {
|
||||
publicKey = IOUtils.readInputStreamToString(resource.getInputStream());
|
||||
publicKey = StringUtils.replace(publicKey, "-----BEGIN PUBLIC KEY-----", "");
|
||||
publicKey = StringUtils.replace(publicKey, "-----END PUBLIC KEY-----", "");
|
||||
publicKey = StringUtils.remove(publicKey, "\r");
|
||||
publicKey = StringUtils.remove(publicKey, "\n");
|
||||
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
jwsVerifier = new RSASSAVerifier((RSAPublicKey) keyFactory.generatePublic(keySpec));
|
||||
} catch (final IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
String apiId = assignApiId(adptGrpName, adptName, message, prop, request);
|
||||
if (StringUtils.isBlank(apiId)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Can not find apiId(apiCode) info");
|
||||
}
|
||||
|
||||
try {
|
||||
String token = JwtAuthFilter.extractJWTToken(request);
|
||||
SignedJWT signedJWT = SignedJWT.parse(token);
|
||||
|
||||
if (new Date().after(signedJWT.getJWTClaimsSet().getExpirationTime())) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token - expired (B2B)");
|
||||
}
|
||||
|
||||
if (!signedJWT.verify(jwsVerifier)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token (B2B)");
|
||||
}
|
||||
|
||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||
HashSet<String> scopeSet = manager.getApiScopeMap().get(apiId);
|
||||
if (!verifyScope(scopeSet, signedJWT)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
String.format("Insufficient [Scope](Allowed Scope=%s)", scopeSet.toString()));
|
||||
}
|
||||
|
||||
// header 값으로 전송된 clientId와 토큰 소유 clientId check
|
||||
if (!verifyClientId(prop, signedJWT)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"client_id not matched(header/token)");
|
||||
}
|
||||
} catch (JwtAuthException e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token (B2B)");
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private boolean verifyClientId(Properties prop, SignedJWT signedJWT) {
|
||||
try {
|
||||
// 이전 filter에서 셋팅한 clientId 확보
|
||||
String headerClientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
||||
String tokenClientId = (String) signedJWT.getJWTClaimsSet().getClaim(PAYLOAD_PARAM_NAME_CLIENT_ID);
|
||||
|
||||
// 이전 filter에서 셋팅한 값이 없다면 token 정보에서 확보
|
||||
if (StringUtils.isBlank(headerClientId)) {
|
||||
if (StringUtils.isNotBlank(tokenClientId)) {
|
||||
prop.put(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID, tokenClientId);
|
||||
}
|
||||
} else { // header로 전달된 clientId가 있을때만 비교
|
||||
if (!headerClientId.equals(tokenClientId)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return resultMessage;
|
||||
}
|
||||
|
||||
private boolean verifyScope(HashSet<String> scopeSet, SignedJWT signedJWT) throws ParseException {
|
||||
if (scopeSet == null || scopeSet.isEmpty()) {
|
||||
return true; // If no scope is specified in the api, all are allowed
|
||||
}
|
||||
|
||||
String[] scopeArr = signedJWT.getJWTClaimsSet().getStringArrayClaim(PAYLOAD_PARAM_NAME_SCOPE);
|
||||
if (scopeArr == null || scopeArr.length == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (String scope : scopeArr) {
|
||||
if (scopeSet.contains(scope)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static String extractJWTToken(HttpServletRequest request) throws JwtAuthException {
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (StringUtils.isBlank(authorization)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"No have header info: Authorization");
|
||||
}
|
||||
|
||||
String[] components = authorization.split("\\s");
|
||||
|
||||
if (components.length != 2) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Malformat [Authorization] content");
|
||||
}
|
||||
|
||||
if (!StringUtils.equalsIgnoreCase(components[0], "Bearer")) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"[Bearer] is needed");
|
||||
}
|
||||
|
||||
return components[1].trim();
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.util.BeanUtils;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.inbound.action.ActionFactory;
|
||||
import com.eactive.eai.inbound.action.RequestAction;
|
||||
import com.eactive.eai.inbound.processor.Processor;
|
||||
import com.eactive.eai.message.StandardMessageUtil;
|
||||
|
||||
public class SnapSimpleOauth2Filter implements HttpAdapterFilter {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
||||
|
||||
private TokenStore tokenStore;
|
||||
|
||||
public SnapSimpleOauth2Filter() {
|
||||
super();
|
||||
tokenStore = BeanUtils.getBean("tokenStore", TokenStore.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
try {
|
||||
String apiId = assignApiId(adptGrpName, adptName, message, prop, request);
|
||||
if (StringUtils.isBlank(apiId)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Can not find apiId(apiCode) info");
|
||||
}
|
||||
|
||||
String tokenStr = extractToken(request);
|
||||
|
||||
OAuth2AccessToken token = tokenStore.readAccessToken(tokenStr);
|
||||
if (token == null) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "03"),
|
||||
"Token Not Found (B2B)");
|
||||
}
|
||||
|
||||
if (token.isExpired()) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token - expired (B2B)");
|
||||
}
|
||||
|
||||
OAuth2Authentication authentication = tokenStore.readAuthentication(token);
|
||||
if (!authentication.isAuthenticated()) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token (B2B)");
|
||||
}
|
||||
|
||||
// check scope
|
||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||
HashSet<String> scopeSet = manager.getApiScopeMap().get(apiId);
|
||||
if (!verifyScope(scopeSet, authentication)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
String.format("Insufficient [Scope](Allowed Scope=%s)", scopeSet.toString()));
|
||||
}
|
||||
|
||||
// header 값으로 전송된 clientId와 토큰 소유 clientId check
|
||||
if (!verifyClientId(prop, authentication)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"client_id not matched(header/token)");
|
||||
}
|
||||
} catch (JwtAuthException e) {
|
||||
logger.debug(e.getMessage());
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
||||
"Invalid Token (B2B)");
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
private boolean verifyScope(HashSet<String> scopeSet, OAuth2Authentication auth) {
|
||||
if (scopeSet == null || scopeSet.isEmpty()) {
|
||||
return true; // If no scope is specified in the api, all are allowed
|
||||
}
|
||||
|
||||
Set<String> scopesInToken = auth.getOAuth2Request().getScope();
|
||||
|
||||
if (scopesInToken == null || scopesInToken.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (String scope : scopesInToken) {
|
||||
if (scopeSet.contains(scope)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean verifyClientId(Properties prop, Authentication authentication) {
|
||||
try {
|
||||
// 이전 filter에서 셋팅한 clientId 확보
|
||||
String headerClientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
||||
String tokenClientId = ((OAuth2Authentication) authentication).getOAuth2Request().getClientId();
|
||||
|
||||
// 이전 filter에서 셋팅한 값이 없다면 token 정보에서 확보
|
||||
if (StringUtils.isBlank(headerClientId)) {
|
||||
if (StringUtils.isNotBlank(tokenClientId)) {
|
||||
prop.put(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID, tokenClientId);
|
||||
}
|
||||
} else { // header로 전달된 clientId가 있을때만 비교
|
||||
if (!headerClientId.equals(tokenClientId)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public static String extractToken(HttpServletRequest request) throws JwtAuthException {
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (StringUtils.isBlank(authorization)) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"No have header info: Authorization");
|
||||
}
|
||||
|
||||
String[] components = authorization.split("\\s");
|
||||
|
||||
if (components.length != 2) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"Malformat [Authorization] content");
|
||||
}
|
||||
|
||||
if (!StringUtils.equalsIgnoreCase(components[0], "Bearer")) {
|
||||
throw new JwtAuthException(
|
||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
||||
"[Bearer] is needed");
|
||||
}
|
||||
|
||||
return components[1].trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return resultMessage;
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
||||
import com.eactive.eai.authserver.vo.ClientVO;
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.property.PropGroupVO;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.custom.adapter.http.util.VirtualAccountBatchUtil;
|
||||
import com.eactive.eai.custom.adapter.http.util.VirtualAccountTransform;
|
||||
|
||||
public class VirtualAccountCryptoFilter implements HttpAdapterFilter {
|
||||
// FIXME : kbank - 프라퍼티 그릅정의 확정
|
||||
private static final String BATCH_CHECK_URL = "/batch/";
|
||||
private static final String BATCH_PROP_GROUP = "VIRTUALACCOUNT_INFO";
|
||||
private static final String BATCH_FILE_PATH = "BATCH_FILE_PATH";
|
||||
private static final String FILE_NAME_PATTERN = "FILE_NAME_PATTERN";
|
||||
|
||||
private String getAesKey(String clientId) {
|
||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
||||
try {
|
||||
ClientVO client = manager.getClientInfo(clientId);
|
||||
return client.getSecurityKey();
|
||||
} catch (DAOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isBatch(HttpServletRequest request) {
|
||||
String uri = request.getRequestURI();
|
||||
return uri != null && uri.contains(BATCH_CHECK_URL);
|
||||
}
|
||||
|
||||
private String getRootFilePath() {
|
||||
PropGroupVO vo = PropManager.getInstance().getPropGroupVO(BATCH_PROP_GROUP);
|
||||
return vo.getProperty(BATCH_FILE_PATH);
|
||||
}
|
||||
|
||||
private String getFileNamePattern() {
|
||||
PropGroupVO vo = PropManager.getInstance().getPropGroupVO(BATCH_PROP_GROUP);
|
||||
return vo.getProperty(FILE_NAME_PATTERN);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
||||
String encPaths = prop.getProperty(HttpAdapterServiceKey.ENC_PATHS);
|
||||
List<String> encFieldList = null;
|
||||
String clientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
||||
String aesKey = getAesKey(clientId);
|
||||
|
||||
String convertedMessage = null;
|
||||
if(isBatch(request)) {
|
||||
String rootFilePath = getRootFilePath();
|
||||
String fileNamePattern = getFileNamePattern();
|
||||
VirtualAccountBatchUtil batchUtil = new VirtualAccountBatchUtil();
|
||||
if(message instanceof byte[]) {
|
||||
convertedMessage = new String((byte[])message, charset);
|
||||
} else {
|
||||
convertedMessage = (String) message;
|
||||
}
|
||||
batchUtil.unzipAndSave(aesKey, convertedMessage, rootFilePath, fileNamePattern);
|
||||
}
|
||||
else {
|
||||
if(StringUtils.isNotBlank(encPaths)) {
|
||||
String[] items = encPaths.split(",");
|
||||
encFieldList = Arrays.asList(items);
|
||||
if(message instanceof byte[]) {
|
||||
convertedMessage = new String((byte[])message, charset);
|
||||
} else {
|
||||
convertedMessage = (String) message;
|
||||
}
|
||||
convertedMessage = VirtualAccountTransform.toCubeOne(aesKey, encFieldList, convertedMessage);
|
||||
}
|
||||
}
|
||||
return convertedMessage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
||||
String encPaths = prop.getProperty(HttpAdapterServiceKey.ENC_PATHS);
|
||||
List<String> encFieldList = null;
|
||||
String clientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
||||
String aesKey = getAesKey(clientId);
|
||||
|
||||
if(isBatch(request)) {
|
||||
return resultMessage;
|
||||
}
|
||||
else {
|
||||
String resMessageString = null;
|
||||
if(StringUtils.isNotBlank(encPaths)) {
|
||||
String[] items = encPaths.split(",");
|
||||
encFieldList = Arrays.asList(items);
|
||||
if(resultMessage instanceof byte[]) {
|
||||
resMessageString = new String((byte[])resultMessage, charset);
|
||||
} else {
|
||||
resMessageString = (String) resultMessage;
|
||||
}
|
||||
resMessageString = VirtualAccountTransform.toAES(aesKey, encFieldList, resMessageString);
|
||||
}
|
||||
return resMessageString;
|
||||
}
|
||||
}
|
||||
}
|
||||
+765
@@ -0,0 +1,765 @@
|
||||
package com.eactive.eai.custom.adapter.http.dynamic.impl;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
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.fileupload.FileItem;
|
||||
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
|
||||
import org.apache.commons.fileupload.servlet.ServletFileUpload;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.mina.common.ByteBuffer;
|
||||
import org.json.simple.JSONArray;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
|
||||
import com.eactive.eai.adapter.AdapterManager;
|
||||
import com.eactive.eai.adapter.AdapterPropManager;
|
||||
import com.eactive.eai.adapter.AdapterVO;
|
||||
import com.eactive.eai.adapter.Keys;
|
||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
||||
import com.eactive.eai.adapter.http.HttpStatusException;
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
||||
import com.eactive.eai.common.TransactionContextKeys;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.MessageType;
|
||||
import com.eactive.eai.common.util.CommonLib;
|
||||
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.env.ElinkConfig;
|
||||
import com.eactive.eai.inbound.action.ActionFactory;
|
||||
import com.eactive.eai.inbound.action.RequestAction;
|
||||
import com.eactive.eai.inbound.processor.Processor;
|
||||
import com.eactive.eai.message.StandardMessageUtil;
|
||||
|
||||
/*
|
||||
* Kbank 가상계좌 INBOUND
|
||||
* @see com.eactive.eai.custom.adapter.http.dynamic.filter.VirtualAccountCryptoFilter
|
||||
* @Deprecated
|
||||
*/
|
||||
// FIXME : kbank - kbank에서는 Controller 방식을 사용하므로, 이 어댑터는 사용되지 않음 (VirtualAccountCryptoFilter 로 대체)
|
||||
public class HttpAdapterServiceVirtualAccount extends HttpAdapterServiceSupport {
|
||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
||||
// HEADER_GROUP JSON에 추가할 항목 정의, 없으면 전체 header 추가
|
||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
||||
public static final String HTTP_STATUS = "HTTP_STATUS";
|
||||
public static final String PROPERTIES_NAME_HTTP_REQUEST_METHOD = "httpRequestMethod";
|
||||
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
private String logPrefix = "HttpAdapterServiceRest] ";
|
||||
|
||||
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";
|
||||
|
||||
private Properties addCryptoFilter(Properties prop) {
|
||||
String cryptoFilterName = "com.eactive.eai.custom.adapter.http.dynamic.filter.VirtualAccountCryptoFilter";
|
||||
String addedPreFilter = prop.getProperty(PRE_FILTERS);
|
||||
String addedPostFilter = prop.getProperty(POST_FILTERS);
|
||||
|
||||
if(StringUtils.isBlank(addedPreFilter)) {
|
||||
addedPreFilter = cryptoFilterName;
|
||||
}
|
||||
else {
|
||||
addedPreFilter = addedPreFilter + "," +cryptoFilterName;
|
||||
}
|
||||
|
||||
if(StringUtils.isBlank(addedPostFilter)) {
|
||||
addedPostFilter = cryptoFilterName;
|
||||
}
|
||||
else {
|
||||
addedPostFilter = cryptoFilterName + "," +addedPostFilter;
|
||||
}
|
||||
|
||||
prop.setProperty(PRE_FILTERS, addedPreFilter);
|
||||
prop.setProperty(POST_FILTERS, addedPostFilter);
|
||||
return prop;
|
||||
}
|
||||
|
||||
private String readMultipartBody(HttpServletRequest request) throws Exception {
|
||||
String jsonString = null;
|
||||
// Create a factory for disk-based file items
|
||||
DiskFileItemFactory factory = new DiskFileItemFactory();
|
||||
|
||||
// Set the maximum size of the files to be uploaded
|
||||
factory.setSizeThreshold(1024 * 1024);
|
||||
|
||||
// Set the temporary directory to store uploaded files
|
||||
File tempDir = (File) request.getSession().getServletContext().getAttribute("javax.servlet.context.tempdir");
|
||||
factory.setRepository(tempDir);
|
||||
|
||||
ServletFileUpload upload = new ServletFileUpload(factory);
|
||||
Map<String, String> fileMap = new HashMap<>();
|
||||
|
||||
InputStream fin = null;
|
||||
try {
|
||||
byte[] buffer = new byte[1024];
|
||||
int read = 0;
|
||||
|
||||
List<FileItem> items = upload.parseRequest(request);
|
||||
for (FileItem item : items) {
|
||||
if (!item.isFormField()) {
|
||||
// file
|
||||
String fieldName = item.getFieldName();
|
||||
String fileName = item.getName();
|
||||
fin = item.getInputStream();
|
||||
ByteArrayOutputStream fo = new ByteArrayOutputStream();
|
||||
while ((read = fin.read(buffer)) > 0) {
|
||||
fo.write(buffer, 0, read);
|
||||
}
|
||||
int fileSize = fo.size();
|
||||
byte[] fileBytes = fo.toByteArray();
|
||||
String fileContents = new String(fileBytes);
|
||||
if (logger.isInfo()) {
|
||||
logger.info("[FILE]-------------------------------------------------->");
|
||||
logger.info("Field name = " + fieldName);
|
||||
logger.info("File name = " + fileName + " contents length = " + fileSize);
|
||||
logger.info("File Contents [" + fileContents + "]");
|
||||
logger.info("[FILE]<--------------------------------------------------");
|
||||
}
|
||||
fileMap.put(fileName, fileContents);
|
||||
fin.close();
|
||||
} else {
|
||||
// regular form field
|
||||
String fieldName = item.getFieldName();
|
||||
String fieldValue = item.getString();
|
||||
if (logger.isInfo()) {
|
||||
logger.info("[FIELD] " + fieldName + " [" + fieldValue + "]");
|
||||
}
|
||||
if (JSON_CONTENT_TYPE.equalsIgnoreCase(item.getContentType())
|
||||
|| JSON_FIELD_NAME.equals(fieldName)) {
|
||||
jsonString = fieldValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (logger.isInfo()) {
|
||||
logger.info("Json body [" + jsonString + "]");
|
||||
}
|
||||
|
||||
if (jsonString == null) {
|
||||
jsonString = "{}";
|
||||
} else {
|
||||
// parsing json & add file contents
|
||||
JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString);
|
||||
if (jsonObject == null) {
|
||||
jsonString = "{}";
|
||||
} else {
|
||||
JSONObject fileGroup = new JSONObject();
|
||||
|
||||
for (Map.Entry<String, String> entry : fileMap.entrySet()) {
|
||||
fileGroup.put("fileName", entry.getKey());
|
||||
fileGroup.put("fileContents", entry.getValue());
|
||||
}
|
||||
jsonObject.put(FILE_GROUP_NAME, fileGroup);
|
||||
jsonString = jsonObject.toJSONString();
|
||||
}
|
||||
}
|
||||
|
||||
if (logger.isInfo()) {
|
||||
logger.info("Json with file [" + jsonString + "]");
|
||||
}
|
||||
return jsonString;
|
||||
} catch (Exception e) {
|
||||
logger.error("Read multipart body error.", e);
|
||||
throw e;
|
||||
} finally {
|
||||
if (fin != null) {
|
||||
try {
|
||||
fin.close();
|
||||
} catch (Exception ex) {
|
||||
// empty
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String checkRootPath(String path) {
|
||||
if (StringUtils.isEmpty(path)) {
|
||||
logger.info("upload dir not set(UPLOAD_ROOT_PATH), use system temp " + path);
|
||||
return System.getProperty("java.io.tmpdir");
|
||||
}
|
||||
File file = new File(path);
|
||||
if (!file.exists()) {
|
||||
file.mkdirs();
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private String uploadMultipartBody(HttpServletRequest request, String uploadRootPath) throws Exception {
|
||||
String jsonString = null;
|
||||
// Create a factory for disk-based file items
|
||||
DiskFileItemFactory factory = new DiskFileItemFactory();
|
||||
|
||||
// Set the maximum size of the files to be uploaded
|
||||
factory.setSizeThreshold(1024 * 1024);
|
||||
|
||||
// Set the temporary directory to store uploaded files
|
||||
File tempDir = (File) request.getSession().getServletContext().getAttribute("javax.servlet.context.tempdir");
|
||||
factory.setRepository(tempDir);
|
||||
|
||||
ServletFileUpload upload = new ServletFileUpload(factory);
|
||||
try {
|
||||
// if not exist, create folders
|
||||
String uploadDir = checkRootPath(uploadRootPath);
|
||||
List<FileItem> items = upload.parseRequest(request);
|
||||
for (FileItem item : items) {
|
||||
if (!item.isFormField()) {
|
||||
// file
|
||||
String fieldName = item.getFieldName();
|
||||
String fileName = item.getName();
|
||||
String uploadFilePath = uploadDir + File.separator + fileName;
|
||||
File uploadFile = new File(uploadFilePath);
|
||||
item.write(uploadFile);
|
||||
|
||||
if (logger.isInfo()) {
|
||||
logger.info("[FILE]-------------------------------------------------->");
|
||||
logger.info("Field name = " + fieldName);
|
||||
logger.info("File name = " + fileName + " path = " + uploadFile.getAbsolutePath());
|
||||
logger.info("[FILE]<--------------------------------------------------");
|
||||
}
|
||||
} else {
|
||||
// regular form field
|
||||
String fieldName = item.getFieldName();
|
||||
String fieldValue = item.getString();
|
||||
if (logger.isInfo()) {
|
||||
logger.info("[FIELD] " + fieldName + " [" + fieldValue + "]");
|
||||
}
|
||||
if (JSON_CONTENT_TYPE.equalsIgnoreCase(item.getContentType())
|
||||
|| JSON_FIELD_NAME.equals(fieldName)) {
|
||||
jsonString = fieldValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (logger.isInfo()) {
|
||||
logger.info("Json body [" + jsonString + "]");
|
||||
}
|
||||
return jsonString;
|
||||
} catch (Exception e) {
|
||||
logger.error("Read multipart body error.", e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "deprecation" })
|
||||
public void service(String adptGrpName, String adptName, HttpServletRequest request, HttpServletResponse response) {
|
||||
int traceLevel = 0;
|
||||
|
||||
AdapterVO adptVO = null;
|
||||
AdapterPropManager manager = null;
|
||||
|
||||
Properties httpProp = null;
|
||||
String responseType = null;
|
||||
String urlDecodeYn = null;
|
||||
String encode = null;
|
||||
|
||||
String traceLevelTemp = null;
|
||||
String relayRequestHeaderKeys = null;
|
||||
String headerGroupName = null;
|
||||
|
||||
boolean isParameterType = false;
|
||||
String message = null;
|
||||
|
||||
StopWatch stopWatch = null;
|
||||
Properties prop = null;
|
||||
String paramValue = null;
|
||||
String adptMsgType = null;
|
||||
String errorResponseFormat = null;
|
||||
String uploadRootPath = null;
|
||||
try {
|
||||
AdapterManager adapterManager = AdapterManager.getInstance();
|
||||
adptVO = adapterManager.getAdapterVO(adptGrpName, adptName);
|
||||
if (adptVO == null) {
|
||||
throw new Exception("Adapter not found error");
|
||||
}
|
||||
|
||||
manager = AdapterPropManager.getInstance();
|
||||
|
||||
httpProp = manager.getProperties(adptVO.getPropGroupName());
|
||||
responseType = httpProp.getProperty(RESPONSE_TYPE, "SYNC");
|
||||
urlDecodeYn = httpProp.getProperty(URL_DECODE_YN, "N");
|
||||
// encode = httpProp.getProperty(ENCODE, "UTF-8");
|
||||
encode = StringUtils.defaultIfBlank(adapterManager.getAdapterGroupVO(adptGrpName).getMessageEncode(),
|
||||
"UTF-8");
|
||||
traceLevelTemp = httpProp.getProperty(TRACE_LEVEL, "0");
|
||||
relayRequestHeaderKeys = httpProp.getProperty(HEADER_KEYS);
|
||||
headerGroupName = httpProp.getProperty(HEADER_GROUP);
|
||||
errorResponseFormat = httpProp.getProperty(ERROR_RESPONSE_FORMAT);
|
||||
uploadRootPath = httpProp.getProperty(UPLOAD_ROOT_PATH);
|
||||
prop = new Properties();
|
||||
prop.put(INBOUND_METHOD, request.getMethod());
|
||||
prop.put(INBOUND_URI, request.getRequestURI());
|
||||
prop.put(INBOUND_HEADER, getHeaders(request));
|
||||
if (StringUtils.equals(adptVO.getAdapterGroupVO().getType(), Keys.TYPE_REST)
|
||||
|| StringUtils.equals(adptVO.getAdapterGroupVO().getType(), Keys.TYPE_HTTP_CUSTOM)) {
|
||||
// /api/v1/public/getUserInfo.svc
|
||||
String extUrl = StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
|
||||
prop.put(INBOUND_EXTURI, extUrl);
|
||||
} else {
|
||||
prop.put(INBOUND_EXTURI, getExtUri(request));
|
||||
}
|
||||
prop.put(Processor.REQUEST_ACTION, adptVO.getAdapterGroupVO().getRefClass());
|
||||
prop.put(API_PATH, httpProp.getProperty(API_PATH, ""));
|
||||
prop.put(PRE_FILTERS, httpProp.getProperty(PRE_FILTERS, ""));
|
||||
prop.put(POST_FILTERS, httpProp.getProperty(POST_FILTERS, ""));
|
||||
prop.put(PROPERTIES_NAME_HTTP_REQUEST_METHOD, request.getMethod());
|
||||
prop.put(ALLOW_IP, httpProp.getProperty(ALLOW_IP, ""));
|
||||
|
||||
isParameterType = false;
|
||||
try {
|
||||
traceLevel = Integer.parseInt(traceLevelTemp);
|
||||
} catch (Exception e) {
|
||||
traceLevel = 0;
|
||||
}
|
||||
|
||||
stopWatch = new StopWatch();
|
||||
stopWatch.start();
|
||||
|
||||
logger.debug("시작 >> encode = [" + encode + "]");
|
||||
|
||||
switch (HttpMethodType.getValue(request.getMethod())) {
|
||||
case GET:
|
||||
case DELETE:
|
||||
isParameterType = true;
|
||||
break;
|
||||
case POST:
|
||||
case PUT:
|
||||
if (StringUtils.contains(request.getContentType(), "application/x-www-form-urlencoded")) {
|
||||
isParameterType = true;
|
||||
} else {
|
||||
isParameterType = false;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (isParameterType) {
|
||||
paramValue = request.getQueryString();
|
||||
if (paramValue == null)
|
||||
paramValue = "";
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(paramValue));
|
||||
}
|
||||
|
||||
// json으로 변환
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("{");
|
||||
Map<String, String[]> paramMap = assignParameterMap(request, adptGrpName, adptName, null, prop);
|
||||
int i = 0;
|
||||
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
|
||||
if (i > 0) {
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append("\"").append(entry.getKey()).append("\":");
|
||||
String[] values = entry.getValue();
|
||||
if (values.length > 1) {
|
||||
// ["111", "222"]
|
||||
sb.append("[");
|
||||
for (int j = 0; j < values.length; j++) {
|
||||
if (j > 0) {
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append("\"").append(JSONValue.escape(values[j])).append("\"");
|
||||
}
|
||||
sb.append("]");
|
||||
} else {
|
||||
sb.append("\"").append(JSONValue.escape(values[0])).append("\"");
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
sb.append("}");
|
||||
|
||||
paramValue = sb.toString();
|
||||
} else {
|
||||
if (ServletFileUpload.isMultipartContent(request)) {
|
||||
// TODO : 아래의 로직은 업무에 맞게 수정이 필요함.
|
||||
// 불필요할 경우 제거
|
||||
// if(StringUtils.isEmpty(uploadRootPath)) {
|
||||
// uploadRootPath = System.getProperty("java.io.tmpdir");
|
||||
// }
|
||||
|
||||
// 임시로직 : UPLOAD_ROOT_PATH 가 없는 경우에는 JSON에 추가
|
||||
if (StringUtils.isEmpty(uploadRootPath)) {
|
||||
paramValue = readMultipartBody(request);
|
||||
} else {
|
||||
paramValue = uploadMultipartBody(request, uploadRootPath);
|
||||
}
|
||||
// TEST : 테스트용 임시코드
|
||||
// response.setCharacterEncoding(encode);
|
||||
// response.getWriter().print(paramValue);
|
||||
// return;
|
||||
} else {
|
||||
ServletInputStream sis = request.getInputStream();
|
||||
ByteBuffer bb = ByteBuffer.allocate(1024).setAutoExpand(true);
|
||||
int i = 0;
|
||||
byte[] cbuf = new byte[1024];
|
||||
while ((i = sis.read(cbuf, 0, 1024)) != -1) {
|
||||
if (i == 1024) {
|
||||
bb.put(cbuf);
|
||||
} else {
|
||||
byte[] tail = new byte[i];
|
||||
System.arraycopy(cbuf, 0, tail, 0, i);
|
||||
bb.put(tail);
|
||||
}
|
||||
}
|
||||
byte[] data = new byte[bb.position()];
|
||||
bb.position(0);
|
||||
bb.get(data);
|
||||
paramValue = new String(data, encode);
|
||||
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||
"RECV " + "[" + paramValue + "]" + CommonLib.getDumpMessage(paramValue));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (paramValue == null) { // parameter가 없는 경우때문에 처리
|
||||
paramValue = "";
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] RECV (" + adptGrpName + ") = [" + paramValue + "]\n"
|
||||
+ CommonLib.getDumpMessage(paramValue));
|
||||
}
|
||||
|
||||
if ("Y".equals(urlDecodeYn) && isParameterType) {
|
||||
message = URLDecoder.decode(paramValue);
|
||||
} else {
|
||||
message = paramValue;
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
String[] msgArgs = new String[2];
|
||||
msgArgs[0] = adptGrpName;
|
||||
msgArgs[1] = message;
|
||||
String resMsg = ExceptionUtil.make("RICEAIAHA005", msgArgs);
|
||||
logger.debug(logPrefix + resMsg);
|
||||
}
|
||||
|
||||
adptMsgType = adptVO.getAdapterGroupVO().getMessageType();
|
||||
if (StringUtils.equals(adptMsgType, MessageType.JSON)) {
|
||||
response.setContentType(JSON_CONTENT_TYPE+"; charset="+encode);
|
||||
}
|
||||
|
||||
// HEADER_GROUP 셋팅
|
||||
if (MessageType.JSON.equals(adptMsgType) && StringUtils.isNotBlank(headerGroupName)
|
||||
&& StringUtils.isNotBlank(relayRequestHeaderKeys)) {
|
||||
JSONObject jsonMessage = (JSONObject) JSONValue.parse(message);
|
||||
JSONObject headerJson = new JSONObject();
|
||||
if (StringUtils.equalsIgnoreCase(relayRequestHeaderKeys, "ALL")) {
|
||||
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
|
||||
String key = e.nextElement();
|
||||
headerJson.put(key, request.getHeader(key));
|
||||
}
|
||||
} else {
|
||||
String[] relayKeyArr = org.springframework.util.StringUtils
|
||||
.tokenizeToStringArray(relayRequestHeaderKeys, ",");
|
||||
|
||||
for (String key : relayKeyArr) {
|
||||
String headerValue = request.getHeader(key);
|
||||
if (StringUtils.isNotBlank(headerValue)) {
|
||||
headerJson.put(key, headerValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (headerJson.size() > 0) {
|
||||
jsonMessage.put(headerGroupName, headerJson);
|
||||
message = jsonMessage.toJSONString();
|
||||
}
|
||||
}
|
||||
|
||||
if (message == null) {
|
||||
message = "";
|
||||
}
|
||||
|
||||
// com.eactive.eai.custom.adapter.http.dynamic.filter.VirtualAccountCryptoFilter
|
||||
prop = addCryptoFilter(prop);
|
||||
|
||||
// 로컬 서비스 호출 ,encoding 처리 추가
|
||||
String result = (String) service(adptGrpName, adptName, message, prop, request, response);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] result " + encode + " (" + adptGrpName + ") = [" + result + "]");
|
||||
}
|
||||
|
||||
stopWatch.stop();
|
||||
|
||||
String responseData = "";
|
||||
if (RESPONSE_TYPE_ASYNC.equals(responseType)) {
|
||||
if (stopWatch.getTime() > slowTranTime && (logger.isInfo())) {
|
||||
logger.info("HttpAdapterServiceRest] dummy response time = " + stopWatch.toString() + ", message = "
|
||||
+ message);
|
||||
|
||||
}
|
||||
if (result == null) {
|
||||
responseData = ElinkConfig.getAsyncDummyDataForAdapterGroup(adptGrpName);
|
||||
}
|
||||
|
||||
response.setCharacterEncoding(encode);
|
||||
response.getWriter().print(responseData);
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||
"SEND " + "[" + responseData + "]" + CommonLib.getDumpMessage(responseData));
|
||||
}
|
||||
} else {
|
||||
responseData = result;
|
||||
logger.info("종료 >> encode = [" + encode + "]");
|
||||
|
||||
JSONObject dataObject = null;
|
||||
if (MessageType.JSON.equals(adptMsgType)) {
|
||||
dataObject = (JSONObject) JSONValue.parse(responseData);
|
||||
}
|
||||
|
||||
// HEADER_GROUP 하위 필드를 response Header에 세팅한다.
|
||||
HashMap<String, String> header = new HashMap<>();
|
||||
boolean redirect = assignHttpHeaders(header, dataObject, headerGroupName);
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] response header field (" + adptGrpName + ") = ["
|
||||
+ header.toString() + "]");
|
||||
}
|
||||
|
||||
if (redirect) {
|
||||
response.setStatus(302);
|
||||
logger.debug("HttpAdapterServiceRest] set response status_code: 302");
|
||||
} else {
|
||||
String httpStatus = header.get(HTTP_STATUS);
|
||||
if (httpStatus != null && !"".equals(httpStatus))
|
||||
response.setStatus(Integer.parseInt(httpStatus));
|
||||
header.remove(HTTP_STATUS);
|
||||
}
|
||||
|
||||
// response header 셋팅
|
||||
for (Map.Entry<String, String> entry : header.entrySet()) {
|
||||
response.setHeader(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
if (dataObject != null) {
|
||||
responseData = dataObject.toJSONString();
|
||||
}
|
||||
|
||||
// UI와 통신시(UTF-8) 변환오류로 ENCODE 제거
|
||||
response.setCharacterEncoding(encode);
|
||||
response.getWriter().print(responseData);
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpAdapterServiceRest] SEND (" + adptGrpName + ") = [" + responseData + "]");
|
||||
logger.debug("HttpAdapterServiceRest] SEND (" + adptGrpName + ") = "
|
||||
+ CommonLib.getDumpMessage(responseData));
|
||||
}
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.txlog(adptGrpName + adptName,
|
||||
"SEND " + "[" + responseData + "]" + CommonLib.getDumpMessage(responseData));
|
||||
}
|
||||
}
|
||||
} catch (HttpStatusException e) {
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.error(adptGrpName + adptName, e.toString(), e);
|
||||
}
|
||||
logger.warn("HttpAdapter] " + adptGrpName + "-" + adptName + ">>" + e.getMessage());
|
||||
response.setStatus(e.getStatus());
|
||||
try {
|
||||
String errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode, e.getCode(),
|
||||
e.getMessage(), errorResponseFormat);
|
||||
response.getWriter().println(errorMsg);
|
||||
} catch (Exception ex) {
|
||||
// IGNORE
|
||||
}
|
||||
} catch (JwtAuthException e) {
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.error(adptGrpName + adptName, e.toString(), e);
|
||||
}
|
||||
logger.error(logPrefix + adptGrpName + "-" + adptName + ">>" + e.getMessage(), e);
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
try {
|
||||
String errorMsg = MessageUtil.makeErrorMessageByMessageType(adptMsgType, encode, e.getCode(),
|
||||
e.getMessage(), errorResponseFormat);
|
||||
response.getWriter().println(errorMsg);
|
||||
} catch (Exception ex) {
|
||||
// IGNORE
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (traceLevel >= 3) {
|
||||
HttpMemoryLogger.error(adptGrpName + adptName, e.toString(), e);
|
||||
}
|
||||
logger.error(logPrefix + adptGrpName + "-" + adptName + ">>" + e.getMessage(), e);
|
||||
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
|
||||
try {
|
||||
response.getWriter().println(e.getMessage());
|
||||
String errCode = ExceptionUtil.getErrorCode(e, "RECEAIAHA003");
|
||||
throw new Exception(errCode);
|
||||
} catch (Exception ex) {
|
||||
// IGNORE
|
||||
logger.warn(logPrefix + adptGrpName + "-" + adptName + ">>" + e.getMessage(), e);
|
||||
}
|
||||
} finally {
|
||||
String uuid = prop.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
||||
String url = prop.getProperty(HttpClientAdapterServiceKey.INBOUND_EXTURI);
|
||||
String method = prop.getProperty(HttpClientAdapterServiceKey.INBOUND_METHOD);
|
||||
String adapterGroupName = prop.getProperty(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME);
|
||||
String adapterName = prop.getProperty(HttpClientAdapterServiceKey.ADAPTER_NAME);
|
||||
int httpStatusCode = response.getStatus();
|
||||
HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName, adapterName, new HashMap<>(), url, method, httpStatusCode);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String[]> assignParameterMap(HttpServletRequest request, String adptGrpName, String adptName,
|
||||
Object requestBytes, Properties prop) {
|
||||
// PathVariable 체크
|
||||
if (StringUtils.equalsAnyIgnoreCase(request.getMethod(), HttpMethod.GET.name(), HttpMethod.DELETE.name())
|
||||
&& StringUtils.isBlank(request.getQueryString())) {
|
||||
try {
|
||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
||||
RequestAction action = ActionFactory.createAction(actionName);
|
||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
||||
String[] keys = action.perform(requestBytes);
|
||||
String requestPath = keys[0];
|
||||
|
||||
// PathVariable 지원 추가
|
||||
String ruledPath = StandardMessageUtil.getMatchedKey(requestPath, actionName);
|
||||
if (!StringUtils.equals(requestPath, ruledPath) && StringUtils.contains(ruledPath, "{")) {
|
||||
Map<String, String> paramMap = new AntPathMatcher().extractUriTemplateVariables(ruledPath,
|
||||
requestPath);
|
||||
if (paramMap != null && paramMap.size() > 0) {
|
||||
Map<String, String[]> returnMap = new HashMap<>();
|
||||
for (String key : paramMap.keySet()) {
|
||||
if (StringUtils.equalsIgnoreCase(key, "method")) {
|
||||
continue;
|
||||
}
|
||||
returnMap.put(key, new String[] { paramMap.get(key) });
|
||||
}
|
||||
|
||||
return returnMap;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
return request.getParameterMap();
|
||||
}
|
||||
|
||||
private void validateServiceAndAdapter(String adptGrpName, String adptName, byte[] requestBytes, Properties prop)
|
||||
throws JwtAuthException {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* request header 를 hashmap으로 조립
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
private Properties getHeaders(HttpServletRequest request) {
|
||||
Properties prop = new Properties();
|
||||
|
||||
Enumeration<String> headerNames = request.getHeaderNames();
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String key = headerNames.nextElement();
|
||||
String value = request.getHeader(key);
|
||||
prop.setProperty(key, value);
|
||||
}
|
||||
|
||||
return prop;
|
||||
}
|
||||
|
||||
/**
|
||||
* adapter property의 HEADER_GROUP으로 정의된 (MFE_HEADER) 그룹의 하위 필드를 http Header에
|
||||
* 세팅한다.
|
||||
*
|
||||
* @param header
|
||||
* @param object
|
||||
*/
|
||||
private boolean assignHttpHeaders(HashMap<String, String> header, Object msg, String headerGroupName) {
|
||||
boolean redirect = false;
|
||||
|
||||
if (msg == null || StringUtils.isBlank(headerGroupName)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (msg instanceof JSONObject) {
|
||||
JSONObject headerObject = (JSONObject) ((JSONObject) msg).get(headerGroupName);
|
||||
|
||||
if (headerObject == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// List<String> headerKeys = new ArrayList<>();
|
||||
for (Object key : headerObject.keySet()) {
|
||||
|
||||
Object obj = headerObject.get(key);
|
||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
header.put((String) key, (String) obj);
|
||||
|
||||
if (StringUtils.equalsIgnoreCase((String) key, "Location")) {
|
||||
redirect = true;
|
||||
}
|
||||
}
|
||||
|
||||
((JSONObject) msg).remove(headerGroupName);
|
||||
}
|
||||
|
||||
return redirect;
|
||||
}
|
||||
|
||||
/**
|
||||
* 어댑터 명 이후의 URI값을 가져온다.
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
private String getExtUri(HttpServletRequest request) {
|
||||
String orgUri = request.getRequestURI().replaceAll(request.getContextPath(), "");
|
||||
String uri = getExtUri(orgUri, 3);
|
||||
if (uri != null && uri.trim().length() > 0) {
|
||||
return "/" + uri;
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static String getExtUri(String url, int length) {
|
||||
String[] urls = url.split("/");
|
||||
List<String> newUrls = new ArrayList<>();
|
||||
Collections.addAll(newUrls, urls);
|
||||
return StringUtils.join(newUrls.subList(length, urls.length).toArray(), "/");
|
||||
}
|
||||
|
||||
// public static void main(String[] args) throws Exception {
|
||||
// String orgUri = "/HTT/CbsInNetSys/abcd/123456";
|
||||
// String result = "";
|
||||
// result = getExtUri(orgUri, 3);
|
||||
// System.out.println(result);
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.eactive.eai.custom.adapter.http.util;
|
||||
|
||||
import com.eactive.eai.util.TestModeChecker;
|
||||
|
||||
import com.cubeone.CubeOneAPI;
|
||||
|
||||
public class CubeOneCryptoUtil {
|
||||
private static boolean testMode = TestModeChecker.isTestMode();
|
||||
|
||||
public static String encryptPI(String plainText) throws Exception {
|
||||
// FIXME : kbank - kbank내애서는 testMode 체크 제거 검토
|
||||
if (testMode) {
|
||||
return plainText;
|
||||
} else {
|
||||
String encryptedText = null;
|
||||
byte errbyte[] = new byte[5];
|
||||
byte[] inbyte;
|
||||
try {
|
||||
inbyte = plainText.getBytes();
|
||||
encryptedText = CubeOneAPI.coencbytes(inbyte, inbyte.length, "AES_PI", 11, null, null, errbyte);
|
||||
} catch (UnsatisfiedLinkError e) {
|
||||
throw new Exception("encryptPI error - ", e);
|
||||
} catch (Exception e) {
|
||||
throw new Exception("encryptPI error - ", e);
|
||||
}
|
||||
//
|
||||
|
||||
if (errbyte[0] != 48) {
|
||||
throw new Exception("encryptPI error - " + new String(errbyte));
|
||||
}
|
||||
return encryptedText;
|
||||
}
|
||||
}
|
||||
|
||||
public static String decryptPI(String encryptedText) throws Exception {
|
||||
// FIXME : kbank - kbank내애서는 testMode 체크 제거 검토
|
||||
if (testMode) {
|
||||
return encryptedText;
|
||||
} else {
|
||||
String decryptedText = null;
|
||||
byte errbyte[] = new byte[5];
|
||||
byte[] decbyte;
|
||||
decbyte = CubeOneAPI.codecbyte(encryptedText, "AES_PI", 11, null, null, errbyte);
|
||||
if (decbyte != null) {
|
||||
decryptedText = new String(decbyte);
|
||||
}
|
||||
if (errbyte[0] != 48) {
|
||||
throw new Exception("decryptPI error - " + new String(errbyte));
|
||||
}
|
||||
return decryptedText;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.eactive.eai.custom.adapter.http.util;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
public class GzipBase64Util {
|
||||
|
||||
private static final String DEFAULT_CAHRSET = "UTF-8";
|
||||
|
||||
public static void main(String[] args) {
|
||||
String originalString = "압축하고 인코딩할 문자열입니다.";
|
||||
|
||||
try {
|
||||
String base64EncodedData = compress(originalString);
|
||||
|
||||
System.out.println("Original String: " + originalString);
|
||||
System.out.println("Base64 Encoded String: " + base64EncodedData);
|
||||
|
||||
// Base64 디코딩 후 gzip 압축 해제
|
||||
String decodedString = decompress(base64EncodedData);
|
||||
|
||||
System.out.println("Decoded String: " + decodedString);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static String compress(String plainText) throws IOException {
|
||||
if (plainText == null || plainText.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
|
||||
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
|
||||
gzipOutputStream.write(plainText.getBytes(DEFAULT_CAHRSET));
|
||||
}
|
||||
byte[] compressedData = byteArrayOutputStream.toByteArray();
|
||||
return Base64.getEncoder().encodeToString(compressedData);
|
||||
}
|
||||
}
|
||||
|
||||
public static String decompress(String base64EncodedData) throws IOException {
|
||||
|
||||
if (base64EncodedData == null || base64EncodedData.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
byte[] compressedData = Base64.getDecoder().decode(base64EncodedData);
|
||||
|
||||
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
|
||||
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressedData);
|
||||
GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream)) {
|
||||
|
||||
byte[] buffer = new byte[1024];
|
||||
int len;
|
||||
while ((len = gzipInputStream.read(buffer)) > 0) {
|
||||
byteArrayOutputStream.write(buffer, 0, len);
|
||||
}
|
||||
}
|
||||
return byteArrayOutputStream.toString(DEFAULT_CAHRSET);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.eactive.eai.custom.adapter.http.util;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.eactive.eai.util.CryptoUtil;
|
||||
import com.eactive.eai.util.json.transformer.ValueTransformer;
|
||||
|
||||
public class ToAesTransformer implements ValueTransformer<String, String> {
|
||||
public static final String AESKEY = "AESKEY";
|
||||
public static final String PLAIN_VALUE = "PLAIN_VALUE";
|
||||
private final Map<String, Object> properties = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public void setProperty(String propertyName, Object value) {
|
||||
properties.put(propertyName, value);
|
||||
}
|
||||
@Override
|
||||
public String getProperty(String propertyName) {
|
||||
return (String)properties.get(propertyName);
|
||||
}
|
||||
@Override
|
||||
public String transform(String value) throws Exception {
|
||||
String apiKey = (String) properties.get(ToAesTransformer.AESKEY);
|
||||
String text = CubeOneCryptoUtil.decryptPI(value);
|
||||
properties.put(PLAIN_VALUE, text);
|
||||
return CryptoUtil.encryptAES(apiKey, text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.eactive.eai.custom.adapter.http.util;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.eactive.eai.util.CryptoUtil;
|
||||
import com.eactive.eai.util.json.transformer.ValueTransformer;
|
||||
|
||||
public class ToCubeOneTransformer implements ValueTransformer<String, String> {
|
||||
public static final String AESKEY = "AESKEY";
|
||||
public static final String PLAIN_VALUE = "PLAIN_VALUE";
|
||||
private final Map<String, Object> properties = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public void setProperty(String propertyName, Object value) {
|
||||
properties.put(propertyName, value);
|
||||
}
|
||||
@Override
|
||||
public String getProperty(String propertyName) {
|
||||
return (String)properties.get(propertyName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String transform(String value) throws Exception {
|
||||
String apiKey = (String) properties.get(ToCubeOneTransformer.AESKEY);
|
||||
String text = CryptoUtil.decryptAES(apiKey, value);
|
||||
properties.put(PLAIN_VALUE, text);
|
||||
return CubeOneCryptoUtil.encryptPI(text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.eactive.eai.custom.adapter.http.util;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.eactive.eai.util.CryptoUtil;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
public class VirtualAccountBatchUtil {
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
public String getGzipValue(String jsonString, String path) {
|
||||
try {
|
||||
JsonNode rootNode = mapper.readTree(jsonString);
|
||||
JsonNode childNode = rootNode.get(path);
|
||||
String gzippedValue = childNode.asText();
|
||||
return gzippedValue;
|
||||
}
|
||||
catch(Exception ex) {
|
||||
ex.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// AZZ22-%d{yyyyMMdd}-%d{hhmmss}.enc -> AZZ22-20240924-093257.enc
|
||||
public static String updateDatePattern(String patterm) {
|
||||
String str[] = patterm.split("%d");
|
||||
String converted = "";
|
||||
for(int i=0; i<str.length; i++){
|
||||
if(i<1){
|
||||
converted = str[i];
|
||||
}else{
|
||||
String newMsg = "%d"+str[i];
|
||||
Matcher matcher = Pattern.compile("%d\\{([a-zA-Z \\-]+)\\}").matcher(newMsg);
|
||||
if (matcher.find()) {
|
||||
String datePattern = matcher.group(1);
|
||||
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(datePattern);
|
||||
converted = converted + newMsg.replaceAll("%d\\{([a-zA-Z \\-]+)\\}", dateFormat.format(ZonedDateTime.now()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return converted;
|
||||
}
|
||||
|
||||
// FIXME : kbank - 배치 파일명 생성 규칙에 따라 수정
|
||||
public String unzipAndSave(String aesKey, String jsonString, String rootFilePath, String fileNamePattern) throws Exception {
|
||||
// gzippedValue 추출
|
||||
String gzippedValue = getGzipValue(jsonString, "encData");
|
||||
System.out.println("gzippedValue[" + gzippedValue + "]");
|
||||
|
||||
// 압축 해제
|
||||
String unziped = GzipBase64Util.decompress(gzippedValue);
|
||||
// AES 복호화
|
||||
String text = CryptoUtil.decryptAES(aesKey, unziped);
|
||||
|
||||
// 현재 처리 시각을 기반으로 파일명 생성
|
||||
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
|
||||
// String fileName = LocalDateTime.now().format(formatter) + ".txt";
|
||||
|
||||
String fileName = updateDatePattern(fileNamePattern);
|
||||
// TODO : Add additional pattern logic
|
||||
|
||||
String filePath = Paths.get(rootFilePath, fileName).toString();
|
||||
|
||||
Files.write(Paths.get(filePath), text.getBytes(), StandardOpenOption.CREATE);
|
||||
|
||||
// 결과 JSON 구성
|
||||
ObjectNode replacedJson = mapper.createObjectNode();
|
||||
replacedJson.put("filePath", filePath);
|
||||
replacedJson.put("fileName", fileName);
|
||||
return replacedJson.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.eactive.eai.custom.adapter.http.util;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.util.json.JsonPathsTransform;
|
||||
import com.eactive.eai.util.json.transformer.ValueTransformer;
|
||||
|
||||
public class VirtualAccountTransform {
|
||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
||||
|
||||
public static String toAES(String aesKey, List<String> encFieldPaths, String message) {
|
||||
ToAesTransformer encTramsformer = new ToAesTransformer();
|
||||
encTramsformer.setProperty("AESKEY", aesKey);
|
||||
|
||||
Map<String, ValueTransformer<String, String>> pathTransformerMap = new HashMap<>();
|
||||
for (String path : encFieldPaths) {
|
||||
pathTransformerMap.put(path.trim(), encTramsformer);
|
||||
}
|
||||
String modifiedJsonString = JsonPathsTransform.modifyValuesAtPaths(message, pathTransformerMap, false);
|
||||
|
||||
return modifiedJsonString;
|
||||
}
|
||||
|
||||
public static byte[] toCubeOne(String aesKey, List<String> encFieldPaths, byte[] messageBytes) {
|
||||
String defaultCharset = "utf-8";
|
||||
try {
|
||||
String message = new String(messageBytes, defaultCharset);
|
||||
String retMessage = toCubeOne(aesKey, encFieldPaths, message);
|
||||
return retMessage.getBytes(defaultCharset);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
return messageBytes;
|
||||
}
|
||||
}
|
||||
|
||||
public static String toCubeOne(String aesKey, List<String> encFieldPaths, String message) {
|
||||
ToCubeOneTransformer encTramsformer = new ToCubeOneTransformer();
|
||||
|
||||
if(logger.isDebug()) {
|
||||
logger.debug("AESKEY=" + aesKey);
|
||||
}
|
||||
encTramsformer.setProperty("AESKEY", aesKey);
|
||||
|
||||
Map<String, ValueTransformer<String, String>> pathTransformerMap = new HashMap<>();
|
||||
for (String path : encFieldPaths) {
|
||||
pathTransformerMap.put(path.trim(), encTramsformer);
|
||||
}
|
||||
String modifiedJsonString = JsonPathsTransform.modifyValuesAtPaths(message, pathTransformerMap, false);
|
||||
|
||||
return modifiedJsonString;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String aesKey = "ONAuROzlqWB4VuBwO5C/FA==";
|
||||
String text = "Hello AES 한글";
|
||||
String encText = "3hQyg4xrUrFQt09XKLkmutQ4pZyuKc242LGQ1dyDMTg=";
|
||||
String json = "{\"encAccount\":\"3hQyg4xrUrFQt09XKLkmutQ4pZyuKc242LGQ1dyDMTg=\"}";
|
||||
List<String> list = new ArrayList<>();
|
||||
list.add(" $.encAccount ");
|
||||
list.add(" $.accounts$.encAccount ");
|
||||
String cubeOneJson = toCubeOne(aesKey, list, json);
|
||||
System.out.println(cubeOneJson);
|
||||
System.out.println(toAES(aesKey, list, cubeOneJson));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
package com.eactive.eai.custom.inflow;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Calendar;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.common.dao.DAOFactory;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.inflow.CustomBucket;
|
||||
import com.eactive.eai.common.inflow.InflowControlDAO;
|
||||
import com.eactive.eai.common.inflow.InflowControlManager;
|
||||
import com.eactive.eai.common.inflow.InflowTargetVO;
|
||||
import com.eactive.eai.common.lifecycle.Lifecycle;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleException;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleListener;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleSupport;
|
||||
import com.eactive.eai.common.message.EAIMessage;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
import io.github.bucket4j.Bandwidth;
|
||||
import io.github.bucket4j.Bucket4j;
|
||||
import io.github.bucket4j.local.LocalBucketBuilder;
|
||||
|
||||
public class InflowControlManagerSBI implements Lifecycle, com.eactive.eai.common.inflow.Bucket
|
||||
{
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
private static InflowControlManagerSBI manager;
|
||||
|
||||
private HashMap<String,CustomBucket> adapterBucketList;
|
||||
private HashMap<String,CustomBucket> interfaceBucketList;
|
||||
private boolean started;
|
||||
private LifecycleSupport lifecycle = new LifecycleSupport(this);
|
||||
|
||||
/**
|
||||
* 1. 기능 : Default Constructor
|
||||
* 2. 처리 개요 : C2RServiceVO Rule 정보를 저장하기 위한 HashMap을 초기화한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
private InflowControlManagerSBI() {
|
||||
adapterBucketList = new HashMap<String, CustomBucket>();
|
||||
interfaceBucketList = new HashMap<String, CustomBucket>();
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : InflowControlManagerSBI Singleton Object를 반환하는 getter method
|
||||
* 2. 처리 개요 : C2RServiceManager Singleton Object를 반환한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @return InflowControlManagerSBI Singleton object
|
||||
**/
|
||||
public static InflowControlManagerSBI getInstance() {
|
||||
if(manager == null) {
|
||||
synchronized(InflowControlManagerSBI.class) {
|
||||
if(manager == null) {
|
||||
manager = new InflowControlManagerSBI();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return manager;
|
||||
}
|
||||
|
||||
public static com.eactive.eai.common.inflow.Bucket getBucket() {
|
||||
if(manager == null) {
|
||||
synchronized(InflowControlManagerSBI.class) {
|
||||
if(manager == null) {
|
||||
manager = new InflowControlManagerSBI();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* 유량제어 대상인 거래인지 체크한다.(사이트에 맞게 구성)
|
||||
* @param eaiServerManager
|
||||
* @param eaiMessage
|
||||
* @return
|
||||
*/
|
||||
public static Boolean isTargetOfInflowControl(EAIServerManager eaiServerManager, EAIMessage eaiMessage) {
|
||||
// 1. 모든 요청거래
|
||||
InterfaceMapper mapper = eaiMessage.getMapper();
|
||||
String returnType = mapper.getSendRecvDivision(eaiMessage.getStandardMessage()); // S|R
|
||||
|
||||
if (STDMessageKeys.SEND_RECV_CD_SEND.equals(returnType)) {
|
||||
return new Boolean(true);
|
||||
}
|
||||
|
||||
return new Boolean(false);
|
||||
}
|
||||
|
||||
public void start() throws LifecycleException {
|
||||
if (started)
|
||||
throw new LifecycleException("RECEAICMM201");
|
||||
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
|
||||
|
||||
// C2RServiceVO Table Initializing ....
|
||||
|
||||
try {
|
||||
init();
|
||||
} catch(Exception e) {
|
||||
//throw new LifecycleException("RECEAICMM202");
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e,"RECEAICMM202"));
|
||||
}
|
||||
|
||||
started = true;
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
|
||||
}
|
||||
|
||||
private void init() throws Exception {
|
||||
initAdapter();
|
||||
initInterface();
|
||||
}
|
||||
|
||||
private void initAdapter() throws Exception {
|
||||
// Initializing ....
|
||||
adapterBucketList = new HashMap<String, CustomBucket>();
|
||||
InflowControlDAO dao = null;
|
||||
dao = (InflowControlDAO) DAOFactory.newInstance().create(InflowControlDAO.class);
|
||||
List<InflowTargetVO> inflowAdapterVoList = dao.getInflowAdapterList();
|
||||
|
||||
for (InflowTargetVO inflowVo : inflowAdapterVoList) {
|
||||
if (InflowControlManagerSBI.isInflowTarget(inflowVo)) {
|
||||
CustomBucket bucket = makeBucketUsingInflowVO(inflowVo);
|
||||
if (bucket != null) {
|
||||
adapterBucketList.put(inflowVo.getName(), bucket);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void initInterface() throws Exception {
|
||||
// Initializing ....
|
||||
interfaceBucketList = new HashMap<String, CustomBucket>();
|
||||
InflowControlDAO dao = null;
|
||||
dao = (InflowControlDAO) DAOFactory.newInstance().create(InflowControlDAO.class);
|
||||
List<InflowTargetVO> inflowInterfaceVoList = dao.getInflowInterfaceList();
|
||||
|
||||
for (InflowTargetVO inflowVo : inflowInterfaceVoList) {
|
||||
if (InflowControlManagerSBI.isInflowTarget(inflowVo)) {
|
||||
CustomBucket bucket = makeBucketUsingInflowVO(inflowVo);
|
||||
if (bucket != null) {
|
||||
interfaceBucketList.put(inflowVo.getName(), bucket);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void reloadAdapter() throws Exception {
|
||||
if(logger.isWarn()) {
|
||||
logger.warn("InflowControlManagerSBI] reload all Started ...");
|
||||
}
|
||||
initAdapter();
|
||||
if(logger.isWarn()) {
|
||||
logger.warn("InflowControlManagerSBI] reload all finished ...");
|
||||
}
|
||||
}
|
||||
public synchronized void reloadInterface() throws Exception {
|
||||
if(logger.isWarn()) {
|
||||
logger.warn("InflowControlManagerSBI] reload all Started ...");
|
||||
}
|
||||
initInterface();
|
||||
if(logger.isWarn()) {
|
||||
logger.warn("InflowControlManagerSBI] reload all finished ...");
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void reloadAdapter(String adapter) throws Exception {
|
||||
if (logger.isWarn()) {
|
||||
logger.warn("InflowControlManagerSBI] reload Started ...");
|
||||
}
|
||||
InflowControlDAO dao = null;
|
||||
dao = (InflowControlDAO) DAOFactory.newInstance().create(InflowControlDAO.class);
|
||||
Map<String, InflowTargetVO> map = dao.getInflowTargetByAdater(adapter);
|
||||
if (map != null) {
|
||||
Iterator it = map.keySet().iterator();
|
||||
String key = "";
|
||||
for (int i = 0; it.hasNext(); i++) {
|
||||
key = (String) it.next();
|
||||
|
||||
InflowTargetVO inflowTarget = map.get(key);
|
||||
if (InflowControlManagerSBI.isInflowTarget(inflowTarget)) {
|
||||
CustomBucket bucket = makeBucketUsingInflowVO(inflowTarget);
|
||||
if (bucket != null) {
|
||||
adapterBucketList.put(inflowTarget.getName(), bucket);
|
||||
} else {
|
||||
adapterBucketList.remove(inflowTarget.getName());
|
||||
}
|
||||
} else {
|
||||
adapterBucketList.remove(inflowTarget.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (logger.isWarn()) {
|
||||
logger.warn("InflowControlManagerSBI] reload finished ...");
|
||||
}
|
||||
}
|
||||
public synchronized void reloadInterface(String inter) throws Exception {
|
||||
if (logger.isWarn()) {
|
||||
logger.warn("InflowControlManagerSBI] reload Started ...");
|
||||
}
|
||||
InflowControlDAO dao = null;
|
||||
dao = (InflowControlDAO) DAOFactory.newInstance().create(InflowControlDAO.class);
|
||||
Map<String, InflowTargetVO> map = dao.getInflowTargetByInterface(inter);
|
||||
if (map != null) {
|
||||
Iterator it = map.keySet().iterator();
|
||||
String key = "";
|
||||
for (int i = 0; it.hasNext(); i++) {
|
||||
key = (String) it.next();
|
||||
|
||||
InflowTargetVO inflowTarget = map.get(key);
|
||||
if (InflowControlManagerSBI.isInflowTarget(inflowTarget)) {
|
||||
CustomBucket bucket = makeBucketUsingInflowVO(inflowTarget);
|
||||
if (bucket != null) {
|
||||
interfaceBucketList.put(inflowTarget.getName(), bucket);
|
||||
} else {
|
||||
interfaceBucketList.remove(inflowTarget.getName());
|
||||
}
|
||||
} else {
|
||||
interfaceBucketList.remove(inflowTarget.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (logger.isWarn()) {
|
||||
logger.warn("InflowControlManagerSBI] reload finished ...");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : Lifecycle의 stop 메서드로 C2RServiceManager를 종료하는 메서드
|
||||
* 2. 처리 개요 : 멤버에 캐싱한 C2RServiceVO Rule 정보를 clear한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @exception LifecycleException 이미 종료된 경우 발생(RECEAICMM203)
|
||||
**/
|
||||
public void stop() throws LifecycleException {
|
||||
// Validate and update our current component state
|
||||
if (!started)
|
||||
throw new LifecycleException("RECEAICMM203");
|
||||
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
|
||||
|
||||
adapterBucketList.clear();
|
||||
interfaceBucketList.clear();
|
||||
|
||||
started = false;
|
||||
// Notify our interested LifecycleListeners
|
||||
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : LifecycleListener를 등록하는 메서드
|
||||
* 2. 처리 개요 : LifecycleListener를 등록한다.
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @param listener LifecycleEvent를 수신한 LifecycleListener
|
||||
**/
|
||||
public void addLifecycleListener(LifecycleListener listener)
|
||||
{
|
||||
lifecycle.addLifecycleListener(listener);
|
||||
}
|
||||
|
||||
public LifecycleListener[] findLifecycleListeners()
|
||||
{
|
||||
return lifecycle.findLifecycleListeners();
|
||||
}
|
||||
|
||||
public void removeLifecycleListener(LifecycleListener listener)
|
||||
{
|
||||
lifecycle.removeLifecycleListener(listener);
|
||||
}
|
||||
|
||||
public boolean isStarted() {
|
||||
return this.started;
|
||||
}
|
||||
|
||||
public String[] getAdapterAllKeys() {
|
||||
Iterator it = this.adapterBucketList.keySet().iterator();
|
||||
String[] svcCd = new String[this.adapterBucketList.size()];
|
||||
for(int i = 0; it.hasNext(); i++){
|
||||
svcCd[i] = (String)it.next();
|
||||
}
|
||||
Arrays.sort(svcCd);
|
||||
return svcCd;
|
||||
}
|
||||
public String[] getInterfaceAllKeys() {
|
||||
Iterator it = this.interfaceBucketList.keySet().iterator();
|
||||
String[] svcCd = new String[this.interfaceBucketList.size()];
|
||||
for(int i = 0; it.hasNext(); i++){
|
||||
svcCd[i] = (String)it.next();
|
||||
}
|
||||
Arrays.sort(svcCd);
|
||||
return svcCd;
|
||||
}
|
||||
|
||||
public void removeAdapter(String adapter) {
|
||||
adapterBucketList.remove(adapter);
|
||||
}
|
||||
public void removeInterface(String inter) {
|
||||
interfaceBucketList.remove(inter);
|
||||
}
|
||||
|
||||
private CustomBucket makeBucketUsingInflowVO(InflowTargetVO inflowTarget) {
|
||||
if (InflowControlManagerSBI.isInflowTarget(inflowTarget)) {
|
||||
LocalBucketBuilder builder = Bucket4j.builder();
|
||||
if (inflowTarget.getThresholdPerSecond() > 0) { // TPS
|
||||
builder.addLimit(Bandwidth.simple(inflowTarget.getThresholdPerSecond(), Duration.ofSeconds(1)));
|
||||
}
|
||||
|
||||
if (inflowTarget.getThreshold() > 0 && StringUtils.isNotBlank(inflowTarget.getThresholdTimeUnit())) {
|
||||
builder.addLimit(Bandwidth.simple(inflowTarget.getThreshold(),
|
||||
InflowControlManagerSBI.getPeriod(inflowTarget.getThresholdTimeUnit())));
|
||||
}
|
||||
|
||||
return new CustomBucket(builder.build(), inflowTarget);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAdapterPass(String adapter) {
|
||||
CustomBucket b = adapterBucketList.get(adapter);
|
||||
|
||||
if ( b == null ) return true;
|
||||
|
||||
return b.getLocalBucket().tryConsume(1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInterfacePass(String inter) {
|
||||
CustomBucket b = interfaceBucketList.get(inter);
|
||||
|
||||
if ( b == null ) return true;
|
||||
|
||||
return b.getLocalBucket().tryConsume(1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InflowTargetVO getAdapterInflowThreashold(String adapter) {
|
||||
CustomBucket b = adapterBucketList.get(adapter);
|
||||
if (b == null) return null;
|
||||
return b.getInflowTargetVo();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InflowTargetVO getInterfaceInflowThreashold(String inter) {
|
||||
CustomBucket b = interfaceBucketList.get(inter);
|
||||
if (b == null) return null;
|
||||
return b.getInflowTargetVo();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InflowTargetVO getInflowThreashold(String inter) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public InflowTargetVO getAdapterInflow(String adapter) {
|
||||
CustomBucket b = adapterBucketList.get(adapter);
|
||||
if (b == null) return null;
|
||||
return b.getInflowTargetVo();
|
||||
}
|
||||
|
||||
public InflowTargetVO getInterfaceInflow(String inter) {
|
||||
CustomBucket b = interfaceBucketList.get(inter);
|
||||
if (b == null) return null;
|
||||
return b.getInflowTargetVo();
|
||||
}
|
||||
|
||||
public static boolean isInflowTarget(InflowTargetVO inflowTarget) {
|
||||
if (inflowTarget == null || !inflowTarget.isActivate()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (inflowTarget.getThresholdPerSecond() > 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (inflowTarget.getThreshold() > 0 && StringUtils.equalsAnyIgnoreCase(inflowTarget.getThresholdTimeUnit(),
|
||||
InflowControlManager.QUOTA_TIMEUNIT_DAY, InflowControlManager.QUOTA_TIMEUNIT_SECOND,
|
||||
InflowControlManager.QUOTA_TIMEUNIT_MINUTE, InflowControlManager.QUOTA_TIMEUNIT_HOUR,
|
||||
InflowControlManager.QUOTA_TIMEUNIT_DAY, InflowControlManager.QUOTA_TIMEUNIT_MONTH)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static Duration getPeriod(String timeUnit) {
|
||||
if (StringUtils.equalsIgnoreCase(timeUnit, InflowControlManager.QUOTA_TIMEUNIT_SECOND)) {
|
||||
return Duration.ofSeconds(1);
|
||||
} else if (StringUtils.equalsIgnoreCase(timeUnit, InflowControlManager.QUOTA_TIMEUNIT_MINUTE)) {
|
||||
return Duration.ofMinutes(1);
|
||||
} else if (StringUtils.equalsIgnoreCase(timeUnit, InflowControlManager.QUOTA_TIMEUNIT_HOUR)) {
|
||||
return Duration.ofHours(1);
|
||||
} else if (StringUtils.equalsIgnoreCase(timeUnit, InflowControlManager.QUOTA_TIMEUNIT_DAY)) {
|
||||
return Duration.ofDays(1);
|
||||
} else if (StringUtils.equalsIgnoreCase(timeUnit, InflowControlManager.QUOTA_TIMEUNIT_MONTH)) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
return Duration.ofDays(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.message.StandardItem;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.filter.MessageFilter;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class FlatMessageFilterKAKAOCARD implements MessageFilter {
|
||||
|
||||
@Override
|
||||
public StandardMessage doFilter(StandardMessage message) {
|
||||
|
||||
// 카카오은행 기준
|
||||
// 전체길이(8) : 전체길이포함 전체
|
||||
// 헤더 : 150
|
||||
// 공통부: 850
|
||||
// DATA헤더 : 10
|
||||
// DATA : ?
|
||||
// 종료 : @@ : 2
|
||||
// 예) DATA가 320byte이면 전체길이는 1332 임
|
||||
|
||||
// 요청시 MESSAGE 부가 없음
|
||||
// 응답시 MESSAGE 부가 있음
|
||||
|
||||
boolean isMessageHidden = true;
|
||||
// 아래로직은 표준전문에서 요청일때 MESSAGE부가 안보이고 응답일때 MESSAGE부 보이게 설정
|
||||
StandardItem mesgDmanDvcd = message.findItem("Header.MESG_DMAN_DVCD");
|
||||
if (mesgDmanDvcd != null && StringUtils.equals(mesgDmanDvcd.getValue(), "R")) {
|
||||
isMessageHidden = false;
|
||||
}
|
||||
|
||||
// message부 보이기 여부
|
||||
StandardItem msg = message.findItem("MSG");
|
||||
// 아래로직은 표준전문에서 요청일때 MESSAGE부가 안보이고 응답일때 MESSAGE부 보이게 설정
|
||||
msg.setHidden(isMessageHidden);
|
||||
|
||||
int totalSize = 0; // 전체 길이 ( 메시지여부에 따라 변경됨)
|
||||
int ioSize = 0; // 데이터부 길이
|
||||
int messageSize = 0; // 메시지부 길이
|
||||
|
||||
try {
|
||||
ioSize = message.getBizDataBytes().length;
|
||||
// 데이터부 길이 설정
|
||||
StandardItem dataHedrLen = message.findItem("DataPart.DataHeader.DATA_HEDR_LEN");
|
||||
dataHedrLen.setValue(String.valueOf(ioSize));
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
try {
|
||||
messageSize = message.getBytesDataLengthForPath("MSG");
|
||||
if (messageSize > 10) {
|
||||
StandardItem msgLen = message.findItem("MSG.MSG_HEDR_LEN");
|
||||
msgLen.setValue(String.valueOf(messageSize - 10));
|
||||
}
|
||||
StandardItem msgCnt = message.findItem("MSG.OUTPUT_MSG_NCNT");
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
|
||||
if (isMessageHidden) {
|
||||
// 전체길이 = 150 + 850 + 메시지부길이(X) + DATA부(10) + bizData(?) +종료부(2)
|
||||
totalSize = 150 + 850 + 0 + 10 + ioSize + 2;
|
||||
} else {
|
||||
// 전체길이 = 150 + 850 + 메시지부길이(배열존재(출력메시지개수)) + DATA부(10) + bizData +종료부(2)
|
||||
totalSize = 150 + 850 + messageSize + 10 + ioSize + 2;
|
||||
}
|
||||
// 전체 길이 셋팅
|
||||
try {
|
||||
message.setLlData(String.valueOf(totalSize));
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.message.StandardItem;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.filter.MessageFilter;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class FlatMessageFilterSBI implements MessageFilter {
|
||||
|
||||
@Override
|
||||
public StandardMessage doFilter(StandardMessage message) {
|
||||
// total 메시지 길이 설정
|
||||
int totalSize = 0;
|
||||
try {
|
||||
totalSize = message.getBytesDataLength();
|
||||
message.setLlData(String.valueOf(totalSize));
|
||||
} catch (Exception e) {
|
||||
}
|
||||
|
||||
// whlMesgLen=전체길이 - 채널헤더길이(24) - ZZ(2)
|
||||
try {
|
||||
StandardItem whlMesgLenItem = message.findItem("STD_HEADER.whlMesgLen");
|
||||
if (whlMesgLenItem != null) {
|
||||
int whlMesgLen = totalSize - 24 - 2;
|
||||
whlMesgLenItem.setValue(String.valueOf(whlMesgLen));
|
||||
}
|
||||
|
||||
// stndHdrLen=전체길이 - 채널헤더길이(24) - bizData길이 - ZZ(2)
|
||||
StandardItem stndHdrLenItem = message.findItem("STD_HEADER.stndHdrLen");
|
||||
if (stndHdrLenItem != null) {
|
||||
int stndHdrLen = totalSize - 24 - message.getBizDataBytes().length - 2;
|
||||
stndHdrLenItem.setValue(String.valueOf(stndHdrLen));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
}
|
||||
|
||||
// STD_HEADER.rsltCd 설정
|
||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = standardManager.getMapper();
|
||||
if (StringUtils.equals(mapper.getSendRecvDivision(message), "R")) {
|
||||
StandardItem rsltCdItem = message.findItem("STD_HEADER.rsltCd");
|
||||
if (StringUtils.equals(mapper.getResponseType(message), STDMessageKeys.RESPONSE_TYPE_CODE_N)) {
|
||||
rsltCdItem.setValue("00"); // STD_MSG_RSLT_CD_SUCCESS
|
||||
} else {
|
||||
rsltCdItem.setValue("99"); // STD_MSG_RSLT_CD_ERROR_UNKNOWN
|
||||
}
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.common.server.Keys;
|
||||
import com.eactive.eai.common.util.StringUtil;
|
||||
import com.eactive.eai.common.util.UUID;
|
||||
|
||||
/**
|
||||
* 1. 기능 : UUID Generation Class 2. 처리 개요 : * - 3. 주의사항
|
||||
*
|
||||
* @author :
|
||||
* @version : v 1.0.0
|
||||
* @see : 관련 기능을 참조
|
||||
* @since : :
|
||||
*/
|
||||
public final class GUIDGeneratorKAKAOCARD {
|
||||
|
||||
private static final DateTimeFormatter SDF_YYYYMMDDHHMMSSMS = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
|
||||
|
||||
/*
|
||||
* 날짜(17) + "-"(1) + 시스템코드(3) + hostname(6) + 일련번호(5) + "-"(1) + 001(3)
|
||||
*
|
||||
*/
|
||||
|
||||
public static final int GUID_LENGTH = 33; // seq값 제외부분
|
||||
|
||||
/**
|
||||
* 1. 기능 : Private 생성자 2. 처리 개요 : - 3. 주의사항 - Instance 생성하지 못함
|
||||
**/
|
||||
private GUIDGeneratorKAKAOCARD() {
|
||||
}
|
||||
|
||||
public synchronized static String getGUID(String systemCode) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(SDF_YYYYMMDDHHMMSSMS.format(ZonedDateTime.now()));
|
||||
sb.append("-");
|
||||
sb.append(systemCode);
|
||||
sb.append(UNIQUE_NUM);
|
||||
char[] formatSeq = { '0', '0', '0', '0', '0' };
|
||||
char[] seqCharArray = String.valueOf(seq).toCharArray();
|
||||
int destPos = formatSeq.length - seqCharArray.length;
|
||||
System.arraycopy(seqCharArray, 0, formatSeq, destPos, seqCharArray.length);
|
||||
|
||||
sb.append(formatSeq);
|
||||
seq++;
|
||||
if (seq > 99999) {
|
||||
seq = 1;
|
||||
}
|
||||
|
||||
return sb.toString() + "-" + "001";
|
||||
}
|
||||
|
||||
private static String UNIQUE_NUM;
|
||||
private static int seq = 1;
|
||||
private static int hostlength = 6;
|
||||
static {
|
||||
String uniqueValue = System.getProperty(Keys.SERVER_KEY);
|
||||
if (StringUtils.isBlank(uniqueValue)) {
|
||||
try {
|
||||
uniqueValue = java.net.InetAddress.getLocalHost().getHostName();
|
||||
} catch (Exception e) {
|
||||
uniqueValue = StringUtil.stringFormat("", false, 'X', hostlength);
|
||||
}
|
||||
}
|
||||
if (uniqueValue.length() > hostlength) {
|
||||
uniqueValue = uniqueValue.substring(uniqueValue.length() - hostlength, uniqueValue.length());
|
||||
} else if (uniqueValue.length() < hostlength) {
|
||||
uniqueValue = StringUtil.stringFormat(uniqueValue, false, 'X', hostlength);
|
||||
}
|
||||
UNIQUE_NUM = uniqueValue.toUpperCase();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String guid = getGUID("FEP");
|
||||
System.out.println("[" + guid.length() + "]" + guid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import com.eactive.eai.common.server.Keys;
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.common.util.StringUtil;
|
||||
|
||||
public class GUIDGeneratorKBANK {
|
||||
private static String UNIQUE_NUM;
|
||||
private static int seq = 1;
|
||||
|
||||
static {
|
||||
String uniqueValue = System.getProperty(Keys.SERVER_KEY);
|
||||
if(uniqueValue.length() < 8) {
|
||||
uniqueValue = StringUtil.stringFormat(uniqueValue, false, '0', 8);
|
||||
}else if(uniqueValue.length() > 8){
|
||||
uniqueValue = uniqueValue.substring(uniqueValue.length() - 8);
|
||||
}
|
||||
UNIQUE_NUM = uniqueValue.toUpperCase();
|
||||
}
|
||||
|
||||
public synchronized static String makeGUID() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(DatetimeUtil.getCurrentDateTime());
|
||||
sb.append(UNIQUE_NUM);
|
||||
|
||||
char[] formatSeq = {'0','0','0','0','0','0','0','0'};
|
||||
char[] seqCharArray = String.valueOf(seq).toCharArray();
|
||||
int destPos = formatSeq.length - seqCharArray.length;
|
||||
System.arraycopy(seqCharArray, 0, formatSeq, destPos, seqCharArray.length);
|
||||
|
||||
sb.append(formatSeq);
|
||||
|
||||
seq ++;
|
||||
if(seq > 99999999) {
|
||||
seq = 1;
|
||||
}
|
||||
|
||||
return sb.toString() ;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import com.eactive.eai.common.server.Keys;
|
||||
import com.eactive.eai.common.util.StringUtil;
|
||||
|
||||
public final class GUIDGeneratorSBI {
|
||||
|
||||
private static final SimpleDateFormat SDF_YYYYMMDDHHMMSSMI = new SimpleDateFormat("yyyyMMddHHmmssSSS");
|
||||
|
||||
private GUIDGeneratorSBI() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 시스템일시(17)+시스템환경코드(1)+시스템코드(3)+시스템고유번호(9)+일련번호(2)
|
||||
*
|
||||
* @param envDvcd
|
||||
* @return
|
||||
*/
|
||||
public synchronized static String getGUID(String envDvcd, String systemType) {
|
||||
String guid = (SDF_YYYYMMDDHHMMSSMI).format(new java.util.Date()) + envDvcd + systemType + UNIQUE_NUM;
|
||||
|
||||
if (seq < 10) {
|
||||
guid = guid + "0" + seq;
|
||||
} else {
|
||||
guid = guid + seq;
|
||||
}
|
||||
|
||||
seq++;
|
||||
if (seq > 99) {
|
||||
seq = 1;
|
||||
}
|
||||
|
||||
return guid;
|
||||
}
|
||||
|
||||
private static String UNIQUE_NUM;
|
||||
private static int seq = 1;
|
||||
static {
|
||||
String hostname = "";
|
||||
try {
|
||||
hostname = java.net.InetAddress.getLocalHost().getHostName();
|
||||
} catch (Exception e) {
|
||||
hostname = "_______";
|
||||
}
|
||||
|
||||
if (hostname.getBytes().length != 7) {
|
||||
hostname = StringUtil.stringFormat(hostname, false, '_', 7);
|
||||
}
|
||||
|
||||
String serverName = System.getProperty(Keys.SERVER_KEY); // inst.Name
|
||||
String instid = "11";
|
||||
if (serverName != null && serverName.length() > 2) {
|
||||
instid = serverName.substring(serverName.length() - 2, serverName.length());
|
||||
}
|
||||
|
||||
UNIQUE_NUM = hostname.toUpperCase() + instid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.StringUtil;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.service.DefaultInterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class InterfaceMapperKAKAOCARD extends DefaultInterfaceMapper {
|
||||
private static String SESSION_ID = "INTERFACE_COMMON.MCI_SESN_ID";
|
||||
private static String INSTANCE_ID = "INTERFACE_COMMON.MCI_INSTNC_ID";
|
||||
|
||||
@Override
|
||||
public String getEaiSvcCode(StandardMessage standardMessage) {
|
||||
String eaiSvcCode = null;
|
||||
String interfaceId = getInterfaceId(standardMessage);
|
||||
String returnType = getSendRecvDivision(standardMessage); // S | R
|
||||
String inExDivision = getInExDivision(standardMessage); // 1 | 2
|
||||
if (interfaceId == null)
|
||||
interfaceId = "";
|
||||
interfaceId = interfaceId.trim();
|
||||
|
||||
// TODO : site에 맞게 조합해야 함.
|
||||
eaiSvcCode = interfaceId + returnType + StringUtils.defaultString(inExDivision);
|
||||
return eaiSvcCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setGuid(StandardMessage standardMessage, String guid) {
|
||||
if (guid == null)
|
||||
throw new RuntimeException("guid is null");
|
||||
if (guid.length() != 36)
|
||||
throw new RuntimeException("The length of guid is not 36");
|
||||
setItemValue(standardMessage, getPath(GUID), guid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getGuid(StandardMessage standardMessage) {
|
||||
String guid = getItemValue(standardMessage, getPath(GUID));
|
||||
if (guid.length() == 36) {
|
||||
guid = guid.substring(0, 33);
|
||||
}
|
||||
return guid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getGuidSeq(StandardMessage standardMessage) {
|
||||
String guidseq = null;
|
||||
String guid = getItemValue(standardMessage, getPath(GUID));
|
||||
if (guid.length() == 36) {
|
||||
guidseq = guid.substring(33);
|
||||
} else {
|
||||
guidseq = "000";
|
||||
}
|
||||
return guidseq;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setGuidSeq(StandardMessage standardMessage, String guidSeq) {
|
||||
setItemValue(standardMessage, getPath(GUID), getGuid(standardMessage) + guidSeq);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getOrgGuid(StandardMessage standardMessage) {
|
||||
String orgGuid = getItemValue(standardMessage, getPath(GUID_ORG));
|
||||
if (orgGuid.length() == 36) {
|
||||
orgGuid = orgGuid.substring(0, 33);
|
||||
}
|
||||
return orgGuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setOrgGuid(StandardMessage standardMessage, String orgGuid) {
|
||||
if (orgGuid.length() == 36) {
|
||||
orgGuid = orgGuid.substring(0, 33);
|
||||
}
|
||||
setItemValue(standardMessage, getPath(GUID_ORG), orgGuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String nextGuidSeq(StandardMessage standardMessage) {
|
||||
String guidSeq = getGuidSeq(standardMessage);
|
||||
if (guidSeq == null)
|
||||
return "";
|
||||
int seq = 0;
|
||||
try {
|
||||
seq = Integer.parseInt(guidSeq) + 1;
|
||||
} catch (NumberFormatException e) {
|
||||
seq = 1;
|
||||
}
|
||||
guidSeq = StringUtil.stringFormat(Integer.toString(seq), true, '0', 3);
|
||||
setGuidSeq(standardMessage, guidSeq);
|
||||
return guidSeq;
|
||||
}
|
||||
|
||||
/**
|
||||
* 표준전문의 복원은 COMMON.ORTR_RESTR_YN 의 value는 (Y/N) 엔진에서 복원여부 의 value는 (1/0)
|
||||
*/
|
||||
@Override
|
||||
public String getRecoverYn(StandardMessage standardMessage) {
|
||||
String data = getItemValue(standardMessage, getPath(RECOVER_YN));
|
||||
if ("Y".equals(data)) {
|
||||
return "1";
|
||||
} else {
|
||||
return "0";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRecoverYn(StandardMessage standardMessage, String recoverYn) {
|
||||
if ("1".equals(recoverYn)) {
|
||||
setItemValue(standardMessage, getPath(RECOVER_YN), "Y");
|
||||
} else {
|
||||
setItemValue(standardMessage, getPath(RECOVER_YN), "N");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getInstCode(StandardMessage standardMessage) {
|
||||
EAIServerManager server = EAIServerManager.getInstance();
|
||||
if (server != null && server.isMCI()) {
|
||||
return getItemValue(standardMessage, INSTANCE_ID);
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInstCode(StandardMessage standardMessage, String instCode) {
|
||||
EAIServerManager server = EAIServerManager.getInstance();
|
||||
if (server != null && server.isMCI()) {
|
||||
setItemValue(standardMessage, INSTANCE_ID, instCode);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSessionId(StandardMessage standardMessage) {
|
||||
EAIServerManager server = EAIServerManager.getInstance();
|
||||
if (server != null && server.isMCI()) {
|
||||
return getItemValue(standardMessage, SESSION_ID);
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSessionId(StandardMessage standardMessage, String sessionId) {
|
||||
EAIServerManager server = EAIServerManager.getInstance();
|
||||
if (server != null && server.isMCI()) {
|
||||
setItemValue(standardMessage, SESSION_ID, sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* 엔진 에서는 public static final String RESPONSE_TYPE_CODE_N = "0";//정상(normal)
|
||||
* public static final String RESPONSE_TYPE_CODE_E = "1";//오류(error)
|
||||
*/
|
||||
@Override
|
||||
public void setResponseType(StandardMessage standardMessage, String responseType) {
|
||||
if (responseType != null && (STDMessageKeys.RESPONSE_TYPE_CODE_N.equals(responseType)
|
||||
|| STDMessageKeys.RESPONSE_TYPE_CODE_E.equals(responseType))) {
|
||||
if (STDMessageKeys.RESPONSE_TYPE_CODE_N.equals(responseType)) {
|
||||
setItemValue(standardMessage, getPath(RESPONSE_TYPE), "NR");
|
||||
} else {
|
||||
setItemValue(standardMessage, getPath(RESPONSE_TYPE), "ER");
|
||||
}
|
||||
} else {
|
||||
setItemValue(standardMessage, getPath(RESPONSE_TYPE), responseType);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getInterfaceId(StandardMessage standardMessage) {
|
||||
String interfaceId = getItemValue(standardMessage, getPath(INTERFACE_ID));
|
||||
if (interfaceId == null)
|
||||
return "";
|
||||
interfaceId = interfaceId.trim();
|
||||
return interfaceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReqSysCode(StandardMessage standardMessage) {
|
||||
// apiPath의 값에서 추출할 예정 : serviceId = api_path
|
||||
String apiPath = getItemValue(standardMessage, getPath(SERVICE_ID));
|
||||
if (apiPath != null) {
|
||||
String[] split = apiPath.split("/");
|
||||
if (split.length > 2) {
|
||||
String route = split[1].toUpperCase();
|
||||
if (route.length() > 3) {
|
||||
route = route.substring(0, 3);
|
||||
}
|
||||
return route;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.service.DefaultInterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
public class InterfaceMapperKBANK extends DefaultInterfaceMapper {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
//전문작성일시
|
||||
String ITEM_TLGR_WRTN_DT = "header_part.tlgrWrtnDt";
|
||||
//전문생성시스템
|
||||
String ITEM_TLGR_CRTN_SYS_NM = "header_part.tlgrCrtnSysNm";
|
||||
//전문일련번호
|
||||
String ITEM_TLGR_SRL_NO = "header_part.tlgrSrlNo";
|
||||
|
||||
@Override
|
||||
public String getInExDivision(StandardMessage standardMessage) {
|
||||
return "1";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setGuid(StandardMessage standardMessage, String guid) {
|
||||
String tlgrWrtnDt = StringUtils.substring(guid, 0, 14);
|
||||
String tlgrCrtnSysNm = StringUtils.substring(guid, 14, 22);
|
||||
String tlgrSrlNo = StringUtils.substring(guid, 22, 30);
|
||||
setItemValue(standardMessage, ITEM_TLGR_WRTN_DT, tlgrWrtnDt);
|
||||
setItemValue(standardMessage, ITEM_TLGR_CRTN_SYS_NM, tlgrCrtnSysNm);
|
||||
setItemValue(standardMessage, ITEM_TLGR_SRL_NO, tlgrSrlNo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setGuidSeq(StandardMessage standardMessage, String guidSeq) {
|
||||
if(guidSeq.length() == 1) {
|
||||
guidSeq = "0"+guidSeq;
|
||||
}
|
||||
super.setGuidSeq(standardMessage, guidSeq);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getGuid(StandardMessage standardMessage) {
|
||||
String tlgrWrtnDt = getItemValue(standardMessage, ITEM_TLGR_WRTN_DT);
|
||||
String tlgrCrtnSysNm = getItemValue(standardMessage, ITEM_TLGR_CRTN_SYS_NM);
|
||||
String tlgrSrlNo = getItemValue(standardMessage, ITEM_TLGR_SRL_NO);
|
||||
return tlgrWrtnDt+tlgrCrtnSysNm+tlgrSrlNo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.service.DefaultInterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class InterfaceMapperSBI extends DefaultInterfaceMapper {
|
||||
|
||||
@Override
|
||||
public String getSendRecvDivision(StandardMessage standardMessage) {
|
||||
String sendRecvDivision = super.getSendRecvDivision(standardMessage);
|
||||
if (StringUtils.equals(sendRecvDivision, "Q")) {
|
||||
return STDMessageKeys.SEND_RECV_CD_SEND;
|
||||
} else {
|
||||
return sendRecvDivision;
|
||||
}
|
||||
}
|
||||
}
|
||||
+419
@@ -0,0 +1,419 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.message.EAIMessage;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.custom.stderrorcode.ChannelErrorCodeManager;
|
||||
import com.eactive.eai.custom.stderrorcode.ChannelErrorCodeVO;
|
||||
import com.eactive.eai.custom.stderrorcode.StdErrorCodeManager;
|
||||
import com.eactive.eai.custom.stderrorcode.StdErrorCodeVO;
|
||||
import com.eactive.eai.inbound.error.InboundErrorKeys;
|
||||
import com.eactive.eai.inbound.processor.ProcessVO;
|
||||
import com.eactive.eai.message.StandardItem;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.service.DefaultStandardMessageCoordinator;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageErrorKeys;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
public class StandardMessageCoordinatorKAKAOCARD extends DefaultStandardMessageCoordinator {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
//private static int defaultTimeout = 30;
|
||||
private static String GW_SESSION_ID = "INTERFACE_COMMON.GTWY_SESN_ID";
|
||||
private static String GW_INSTANCE_ID = "INTERFACE_COMMON.GTWY_INSTNC_ID";
|
||||
private static String MESSAGE_OUT_ATRB_CD = "MESSAGE.OUT_ATRB_CD";//출력속성코드
|
||||
private static String MESSAGE_OUT_MSG_DESC = "MESSAGE.OUT_MSG_DESC";//출력메시지설명
|
||||
private static String COMMON_OUT_FMSG_DSTCD = "COMMON.OUT_FMSG_DSTCD";//출력전문구별코드
|
||||
private static String MESSAGE = "MESSAGE";//메시지부
|
||||
|
||||
@Override
|
||||
public void coordinateAfterParsing(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = standardManager.getMapper();
|
||||
//표준에서 들어올때 표준전문의 값을 header에 셋팅
|
||||
//표준전문 to prop
|
||||
if (EAIServerManager.getInstance().isFEP()) {
|
||||
StandardItem gwSesnId = standardMessage.findItem(GW_SESSION_ID);//transactionId
|
||||
StandardItem gwNodeNo = standardMessage.findItem(GW_INSTANCE_ID);//instanceId
|
||||
if (gwSesnId != null && gwNodeNo != null && StringUtils.isNotBlank(gwSesnId.getValue()) && StringUtils.isNotBlank(gwNodeNo.getValue())) {
|
||||
prop.put(HttpClientAdapterServiceKey.TRANSACTION_ID, gwSesnId.getValue());
|
||||
prop.put(HttpClientAdapterServiceKey.INSTANCE_ID, gwNodeNo.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
// REST용 전달값 중 api_path 이후의 값을 표준전문 API_PATH에 셋팅
|
||||
String adapterApiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH);
|
||||
if (StringUtils.isNotBlank(adapterApiPath)) {
|
||||
String adapterExtUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
|
||||
/*
|
||||
* apiPath 나머지를 추출하기 위해서
|
||||
* 예) 어댑터에 설정되어 있는 API_PATH = /api/cts
|
||||
* 어댑터에 들어온 INBOUND_EXTURI = /api/cts/cmb/api/user/custom
|
||||
* 표준전문에 셋팅하고 싶은값 /cmb/api/user/custom
|
||||
*/
|
||||
String standardApiPath = adapterExtUri.replaceAll(adapterApiPath, "");
|
||||
if (!standardApiPath.startsWith("/")) {
|
||||
standardApiPath = standardApiPath + "/";
|
||||
}
|
||||
if (standardApiPath.length() > 1) {
|
||||
mapper.setServiceId(standardMessage,standardApiPath);
|
||||
}
|
||||
}
|
||||
|
||||
//아래로직은 표준전문에서 요청일때 MESSAGE부가 안보이고 응답일때 MESSAGE부 보이게 설정
|
||||
String sendRecvDivision = mapper.getSendRecvDivision(standardMessage);
|
||||
StandardItem msg = standardMessage.findItem(MESSAGE);
|
||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_SEND)) {
|
||||
msg.setHidden(true);
|
||||
}
|
||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
||||
msg.setHidden(false);
|
||||
}
|
||||
|
||||
//mci이고 요청 거래시에 설정 인스턴스ID설정
|
||||
EAIServerManager server = EAIServerManager.getInstance();
|
||||
if (server != null && server.isMCI() && (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_SEND))) {
|
||||
//인스턴스ID설정
|
||||
String instCode = mapper.getInstCode(standardMessage);
|
||||
String localServer = server.getLocalServerName();
|
||||
if (instCode != null && localServer != null) {
|
||||
mapper.setInstCode(standardMessage, localServer);
|
||||
}
|
||||
//타임아웃값이 없을경우 default값 설정
|
||||
String timeout = mapper.getTimeout(standardMessage);
|
||||
|
||||
int defaultTimeout = getDefaultTimeout();
|
||||
if (StringUtils.isBlank(timeout)) {
|
||||
mapper.setTimeout(standardMessage, Integer.toString(defaultTimeout));
|
||||
}else {
|
||||
try {
|
||||
Integer.parseInt(timeout);
|
||||
}catch(Exception e) {
|
||||
mapper.setTimeout(standardMessage, Integer.toString(defaultTimeout));
|
||||
}
|
||||
}
|
||||
}
|
||||
//TODO 표준전문 메시지 설정해야됨
|
||||
//표준전문에 메시지 부에 값이 있을경우 처리
|
||||
if (!msg.isHidden()) {
|
||||
String errmsg = mapper.getErrorMsg(standardMessage);
|
||||
if (StringUtils.isBlank(errmsg)) {
|
||||
String errCode = mapper.getErrorCode(standardMessage);
|
||||
if (StringUtils.isNotBlank(errCode)) {
|
||||
StdErrorCodeManager manager = StdErrorCodeManager.getInstance();
|
||||
StdErrorCodeVO vo = manager.getSTDErrorCode(errCode);
|
||||
if (vo != null) {
|
||||
mapper.setErrorMsg(standardMessage, vo.getErrMsg());
|
||||
if (server != null && server.isMCI()) {
|
||||
String type = mapper.getChannelDetailCd(standardMessage);
|
||||
//채널오류코드 셋팅
|
||||
ChannelErrorCodeManager cmanager = ChannelErrorCodeManager.getInstance();
|
||||
ChannelErrorCodeVO cvo = cmanager.getChannelErrorCode(errCode+"_"+type);
|
||||
if (cvo != null) {
|
||||
mapper.setErrorMsg(standardMessage, cvo.getErrMsg());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
//비표준처리
|
||||
public void coordinateAfterCreateMessageByRule(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = standardManager.getMapper();
|
||||
//비표준에서 들어올때 header값을 표준전문에 셋팅
|
||||
//prop to 표준전문
|
||||
if (EAIServerManager.getInstance().isFEP()) {
|
||||
String trandactionId = prop.getProperty(HttpClientAdapterServiceKey.TRANSACTION_ID);
|
||||
String instanceId = prop.getProperty(HttpClientAdapterServiceKey.INSTANCE_ID);
|
||||
if (StringUtils.isNotBlank(trandactionId) && StringUtils.isNotBlank(instanceId)) {
|
||||
StandardItem gwSesnId = standardMessage.findItem(GW_SESSION_ID);//transactionId
|
||||
if (gwSesnId != null) {
|
||||
gwSesnId.setValue(trandactionId);
|
||||
}
|
||||
StandardItem gwNodeNo = standardMessage.findItem(GW_INSTANCE_ID);//instanceId
|
||||
if (gwNodeNo != null) {
|
||||
gwNodeNo.setValue(instanceId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||
//HEADER.GUID설정
|
||||
mapper.setGuid(standardMessage,GUIDGeneratorKAKAOCARD.getGUID(eaiServerManager.getSystemType()));
|
||||
//HEADER.FMSG_REQ_RES_DSTCD 전문요청응답구별코드 : 표준전문값
|
||||
|
||||
//HEADER.FRST_TRNM_IPAD 최초전송IP주소
|
||||
mapper.setFirstReqIp(standardMessage, "0.0.0.0");
|
||||
//HEADER.GNRZ_TMOT_TM 총괄타임아웃시간
|
||||
mapper.setTimeout(standardMessage, "180");
|
||||
// HEADER.SYS_ENV_DSTCD 시스템운영환경구분코드
|
||||
String operationEnv = mapper.getOperationEnv(standardMessage);
|
||||
if (operationEnv != null && StringUtils.isBlank(operationEnv)) {
|
||||
mapper.setOperationEnv(standardMessage, getSysOprtEnvDvcd(eaiServerManager));
|
||||
}
|
||||
// HEADER.CARD_TX_TYP_DSTCD 거래유형구별코드
|
||||
StandardItem cardTxTypDstcd = standardMessage.findItem("HEADER.CARD_TX_TYP_DSTCD");
|
||||
if (cardTxTypDstcd != null ) {
|
||||
cardTxTypDstcd.setValue("O");
|
||||
}
|
||||
//COMMON.GROUP_CMP_CD 그룹회사코드
|
||||
StandardItem groupCmpCd = standardMessage.findItem("COMMON.GROUP_CMP_CD");
|
||||
if (groupCmpCd != null ) {
|
||||
groupCmpCd.setValue("090");
|
||||
}
|
||||
//COMMON.TX_BRCD 거래부점코드
|
||||
StandardItem txBrcd = standardMessage.findItem("COMMON.TX_BRCD");
|
||||
if (txBrcd != null ) {
|
||||
txBrcd.setValue("0000");
|
||||
}
|
||||
//COMMON.RLTR_BRCD 실거래부점코드
|
||||
StandardItem rltrBrcd = standardMessage.findItem("COMMON.RLTR_BRCD");
|
||||
if (rltrBrcd != null ) {
|
||||
rltrBrcd.setValue("0000");
|
||||
}
|
||||
//COMMON.TLRNO 텔러번호
|
||||
StandardItem tlrno = standardMessage.findItem("COMMON.TLRNO");
|
||||
if (tlrno != null ) {
|
||||
tlrno.setValue("000000");
|
||||
}
|
||||
//COMMON.TX_DT 거래일자
|
||||
StandardItem txDt = standardMessage.findItem("COMMON.TX_DT");
|
||||
if (txDt != null ) {
|
||||
txDt.setValue(DatetimeUtil.getFormattedDate("yyyyMMdd"));
|
||||
}
|
||||
//COMMON.TX_TM 거래시간
|
||||
StandardItem txTm = standardMessage.findItem("COMMON.TX_TM");
|
||||
if (txTm != null ) {
|
||||
txTm.setValue(DatetimeUtil.getFormattedDate("HHmmssSSS"));
|
||||
}
|
||||
|
||||
//아래로직은 표준전문에서 요청일때 MESSAGE부가 안보이고 응답일때 MESSAGE부 보이게 설정
|
||||
String sendRecvDivision = mapper.getSendRecvDivision(standardMessage);
|
||||
StandardItem msg = standardMessage.findItem(MESSAGE);
|
||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_SEND)) {
|
||||
msg.setHidden(true);
|
||||
}
|
||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
||||
msg.setHidden(false);
|
||||
}
|
||||
|
||||
//TODO 표준전문 메시지 설정해야됨
|
||||
//응답일경우 MESSAGE부에 정상 메시지 헤더를 설정하기 위해서
|
||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
||||
StandardItem outputAtrbCd = standardMessage.findItem(MESSAGE_OUT_ATRB_CD);//출력속성코드
|
||||
outputAtrbCd.setValue("1");
|
||||
|
||||
mapper.setErrorCode(standardMessage, STDMessageErrorKeys.SUCCESS_CODE_VALUE);
|
||||
mapper.setErrorMsg(standardMessage, STDMessageErrorKeys.SUCCESS_MSG_VALUE);
|
||||
mapper.setResponseType(standardMessage, STDMessageKeys.RESPONSE_TYPE_CODE_N);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void coordinateInReturnObject(StandardMessage standardMessage) {
|
||||
//아래로직은 표준전문에서 응답일때 MESSAGE부가 보이게 하기위해서
|
||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = standardManager.getMapper();
|
||||
mapper.setSendRecvDivision(standardMessage, STDMessageKeys.SEND_RECV_CD_RECV);
|
||||
StandardItem msg = standardMessage.findItem(MESSAGE);
|
||||
msg.setHidden(false);
|
||||
}
|
||||
public String getSysOprtEnvDvcd(EAIServerManager eaiServerManager) {
|
||||
String result = "";
|
||||
if (eaiServerManager.isPEAIServer()) { // 운영
|
||||
result = "R";
|
||||
} else if (eaiServerManager.isDEAIServer()) { // 개발
|
||||
result = "D";
|
||||
} else if (eaiServerManager.isSEAIServer()) { // 테스트/검증
|
||||
result = "T";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void coordinateBeforeInboundErrorResponse(StandardMessage standardMessage) {
|
||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = standardManager.getMapper();
|
||||
mapper.setSendRecvDivision(standardMessage, STDMessageKeys.SEND_RECV_CD_RECV);
|
||||
StandardItem msg = standardMessage.findItem(MESSAGE);
|
||||
msg.setHidden(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean coordinateSetStandardMessageError(StandardMessage standardMessage, InterfaceMapper mapper,
|
||||
String errCode, String errMsg) {
|
||||
String siteErrCode = null;
|
||||
String siteErrMessage = null;
|
||||
if(errCode != null) {
|
||||
siteErrCode = MessageUtil.getTobeCode(errCode);
|
||||
siteErrMessage = MessageUtil.getTobeMessage(errCode);
|
||||
}
|
||||
|
||||
String sendRecvDivision = mapper.getSendRecvDivision(standardMessage);
|
||||
if (StringUtils.equals(sendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
||||
StandardItem msg = standardMessage.findItem(MESSAGE);
|
||||
msg.setHidden(false);
|
||||
}
|
||||
|
||||
StandardItem outputAtrbCd = standardMessage.findItem(MESSAGE_OUT_ATRB_CD);//출력속성코드
|
||||
outputAtrbCd.setValue("1");
|
||||
|
||||
if (siteErrCode != null) {
|
||||
mapper.setErrorCode(standardMessage, siteErrCode);
|
||||
}else if (errCode != null) {
|
||||
mapper.setErrorCode(standardMessage, errCode);
|
||||
}
|
||||
|
||||
if (siteErrMessage != null) {
|
||||
mapper.setErrorMsg(standardMessage, siteErrMessage);
|
||||
}else if (errMsg != null){
|
||||
mapper.setErrorMsg(standardMessage, errMsg);
|
||||
}
|
||||
|
||||
StandardItem outputMsgDesc = standardMessage.findItem(MESSAGE_OUT_MSG_DESC);//출력메시지설명
|
||||
if (errMsg != null){
|
||||
outputMsgDesc.setValue(errMsg);
|
||||
}
|
||||
mapper.setResponseType(standardMessage, STDMessageKeys.RESPONSE_TYPE_CODE_E);
|
||||
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
//복원시
|
||||
public void coordinateAfterRestored(StandardMessage dbMessage, StandardMessage responseMessage) {
|
||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = standardManager.getMapper();
|
||||
String interfaceId = mapper.getInterfaceId(responseMessage);
|
||||
mapper.setInterfaceId(dbMessage, interfaceId);
|
||||
|
||||
String sendRecvDivision = mapper.getSendRecvDivision(responseMessage);
|
||||
mapper.setSendRecvDivision(dbMessage, sendRecvDivision);
|
||||
|
||||
String inExDivision = mapper.getInExDivision(responseMessage);
|
||||
mapper.setInExDivision(dbMessage, inExDivision);
|
||||
|
||||
String recoverYn = mapper.getRecoverYn(responseMessage);
|
||||
mapper.setRecoverYn(dbMessage, recoverYn);
|
||||
|
||||
//복원시 처리결과수신 서비스코드를 서비스코드에 셋팅한다.
|
||||
//처리결과수신값이 없을경우 원거래 서비스ID를 셋팅한다.
|
||||
String returnServiceId = mapper.getReturnServiceId(dbMessage);
|
||||
if (StringUtils.isBlank(returnServiceId)){
|
||||
returnServiceId = mapper.getServiceId(dbMessage);
|
||||
}
|
||||
mapper.setServiceId(dbMessage, returnServiceId);
|
||||
|
||||
//표준전문 메시지 관련 설정
|
||||
String dbSendRecvDivision = mapper.getSendRecvDivision(dbMessage);
|
||||
StandardItem msg = dbMessage.findItem(MESSAGE);
|
||||
if ( StringUtils.equals(dbSendRecvDivision, STDMessageKeys.SEND_RECV_CD_SEND)) {
|
||||
msg.setHidden(true);
|
||||
}
|
||||
if (StringUtils.equals(dbSendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
||||
msg.setHidden(false);
|
||||
}
|
||||
//응답일경우 MESSAGE부 정상설정
|
||||
if (StringUtils.equals(dbSendRecvDivision, STDMessageKeys.SEND_RECV_CD_RECV)) {
|
||||
StandardItem outputAtrbCd = dbMessage.findItem(MESSAGE_OUT_ATRB_CD);//출력속성코드
|
||||
outputAtrbCd.setValue("1");
|
||||
|
||||
mapper.setErrorCode(dbMessage, STDMessageErrorKeys.SUCCESS_CODE_VALUE);//출력메시지코드
|
||||
mapper.setErrorMsg(dbMessage, STDMessageErrorKeys.SUCCESS_MSG_VALUE);//출력메시지내용
|
||||
mapper.setResponseType(dbMessage, STDMessageKeys.RESPONSE_TYPE_CODE_N);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public boolean coordinateIsWaitCheckForSync(StandardMessage responseMessage) {
|
||||
StandardItem outputMesgTycd = responseMessage.findItem(COMMON_OUT_FMSG_DSTCD);
|
||||
if (outputMesgTycd != null && StringUtils.equals(outputMesgTycd.getValue(), "9")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public int coordinateForTimeoutCodeToValue(EAIMessage eaiMessage) {
|
||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = standardManager.getMapper();
|
||||
EAIServerManager server = EAIServerManager.getInstance();
|
||||
if (server != null && server.isMCI()) { //MCI 일경우 처리
|
||||
StandardMessage standardMessage = eaiMessage.getStandardMessage();
|
||||
String timeout = mapper.getTimeout(standardMessage);
|
||||
int defaultTimeout = getDefaultTimeout();
|
||||
|
||||
if (StringUtils.isBlank(timeout)) {
|
||||
return defaultTimeout;
|
||||
}else {
|
||||
try {
|
||||
return Integer.parseInt(timeout);
|
||||
}catch(Exception e) {
|
||||
return defaultTimeout;
|
||||
}
|
||||
}
|
||||
}else { //MCI 이외일 경우 처리 (인터페이스에 있는 타임아웃기준)
|
||||
return eaiMessage.getCurrentSvcMsg().getTmoVl();
|
||||
}
|
||||
}
|
||||
private int getDefaultTimeout() {
|
||||
PropManager manager = PropManager.getInstance();
|
||||
int defaultTimeout = 30;
|
||||
try {
|
||||
String sdefaultTimeout = manager.getProperty("KAKAO_CARD", "DEFAULT_TIMEOUT", Integer.toString(defaultTimeout));
|
||||
defaultTimeout = Integer.parseInt(sdefaultTimeout);
|
||||
}catch(Exception e) {
|
||||
|
||||
}
|
||||
return defaultTimeout;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean coordinateValidation(StandardMessage standardMessage, ProcessVO vo) {
|
||||
// RECEAIIRP110 인터페이스 ({1}) 에 표준전문 항목 ({2}) 의 값이 없습니다.
|
||||
// RECEAIIRP120 인터페이스 ({1}) 에 표준전문 항목 ({2}) 의 값을 확인하세요.
|
||||
|
||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = standardManager.getMapper();
|
||||
String interfaceId = mapper.getInterfaceId(standardMessage);
|
||||
|
||||
String guid = mapper.getGuid(standardMessage);
|
||||
if (StringUtils.isBlank(guid)) {
|
||||
vo.setRspErrorCode("RECEAIIRP110");
|
||||
vo.setRspErrorMsg(ExceptionUtil.make(vo.getRspErrorCode(), new String[] { interfaceId, "GUID" }));
|
||||
vo.setErrTypeCode(InboundErrorKeys.IN_ERROR);
|
||||
return false;
|
||||
}
|
||||
String guidSeq = mapper.getGuidSeq(standardMessage);
|
||||
if (StringUtils.isBlank(guidSeq)) {
|
||||
vo.setRspErrorCode("RECEAIIRP110");
|
||||
vo.setRspErrorMsg(ExceptionUtil.make(vo.getRspErrorCode(), new String[] { interfaceId, "GUID" }));
|
||||
vo.setErrTypeCode(InboundErrorKeys.IN_ERROR);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (guid.length() + guidSeq.length() != 36) {
|
||||
vo.setRspErrorCode("RECEAIIRP120");
|
||||
vo.setRspErrorMsg(ExceptionUtil.make(vo.getRspErrorCode(), new String[] { interfaceId, "GUID" }));
|
||||
vo.setErrTypeCode(InboundErrorKeys.IN_ERROR);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.server.Keys;
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.common.util.MessageUtil;
|
||||
import com.eactive.eai.common.util.StringUtil;
|
||||
import com.eactive.eai.message.StandardItem;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.service.DefaultStandardMessageCoordinator;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
||||
|
||||
public class StandardMessageCoordinatorKBANK extends DefaultStandardMessageCoordinator {
|
||||
|
||||
private static final String MESSAGE_PART_SUB_MSG_GOUP = "message_part.subMsgGoup";
|
||||
private static final String MESSAGE_PART_MSG_TYPE = "message_part.msgType";
|
||||
private static final String MESSAGE_PART = "message_part";
|
||||
|
||||
@Override
|
||||
public void coordinateAfterParsing(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void coordinateAfterCreateMessageByRule(StandardMessage standardMessage, Object paramObject, Properties prop) {
|
||||
// guid 설정
|
||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = standardManager.getMapper();
|
||||
|
||||
String guid = GUIDGeneratorKBANK.makeGUID();
|
||||
|
||||
mapper.setGuid(standardMessage, guid);
|
||||
|
||||
String orgGuid = guid + mapper.getGuidSeq(standardMessage);
|
||||
|
||||
mapper.setOrgGuid(standardMessage, orgGuid);
|
||||
|
||||
mapper.setOperationEnv(standardMessage, System.getProperty(Keys.EAI_SYSTEMMODE));
|
||||
|
||||
mapper.setFirstReqIp(standardMessage, EAIServerManager.getInstance().getServerIp());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean coordinateSetStandardMessageError(StandardMessage standardMessage, InterfaceMapper mapper,
|
||||
String errCode, String errMsg) {
|
||||
|
||||
mapper.setResponseType(standardMessage, STDMessageKeys.RESPONSE_TYPE_CODE_E);
|
||||
|
||||
StandardItem messagePart = standardMessage.findItem(MESSAGE_PART);
|
||||
messagePart.setHidden(false);
|
||||
messagePart.setSize(1);
|
||||
StandardItem messageType = standardMessage.findItem(MESSAGE_PART_MSG_TYPE);
|
||||
messageType.setValue("99");
|
||||
StandardItem subMsgGoup = standardMessage.findItem(MESSAGE_PART_SUB_MSG_GOUP);
|
||||
subMsgGoup.getList().clear();
|
||||
subMsgGoup.setRefValue("0");
|
||||
|
||||
if(errCode != null) {
|
||||
String siteErrCode = MessageUtil.getTobeCode(errCode);
|
||||
String siteErrMessage;
|
||||
switch(errCode) {
|
||||
case("RECEAIIRP070"):
|
||||
siteErrMessage = "거래 통제 되었습니다.";
|
||||
break;
|
||||
default:
|
||||
siteErrMessage = MessageUtil.getTobeMessage(errCode); break;
|
||||
}
|
||||
|
||||
mapper.setErrorCode(standardMessage, siteErrCode);
|
||||
mapper.setErrorMsg(standardMessage, siteErrMessage);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void coordinateAfterRecvNonStdSyncResponse(StandardMessage responseMessage) {
|
||||
StandardItem messagePart = responseMessage.findItem(MESSAGE_PART);
|
||||
messagePart.setHidden(false);
|
||||
messagePart.setSize(1);
|
||||
StandardItem subMsgGoup = responseMessage.findItem(MESSAGE_PART_SUB_MSG_GOUP);
|
||||
subMsgGoup.getList().clear();
|
||||
subMsgGoup.setRefValue("0");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.eactive.eai.custom.message;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.eactive.eai.common.server.EAIServerManager;
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.inbound.processor.ProcessVO;
|
||||
import com.eactive.eai.message.StandardItem;
|
||||
import com.eactive.eai.message.StandardMessage;
|
||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
||||
import com.eactive.eai.message.service.DefaultStandardMessageCoordinator;
|
||||
import com.eactive.eai.message.service.InterfaceMapper;
|
||||
import com.eactive.eai.message.service.StandardMessageCoordinator;
|
||||
|
||||
public class StandardMessageCoordinatorSBI extends DefaultStandardMessageCoordinator {
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
@Override
|
||||
public void coordinateAfterCreateMessageByRule(StandardMessage message, Object paramObject, Properties prop) {
|
||||
// STD_HEADER.mesgDvcd 설정
|
||||
StandardItem mesgDvcdItem = message.findItem("STD_HEADER.mesgDvcd");
|
||||
if (mesgDvcdItem != null && StringUtils.equals(mesgDvcdItem.getValue(), "S")) {
|
||||
mesgDvcdItem.setValue("Q");
|
||||
}
|
||||
|
||||
// STD_HEADER.mesgKind 설정
|
||||
StandardItem mesgKindItem = message.findItem("STD_HEADER.mesgKind");
|
||||
if (mesgKindItem != null && StringUtils.isBlank(mesgKindItem.getValue())) {
|
||||
mesgKindItem.setValue("3"); // 3:데이터 4:시스템
|
||||
}
|
||||
|
||||
// STD_HEADER.envDvcd 설정
|
||||
StandardItem envDvcdItem = message.findItem("STD_HEADER.envDvcd");
|
||||
EAIServerManager eaiServerManager = EAIServerManager.getInstance();
|
||||
if (envDvcdItem != null && StringUtils.isBlank(envDvcdItem.getValue())) {
|
||||
envDvcdItem.setValue(getSysOprtEnvDvcd(eaiServerManager));
|
||||
}
|
||||
|
||||
// guid 설정
|
||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
||||
InterfaceMapper mapper = standardManager.getMapper();
|
||||
mapper.setGuid(message,
|
||||
GUIDGeneratorSBI.getGUID(getSysOprtEnvDvcd(eaiServerManager), eaiServerManager.getSystemType()));
|
||||
|
||||
// STD_HEADER.frstTrnmChnlCd 설정
|
||||
StandardItem frstTrnmChnlCdItem = message.findItem("STD_HEADER.frstTrnmChnlCd");
|
||||
if (frstTrnmChnlCdItem != null && StringUtils.isBlank(frstTrnmChnlCdItem.getValue())) {
|
||||
frstTrnmChnlCdItem.setValue(eaiServerManager.getSystemType());
|
||||
}
|
||||
|
||||
// STD_HEADER.trnmChnlCd 설정
|
||||
StandardItem trnmChnlCdItem = message.findItem("STD_HEADER.trnmChnlCd");
|
||||
if (trnmChnlCdItem != null && StringUtils.isBlank(trnmChnlCdItem.getValue())) {
|
||||
trnmChnlCdItem.setValue(eaiServerManager.getSystemType());
|
||||
}
|
||||
|
||||
// STD_HEADER.userNo 설정
|
||||
StandardItem userNoItem = message.findItem("STD_HEADER.userNo");
|
||||
if (userNoItem != null && StringUtils.isBlank(userNoItem.getValue())) {
|
||||
ProcessVO processVo = (ProcessVO) paramObject;
|
||||
if (StringUtils.isNotBlank(processVo.getInAdapterUserEmpid())) {
|
||||
userNoItem.setValue(eaiServerManager.getSystemType());
|
||||
}
|
||||
}
|
||||
|
||||
// STD_HEADER.mesgDmndDttm 설정
|
||||
StandardItem mesgDmndDttmItem = message.findItem("STD_HEADER.mesgDmndDttm");
|
||||
if (mesgDmndDttmItem != null && StringUtils.isBlank(mesgDmndDttmItem.getValue())) {
|
||||
mesgDmndDttmItem.setValue(DatetimeUtil.getCurrentTimeMillis());
|
||||
}
|
||||
|
||||
// STD_HEADER.ipAd 설정
|
||||
StandardItem ipAdItem = message.findItem("STD_HEADER.ipAd");
|
||||
if (ipAdItem != null && StringUtils.isBlank(ipAdItem.getValue())) {
|
||||
try {
|
||||
ipAdItem.setValue(InetAddress.getLocalHost().getHostAddress());
|
||||
} catch (UnknownHostException e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// STD_HEADER.mesgTycd 설정
|
||||
StandardItem mesgTycdItem = message.findItem("STD_HEADER.mesgTycd");
|
||||
if (mesgTycdItem != null && StringUtils.isBlank(mesgTycdItem.getValue())) {
|
||||
mesgTycdItem.setValue("1");
|
||||
}
|
||||
|
||||
// STD_HEADER.mesgCntySrno 설정
|
||||
StandardItem mesgCntySrnoItem = message.findItem("STD_HEADER.mesgCntySrno");
|
||||
if (mesgCntySrnoItem != null && StringUtils.isBlank(mesgCntySrnoItem.getValue())) {
|
||||
mesgCntySrnoItem.setValue("00");
|
||||
}
|
||||
|
||||
// STD_HEADER.bfrDtLoinYn 설정
|
||||
StandardItem bfrDtLoinYnItem = message.findItem("STD_HEADER.bfrDtLoinYn");
|
||||
if (bfrDtLoinYnItem != null && StringUtils.isBlank(bfrDtLoinYnItem.getValue())) {
|
||||
bfrDtLoinYnItem.setValue("N");
|
||||
}
|
||||
|
||||
// STD_HEADER.canCrctDvcd 설정
|
||||
StandardItem canCrctDvcdItem = message.findItem("STD_HEADER.canCrctDvcd");
|
||||
if (canCrctDvcdItem != null && StringUtils.isBlank(canCrctDvcdItem.getValue())) {
|
||||
canCrctDvcdItem.setValue("0");
|
||||
}
|
||||
|
||||
// STD_HEADER.cmpgRelmUseDvcd 설정
|
||||
StandardItem cmpgRelmUseDvcdItem = message.findItem("STD_HEADER.cmpgRelmUseDvcd");
|
||||
if (cmpgRelmUseDvcdItem != null && StringUtils.isBlank(cmpgRelmUseDvcdItem.getValue())) {
|
||||
cmpgRelmUseDvcdItem.setValue("0");
|
||||
}
|
||||
|
||||
// STD_HEADER.bzwrSvrCd 설정
|
||||
StandardItem bzwrSvrCdItem = message.findItem("STD_HEADER.bzwrSvrCd");
|
||||
if (bzwrSvrCdItem != null && StringUtils.isBlank(bzwrSvrCdItem.getValue())) {
|
||||
String serverName = eaiServerManager.getLocalServerName();
|
||||
if (StringUtils.isNotBlank(serverName)) {
|
||||
String instanceid1 = serverName.substring(0, 2);
|
||||
String instanceid2 = serverName.substring(serverName.length() - 2, serverName.length());
|
||||
bzwrSvrCdItem.setValue(StringUtils.upperCase(instanceid1 + instanceid2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String getSysOprtEnvDvcd(EAIServerManager eaiServerManager) {
|
||||
String result = "";
|
||||
if (eaiServerManager.isPEAIServer()) { // 운영
|
||||
result = "R";
|
||||
} else if (eaiServerManager.isDEAIServer()) { // 개발
|
||||
result = "D";
|
||||
} else if (eaiServerManager.isSEAIServer()) { // 테스트/검증
|
||||
result = "T";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.eactive.eai.custom.stderrorcode;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.eactive.eai.common.dao.BaseDAO;
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.custom.stderrorcode.loader.ChannelErrorCodeLoader;
|
||||
import com.eactive.eai.custom.stderrorcode.mapper.ChannelErrorCodeMapper;
|
||||
import com.eactive.eai.data.entity.custom.stderrorcode.ChannelErrorCode;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class ChannelErrorCodeDAO extends BaseDAO {
|
||||
private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
@Autowired
|
||||
private ChannelErrorCodeLoader channelErrorCodeEntityService;
|
||||
|
||||
@Autowired
|
||||
private ChannelErrorCodeMapper channelErrorCodeMapper;
|
||||
|
||||
public HashMap getAllChannelErrorCode() throws DAOException {
|
||||
try {
|
||||
HashMap groups = new HashMap();
|
||||
List<ChannelErrorCode> services = channelErrorCodeEntityService.findAllByNow();
|
||||
logger.info("[ @@ Load Channel Error Code Configuration - starting >>>>>>>>>>>>>>>>> ]");
|
||||
for (ChannelErrorCode channelErr : services) {
|
||||
ChannelErrorCodeVO vo = channelErrorCodeMapper.toVo(channelErr);
|
||||
String key = vo.getErrCd() + "_" + vo.getType();
|
||||
groups.put(key, vo);
|
||||
logger.info("[>>Load Channel Error Code vo(" + key + ") =" + vo + " ]");
|
||||
}
|
||||
logger.info("[>>Load Channel Error Code Configuration - ended ]");
|
||||
return groups;
|
||||
} catch (Exception e) {
|
||||
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICPM101"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.eactive.eai.custom.stderrorcode;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.lifecycle.Lifecycle;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleException;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleListener;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleSupport;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
@Component
|
||||
public class ChannelErrorCodeManager implements Lifecycle {
|
||||
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
private LifecycleSupport lifecycle = new LifecycleSupport(this);
|
||||
private Map<String, ChannelErrorCodeVO> channelErrorCodes = new HashMap();
|
||||
private boolean started;
|
||||
|
||||
@Autowired
|
||||
private ChannelErrorCodeDAO dao;
|
||||
|
||||
public static ChannelErrorCodeManager getInstance() {
|
||||
return ApplicationContextProvider.getContext().getBean(ChannelErrorCodeManager.class);
|
||||
}
|
||||
|
||||
public boolean isStarted() {
|
||||
return this.started;
|
||||
}
|
||||
|
||||
public synchronized void reload() throws LifecycleException {
|
||||
logger.warn("reload ChannelErrorCodeManager ...");
|
||||
|
||||
try {
|
||||
init();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
logger.warn("reload ChannelErrorCodeManager finish...");
|
||||
}
|
||||
|
||||
private void init() throws LifecycleException, Exception {
|
||||
try {
|
||||
this.channelErrorCodes = dao.getAllChannelErrorCode();
|
||||
} catch (DAOException e) {
|
||||
// throw new LifecycleException("RECEAICPM201");
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAICPM201"));
|
||||
}
|
||||
}
|
||||
|
||||
public void start() throws LifecycleException {
|
||||
if (started)
|
||||
throw new LifecycleException("RECEAICCM201");
|
||||
|
||||
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
|
||||
|
||||
try {
|
||||
init();
|
||||
} catch (Exception e) {
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAICCM202"));
|
||||
}
|
||||
|
||||
started = true;
|
||||
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
|
||||
}
|
||||
|
||||
public void stop() throws LifecycleException {
|
||||
if (!started)
|
||||
throw new LifecycleException("RECEAICCM203");
|
||||
|
||||
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
|
||||
started = false;
|
||||
logger.info("ChannelErrorCodeManager] It is stopped.");
|
||||
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
|
||||
}
|
||||
|
||||
public void addLifecycleListener(LifecycleListener listener) {
|
||||
lifecycle.addLifecycleListener(listener);
|
||||
}
|
||||
|
||||
public LifecycleListener[] findLifecycleListeners() {
|
||||
return lifecycle.findLifecycleListeners();
|
||||
}
|
||||
|
||||
public void removeLifecycleListener(LifecycleListener listener) {
|
||||
lifecycle.removeLifecycleListener(listener);
|
||||
}
|
||||
public ChannelErrorCodeVO getChannelErrorCode(String code) {
|
||||
return channelErrorCodes.get(code);
|
||||
}
|
||||
|
||||
public String[] getAllKeyNames() {
|
||||
String[] names = this.channelErrorCodes.keySet().toArray(new String[0]);
|
||||
Arrays.sort(names);
|
||||
return names;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.eactive.eai.custom.stderrorcode;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class ChannelErrorCodeVO implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String errCd; // 오류코드[TSEAIMX06.STD_ERR_CD]
|
||||
private String errMsg; // 오류메시지내용[TSEAIMX06.CHNL_ERR_MSG_CTS]
|
||||
private String type; // 채널세부코드[TSEAIMX06.CHNL_DTLS_CLCD]
|
||||
private String channelErrCd; // 채널세부코드[TSEAIMX06.CHNL_ERR_CD]
|
||||
|
||||
public ChannelErrorCodeVO() {
|
||||
this("", "", "", "");
|
||||
}
|
||||
|
||||
public ChannelErrorCodeVO(String errCd, String errMsg, String type, String channelErrCd) {
|
||||
super();
|
||||
this.errCd = errCd;
|
||||
this.errMsg = errMsg;
|
||||
this.type = type;
|
||||
this.channelErrCd = channelErrCd;
|
||||
}
|
||||
|
||||
public String getErrCd() {
|
||||
return errCd;
|
||||
}
|
||||
|
||||
public void setErrCd(String errCd) {
|
||||
this.errCd = errCd;
|
||||
}
|
||||
|
||||
public String getErrMsg() {
|
||||
return errMsg;
|
||||
}
|
||||
|
||||
public void setErrMsg(String errMsg) {
|
||||
this.errMsg = errMsg;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getChannelErrCd() {
|
||||
return channelErrCd;
|
||||
}
|
||||
|
||||
public void setChannelErrCd(String channelErrCd) {
|
||||
this.channelErrCd = channelErrCd;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.eactive.eai.custom.stderrorcode;
|
||||
|
||||
import com.eactive.eai.agent.AgentUtil;
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 ChannelErrorCodeManager의 정보 변경
|
||||
* 2. 처리 개요 : 메모리 전체 정보를 manager에서 reload
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*
|
||||
*/
|
||||
public class ReloadChannelErrorCodeCommand extends Command {
|
||||
/**
|
||||
* 1. 기능 : ReloadAdapterGroupCommand 생성자
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public ReloadChannelErrorCodeCommand() {
|
||||
super("ReloadChannelErrorCodeCommand");
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : ChannelErrorCodeManager에 errorCode를 reload
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항 :
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException {
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
if (logger.isInfo())
|
||||
logger.info(this.name + " is executed");
|
||||
|
||||
ChannelErrorCodeManager manager = ChannelErrorCodeManager.getInstance();
|
||||
try {
|
||||
manager.reload();
|
||||
} catch (Exception e) {
|
||||
String rspErrorCode = "RECEAIMCM002";
|
||||
String msg = makeException(rspErrorCode, e);
|
||||
if (logger.isError())
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
if (logger.isInfo())
|
||||
logger.info(this.name + " is finished");
|
||||
return "success";
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Command command = new ReloadChannelErrorCodeCommand();
|
||||
AgentUtil.broadcast(command);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.eactive.eai.custom.stderrorcode;
|
||||
|
||||
import com.eactive.eai.agent.AgentUtil;
|
||||
import com.eactive.eai.agent.command.Command;
|
||||
import com.eactive.eai.agent.command.CommandException;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
/**
|
||||
* 1. 기능 : Running중인 EAI Server의 메모리에 로딩된 StdErrorCodeManager의 정보 변경
|
||||
* 2. 처리 개요 : 메모리 전체 정보를 manager에서 reload
|
||||
* 3. 주의사항
|
||||
*
|
||||
* @author
|
||||
* @version v 1.0.0
|
||||
* @see 관련 기능을 참조
|
||||
* @since
|
||||
*
|
||||
*/
|
||||
public class ReloadStdErrorCodeCommand extends Command {
|
||||
/**
|
||||
* 1. 기능 : ReloadAdapterGroupCommand 생성자
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항
|
||||
*
|
||||
**/
|
||||
public ReloadStdErrorCodeCommand() {
|
||||
super("ReloadStdErrorCodeCommand");
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 기능 : StdErrorCodeManager에 errorCode를 reload
|
||||
* 2. 처리 개요 :
|
||||
* 3. 주의사항 :
|
||||
*
|
||||
* @exception CommandException Argument Type이 다르거나 Command 수행중 Excpetion이 발생할 경우
|
||||
**/
|
||||
public Object execute() throws CommandException {
|
||||
Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
if (logger.isInfo())
|
||||
logger.info(this.name + " is executed");
|
||||
|
||||
StdErrorCodeManager manager = StdErrorCodeManager.getInstance();
|
||||
try {
|
||||
manager.reload();
|
||||
} catch (Exception e) {
|
||||
String rspErrorCode = "RECEAIMCM002";
|
||||
String msg = makeException(rspErrorCode, e);
|
||||
if (logger.isError())
|
||||
logger.error(msg, e);
|
||||
throw new CommandException(msg);
|
||||
}
|
||||
|
||||
if (logger.isInfo())
|
||||
logger.info(this.name + " is finished");
|
||||
return "success";
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Command command = new ReloadChannelErrorCodeCommand();
|
||||
AgentUtil.broadcast(command);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.eactive.eai.custom.stderrorcode;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.eactive.eai.common.dao.BaseDAO;
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.eactive.eai.custom.stderrorcode.loader.StdErrorCodeLoader;
|
||||
import com.eactive.eai.custom.stderrorcode.mapper.StdErrorCodeMapper;
|
||||
import com.eactive.eai.data.entity.custom.stderrorcode.StdErrorCode;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class StdErrorCodeDAO extends BaseDAO {
|
||||
private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
@Autowired
|
||||
private StdErrorCodeLoader stdErrorCodeEntityService;
|
||||
|
||||
@Autowired
|
||||
private StdErrorCodeMapper stdErrorCodeMapper;
|
||||
|
||||
public HashMap getAllSTDErrorCode() throws DAOException {
|
||||
try {
|
||||
HashMap groups = new HashMap();
|
||||
List<StdErrorCode> services = stdErrorCodeEntityService.findAllByNow();
|
||||
logger.info("[ @@ Load STD Error Code Configuration - starting >>>>>>>>>>>>>>>>> ]");
|
||||
for (StdErrorCode stdErr : services) {
|
||||
StdErrorCodeVO vo = stdErrorCodeMapper.toVo(stdErr);
|
||||
groups.put(vo.getErrCd(), vo);
|
||||
logger.info("[>>Load STD Error Code vo(" + vo.getErrCd() + ") =" + vo + " ]");
|
||||
}
|
||||
logger.info("[>>Load STD Error Code Configuration - ended ]");
|
||||
return groups;
|
||||
} catch (Exception e) {
|
||||
throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICPM101"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.eactive.eai.custom.stderrorcode;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.eactive.eai.common.dao.DAOException;
|
||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
||||
import com.eactive.eai.common.lifecycle.Lifecycle;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleException;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleListener;
|
||||
import com.eactive.eai.common.lifecycle.LifecycleSupport;
|
||||
import com.eactive.eai.common.util.ApplicationContextProvider;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
|
||||
@Component
|
||||
public class StdErrorCodeManager implements Lifecycle {
|
||||
|
||||
static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
private LifecycleSupport lifecycle = new LifecycleSupport(this);
|
||||
private Map<String, StdErrorCodeVO> stdErrorCodes = new HashMap();
|
||||
private boolean started;
|
||||
|
||||
@Autowired
|
||||
private StdErrorCodeDAO dao;
|
||||
|
||||
public static StdErrorCodeManager getInstance() {
|
||||
return ApplicationContextProvider.getContext().getBean(StdErrorCodeManager.class);
|
||||
}
|
||||
|
||||
public boolean isStarted() {
|
||||
return this.started;
|
||||
}
|
||||
|
||||
public synchronized void reload() throws LifecycleException {
|
||||
logger.warn("reload StdErrorCodeManager ...");
|
||||
|
||||
try {
|
||||
init();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
logger.warn("reload StdErrorCodeManager finish...");
|
||||
}
|
||||
|
||||
private void init() throws LifecycleException, Exception {
|
||||
try {
|
||||
this.stdErrorCodes = dao.getAllSTDErrorCode();
|
||||
} catch (DAOException e) {
|
||||
// throw new LifecycleException("RECEAICPM201");
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAICPM201"));
|
||||
}
|
||||
}
|
||||
|
||||
public void start() throws LifecycleException {
|
||||
if (started)
|
||||
throw new LifecycleException("RECEAICCM201");
|
||||
|
||||
lifecycle.fireLifecycleEvent(STARTING_EVENT, this);
|
||||
|
||||
try {
|
||||
init();
|
||||
} catch (Exception e) {
|
||||
throw new LifecycleException(ExceptionUtil.getErrorCode(e, "RECEAICCM202"));
|
||||
}
|
||||
|
||||
started = true;
|
||||
lifecycle.fireLifecycleEvent(STARTED_EVENT, this);
|
||||
}
|
||||
|
||||
public void stop() throws LifecycleException {
|
||||
if (!started)
|
||||
throw new LifecycleException("RECEAICCM203");
|
||||
|
||||
lifecycle.fireLifecycleEvent(STOPING_EVENT, this);
|
||||
started = false;
|
||||
logger.info("StdErrorCodeManager] It is stopped.");
|
||||
lifecycle.fireLifecycleEvent(STOPPED_EVENT, this);
|
||||
}
|
||||
|
||||
public void addLifecycleListener(LifecycleListener listener) {
|
||||
lifecycle.addLifecycleListener(listener);
|
||||
}
|
||||
|
||||
public LifecycleListener[] findLifecycleListeners() {
|
||||
return lifecycle.findLifecycleListeners();
|
||||
}
|
||||
|
||||
public void removeLifecycleListener(LifecycleListener listener) {
|
||||
lifecycle.removeLifecycleListener(listener);
|
||||
}
|
||||
public StdErrorCodeVO getSTDErrorCode(String code) {
|
||||
return stdErrorCodes.get(code);
|
||||
}
|
||||
|
||||
public String[] getAllKeyNames() {
|
||||
String[] names = this.stdErrorCodes.keySet().toArray(new String[0]);
|
||||
Arrays.sort(names);
|
||||
return names;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.eactive.eai.custom.stderrorcode;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class StdErrorCodeVO implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String errCd; // 오류코드[TSEAIMX03.ERR_CD]
|
||||
private String errMsg; // 오류메시지내용[TSEAIMX03.ISD_ERR_CAS_CTS]
|
||||
|
||||
public StdErrorCodeVO() {
|
||||
this("", "");
|
||||
}
|
||||
|
||||
public StdErrorCodeVO(String errCd, String errMsg) {
|
||||
super();
|
||||
this.errCd = errCd;
|
||||
this.errMsg = errMsg;
|
||||
}
|
||||
|
||||
public String getErrCd() {
|
||||
return errCd;
|
||||
}
|
||||
|
||||
public void setErrCd(String errCd) {
|
||||
this.errCd = errCd;
|
||||
}
|
||||
|
||||
public String getErrMsg() {
|
||||
return errMsg;
|
||||
}
|
||||
|
||||
public void setErrMsg(String errMsg) {
|
||||
this.errMsg = errMsg;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.eactive.eai.custom.stderrorcode.loader;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.data.entity.custom.stderrorcode.ChannelErrorCode;
|
||||
import com.eactive.eai.data.jpa.AbstractDataService;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class ChannelErrorCodeLoader extends AbstractDataService<ChannelErrorCode, String, ChannelErrorCodeLoaderRepository> {
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<ChannelErrorCode> findAllByNow() {
|
||||
return repository.selectAll(DatetimeUtil.getFormattedDate("yyyy-MM-dd"));
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.eactive.eai.custom.stderrorcode.loader;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.eactive.eai.data.entity.custom.stderrorcode.ChannelErrorCode;
|
||||
import com.eactive.eai.data.jpa.BaseRepository;
|
||||
|
||||
public interface ChannelErrorCodeLoaderRepository extends BaseRepository<ChannelErrorCode, String> {
|
||||
|
||||
@Query("from ChannelErrorCode where err_tlg_lan_dscd ='KOR' and err_cd_us_yn ='Y' and err_cd_apl_dt <= :pNow and del_yn = 'N' order by std_err_cd ")
|
||||
List<ChannelErrorCode> selectAll(@Param("pNow")String now);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.eactive.eai.custom.stderrorcode.loader;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.eactive.eai.common.util.DatetimeUtil;
|
||||
import com.eactive.eai.data.entity.custom.stderrorcode.StdErrorCode;
|
||||
import com.eactive.eai.data.jpa.AbstractDataService;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class StdErrorCodeLoader extends AbstractDataService<StdErrorCode, String, StdErrorCodeLoaderRepository> {
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<StdErrorCode> findAllByNow() {
|
||||
return repository.selectAll(DatetimeUtil.getFormattedDate("yyyy-MM-dd"));
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.eactive.eai.custom.stderrorcode.loader;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.eactive.eai.data.entity.custom.stderrorcode.StdErrorCode;
|
||||
import com.eactive.eai.data.jpa.BaseRepository;
|
||||
|
||||
public interface StdErrorCodeLoaderRepository extends BaseRepository<StdErrorCode, String> {
|
||||
|
||||
@Query("from StdErrorCode where std_err_cd_yn ='Y' and err_tlg_lan_dscd ='KOR' and err_cd_us_yn ='Y' and err_cd_apl_dt <= :pNow and del_yn = 'N' order by err_cd ")
|
||||
List<StdErrorCode> selectAll(@Param("pNow")String now);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.eactive.eai.custom.stderrorcode.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
import com.eactive.eai.custom.stderrorcode.ChannelErrorCodeVO;
|
||||
import com.eactive.eai.data.entity.custom.stderrorcode.ChannelErrorCode;
|
||||
import com.eactive.eai.data.mapper.GenericMapper;
|
||||
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface ChannelErrorCodeMapper extends GenericMapper<ChannelErrorCodeVO, ChannelErrorCode> {
|
||||
|
||||
@Mapping(source = "STD_ERR_CD", target = "errCd") //표준오류코드
|
||||
@Mapping(source = "CHNL_ERR_CD", target = "channelErrCd") //채널오류코드
|
||||
@Mapping(source = "CHNL_DTLS_CLCD", target = "type") //채널세부코드
|
||||
@Mapping(source = "CHNL_ERR_MSG_CTS", target = "errMsg") //채널오류메시니내용
|
||||
@Override
|
||||
ChannelErrorCodeVO toVo(ChannelErrorCode entity);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.eactive.eai.custom.stderrorcode.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
import com.eactive.eai.custom.stderrorcode.StdErrorCodeVO;
|
||||
import com.eactive.eai.data.entity.custom.stderrorcode.StdErrorCode;
|
||||
import com.eactive.eai.data.mapper.GenericMapper;
|
||||
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface StdErrorCodeMapper extends GenericMapper<StdErrorCodeVO, StdErrorCode> {
|
||||
|
||||
@Mapping(source = "ERR_CD", target = "errCd")
|
||||
@Mapping(source = "ISD_ERR_CAS_CTS", target = "errMsg")
|
||||
@Override
|
||||
StdErrorCodeVO toVo(StdErrorCode entity);
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package com.eactive.eai.custom.token.client.impl;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.httpclient.HttpClient;
|
||||
import org.apache.commons.httpclient.HttpVersion;
|
||||
import org.apache.commons.httpclient.methods.PostMethod;
|
||||
import org.apache.commons.httpclient.protocol.Protocol;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.JSONValue;
|
||||
|
||||
import com.eactive.eai.adapter.http.secure.CustomHttpsSocketFactory;
|
||||
import com.eactive.eai.adapter.http.secure.EasySSLProtocolSocketFactory;
|
||||
import com.eactive.eai.common.property.PropManager;
|
||||
import com.eactive.eai.common.util.Logger;
|
||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
||||
import com.openbanking.eai.common.token.client.HttpClientAccessTokenService;
|
||||
|
||||
public class HttpClientAccessTokenServiceForFinastra implements HttpClientAccessTokenService {
|
||||
public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
|
||||
|
||||
public static final String OAUTH_ACCESS_TOKEN_URI = "url";
|
||||
public static final String OAUTH_USER_NAME = "userName";
|
||||
public static final String OAUTH_PASSWORD = "password";
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public AccessTokenVO execute(String name, Properties prop) throws Exception {
|
||||
String url = prop.getProperty("URL");
|
||||
String timeoutTemp = prop.getProperty("HTTP_TIME_OUT", "30");
|
||||
String connectionTimeoutTemp = prop.getProperty("CONNECTION_TIMEOUT", "30");
|
||||
String httpVersion = prop.getProperty("HTTP_VERSION", "HTTP_1_0");
|
||||
|
||||
int timeout = Integer.parseInt(timeoutTemp);
|
||||
int connectionTimeout = Integer.parseInt(connectionTimeoutTemp);
|
||||
|
||||
PropManager propManager = PropManager.getInstance();
|
||||
String oAuthInfo = propManager.getProperty(AccessTokenVO.PROP_GROUP, name);
|
||||
|
||||
if (StringUtils.isBlank(oAuthInfo)) {
|
||||
throw new Exception("oAuthInfo is NULL");
|
||||
}
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* 프로퍼티 OAuthInfo에 프로퍼티 명이 TokenManager에서 관리하는 Key(어댑터그룹명)로 등록
|
||||
* ex) _TST_OU_RST_SyC =>
|
||||
* {
|
||||
* "url": "MisysSSOFBPService/SSOloginService",
|
||||
* "userName": "interfaceuser",
|
||||
* "password": "interfaceuser"
|
||||
* }
|
||||
* @formatter:on
|
||||
*/
|
||||
JSONObject oauthInfoObject = (JSONObject) JSONValue.parseWithException(oAuthInfo);
|
||||
|
||||
String oauthAccessTokenUrl = oauthInfoObject.containsKey(OAUTH_ACCESS_TOKEN_URI)
|
||||
? (String) oauthInfoObject.get(OAUTH_ACCESS_TOKEN_URI)
|
||||
: "";
|
||||
String oauthUserName = oauthInfoObject.containsKey(OAUTH_USER_NAME)
|
||||
? (String) oauthInfoObject.get(OAUTH_USER_NAME)
|
||||
: "";
|
||||
String oauthPassword = oauthInfoObject.containsKey(OAUTH_PASSWORD)
|
||||
? (String) oauthInfoObject.get(OAUTH_USER_NAME)
|
||||
: "";
|
||||
|
||||
String uri = "";
|
||||
if (StringUtils.contains(oauthAccessTokenUrl, "http://")
|
||||
|| StringUtils.contains(oauthAccessTokenUrl, "https://")) {
|
||||
uri = oauthAccessTokenUrl;
|
||||
} else {
|
||||
uri = url + "/" + oauthAccessTokenUrl;
|
||||
}
|
||||
|
||||
HttpClient mclient = new HttpClient();
|
||||
PostMethod httpMethod = new PostMethod(uri);
|
||||
|
||||
if (timeout > -1) {
|
||||
mclient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
|
||||
}
|
||||
|
||||
if (connectionTimeout != 0) {
|
||||
mclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
|
||||
}
|
||||
|
||||
if (StringUtils.equals(httpVersion, "HTTP_1_1")) {
|
||||
httpMethod.setRequestHeader("Connection", "close");
|
||||
httpMethod.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
|
||||
} else {
|
||||
httpMethod.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_0);
|
||||
}
|
||||
|
||||
if (uri != null && uri.startsWith("https")) {
|
||||
Protocol.registerProtocol("https",
|
||||
new Protocol("https", new CustomHttpsSocketFactory(new EasySSLProtocolSocketFactory()), 443));
|
||||
}
|
||||
|
||||
try {
|
||||
String bodyMsg = String.format("{\"userName\" : \"%s\",\"password\" : \"%s\"}", oauthUserName,
|
||||
oauthPassword);
|
||||
httpMethod.setRequestBody(bodyMsg);
|
||||
httpMethod.setRequestHeader("Content-Type", "application/json");
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAccessTokenServiceForFinastra] tokenUrl = [" + uri + "]");
|
||||
logger.debug("HttpClientAccessTokenServiceForFinastra] oauthUserName = [" + oauthUserName + "]");
|
||||
logger.debug("HttpClientAccessTokenServiceForFinastra] oauthPassword = [" + oauthPassword + "]");
|
||||
logger.debug("HttpClientAccessTokenServiceForFinastra] bodyMsg = [" + bodyMsg + "]");
|
||||
}
|
||||
|
||||
int status = mclient.executeMethod(httpMethod);
|
||||
|
||||
if (status != 200) {
|
||||
if (status >= 400 && status < 500) {
|
||||
logger.error(new String(httpMethod.getResponseBody()));
|
||||
}
|
||||
throw new Exception("oauth token receive status fail value= " + status);
|
||||
}
|
||||
|
||||
byte[] responseBody = httpMethod.getResponseBody();
|
||||
String responseString = new String(responseBody);
|
||||
|
||||
OAuth2AccessTokenVO accessToken = new OAuth2AccessTokenVO();
|
||||
|
||||
if (StringUtils.isNotBlank(responseString)) {
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAccessTokenServiceForFinastra] oauthToken RECV = [" + responseString + "]");
|
||||
}
|
||||
|
||||
JSONObject responseJSON = (JSONObject) JSONValue.parse(responseString);
|
||||
|
||||
if (responseJSON.containsKey("result")) {
|
||||
accessToken.setAccessToken((String) responseJSON.get("result"));
|
||||
accessToken.setTokenType("bearer");
|
||||
}
|
||||
|
||||
if (logger.isDebug()) {
|
||||
logger.debug("HttpClientAccessTokenServiceForFinastra] oauthToken =" + accessToken.toString());
|
||||
}
|
||||
} else {
|
||||
throw new Exception("oauth token return null");
|
||||
}
|
||||
|
||||
return accessToken;
|
||||
} catch (Exception e) {
|
||||
logger.error("HttpClientAccessTokenServiceForFinastra] oauth token fail : " + e.toString(), e);
|
||||
throw e;
|
||||
} finally {
|
||||
httpMethod.releaseConnection();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package com.eactive.eai.custom.transformer.message;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import com.eactive.eai.transformer.message.ISO8583Message;
|
||||
import com.solab.iso8583.IsoMessage;
|
||||
import com.solab.iso8583.IsoType;
|
||||
import com.solab.iso8583.MessageFactory;
|
||||
import com.solab.iso8583.parse.FieldParseInfo;
|
||||
|
||||
/**
|
||||
* <pre>
|
||||
* ISO 8583 H2H(전문) 형식의 데이터를 변환하기 위한 메시지.(For KB Bukopin)
|
||||
*
|
||||
* [참조]
|
||||
* https://en.wikipedia.org/wiki/ISO_8583
|
||||
* </pre>
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class ISO8583H2HMessage extends ISO8583Message {
|
||||
private static HashMap<Integer, FieldParseInfo> fullSpecMap = null;
|
||||
private static HashMap<Integer, String> fullFieldNameMap = null;
|
||||
|
||||
@Override
|
||||
public MessageFactory<IsoMessage> createMessageFactory() {
|
||||
MessageFactory<IsoMessage> mf = new MessageFactory<>();
|
||||
mf.setCharacterEncoding(System.getProperty("file.encoding"));
|
||||
mf.setForceStringEncoding(false);
|
||||
return mf;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HashMap<Integer, FieldParseInfo> getFullSpecMap(String encode) {
|
||||
if (fullSpecMap != null) {
|
||||
return fullSpecMap;
|
||||
}
|
||||
|
||||
fullSpecMap = new HashMap<>();
|
||||
|
||||
fullSpecMap.put(2, FieldParseInfo.getInstance(IsoType.LLVAR, 19, encode));
|
||||
fullSpecMap.put(3, FieldParseInfo.getInstance(IsoType.NUMERIC, 6, encode));
|
||||
fullSpecMap.put(4, FieldParseInfo.getInstance(IsoType.NUMERIC, 12, encode));
|
||||
fullSpecMap.put(6, FieldParseInfo.getInstance(IsoType.NUMERIC, 12, encode));
|
||||
fullSpecMap.put(7, FieldParseInfo.getInstance(IsoType.DATE10, 10, encode));
|
||||
fullSpecMap.put(11, FieldParseInfo.getInstance(IsoType.NUMERIC, 6, encode));
|
||||
fullSpecMap.put(12, FieldParseInfo.getInstance(IsoType.TIME, 6, encode));
|
||||
fullSpecMap.put(13, FieldParseInfo.getInstance(IsoType.DATE4, 4, encode));
|
||||
fullSpecMap.put(14, FieldParseInfo.getInstance(IsoType.DATE_EXP, 4, encode));
|
||||
fullSpecMap.put(15, FieldParseInfo.getInstance(IsoType.DATE4, 4, encode));
|
||||
fullSpecMap.put(18, FieldParseInfo.getInstance(IsoType.NUMERIC, 4, encode));
|
||||
fullSpecMap.put(22, FieldParseInfo.getInstance(IsoType.NUMERIC, 3, encode));
|
||||
fullSpecMap.put(24, FieldParseInfo.getInstance(IsoType.NUMERIC, 3, encode));
|
||||
fullSpecMap.put(25, FieldParseInfo.getInstance(IsoType.NUMERIC, 2, encode));
|
||||
fullSpecMap.put(26, FieldParseInfo.getInstance(IsoType.NUMERIC, 2, encode));
|
||||
fullSpecMap.put(32, FieldParseInfo.getInstance(IsoType.LLVAR, 11, encode));
|
||||
fullSpecMap.put(33, FieldParseInfo.getInstance(IsoType.LLVAR, 11, encode));
|
||||
fullSpecMap.put(35, FieldParseInfo.getInstance(IsoType.LLVAR, 37, encode));
|
||||
fullSpecMap.put(37, FieldParseInfo.getInstance(IsoType.ALPHA, 12, encode));
|
||||
fullSpecMap.put(38, FieldParseInfo.getInstance(IsoType.ALPHA, 6, encode));
|
||||
fullSpecMap.put(39, FieldParseInfo.getInstance(IsoType.ALPHA, 2, encode));
|
||||
fullSpecMap.put(40, FieldParseInfo.getInstance(IsoType.ALPHA, 3, encode));
|
||||
fullSpecMap.put(41, FieldParseInfo.getInstance(IsoType.ALPHA, 8, encode));
|
||||
fullSpecMap.put(42, FieldParseInfo.getInstance(IsoType.ALPHA, 15, encode));
|
||||
fullSpecMap.put(43, FieldParseInfo.getInstance(IsoType.ALPHA, 40, encode));
|
||||
fullSpecMap.put(48, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||
fullSpecMap.put(49, FieldParseInfo.getInstance(IsoType.ALPHA, 3, encode));
|
||||
// fullSpecMap.put(52, FieldParseInfo.getInstance(IsoType.BINARY, 64, encode));
|
||||
fullSpecMap.put(52, FieldParseInfo.getInstance(IsoType.ALPHA, 16, encode)); // 표준X
|
||||
fullSpecMap.put(54, FieldParseInfo.getInstance(IsoType.LLLVAR, 120, encode));
|
||||
fullSpecMap.put(55, FieldParseInfo.getInstance(IsoType.LLLVAR, 765, encode));
|
||||
fullSpecMap.put(60, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||
fullSpecMap.put(61, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||
fullSpecMap.put(62, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||
fullSpecMap.put(63, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||
fullSpecMap.put(70, FieldParseInfo.getInstance(IsoType.NUMERIC, 3, encode));
|
||||
fullSpecMap.put(90, FieldParseInfo.getInstance(IsoType.NUMERIC, 42, encode));
|
||||
fullSpecMap.put(98, FieldParseInfo.getInstance(IsoType.ALPHA, 25, encode));
|
||||
fullSpecMap.put(102, FieldParseInfo.getInstance(IsoType.LLVAR, 28, encode));
|
||||
fullSpecMap.put(103, FieldParseInfo.getInstance(IsoType.LLVAR, 28, encode));
|
||||
fullSpecMap.put(120, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||
// fullSpecMap.put(126, FieldParseInfo.getInstance(IsoType.LLLVAR, 999,
|
||||
// encode));
|
||||
fullSpecMap.put(126, FieldParseInfo.getInstance(IsoType.LLLLVAR, 9999, encode)); // 표준X
|
||||
fullSpecMap.put(127, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||
fullSpecMap.put(128, FieldParseInfo.getInstance(IsoType.BINARY, 64, encode));
|
||||
|
||||
return fullSpecMap;
|
||||
}
|
||||
|
||||
public String getFieldName(int key) {
|
||||
if (fullFieldNameMap == null) {
|
||||
fullFieldNameMap = new HashMap<>();
|
||||
fullFieldNameMap.put(1, "Bitmap, Secondary");
|
||||
fullFieldNameMap.put(2, "Primary Account Number");
|
||||
fullFieldNameMap.put(3, "Processing Code");
|
||||
fullFieldNameMap.put(4, "Amount, Transaction");
|
||||
fullFieldNameMap.put(6, "Amount, Cardholder Billing");
|
||||
fullFieldNameMap.put(7, "Transmission Date and Time");
|
||||
fullFieldNameMap.put(11, "System Trace Audit Number");
|
||||
fullFieldNameMap.put(12, "Time, Local Transaction");
|
||||
fullFieldNameMap.put(13, "Date, Local Transaction");
|
||||
fullFieldNameMap.put(14, "Date, Expiration");
|
||||
fullFieldNameMap.put(15, "Date, Settlement");
|
||||
fullFieldNameMap.put(18, "Merchant Type");
|
||||
|
||||
fullFieldNameMap.put(22, "Point of Service Entry Mode");
|
||||
fullFieldNameMap.put(24, "Network/Function Indentification Id");
|
||||
fullFieldNameMap.put(25, "Point-Of-Service Condition Code");
|
||||
|
||||
fullFieldNameMap.put(26, "Point-Of-Service PIN Capture Code");
|
||||
fullFieldNameMap.put(32, "Acquiring Institution Identification Code");
|
||||
fullFieldNameMap.put(33, "Forwarding Institution Identification Code");
|
||||
|
||||
fullFieldNameMap.put(35, "Track 2 Data");
|
||||
fullFieldNameMap.put(37, "Retrieval Reference Number");
|
||||
fullFieldNameMap.put(38, "Authorization Identification Response");
|
||||
|
||||
fullFieldNameMap.put(39, "Response Code");
|
||||
fullFieldNameMap.put(40, "Service Restriction Code");
|
||||
fullFieldNameMap.put(41, "Card Acceptor Terminal Identification");
|
||||
|
||||
fullFieldNameMap.put(42, "Card Acceptor Identification");
|
||||
fullFieldNameMap.put(43, "Card Acceptor Name and Location");
|
||||
fullFieldNameMap.put(48, "Additional Data – Private");
|
||||
|
||||
fullFieldNameMap.put(49, "Transaction Currency Code");
|
||||
fullFieldNameMap.put(52, "Personal Identification Number");
|
||||
fullFieldNameMap.put(54, "Amount, Additional");
|
||||
|
||||
fullFieldNameMap.put(55, "Integrated Circuit Card (ICC) System Related Data");
|
||||
|
||||
fullFieldNameMap.put(60, "Reserved Private F60");
|
||||
fullFieldNameMap.put(61, "Reserved Private F61");
|
||||
fullFieldNameMap.put(62, "Reserved Private F62");
|
||||
|
||||
fullFieldNameMap.put(63, "Reserved Private F63");
|
||||
fullFieldNameMap.put(70, "Network Management Information Code");
|
||||
fullFieldNameMap.put(90, "Original Data Element");
|
||||
|
||||
fullFieldNameMap.put(98, "Payee");
|
||||
fullFieldNameMap.put(102, "Account Identification 1");
|
||||
fullFieldNameMap.put(103, "Account Identification 2");
|
||||
|
||||
fullFieldNameMap.put(120, "Reserved Private F120");
|
||||
fullFieldNameMap.put(126, "Reserved Private F126");
|
||||
fullFieldNameMap.put(127, "Destination Institution Identification Code");
|
||||
fullFieldNameMap.put(128, "Message Authentication Code Field");
|
||||
}
|
||||
|
||||
return fullFieldNameMap.get(new Integer(key));
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append(
|
||||
"[ISO8583H2H message]");
|
||||
sb.append("\n" + super.toString());
|
||||
sb.append(
|
||||
"\n");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package com.eactive.eai.custom.transformer.message;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import com.eactive.eai.transformer.message.ISO8583Message;
|
||||
import com.solab.iso8583.IsoMessage;
|
||||
import com.solab.iso8583.IsoType;
|
||||
import com.solab.iso8583.MessageFactory;
|
||||
import com.solab.iso8583.parse.FieldParseInfo;
|
||||
|
||||
/**
|
||||
* @formatter:off
|
||||
* ISO 8583 Silverlake(전문) 형식의 데이터를 변환하기 위한 메시지.(For KB Bukopin)
|
||||
* - Binary, EBCDIC
|
||||
*
|
||||
* [참조] https://en.wikipedia.org/wiki/ISO_8583
|
||||
* @formatter:on
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class ISO8583SilverlakeMessage extends ISO8583Message {
|
||||
private static HashMap<Integer, FieldParseInfo> fullSpecMap = null;
|
||||
private static HashMap<Integer, String> fullFieldNameMap = null;
|
||||
private static String encode = "Cp1047"; // EBCDIC(1047)
|
||||
|
||||
public MessageFactory<IsoMessage> createMessageFactory() {
|
||||
MessageFactory<IsoMessage> mf = new MessageFactory<>();
|
||||
mf.setUseBinaryMessages(true);
|
||||
mf.setUseBinaryBitmap(true);
|
||||
mf.setVariableLengthFieldsInHex(false);
|
||||
mf.setCharacterEncoding(encode);
|
||||
mf.setForceStringEncoding(true);
|
||||
return mf;
|
||||
}
|
||||
|
||||
public HashMap<Integer, FieldParseInfo> getFullSpecMap(String enc) {
|
||||
if (fullSpecMap != null) {
|
||||
return fullSpecMap;
|
||||
}
|
||||
|
||||
fullSpecMap = new HashMap<>();
|
||||
|
||||
fullSpecMap.put(2, FieldParseInfo.getInstance(IsoType.LLBCDBIN, 10, encode));
|
||||
fullSpecMap.put(3, FieldParseInfo.getInstance(IsoType.BINARY, 3, encode));
|
||||
fullSpecMap.put(4, FieldParseInfo.getInstance(IsoType.BINARY, 6, encode));
|
||||
fullSpecMap.put(7, FieldParseInfo.getInstance(IsoType.BINARY, 5, encode));
|
||||
fullSpecMap.put(11, FieldParseInfo.getInstance(IsoType.BINARY, 3, encode));
|
||||
fullSpecMap.put(12, FieldParseInfo.getInstance(IsoType.BINARY, 3, encode));
|
||||
fullSpecMap.put(13, FieldParseInfo.getInstance(IsoType.BINARY, 2, encode));
|
||||
fullSpecMap.put(14, FieldParseInfo.getInstance(IsoType.BINARY, 2, encode));
|
||||
fullSpecMap.put(18, FieldParseInfo.getInstance(IsoType.BINARY, 2, encode));
|
||||
fullSpecMap.put(22, FieldParseInfo.getInstance(IsoType.BINARY, 2, encode));
|
||||
fullSpecMap.put(23, FieldParseInfo.getInstance(IsoType.BINARY, 2, encode));
|
||||
fullSpecMap.put(25, FieldParseInfo.getInstance(IsoType.BINARY, 1, encode));
|
||||
fullSpecMap.put(35, FieldParseInfo.getInstance(IsoType.LLBCDBIN, 19, encode));
|
||||
fullSpecMap.put(37, FieldParseInfo.getInstance(IsoType.ALPHA, 12, encode));
|
||||
fullSpecMap.put(38, FieldParseInfo.getInstance(IsoType.ALPHA, 6, encode));
|
||||
fullSpecMap.put(39, FieldParseInfo.getInstance(IsoType.ALPHA, 2, encode));
|
||||
fullSpecMap.put(41, FieldParseInfo.getInstance(IsoType.ALPHA, 8, encode));
|
||||
fullSpecMap.put(42, FieldParseInfo.getInstance(IsoType.ALPHA, 15, encode));
|
||||
fullSpecMap.put(43, FieldParseInfo.getInstance(IsoType.ALPHA, 40, encode));
|
||||
fullSpecMap.put(47, FieldParseInfo.getInstance(IsoType.LLLVAR, 256, encode));
|
||||
fullSpecMap.put(48, FieldParseInfo.getInstance(IsoType.LLLVAR, 256, encode));
|
||||
fullSpecMap.put(52, FieldParseInfo.getInstance(IsoType.BINARY, 8, encode));
|
||||
fullSpecMap.put(54, FieldParseInfo.getInstance(IsoType.LLLVAR, 120, encode));
|
||||
fullSpecMap.put(55, FieldParseInfo.getInstance(IsoType.LLLVAR, 255, encode));
|
||||
fullSpecMap.put(57, FieldParseInfo.getInstance(IsoType.LLLVAR, 255, encode));
|
||||
fullSpecMap.put(58, FieldParseInfo.getInstance(IsoType.LLLVAR, 255, encode));
|
||||
fullSpecMap.put(60, FieldParseInfo.getInstance(IsoType.LLLVAR, 120, encode));
|
||||
fullSpecMap.put(61, FieldParseInfo.getInstance(IsoType.LLLVAR, 120, encode));
|
||||
fullSpecMap.put(62, FieldParseInfo.getInstance(IsoType.LLLVAR, 512, encode));
|
||||
fullSpecMap.put(63, FieldParseInfo.getInstance(IsoType.LLLVAR, 512, encode));
|
||||
fullSpecMap.put(120, FieldParseInfo.getInstance(IsoType.LLLVAR, 700, encode));
|
||||
fullSpecMap.put(121, FieldParseInfo.getInstance(IsoType.LLLVAR, 500, encode));
|
||||
fullSpecMap.put(122, FieldParseInfo.getInstance(IsoType.LLLVAR, 350, encode));
|
||||
fullSpecMap.put(123, FieldParseInfo.getInstance(IsoType.LLLVAR, 999, encode));
|
||||
fullSpecMap.put(124, FieldParseInfo.getInstance(IsoType.LLLVAR, 450, encode));
|
||||
fullSpecMap.put(125, FieldParseInfo.getInstance(IsoType.LLLVAR, 255, encode));
|
||||
|
||||
return fullSpecMap;
|
||||
}
|
||||
|
||||
public String getFieldName(int key) {
|
||||
if (fullFieldNameMap == null) {
|
||||
fullFieldNameMap = new HashMap<>();
|
||||
fullFieldNameMap.put(1, "Secondary Bit Map");
|
||||
fullFieldNameMap.put(2, "Primary Account Number");
|
||||
fullFieldNameMap.put(3, "Processing code");
|
||||
fullFieldNameMap.put(4, "Amount,transaction");
|
||||
fullFieldNameMap.put(7, "Transmission date & time");
|
||||
fullFieldNameMap.put(11, "System audit trace number");
|
||||
fullFieldNameMap.put(12, "Time, local transaction");
|
||||
fullFieldNameMap.put(13, "Date, local transaction");
|
||||
fullFieldNameMap.put(14, "Date, expiration");
|
||||
fullFieldNameMap.put(18, "Merchant type");
|
||||
fullFieldNameMap.put(22, "POS entry mode");
|
||||
fullFieldNameMap.put(23, "Card sequence number");
|
||||
fullFieldNameMap.put(25, "POS condition code");
|
||||
fullFieldNameMap.put(35, "Track 2 data");
|
||||
fullFieldNameMap.put(37, "Retrieval reference number");
|
||||
fullFieldNameMap.put(38, "Authorisation ID response");
|
||||
fullFieldNameMap.put(39, "Response code");
|
||||
fullFieldNameMap.put(41, "Terminal ID");
|
||||
fullFieldNameMap.put(42, "Card acceptor ID");
|
||||
fullFieldNameMap.put(43, "Card acceptor name/location");
|
||||
fullFieldNameMap.put(47, "Private Use");
|
||||
fullFieldNameMap.put(48, "Request header");
|
||||
fullFieldNameMap.put(52, "PIN data");
|
||||
fullFieldNameMap.put(54, "Private Use");
|
||||
fullFieldNameMap.put(55, "ICC system related data");
|
||||
fullFieldNameMap.put(57, "Private Use");
|
||||
fullFieldNameMap.put(58, "Private Use");
|
||||
fullFieldNameMap.put(60, "Private Use");
|
||||
fullFieldNameMap.put(61, "Private Use");
|
||||
fullFieldNameMap.put(62, "Private Use");
|
||||
fullFieldNameMap.put(63, "Private Use");
|
||||
fullFieldNameMap.put(120, "Private Use");
|
||||
fullFieldNameMap.put(121, "Private Use");
|
||||
fullFieldNameMap.put(122, "Response detail");
|
||||
fullFieldNameMap.put(123, "Response detail");
|
||||
fullFieldNameMap.put(124, "Private Use");
|
||||
fullFieldNameMap.put(125, "Private Use");
|
||||
}
|
||||
|
||||
return fullFieldNameMap.get(new Integer(key));
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append("[ISO8583 Silverlake message]");
|
||||
sb.append("\n" + super.toString());
|
||||
sb.append("\n");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.eactive.eai.data.entity.custom.stderrorcode;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import org.hibernate.annotations.Comment;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
|
||||
import com.eactive.eai.data.entity.AbstractEntity;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NonNull;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = true)
|
||||
|
||||
@Entity
|
||||
@Table(name = "tseaimx06")
|
||||
@org.hibernate.annotations.Table(appliesTo = "tseaimx06", comment = "채널 에러코드")
|
||||
public class ChannelErrorCode extends AbstractEntity<String> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@Column(unique = true, nullable = false, length = 36)
|
||||
@Comment("표준오류코드ID")
|
||||
private String OBJ_ID;
|
||||
|
||||
@Column(length = 10)
|
||||
@Comment("표준오류코드")
|
||||
private String STD_ERR_CD;
|
||||
|
||||
@Column(length = 3)
|
||||
@Comment("언어구분코드")
|
||||
private String ERR_TLG_LAN_DSCD;
|
||||
|
||||
@Column(length = 1)
|
||||
@Comment("오류유형코드")
|
||||
private String ERR_TP_CD;
|
||||
|
||||
@Column(length = 4)
|
||||
@Comment("채널유형코드")
|
||||
private String CHNL_TP_CD;
|
||||
|
||||
@Column(length = 1)
|
||||
@Comment("채널코드사용여부")
|
||||
private String ERR_CD_US_YN;
|
||||
|
||||
@Column(length = 10)
|
||||
@Comment("채널오류코드")
|
||||
private String CHNL_ERR_CD;
|
||||
@Column(length = 3)
|
||||
@Comment("채널세부코드")
|
||||
private String CHNL_DTLS_CLCD;
|
||||
|
||||
@Column(length = 200)
|
||||
@Comment("채널오류메시지내용")
|
||||
private String CHNL_ERR_MSG_CTS;
|
||||
|
||||
@Column(length = 10)
|
||||
@Comment("에러코드적용일자")
|
||||
private String ERR_CD_APL_DT;
|
||||
|
||||
@Column(length = 36)
|
||||
@Comment("채널오류코드의OBJ_ID")
|
||||
private String CHNL_ID;
|
||||
|
||||
@Column(length = 10)
|
||||
@Comment("조치코드")
|
||||
private String ACTN_CD;
|
||||
|
||||
@Column(length = 36)
|
||||
@Comment("조치코드의 OBJ_ID")
|
||||
private String OF_ACTN_CD;
|
||||
|
||||
@Column(name = "CHNG_DTTM", nullable = false)
|
||||
@CreationTimestamp
|
||||
private LocalDateTime createDatetime;
|
||||
|
||||
@Column(length = 1)
|
||||
@Comment("삭제여부")
|
||||
private String DEL_YN;
|
||||
|
||||
@Column(name = "MOD_DTTM", nullable = false)
|
||||
@UpdateTimestamp
|
||||
private LocalDateTime updateDatetime;
|
||||
|
||||
@Override
|
||||
public @NonNull String getId() {
|
||||
return OBJ_ID;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.eactive.eai.data.entity.custom.stderrorcode;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import org.hibernate.annotations.Comment;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
|
||||
import com.eactive.eai.data.entity.AbstractEntity;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NonNull;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = true)
|
||||
|
||||
@Entity
|
||||
@Table(name = "tseaimx03")
|
||||
@org.hibernate.annotations.Table(appliesTo = "tseaimx03", comment = "표준전문 에러코드")
|
||||
public class StdErrorCode extends AbstractEntity<String> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@Column(unique = true, nullable = false, length = 36)
|
||||
@Comment("표준오류코드ID")
|
||||
private String OBJ_ID;
|
||||
|
||||
@Column(length = 1)
|
||||
@Comment("표준오류코드여부")
|
||||
private String STD_ERR_CD_YN;
|
||||
|
||||
@Column(length = 10)
|
||||
@Comment("표준오류코드")
|
||||
private String ERR_CD;
|
||||
|
||||
@Column(length = 10)
|
||||
@Comment("ASIS오류코드")
|
||||
private String STSY_ERR_CD;
|
||||
|
||||
@Column(length = 3)
|
||||
@Comment("언어구분코드")
|
||||
private String ERR_TLG_LAN_DSCD;
|
||||
|
||||
@Column(length = 1)
|
||||
@Comment("메시지구분")
|
||||
private String MSG_DIT;
|
||||
|
||||
@Column(length = 1)
|
||||
@Comment("오류유형코드")
|
||||
private String ERR_TP_CD;
|
||||
|
||||
@Column(length = 1)
|
||||
@Comment("오류코드사용여부")
|
||||
private String ERR_CD_US_YN;
|
||||
|
||||
@Column(length = 1)
|
||||
@Comment("부적정메시지여부")
|
||||
private String IPT_MSG_CD_YN;
|
||||
|
||||
@Column(length = 200)
|
||||
@Comment("오류메시지내용")
|
||||
private String ISD_ERR_CAS_CTS;
|
||||
|
||||
@Column(length = 200)
|
||||
@Comment("고객메시지오류원인내용")
|
||||
private String OSD_ERR_CAS_CTS;
|
||||
|
||||
@Column(length = 10)
|
||||
@Comment("에러코드적용일자")
|
||||
private String ERR_CD_APL_DT;
|
||||
|
||||
@Column(length = 10)
|
||||
@Comment("조치코드")
|
||||
private String ACTN_CD;
|
||||
|
||||
@Column(length = 36)
|
||||
@Comment("조치코드의 OBJ_ID")
|
||||
private String OF_ACTN_CD;
|
||||
|
||||
@Column(name = "CHNG_DTTM", nullable = false)
|
||||
@CreationTimestamp
|
||||
private LocalDateTime createDatetime;
|
||||
|
||||
@Column(length = 1)
|
||||
@Comment("삭제여부")
|
||||
private String DEL_YN;
|
||||
|
||||
@Column(name = "MOD_DTTM", nullable = false)
|
||||
@UpdateTimestamp
|
||||
private LocalDateTime updateDatetime;
|
||||
|
||||
@Override
|
||||
public @NonNull String getId() {
|
||||
return OBJ_ID;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user