This commit is contained in:
Rinjae
2025-09-05 17:16:26 +09:00
commit c54ef1903f
4947 changed files with 817291 additions and 0 deletions
@@ -0,0 +1,147 @@
package com.eactive.eai.rms.ext.cm.epb;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;
@Controller
@RequestMapping(value={"/epb/cmBAP.do","/epb/cmBAP.json"})
public class CmBAPController implements InterceptorSkipController{
private static final Logger logger = Logger.getLogger(CmBAPController.class);
private static final String resultView ="common/loadResult";
@Autowired
private MonitoringContext monitoringContext;
@Autowired
private CmBAPService cmBAPService;
// @Autowired
// @Qualifier("onlAgentUtilService")
// public AgentUtilService agentUtilService;
@RequestMapping(params = { "cmd=load" })
public ModelAndView load(HttpServletRequest request, String deployId, String serviceType, String appCode, String rollbackYn) throws Exception {
boolean isJSONResult=false;
if (request.getRequestURI().endsWith("json")){
isJSONResult = true;
}
try {
Properties prop = monitoringContext.getProperties();
String uploadPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, "/dat/eaiData/upload/");
String afterPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_AFTER_PATH, "/dat/eaiData/after/");
String backupPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_BACKUP_PATH, "/dat/eaiData/backup/");
run(uploadPath, afterPath, backupPath, serviceType, appCode, deployId, rollbackYn );
HashMap result = new HashMap();
result.put("status", "success");
result.put("message", "");
if (isJSONResult){
return new ModelAndView("jsonView", result);
}else{
return new ModelAndView(resultView, "result", result);
}
} catch (Exception e) {
logger.error("CmController: property module error", e);
//throw new Exception(e);
HashMap result = new HashMap();
result.put("status", "error");
result.put("message", e.getMessage());
if (isJSONResult){
return new ModelAndView("jsonView", result);
}else{
return new ModelAndView(resultView, "result", result);
}
}
}
/**
* path : /dat/eaiData/{serviceType}/{deployId}/{appCode}/
* 1. 배포 id 추출
* 2. 배포 id 기준으로 목록 수집
* 3. 배포 id 기준으로 layout, transform, interface 로딩
*
* @throws Exception
*/
private void run(String uploadPath, String afterPath, String backupPath, String serviceType, String appCode, String deployId, String rollbackYn ) throws Exception {
String path = uploadPath + serviceType + File.separator + deployId + File.separator + appCode;
File uploadDir = new File(path);
if (!uploadDir.exists()){
throw new Exception("폴더존재안함 +" + uploadDir.getAbsolutePath());
}
// 시스템셋팅(datasourceType)
DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
if (dt == null){
logger.info("not support serviceType : "+ serviceType);
return;
}
DataSourceContextHolder.setDataSourceType(dt);
ArrayList<String> fileinfoSync = new ArrayList<String>();
String fileinfoPath = path + File.separator + "fileinfo";
//fileinfo 식별
File fileinfoDir = new File(fileinfoPath);
if (fileinfoDir.exists()){
//DB 적재하는 부분
fileinfoSync = cmBAPService.insertFIleInfoFile(dt,fileinfoDir);
}
//메모리 동기화
//TODO HD : 검토 필요: 프라퍼티 정보 관리
//fileinfo
if (fileinfoSync != null && fileinfoSync.size() > 0){
cmBAPService.fileInfoMemorySync();
}
//폴더 이동
// 5. after 경로로 이동
//after folder check & move
// 이동순서 uploadFolder => afterFolder => backupFolder
// uploadFolder는 원본데이터, afterFolder는 적용된 데이터(최근꺼만 존재), backupFolder 은 적용된게 여러개일경우(히스토리성)
//afterfolder에 존재하면 backupFolder로 이관 중복안나게 폴더에 날짜포맷추가
File afterFolder = new File(afterPath + File.separator + serviceType + File.separator + deployId);
logger.info("afterFolder : " + afterFolder.getAbsolutePath() + " , " + afterFolder.exists());
if (afterFolder.exists()){
File backupFolder = new File(backupPath+ File.separator + serviceType + File.separator+ deployId + "_" + DatetimeUtil.getCurrentTimeMsNoMark(afterFolder.lastModified()));
logger.info("backupFolder : " + backupFolder.getAbsolutePath());
if (backupFolder.exists() && backupFolder.isDirectory()){
FileUtils.deleteDirectory(backupFolder);
}
boolean result = afterFolder.renameTo(backupFolder);
logger.info("rename "+afterFolder.getAbsolutePath()+" to " + backupFolder.getAbsolutePath() + " result=" + result);
}
//upload folder to after folder (적용된거 이동)
File uploadFolder = new File(uploadPath + File.separator + serviceType + File.separator + deployId );
logger.info("uploadFolder : " + uploadFolder.getAbsolutePath() + " , "+uploadFolder.exists() );
if (uploadFolder.exists()){
boolean result = uploadFolder.renameTo(afterFolder);
logger.info("rename "+uploadFolder.getAbsolutePath()+" to " + afterFolder.getAbsolutePath() + " result=" + result);
}
}
}
@@ -0,0 +1,55 @@
package com.eactive.eai.rms.ext.cm.epb;
import java.io.File;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.bap.loader.service.TransactionBAPService;
import com.eactive.eai.rms.common.base.BapBaseAnnotationController;
import com.eactive.eai.rms.common.datasource.DataSourceType;
@Service("cmBAPService")
public class CmBAPService extends BapBaseAnnotationController {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(CmBAPService.class);
@Autowired
@Qualifier("loaderBAPService")
private TransactionBAPService loaderBAPService;
public ArrayList<String> insertFIleInfoFile(DataSourceType dt, File fileinfoDir) throws Exception{
ArrayList<String> al = new ArrayList<String>();
String path = fileinfoDir.getAbsolutePath() + File.separator;
File subDir = new File(path);
String[] sublistFiles = subDir.list();
if (sublistFiles != null && sublistFiles.length > 0) {
for(String fileName : sublistFiles){
String data = fileName.substring(0,fileName.length()-4);
al.add(data);
logger.info("CmBAPService fileName : fileName =" + fileName +" , data =" + data +" , path = "+ path);
loaderBAPService.insertFileInfoLoading(dt, path, fileName);
}
}
return al;
}
public boolean fileInfoMemorySync() throws Exception {
CommonCommand command = new CommonCommand("com.eactive.eai.agent.rule.dirInfo.RefreshAllJobCommand");
agentUtilService.broadcast(command);
long currentTime = System.currentTimeMillis();
logger.info(">> 메모리동기화 처리시간(ms) : " + (System.currentTimeMillis() - currentTime));
return true;
}
}
@@ -0,0 +1,160 @@
package com.eactive.eai.rms.ext.cm.epb;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;
import com.eactive.eai.rms.onl.common.util.FileWriteUtil;
@Controller
@RequestMapping(value={"/epb/cmBAT.json"})
public class CmBATController implements InterceptorSkipController{
private static final Logger logger = Logger.getLogger(CmBATController.class);
private static final String resultView ="common/loadResult";
@Autowired
@Qualifier("monitoringContext")
private MonitoringContext monitoringContext;
@Autowired
private CmBATService cmBatService;
@RequestMapping(params = { "cmd=load" })
public ModelAndView load(HttpServletRequest request, String deployId, String serviceType, String appCode, String rollbackYn) throws Exception {
boolean isJSONResult=false;
if (request.getRequestURI().endsWith("json")){
isJSONResult = true;
}
try {
// if (SystemUtil.isDevServer()) {
// logger.info("CmController: 해당 시스템에선 사용할 수 없습니다. ["+ System.getProperty("eai.systemmode") +"]");
// HashMap<String,String> result = new HashMap<String,String>();
// result.put("status", "error");
// result.put("message", "해당 시스템에선 사용할 수 없습니다. ["+ System.getProperty("eai.systemmode") +"]");
// if (isJSONResult){
// return new ModelAndView("jsonView", result);
// }else{
// return new ModelAndView(resultView, "result", result);
// }
// }
Properties prop = monitoringContext.getProperties();
String uploadPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, "/dat/eaiData/upload/");
String afterPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_AFTER_PATH, "/dat/eaiData/after/");
String backupPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_BACKUP_PATH, "/dat/eaiData/backup/");
run(uploadPath, afterPath, backupPath, serviceType, appCode, deployId, rollbackYn );
HashMap result = new HashMap();
result.put("status", "success");
result.put("message", "");
if (isJSONResult){
return new ModelAndView("jsonView", result);
}else{
return new ModelAndView(resultView, "result", result);
}
} catch (Exception e) {
logger.error("CmController: property module error", e);
//throw new Exception(e);
HashMap result = new HashMap();
result.put("status", "error");
result.put("message", e.getMessage());
if (isJSONResult){
return new ModelAndView("jsonView", result);
}else{
return new ModelAndView(resultView, "result", result);
}
}
}
/**
* path : /dat/eaiData/{serviceType}/{deployId}/{appCode}/
* 1. 배포 id 추출
* 2. 배포 id 기준으로 목록 수집
* 3. 배포 id 기준으로 layout, transform, interface 로딩
*
* @throws Exception
*/
private void run(String uploadPath, String afterPath, String backupPath, String serviceType, String appCode, String deployId, String rollbackYn ) throws Exception {
String path = uploadPath + serviceType + File.separator + deployId + File.separator + appCode;
File uploadDir = new File(path);
if (!uploadDir.exists()){
throw new Exception("폴더존재안함 +" + uploadDir.getAbsolutePath());
}
// 시스템셋팅(datasourceType)
DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType.equals("EBT") ? "BAT" : serviceType);
if (dt == null){
logger.info("not support serviceType : "+ serviceType);
return;
}
DataSourceContextHolder.setDataSourceType(dt);
runEbtSync(path, dt);
//폴더 이동
// 5. after 경로로 이동
//after folder check & move
// 이동순서 uploadFolder => afterFolder => backupFolder
// uploadFolder는 원본데이터, afterFolder는 적용된 데이터(최근꺼만 존재), backupFolder 은 적용된게 여러개일경우(히스토리성)
//afterfolder에 존재하면 backupFolder로 이관 중복안나게 폴더에 날짜포맷추가
File afterFolder = new File(afterPath + File.separator + serviceType + File.separator + deployId);
logger.info("afterFolder : " + afterFolder.getAbsolutePath() + " , " + afterFolder.exists());
if (afterFolder.exists()){
File backupFolder = new File(backupPath+ File.separator + serviceType + File.separator+ deployId + "_" + DatetimeUtil.getCurrentTimeMsNoMark(afterFolder.lastModified()));
logger.info("backupFolder : " + backupFolder.getAbsolutePath());
if (backupFolder.exists() && backupFolder.isDirectory()){
FileUtils.deleteDirectory(backupFolder);
}
boolean result = afterFolder.renameTo(backupFolder);
logger.info("rename "+afterFolder.getAbsolutePath()+" to " + backupFolder.getAbsolutePath() + " result=" + result);
}
//upload folder to after folder (적용된거 이동)
File uploadFolder = new File(uploadPath + File.separator + serviceType + File.separator + deployId );
logger.info("uploadFolder : " + uploadFolder.getAbsolutePath() + " , "+uploadFolder.exists() );
if (uploadFolder.exists()){
boolean result = uploadFolder.renameTo(afterFolder);
logger.info("rename "+uploadFolder.getAbsolutePath()+" to " + afterFolder.getAbsolutePath() + " result=" + result);
}
}
/**
* path : /dat/eaiData/{serviceType}/{deployId}/{appCode}/
* 1. 배포 id 추출
* 2. 배포 id 기준으로 목록 수집
* 3. 배포 id 기준으로 layout, transform, interface 로딩
*
* @throws Exception
*/
private void runEbtSync(String path, DataSourceType dt ) throws Exception {
HashMap<String,ArrayList<String>> interfaceSync = new HashMap<String,ArrayList<String>>();
//인터페이스 식별
File interfaceDir = new File(path + File.separator + FileWriteUtil.INTERFACE);
if (interfaceDir.exists()){
//DB 적재하는 부분
interfaceSync = cmBatService.insertInterfaceFile(dt,interfaceDir);
}
}
}
@@ -0,0 +1,51 @@
package com.eactive.eai.rms.ext.cm.epb;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.eactive.eai.rms.bat.loader.service.TransactionLoaderServiceImpl;
import com.eactive.eai.rms.common.base.OnlBaseService;
import com.eactive.eai.rms.common.datasource.DataSourceType;
@Service("cmBATService")
public class CmBATService extends OnlBaseService {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(CmBATService.class);
@Autowired
@Qualifier("batLoaderService")
private TransactionLoaderServiceImpl batLoaderService;
public HashMap<String,ArrayList<String>> insertInterfaceFile(DataSourceType dt, File interfaceDir) throws Exception{
HashMap<String,ArrayList<String>> result = new HashMap<String,ArrayList<String>>();
ArrayList<String> al = new ArrayList<String>();
String path = interfaceDir.getAbsolutePath() + File.separator;
File subDir = new File(path);
String[] sublistFiles = subDir.list();
if (sublistFiles != null && sublistFiles.length > 0) {
for(String fileName : sublistFiles){
String data = fileName.substring(0,fileName.length()-4);
al.add(data);
logger.info("CmBATService interface : fileName =" + fileName +" , data =" + data +" , path = "+ path);
batLoaderService.insertInterfaceLoading(dt,path , fileName);
}
}
if (al.size()>0) {
result.put(interfaceDir.getName(), al);
}
return result;
}
}
@@ -0,0 +1,296 @@
package com.eactive.eai.rms.ext.cm.epb;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;
import com.eactive.eai.rms.common.interceptor.dynamicLog.DynamicLogController;
import com.eactive.eai.rms.onl.common.service.AgentUtilService;
import com.eactive.eai.rms.onl.common.util.FileWriteUtil;
import com.eactive.eai.rms.onl.manage.rule.transform.TransformManService;
@Controller
@RequestMapping(value={"/epb/cm.do","/epb/cm.json"})
public class CmController implements InterceptorSkipController, DynamicLogController{
private static final Logger logger = Logger.getLogger("DYNAMIC_LOGGER");
private static final String resultView ="common/loadResult";
@Autowired
@Qualifier("monitoringContext")
private MonitoringContext monitoringContext;
@Autowired
private CmService cmService;
@Autowired
private CmBATService cmBatService;
@Autowired
private TransformManService transformManService;
@Autowired
@Qualifier("onlAgentUtilService")
public AgentUtilService agentUtilService;
@RequestMapping(params = { "cmd=load" })
public ModelAndView load(HttpServletRequest request, String deployId, String serviceType, String appCode, String rollbackYn) throws Exception {
boolean isJSONResult=false;
if (request.getRequestURI().endsWith("json")){
isJSONResult = true;
}
try {
// if (SystemUtil.isDevServer()) {
// logger.info("CmController: 해당 시스템에선 사용할 수 없습니다. ["+ System.getProperty("eai.systemmode") +"]");
// HashMap<String,String> result = new HashMap<String,String>();
// result.put("status", "error");
// result.put("message", "해당 시스템에선 사용할 수 없습니다. ["+ System.getProperty("eai.systemmode") +"]");
// if (isJSONResult){
// return new ModelAndView("jsonView", result);
// }else{
// return new ModelAndView(resultView, "result", result);
// }
// }
Properties prop = monitoringContext.getProperties();
String uploadPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, "/dat/eaiData/upload/");
String afterPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_AFTER_PATH, "/dat/eaiData/after/");
String backupPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_BACKUP_PATH, "/dat/eaiData/backup/");
run(uploadPath, afterPath, backupPath, serviceType, appCode, deployId, rollbackYn );
HashMap result = new HashMap();
result.put("status", "success");
result.put("message", "");
if (isJSONResult){
return new ModelAndView("jsonView", result);
}else{
return new ModelAndView(resultView, "result", result);
}
} catch (Exception e) {
logger.error("CmController: property module error", e);
//throw new Exception(e);
HashMap result = new HashMap();
result.put("status", "error");
result.put("message", e.getMessage());
if (isJSONResult){
return new ModelAndView("jsonView", result);
}else{
return new ModelAndView(resultView, "result", result);
}
}
}
/**
* path : /dat/eaiData/{serviceType}/{deployId}/{appCode}/
* 1. 배포 id 추출
* 2. 배포 id 기준으로 목록 수집
* 3. 배포 id 기준으로 layout, transform, interface 로딩
*
* @throws Exception
*/
private void run(String uploadPath, String afterPath, String backupPath, String serviceType, String appCode, String deployId, String rollbackYn ) throws Exception {
String path = uploadPath + serviceType + File.separator + deployId + File.separator + appCode;
File uploadDir = new File(path);
if (!uploadDir.exists()){
throw new Exception("폴더존재안함 +" + uploadDir.getAbsolutePath());
}
// 시스템셋팅(datasourceType)
DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
if (dt == null){
logger.info("not support serviceType : "+ serviceType);
return;
}
DataSourceContextHolder.setDataSourceType(dt);
HashMap<String,ArrayList<String>> interfaceSync = new HashMap<String,ArrayList<String>>();
ArrayList<String> layoutSync = new ArrayList<String>();
ArrayList<String> transformSync = new ArrayList<String>();
List<String> additionalTransformSync = new ArrayList<String>();
//layout 식별
File layoutDir = new File(path + File.separator + FileWriteUtil.LAYOUT);
if (layoutDir.exists()){
//DB 적재하는 부분
layoutSync = cmService.insertLayoutFile(dt,layoutDir);
}
//변환 식별
File transformDir = new File(path + File.separator + FileWriteUtil.TRANSFORM);
if (transformDir.exists()){
//DB 적재하는 부분
transformSync = cmService.insertTransformFile(dt,transformDir);
}
// layout을 갖고있는 transform중 upload 파일목록으로 들어온 transform목록과 중복을 제거
if(layoutSync.size() > 0) {
additionalTransformSync = transformManService.selectTransformListByLayoutList(layoutSync);
additionalTransformSync = filterDuplicateTransformList(transformSync, additionalTransformSync);
if(additionalTransformSync.size() > 0) {
transformSync.addAll(additionalTransformSync);
logger.info("additional transform sync list ▼");
additionalTransformSync.forEach(logger::info);
}
}
//인터페이스 식별
File interfaceDir = new File(path + File.separator + FileWriteUtil.INTERFACE);
if (interfaceDir.exists()){
//DB 적재하는 부분
interfaceSync = cmService.insertInterfaceFile(dt,interfaceDir);
}
//메모리 동기화
//레이아웃
if (layoutSync != null && layoutSync.size() > 0){
cmService.layoutMemorySync(layoutSync);
}
//변환
if (transformSync != null && transformSync.size() > 0){
cmService.transformMemorySync(transformSync);
}
//인터페이스
if (interfaceSync != null && interfaceSync.size() > 0){
cmService.interfaceMemorySync(interfaceSync.get(FileWriteUtil.INTERFACE),interfaceSync.get(FileWriteUtil.INTERFACE+"EXT"));
}
//폴더 이동
// 5. after 경로로 이동
//after folder check & move
// 이동순서 uploadFolder => afterFolder => backupFolder
// uploadFolder는 원본데이터, afterFolder는 적용된 데이터(최근꺼만 존재), backupFolder 은 적용된게 여러개일경우(히스토리성)
//afterfolder에 존재하면 backupFolder로 이관 중복안나게 폴더에 날짜포맷추가
File afterFolder = new File(afterPath + File.separator + serviceType + File.separator + deployId);
logger.info("afterFolder : " + afterFolder.getAbsolutePath() + " , " + afterFolder.exists());
if (afterFolder.exists()){
File backupFolder = new File(backupPath+ File.separator + serviceType + File.separator+ deployId + "_" + DatetimeUtil.getCurrentTimeMsNoMark(afterFolder.lastModified()));
logger.info("backupFolder : " + backupFolder.getAbsolutePath());
if (backupFolder.exists() && backupFolder.isDirectory()){
FileUtils.deleteDirectory(backupFolder);
}
boolean result = afterFolder.renameTo(backupFolder);
logger.info("rename "+afterFolder.getAbsolutePath()+" to " + backupFolder.getAbsolutePath() + " result=" + result);
}
//upload folder to after folder (적용된거 이동)
File uploadFolder = new File(uploadPath + File.separator + serviceType + File.separator + deployId );
logger.info("uploadFolder : " + uploadFolder.getAbsolutePath() + " , "+uploadFolder.exists() );
if (uploadFolder.exists()){
if(additionalTransformSync.size() > 0) {
// 추가 reload Transform 존재 할 시에는 reload 폴더 생성 후 추가한 Transform의 정보를 기록
StringBuilder reloadedTransformList = new StringBuilder();
additionalTransformSync.forEach(tName -> reloadedTransformList.append(tName).append(System.getProperty("line.separator")));
File reloadFile = new File(path + File.separator + "additionalReload.txt");
FileUtils.writeStringToFile(reloadFile, reloadedTransformList.toString());
}
boolean result = uploadFolder.renameTo(afterFolder);
if(result) {
logger.info("rename folder success : "+uploadFolder.getAbsolutePath()+" to " + afterFolder.getAbsolutePath());
} else {
logger.error("rename folder error : "+uploadFolder.getAbsolutePath()+" to " + afterFolder.getAbsolutePath());
}
} else {
logger.error("upload folder does not exist : " + uploadFolder.getAbsolutePath());
}
}
private List<String> filterDuplicateTransformList(ArrayList<String> transformSync, List<String> additionalTransformSync) {
return additionalTransformSync.stream().filter(addi -> transformSync.stream().noneMatch(Predicate.isEqual(addi))).collect(Collectors.toList());
}
/**
* path : /dat/eaiData/{serviceType}/{deployId}/{appCode}/
* 1. 배포 id 추출
* 2. 배포 id 기준으로 목록 수집
* 3. 배포 id 기준으로 layout, transform, interface 로딩
*
* @throws Exception
*/
private void runOnlSync(String path, DataSourceType dt) throws Exception {
HashMap<String,ArrayList<String>> interfaceSync = new HashMap<String,ArrayList<String>>();
ArrayList<String> layoutSync = new ArrayList<String>();
ArrayList<String> transformSync = new ArrayList<String>();
//layout 식별
File layoutDir = new File(path + File.separator + FileWriteUtil.LAYOUT);
if (layoutDir.exists()){
//DB 적재하는 부분
layoutSync = cmService.insertLayoutFile(dt,layoutDir);
}
//변환 식별
File transformDir = new File(path + File.separator + FileWriteUtil.TRANSFORM);
if (transformDir.exists()){
//DB 적재하는 부분
transformSync = cmService.insertTransformFile(dt,transformDir);
}
//인터페이스 식별
File interfaceDir = new File(path + File.separator + FileWriteUtil.INTERFACE);
if (interfaceDir.exists()){
//DB 적재하는 부분
interfaceSync = cmService.insertInterfaceFile(dt,interfaceDir);
}
//메모리 동기화
//레이아웃
if (layoutSync != null && layoutSync.size() > 0){
cmService.layoutMemorySync(layoutSync);
}
//변환
if (transformSync != null && transformSync.size() > 0){
cmService.transformMemorySync(transformSync);
}
//인터페이스
if (interfaceSync != null && interfaceSync.size() > 0){
cmService.interfaceMemorySync(interfaceSync.get(FileWriteUtil.INTERFACE),interfaceSync.get(FileWriteUtil.INTERFACE+"EXT"));
}
}
/**
* path : /dat/eaiData/{serviceType}/{deployId}/{appCode}/
* 1. 배포 id 추출
* 2. 배포 id 기준으로 목록 수집
* 3. 배포 id 기준으로 layout, transform, interface 로딩
*
* @throws Exception
*/
private void runEbtSync(String path, DataSourceType dt ) throws Exception {
HashMap<String,ArrayList<String>> interfaceSync = new HashMap<String,ArrayList<String>>();
//인터페이스 식별
File interfaceDir = new File(path + File.separator + FileWriteUtil.INTERFACE);
if (interfaceDir.exists()){
//DB 적재하는 부분
interfaceSync = cmBatService.insertInterfaceFile(dt,interfaceDir);
}
}
}
@@ -0,0 +1,189 @@
package com.eactive.eai.rms.ext.cm.epb;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.common.base.OnlBaseService;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.onl.loader.service.TransactionLoaderService;
@Service("cmService")
public class CmService extends OnlBaseService {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(CmService.class);
@Autowired
@Qualifier("loaderService")
private TransactionLoaderService loaderService;
public ArrayList<String> insertLayoutFile(DataSourceType dt, File layoutDir) throws Exception{
ArrayList<String> al = new ArrayList<String>();
String path = layoutDir.getAbsolutePath() + File.separator;
File subDir = new File(path);
String[] sublistFiles = subDir.list();
if (sublistFiles != null && sublistFiles.length > 0) {
for(String fileName : sublistFiles){
String data = fileName.substring(0,fileName.length()-4);
al.add(data);
logger.info("CmService layout : fileName =" + fileName +" , data =" + data +" , path = "+ path);
loaderService.insertLayoutLoading(dt,path , fileName);
}
}
return al;
}
public HashMap<String,ArrayList<String>> insertInterfaceFile(DataSourceType dt, File interfaceDir) throws Exception{
HashMap<String,ArrayList<String>> result = new HashMap<String,ArrayList<String>>();
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
String path = interfaceDir.getAbsolutePath() + File.separator;
File subDir = new File(path);
String[] sublistFiles = subDir.list();
if (sublistFiles != null && sublistFiles.length > 0) {
for(String fileName : sublistFiles){
String data = fileName.substring(0,fileName.length()-4);
al.add(data);
logger.info("CmService interface : fileName =" + fileName +" , data =" + data +" , path = "+ path);
loaderService.insertInterfaceLoading(dt,path , fileName);
HashMap map = (HashMap)loaderService.parse(path + fileName);
ArrayList<HashMap> list = (ArrayList<HashMap>)map.get("TSEAIHS04");
if (list != null && list.size()>0){
for(HashMap row : list){
//내부표준message
String bzwkKey = (String)row.get("BZWKSVCKEYNAME");
al2.add(bzwkKey);
}
}
}
}
if (al.size()>0) {
result.put(interfaceDir.getName(), al);
}
if (al2.size()>0) {
result.put(interfaceDir.getName()+"EXT", al2);
}
return result;
}
public ArrayList<String> insertTransformFile(DataSourceType dt, File transformDir) throws Exception{
HashMap<String,ArrayList<String>> result = new HashMap<String,ArrayList<String>>();
ArrayList<String> al = new ArrayList<String>();
String path = transformDir.getAbsolutePath() + File.separator;
File subDir = new File(path);
String[] sublistFiles = subDir.list();
if (sublistFiles != null && sublistFiles.length > 0) {
for(String fileName : sublistFiles){
String data = fileName.substring(0,fileName.length()-4);
al.add(data);
logger.info("CmService interface : fileName =" + fileName +" , data =" + data +" , path = "+ path);
loaderService.insertTransformLoading(dt,path , fileName);
}
}
return al;
}
//interface 메모리 동기화
public boolean interfaceMemorySync(ArrayList<String> list, ArrayList<String> list2) throws Exception {
Vector eaiSvcNames = new Vector();
Vector bzwkKeys = new Vector();
if (list != null && list.size() > 0 ){
for (String key : list) {
eaiSvcNames.add(key);
}
}
if (list2 != null && list.size() > 0 ){
for (String key : list2) {
bzwkKeys.add(key);
}
}
long currentTime = System.currentTimeMillis();
if (eaiSvcNames.size() > 0){
syncResult(new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageListCommand"),eaiSvcNames);
syncResult(new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyListCommand"),eaiSvcNames);
syncResult(new CommonCommand("com.eactive.eai.agent.b2bextractor.ReloadB2BExtractListCommand"),eaiSvcNames);
}
if (bzwkKeys.size() > 0 ){
syncResult(new CommonCommand("com.ext.eai.agent.stdmessage.ReloadSTDMessageListCommand"),bzwkKeys);
}
logger.info(">> 메모리동기화 처리시간(ms) : "+ (System.currentTimeMillis() - currentTime));
return true;
}
public boolean layoutMemorySync(ArrayList<String> list) throws Exception {
Vector v = new Vector();
for (String key : list) {
v.add(key);
}
long currentTime = System.currentTimeMillis();
if (v.size() > 0) {
syncResult(new CommonCommand("com.eactive.eai.agent.transformer.ReloadLayoutListCommand"), v);
}
logger.info(">> 메모리동기화 처리시간(ms) : " + (System.currentTimeMillis() - currentTime));
return true;
}
public boolean transformMemorySync(ArrayList<String> list) throws Exception {
Vector v = new Vector();
for (String key : list) {
v.add(key);
}
long currentTime = System.currentTimeMillis();
if (v.size() > 0) {
syncResult(new CommonCommand("com.eactive.eai.agent.transformer.ReloadTransformListCommand"), v);
}
logger.info(">> 메모리동기화 처리시간(ms) : " + (System.currentTimeMillis() - currentTime));
return true;
}
private void syncResult(Command command ,Vector names ) throws Exception {
//layout 동기화 service 에는 transaction 때문에 문제의 소지가 있음
HashMap receive =new HashMap();
if (names != null && names.size() > 0){
command.setArgs(names);
receive = agentUtilService.broadcast(command);
}
String status = "success";
for (Object o : receive.keySet()){
String key = (String)o;
if (receive.get(key) == null || !"success".equals(receive.get(key)) ){
status = "error";
break;
}
}
if (logger.isInfoEnabled()){
logger.info(this.getClass().toString()+"] command = "+command.getName().toString()+ " names="+names + " status = " + status + " message = " + receive.toString());
}
if (!"success".equals(status)){
throw new Exception("메모리 동기화 오류 : " + "command = "+command.getName().toString()+ " names="+names + " status = " + status + " message = " + receive.toString());
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,122 @@
package com.eactive.eai.rms.ext.eims;
public interface EIMSParserKey {
public static String STANDARD = "K";
//어댑터 위치
public static String SRC = "SRC";
public static String TGT = "TGT";
public static String RES_SRC = "RES_SRC";
//interface 관련
public static String ATTRINFO = "Attrinfo";
public static String VER = "ver";
public static String INTF_TYPE = "intfType";//S-요청/R-응답
public static String APP_CD = "appCd";
public static String INF_ID = "infId";
public static String INF_NM = "infNm";
public static String LOGICAL_INF_ID = "logicalInfId";// 인터페이스 논리ID
public static String INF_DST_CD = "infDstCd";//인터페이스구분코드 M/F/E( mmi에서는 EAI서버구분코드)
public static String ORGN_TYPE = "orgnType"; //1:취급(당발) 2:개벌(타발) 대외거래만 들어옮
public static String SRC_ADT_ID = "srcAdtId";//EBHOA001
public static String TRG_ADT_ID = "trgAdtId";//EBHOA001
public static String RES_SRC_ADT_ID = "resSrcAdtId";//EBHOA001
public static String SRC_COM_TYPE = "srcComType";//A/S
public static String TRG_COM_TYPE = "trgComType";//A/S
//추가
public static String INF_DESC = "infDesc";//인터페이스 설명
//public static String DISC_INF_ID = "discInfId";//식별InterfaceId
public static String SRC_SYS_CD = "srcSysCd";//소스시스템코드
public static String TRG_SYS_CD = "trgSysCd";//타겟시스템코드
public static String TRAN_KEY = "tranKey";//전문추적키1,2
public static String TRAN_KEY_ERR = "errTranKey";//에러전문추적키1,2
public static String LOG_KEY = "logKey";//로그키 1,2,3,4
public static String TIMEOUT = "Timeout";//타임아웃
public static String TIMEOUT_CD = "timeoutCd";//타임아웃코드
//public static String PROCTYPE = "procType";//처리유형(온라인/배치)
//20210401 추가
public static String EXT_BIZ_CD = "outBizCd";//대외업무코드
public static String RECV_TRAN_CD = "recvTranCd";//서비스ID(거래ID)
public static String INF_DSTN_KEY1 = "infDstnKey1";//IF식별키값1
public static String INF_DSTN_KEY2 = "infDstnKey2";//IF식별키값2
public static String INF_DSTN_KEY3 = "infDstnKey3";//IF식별키값3
//20210702 추가 인터페이스 실행타입인터페이스 실행 타입(S:요청인터페이스, R:정상응답인터페이스, E:오류응답인터페이스)
public static String INF_TRAN_TYPE = "infTranType";
//
public static String EXTHE01INFO = "Exthe01info";
public static String SYS_SVC_NAME = "sysSvcName";
public static String FLOW_CTRL_ROUT_NAME = "flowCtrlRoutName";
public static String INTERNAL_EXTERNAL_DVCD = "internalExternalDvcd";
//
public static String EXTHS01INFO = "Exths01info";
public static String BZWK_SVC_KEY_NAME = "bzwkSvcKeyName";//업무 서비스키 명
//public static String COMMON_OGTRAN_RSTR_YN = "common_ogtran_rstr_yn";
//
//public static String MSGINFO = "msginfo";
//public static String MSG_FLD_START_SITU_VAL = "msg_fld_start_situ_val";
//public static String MSG_FLD_LEN = "msg_fld_len";
public static String RESTOPTION = "restOption";
public static String AUTHOR = "author";
//공통
public static String ID = "id";
public static String DESC = "desc";
public static String DEFAULT = "default";
public static String DEL_YN = "delYn";
//layout관련
public static String LAYOUT_ID = "layoutId";//레이아웃ID
public static String MSG_TYPE = "msgType";//레이아웃 유형명
public static String LAYOUT_APP_CD = "appCd";//레이아웃 업무구분코드
public static String IN_OUT = "inOut";//I:요청,O:응답,E:오류
// public static String SYS_CD = "sysCd";//사용시스템코드
public static String DATE = "date";//작업일시
public static String TYPE = "type";
public static String LEN = "len";
public static String SCALE = "scale";
public static String COUNT = "count";
public static String LAYOUT_LOG_KEY = "log_key";
public static String LAYOUT_TRAN_KEY = "tran_key";
public static String NO = "no";
public static String DEPTH = "depth";
public static String MAX_CNT = "maxCnt";
public static String MASK = "mask";
public static String ENC = "enc";
//변환
public static String MAPPING = "Mapping";
public static String FROM = "from";
public static String TO = "to";
public static String LINK = "link";
public static String SEQ = "seq";
//layout 항목 종류
public static String GROUP = "Group";
public static String GRID = "Grid";
public static String FLD = "Field";
public static String ATTR = "Attr";
//삭제관련
public static String EIMS_IO_ID = "mmi_io_id";
public static String INTERFACE = "Interface";
public static String FORMAT = "Format";
public static String DELETE_INFO = "Delete_info";
public static String MODID = "modid";
//설정추출키
public static String FC_QUEUE = "QUEUE";
public static String FC_B2B = "B2B";
public static String FC_FAILOVER = "FAILOVER";
}
@@ -0,0 +1,852 @@
package com.eactive.eai.rms.ext.eims;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.View;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.common.util.NullControl;
import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;
import com.eactive.eai.rms.common.logging.UserAccessLogger;
import com.eactive.eai.rms.common.mmilog.MMILogDao;
import com.eactive.eai.rms.common.util.StringUtils;
import com.eactive.eai.rms.onl.common.util.DateUtil;
import com.eactive.eai.transformer.layout.LayoutManager;
import com.eactive.eai.transformer.layout.LayoutTypeManager;
@Controller
public class EIMSSyncController extends OnlBaseAnnotationController implements InterceptorSkipController {
private static final Logger logger = Logger.getLogger(EIMSSyncController.class);
@Autowired
@Qualifier("eimsSyncService")
private EIMSSyncService service;
@Autowired
@Qualifier("monitoringContext")
private MonitoringContext monitoringContext;
@Autowired
@Qualifier("mmiLogDao")
private MMILogDao mmiLogDao;
@Autowired
private LayoutManager layoutManager;
@Autowired
private LayoutTypeManager layoutTypeManager;
/**
* 통합인터페이스 시스템(EIMS)에서 전문 레이아웃에 대한 INSERT, DELETE 요청
*
* 배포 파라미터 key
* 인터페이스 : INTERFACE
* 레이아웃 : LAYOUT_SOURCE_REQ, LAYOUT_SOURCE_RES, LAYOUT_TARGET_REQ, LAYOUT_TARGET_REQ
* 변환 :TRANSFORM_REQ, TRANSFORM_RES
* @param request
* @param response
* @param schema
* @return
* @throws Exception
*/
@RequestMapping(value= "/eimsSync.file", method=RequestMethod.POST)
public View parseMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
UserAccessLogger.log(request, "Message", "L", "cmd=Message");
HashMap<String,String> map = new HashMap<String,String>();
StringBuilder sb = new StringBuilder();
StringBuilder frame = new StringBuilder();
logger.debug("parseMessage content-Type="+request.getContentType());
String deployIfId = "";
String ver = "";
String eaiSvcName = "";
String eaiSevrDstcd = "";
String cnvsnNames = "";
String loutNames = "";
String userId = "";
HashMap<String,Object> logMap = new HashMap<String,Object>();
StringBuffer buffer = new StringBuffer();
try{
if (!SystemUtil.isDevServer()){
throw new Exception("It works only on the development server.");
}
for (String key : request.getParameterMap().keySet()){
String [] datas= request.getParameterValues(key);
StringBuffer resultS = new StringBuffer();
for(String data : datas){
resultS.append(data);
}
if (key.startsWith("INTERFACE") || key.startsWith("LAYOUT_") || key.startsWith("TRANSFORM_") ){
buffer.append(resultS.toString()).append("\n");
}
// if (key.startsWith("FM") ){
// cnvsnNames += ","+key;
// }
// if (key.startsWith("FD")){
// loutNames += ","+key;
// }
logger.info("receive Data "+key+"="+resultS.toString());
map.put(key, resultS.toString());
}
HashMap<String,Object> inter = null;
HashMap<String,Object> info = null;
for(String key : map.keySet()){
if (key.startsWith("INTERFACE") ){
info = EIMSParser.parseInfo(map.get(key));
}
}
if (info == null){
throw new Exception("Interface information does not exist.");
}
eaiSvcName = (String)info.get(EIMSParserKey.SYS_SVC_NAME);//EAI서비스코드
String eaiBzwkDstcd = (String)info.get(EIMSParserKey.APP_CD); //EAI업무구분코드
eaiSevrDstcd = (String)info.get(EIMSParserKey.INF_DST_CD); //M/E/F
String interfaceType = (String)info.get(EIMSParserKey.INTF_TYPE); //인터페이스유형
deployIfId = (String)info.get(EIMSParserKey.INF_ID); //
ver = (String)info.get(EIMSParserKey.VER); // 버전번호
String srcSysId = (String)info.get(EIMSParserKey.SRC_ADT_ID); //소스 시스템ID
String tgtSysId = (String)info.get(EIMSParserKey.TRG_ADT_ID); //타겟 시스템ID
String resSrcSysId = (String)info.get(EIMSParserKey.RES_SRC_ADT_ID); //응답 소스 시스템ID
String srcSysType = (String)info.get(EIMSParserKey.SRC_COM_TYPE); //소스 시스템 type
String tgtSysType = (String)info.get(EIMSParserKey.TRG_COM_TYPE); //타겟 시스템 type
userId = (String)info.get(EIMSParserKey.AUTHOR); //사용자ID
String outBizCd = (String)info.get(EIMSParserKey.EXT_BIZ_CD); //대외업무구분코드
// String stdErrMpng = (String)info.get(EIMSParserKey.STD_ERR_MPNG); //표준 에러코드 사용여부
/** XML 파싱 전에 layoutNames transformNames 추출 **/
List<String> layoutNameList = new ArrayList<>();
List<String> cnvsnNameList = new ArrayList<>();
for (Entry<String, String> entry : map.entrySet()) {
if (entry.getKey().startsWith("LAYOUT")) {
String layoutName = EIMSParser.getResourceName(entry.getValue(), "LAYOUT");
if (StringUtils.isNotBlank(layoutName)) {
layoutNameList.add(layoutName);
}
} else if (entry.getKey().startsWith("TRANSFORM")) {
String cnvsnName = EIMSParser.getResourceName(entry.getValue(), "TRANSFORM");
if (StringUtils.isNotBlank(cnvsnName)) {
cnvsnNameList.add(cnvsnName);
}
}
}
if (layoutNameList.size() > 0) {
loutNames = String.join(",", layoutNameList.toArray(new String[0]));
}
if (cnvsnNameList.size() > 0) {
cnvsnNames = String.join(",", cnvsnNameList.toArray(new String[0]));
}
///////////////////////////////////////////////
//서버구분코드로 DataSourceType 변경
// M : 내부MCI(MCI) , E : EAI(EAI), F : 외부MCI(FEP)
// 개발은 1,2,3 은 DSG 로 4는 ZSG로 처리 한다.
///////////////////////////////////////////////
String serverType = monitoringContext.getStringProperty(MonitoringContext.EIMS_SYNC_SERVERTYPE, "M=MCI,U=MCU,E=EAI,F=FEP");
HashMap<String,String> serverDstcdMap = new HashMap<String,String>();
Matcher matcher = Pattern.compile("[ ]*([A-Z]+)[ ]*=[ ]*([A-Z]+)[ ]*").matcher(serverType);
while(matcher.find()) {
String key = matcher.group(1).trim();
String value = matcher.group(2).trim();
serverDstcdMap.put(key, value);
}
if (serverDstcdMap.containsKey(eaiSevrDstcd)){
String dataSourceType = serverDstcdMap.get(eaiSevrDstcd);
DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(dataSourceType));
}else{
throw new Exception("Unsupported interface classification code."+eaiSevrDstcd);
}
//interface 업무구분코드 valication
boolean isApp = service.selecAppIsYn(new HashMap(){{put("eaiBzwkDstcd",eaiBzwkDstcd);}});
if (!isApp){
throw new Exception("This APP CD is not supported by the interface." + eaiBzwkDstcd);
}
// //변환 업무구분코드 validation
// String[] cnvsnNameList = cnvsnNames.split(",");
// for(String cnvsnName : cnvsnNameList){
// if (!StringUtils.isBlank(cnvsnName) && cnvsnName.length() > 5 ){
// String appcode = cnvsnName.substring(2,5);
// isApp = service.selecAppIsYn(new HashMap(){{put("eaiBzwkDstcd",appcode);}});
// if (!isApp){
// throw new Exception("변환 에서 지원 하지 않는 APP CD 입니다. " + appcode);
// }
//
// }
// }
// //layout 업무구분코드 validation
// String[] layoutNameList = loutNames.split(",");
// for(String layoutName : layoutNameList){
// if (!StringUtils.isBlank(layoutName) && layoutName.length() > 5 ){
// String appcode = layoutName.substring(2,5);
// isApp = service.selecAppIsYn(new HashMap(){{put("eaiBzwkDstcd",appcode);}});
// if (!isApp){
// throw new Exception("레이아웃 에서 지원 하지 않는 APP CD 입니다. " + appcode);
// }
// }
// }
//adapter validation
if ("A".equals(srcSysType) && "S".equals(tgtSysType) && "S".equals(interfaceType)){
if (StringUtils.isEmpty(srcSysId)){
throw new Exception("No source adapter selected.");
}
if (StringUtils.isEmpty(tgtSysId)){
throw new Exception("No target adapter selected.");
}
if (StringUtils.isEmpty(resSrcSysId)){
throw new Exception("No source response adapter selected.");
}
}else if ("A".equals(srcSysType) && "S".equals(tgtSysType) && "R".equals(interfaceType)){
if (StringUtils.isEmpty(srcSysId)){
throw new Exception("No source adapter selected.");
}
}else{
if (StringUtils.isEmpty(srcSysId)){
throw new Exception("No source adapter selected.");
}
if (StringUtils.isEmpty(tgtSysId)){
throw new Exception("No target adapter selected.");
}
}
// adapter 파서
Map<String, Map<String, String>> adapters = service.selectAdapterForNickName(srcSysId,tgtSysId,resSrcSysId);
String adptrMsgDstcd = adapters.get(EIMSParserKey.SRC).get("ADPTRMSGDSTCD");
//option 정보
//1.큐 프라퍼트
//2.B2B 프로퍼티
//3.FailOver 프라퍼티
HashMap options = service.getEngineOption(serverDstcdMap.get(eaiSevrDstcd),eaiSvcName, outBizCd );
// interface 파서
for(String key : map.keySet()){
if (key.startsWith("INTERFACE")){
inter = EIMSParser.parseInterface(map.get(key),adapters, options);
logger.info("interface parsing " +inter);
}
}
HashMap<String,String> reverseName = new HashMap<String,String>();
HashMap<String,String> normalName = new HashMap<String,String>();
// layout 파서
List<HashMap<String,Object>> layouts = new ArrayList<HashMap<String,Object>>();
for(String key : map.keySet()){
if (key.startsWith("LAYOUT")){
// if (key.startsWith("FDEAI_") && key.endsWith("_ERR")){
// continue;
// }
EIMSParser.layoutDupValidation(map.get(key));
HashMap<String,Object> layout = EIMSParser.parseLayout(map.get(key),eaiSevrDstcd);
layouts.add( layout);
String layoutName = (String)layout.get("loutName");
logger.info("layout parsing " + layout);
reverseName.put(layoutName, key );
normalName.put(key, layoutName );
}
}
//변환 파서
List<HashMap<String,Object>> transforms = new ArrayList<HashMap<String,Object>>();
//HashMap<String,String> replaceTransform = new HashMap<String,String>();
for(String key : map.keySet()){
if (key.startsWith("TRANSFORM")){
HashMap<String,Object> transform = EIMSParser.parseTransform(map.get(key), eaiBzwkDstcd, eaiSevrDstcd,userId);
transforms.add( transform );
String cnvsnName = (String)transform.get("cnvsnName");
logger.info("transform parsing " + transform);
reverseName.put(cnvsnName, key );
normalName.put(key, cnvsnName );
}
}
EIMSParser.validation(srcSysType, tgtSysType, interfaceType,adapters, transforms, layouts, eaiSevrDstcd);
// 변환 을 EAI서비스 코드에 셋팅하는 로직
List<HashMap<String,Object>> he02s = (List<HashMap<String,Object>>)inter.get("he02");
if (he02s != null){
HashMap<String,Object> he02 = (HashMap<String, Object>) he02s.get(0);
if (he02 != null){
//async-async 요청인데 RES로 되어 있는거 보강로직
if ("A".equals(srcSysType) && "A".equals(tgtSysType) && transforms.size()==1) {
String cnvsnName =(String)transforms.get(0).get("cnvsnName");
he02.put("chngEonot" , "1" ); // 변환유무
he02.put("chngMsgIDName" , cnvsnName ); // 변환메시지ID명
}else{
for(HashMap<String,Object> tr : transforms) {
String cnvsnName = (String)tr.get("cnvsnName");
if (cnvsnName.endsWith("_REQ")){
he02.put("chngEonot" , "1" ); // 변환유무
he02.put("chngMsgIDName" , cnvsnName ); // 변환메시지ID명
}else if (cnvsnName.endsWith("_RES")){
if ("A".equals(srcSysType) && "A".equals(tgtSysType) && "R".equals(interfaceType) ){//Async Async 패턴 응답이 경우
he02.put("chngEonot" , "1" ); // 변환유무
he02.put("chngMsgIDName" , cnvsnName ); // 변환메시지ID명
} else {
he02.put("bascRspnsChngEonot" , "1" ); // 기본응답변환유무
he02.put("bascRspnsChngMsgIDName" , cnvsnName ); // 기본응답변환메시지ID명
}
}else if (cnvsnName.endsWith("_ERR")){
he02.put("errRspnsChngEonot" , "1" ); // 오류응답변환유무
he02.put("errRspnsChngMsgIDName" , cnvsnName ); // 오류응답변환메시지ID명
}
}
}
// //표준에러매핑 관련
// if ("Y".equals(stdErrMpng)){
//
// //에러변환이 있는경우 표준에러 매핑을 셋팅할수 없음.
// if ("1".equals(he02.get("errRspnsChngEonot"))){
// throw new Exception("에러 변환을 셋팅한 상태에서는 표준 오류 매핑 사용을 Y 로 셋팅 할수 없습니다.");
// }
// if ("A".equals(srcSysType) && "S".equals(tgtSysType) && "R".equals(interfaceType)){
// throw new Exception("표준에러매핑을 셋팅할수 없는 패턴입니다. 거래패턴 :"+srcSysType +"-" +tgtSysType +" 송수신타입 : "+interfaceType );
// }
// String srcKesaUseYn = adapters.get(EIMSParserKey.SRC).get("KESAUSEYN");
// String tgtKesaUseYn = adapters.get(EIMSParserKey.TGT).get("KESAUSEYN");
// String srcMsgDstcd = adapters.get(EIMSParserKey.SRC).get("ADPTRMSGDSTCD");
// String tgtMsgDstcd = adapters.get(EIMSParserKey.TGT).get("ADPTRMSGDSTCD");
// if (!"0".equals(srcKesaUseYn) && !"0".equals(tgtKesaUseYn)){
// //Async - Async 응답에서만 셋팅
// //Sync - Async 요청에서만셋팅
// //Sync - Sync 요청만 있음
// //Async - Sync 요청만 있음
// String cnvsnName = "";
// if ("A".equals(srcSysType) && "A".equals(tgtSysType) && "R".equals(interfaceType)){
// cnvsnName = "TRANSFORM_EAI_" + srcMsgDstcd +"TO" + tgtMsgDstcd + "_ERR";
// he02.put("errRspnsChngEonot" , "1" ); // 오류응답변환유무
// he02.put("errRspnsChngMsgIDName" , cnvsnName ); // 오류응답변환메시지ID명
// }else if ("S".equals(srcSysType) && "A".equals(tgtSysType) && "S".equals(interfaceType)){
// cnvsnName = "TRANSFORM_EAI_" + tgtMsgDstcd +"TO" + srcMsgDstcd + "_ERR";
// he02.put("errRspnsChngEonot" , "1" ); // 오류응답변환유무
// he02.put("errRspnsChngMsgIDName" , cnvsnName ); // 오류응답변환메시지ID명
// }else if ( "S".equals(tgtSysType) ){
// cnvsnName = "TRANSFORM_EAI_" + tgtMsgDstcd +"TO" + srcMsgDstcd + "_ERR";
// he02.put("errRspnsChngEonot" , "1" ); // 오류응답변환유무
// he02.put("errRspnsChngMsgIDName" , cnvsnName ); // 오류응답변환메시지ID명
// }else{
// throw new Exception("표준에러매핑을 셋팅할수 없는 패턴입니다. 거래패턴 :"+srcSysType +"-" +tgtSysType +" 송수신타입 : "+interfaceType );
// }
// }else{
// throw new Exception("소스("+srcKesaUseYn+")와 타겟("+tgtKesaUseYn+")이 두개다 kesa가 아닐경우 표준 오류 매핑 사용을 Y 로 셋팅 할수 없습니다.");
// }
//
// }
}
logger.info("he02 setting " + he02);
}
///////////////////////
// TR , AK
//////////////////////
List<HashMap<String,Object>> tracekeys = new ArrayList<HashMap<String,Object>>();
// tr , ak 파서
List<String> parseKeys = new ArrayList<String>();
for(String key : map.keySet()){
if (key.startsWith("INTERFACE")){
parseKeys = EIMSParser.parseKey(map.get(key));
logger.info("tr ,ak parsing " +parseKeys);
}
}
//tr ,ak validation
for(String parseKey : parseKeys){
String[] keys = parseKey.split(",");
String keyType = keys[0];
String keyIndex = keys[1];
String layoutFullPath = keys[2];
String layout = layoutFullPath.split("\\.")[0];
// if (map.containsKey(layout)){
if (reverseName.containsKey(layout)){
String data = map.get(reverseName.get(layout));
if (EIMSParser.parseKeyValidation(data,layoutFullPath)){
tracekeys.add(EIMSParser.parseKey2(eaiSvcName, keyType, keyIndex, adptrMsgDstcd,layoutFullPath, eaiSevrDstcd));
}else{
throw new Exception("The key path for the field extraction information[필드추출정보] or log lookup key[로그조회키] does not exist."+layoutFullPath);
}
}else{
throw new Exception("Field extraction information or log search key key path(" + layoutFullPath + ") does not exist in the layout used. List of all deployed layouts: " + loutNames);
}
}
//참조메시지에 대한 정의-20200527 jun's
//1.변환매핑이 없고 로그키(필드추출정보)가 없을 경우 참조메시지ID를 셋팅한다.
//2.저장시에도 아래의 조건 만족하는경우에만 DB에서 DELETE & INSERT 한다.
// => 조건이 안맞을시에는 ms02가 생성이 안되고 ASIS 마이그레이션 데이터가 있더라도 삭제 하지 않는다.
if (transforms.size() == 0 && tracekeys.size() == 0 ){
String refMessage ="";
if ("A".equals(srcSysType) && "A".equals(tgtSysType) ){
if ("S".equals(interfaceType)){
refMessage = normalName.get("LAYOUT_SOURCE_REQ");
}else{
refMessage = normalName.get("LAYOUT_TARGET_REQ");
}
}
// for(String key : map.keySet()){
// if (key.startsWith("LAYOUT")){
// refMessage = key;
// break;
// }
// }
List<HashMap<String,Object>> ms02s = new ArrayList<HashMap<String,Object>>();
if (!StringUtils.isBlank(refMessage)){
// interface 에 ms02 설정
HashMap<String,Object> ms02 = new HashMap<String,Object>();
ms02.put("EAISVCNAME", eaiSvcName);
ms02.put("SVCPRCSSNO", "1");
ms02.put("REFMSGIDNO", "1");
ms02.put("REFMSGIDNAME", refMessage);
ms02s.add(ms02);
}
inter.put("ms02", ms02s);
}
// merge 로직 시작
service.transactionEIMSSync(inter, layouts, transforms, tracekeys, userId);
/** LayoutManager Reload Start **/
for(HashMap<String, Object> layout : layouts) {
String layoutName = (String)layout.get("loutName");
try {
layoutTypeManager.reload();
layoutManager.reload(layoutName, DataSourceContextHolder.getDataSourceType().getJndiName(),
DataSourceContextHolder.getDataSourceType().getSchema(), null);
} catch (Exception e) {
throw new Exception("Layout validation error : please check " + layoutName);
}
}
/** LayoutManager Reload End **/
CommonCommand command = null;
//layout동기화
for(HashMap<String,Object> layout : layouts){
String loutName = (String) layout.get("loutName");
command = new CommonCommand("com.eactive.eai.agent.transformer.ReloadLayoutCommand",loutName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("Layout sync error: "+loutName);
}
}
//변환등기화
for(HashMap<String,Object> transform : transforms){
String cnvsnName = (String)transform.get("cnvsnName");
command = new CommonCommand("com.eactive.eai.agent.transformer.ReloadTransformCommand",cnvsnName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("Transform sync error: "+cnvsnName);
}
}
//인터페이스 동기화
if (!StringUtils.isEmpty(eaiSvcName)){
command = new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageCommand",eaiSvcName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("Interface sync error: "+eaiSvcName);
}
}
//추출키 동기화
if (!StringUtils.isEmpty(eaiSvcName)){
command = new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand",eaiSvcName+",TR");
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("field extraction key sync error: "+eaiSvcName);
}
command = new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand",eaiSvcName+",AK");
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("log search key sync error: "+eaiSvcName);
}
}
//내부표준전문 동기화
if (!StringUtils.isEmpty(eaiSvcName)){
ArrayList<HashMap<String, Object>> hs04s = (ArrayList<HashMap<String, Object>>)inter.get("hs04");
if (hs04s != null){
for(HashMap<String,Object> hs04 : hs04s){
String bzwkSvcKeyName = (String)hs04.get("bzwkSvcKeyName");
command = new CommonCommand("com.ext.eai.agent.stdmessage.ReloadSTDMessageCommand",bzwkSvcKeyName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("Internal standard message sync error: "+bzwkSvcKeyName);
}
}
}
}
//juns 어댑터 메시지키 동기화 삭제
// //어댑터 메시지키 동기화
// if (!isMessageKeySame){
// List<HashMap<String,Object>> fr04s = (List<HashMap<String,Object>>)inter.get("fr04");
// if (fr04s != null && fr04s.size()>0){
// String adptrBzwkGroupName = (String)fr04s.get(0).get("adptrBzwkGroupName");
// String key = adptrBzwkGroupName +",I";
// command = new CommonCommand("com.eactive.eai.agent.messagekey.ReloadMessageKeyCommand",key);
// if (!validate(agentUtilService.broadcast(command))){
// throw new Exception("어댑터 메시지키 동기화 오류 "+adptrBzwkGroupName);
// }
// }
// }
sb.append(resultInterface(deployIfId, ver, "True", "Successfully processed."));
} catch(Exception e){
logger.error("EIMSSyncController error="+e.getMessage(),e);
sb.append(resultInterface(deployIfId, ver, "False",e.getMessage()));
}
frame.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
frame.append(sb.toString());
//EIMS Log data
DataSourceType dt = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING);
String schemaId = "";
if(dt != null){
DataSourceContextHolder.setDataSourceType(dt);
schemaId =dt.getSchema();
}else{
logger.error("DataSourceType is null");
return null;
}
//HashMap paramMap = new HashMap();
logMap.put("schemaId" , schemaId);
logMap.put("msgDpstHMS" , DateUtil.getDateTimeMilliSecound());
logMap.put("eaiSvcName" , NullControl.addSpace(eaiSvcName));
logMap.put("eaiSevrDstcd" , NullControl.addSpace(eaiSevrDstcd));
logMap.put("cnvsnName" , NullControl.addSpace(cnvsnNames));
logMap.put("loutName" , NullControl.addSpace(loutNames));
logMap.put("reqDstcd" , NullControl.addSpace(buffer.toString()));
logMap.put("resDstcd" , NullControl.addSpace(frame.toString()));
logMap.put("interfaceId" , NullControl.addSpace(deployIfId));
logMap.put("deployId" , NullControl.addSpace(userId));
try{
mmiLogDao.insert(logMap);
}catch(Exception e){
logger.error("db insert error : " + logMap.toString(),e);
}
response.setCharacterEncoding("UTF-8");
ServletOutputStream sos = null;
try {
sos = response.getOutputStream();
sos.write(frame.toString().getBytes("UTF-8"));
} catch( Exception e ) {
//취약점소스 수정 2020.08.24
logger.error(" error", e);
} finally {
if( sos != null ) sos.close();
}
return null;
}
@RequestMapping(value= "/eimsSync.file",params = "cmd=DELETE", method=RequestMethod.POST)
public View messageDelete(HttpServletRequest request, HttpServletResponse response) throws Exception {
UserAccessLogger.log(request, "Message", "L", "cmd=delete");
HashMap<String,String> map = new HashMap<String,String>();
StringBuilder sb = new StringBuilder();
StringBuilder frame = new StringBuilder();
logger.debug("parseMessage content-Type="+request.getContentType());
HashMap<String,Object> logMap = new HashMap<String,Object>();
StringBuffer buffer = new StringBuffer();
/*
* 삭제 하기 위해 필요한 항목
* 1. eaiSevrDstcd
* 1. eaiSvcName
* 2. bzwkSvcKeyNames
* 3. transforms
* 4. layouts
* 5. deployIfId 배포 인터페이스 ID
*/
String eaiSevrDstcd = null;
String eaiSvcName = null;
String deployIfId = null;
String ver = null;
String userId = null;
String cnvsnNames = "";
String loutNames = "";
List<String> bzwkSvcKeyNames = new ArrayList<String>();
List<String> layouts = new ArrayList<String>();
List<String> transforms = new ArrayList<String>();
try{
if (!SystemUtil.isDevServer()){
throw new Exception("It works only on the development server.");
}
for (String key : request.getParameterMap().keySet()){
String [] datas= request.getParameterValues(key);
StringBuffer resultS = new StringBuffer();
for(String data : datas){
resultS.append(data);
}
if (key.startsWith("INTERFACE") || key.startsWith("LAYOUT_") || key.startsWith("TRANSFORM_") ){
buffer.append(resultS.toString()).append("\n");
}
logger.info("receive Data "+key+"="+resultS.toString());
map.put(key, resultS.toString());
}
for(String key : map.keySet()){
if (key.startsWith("INTERFACE") ){
HashMap<String,Object> info = EIMSParser.parseInfo(map.get(key));
if (info != null){
eaiSevrDstcd = (String)info.get(EIMSParserKey.INF_DST_CD); //M/E/F
String delYn = (String)info.get(EIMSParserKey.DEL_YN);
deployIfId = (String)info.get(EIMSParserKey.INF_ID); //
ver = (String)info.get(EIMSParserKey.VER); // 버전번호
userId = (String)info.get(EIMSParserKey.AUTHOR); //사용자ID
if (delYn != null && "Y".equals(delYn)){
String sysSvcName = (String)info.get(EIMSParserKey.SYS_SVC_NAME);
if (!StringUtils.isBlank(sysSvcName)){
eaiSvcName = sysSvcName;
}
}
}
// bzwkSvcKeyNames = EIMSParser.parseBzwkSvcKeyNames(map.get(key));
}
}
for(String key : map.keySet()){
if (key.startsWith("LAYOUT_")){
String layout = EIMSParser.parseDeleteLayoutName(map.get(key));
if (!StringUtils.isBlank(layout)){
layouts.add(layout);
loutNames += ","+layout;
}
}
}
///////////////////////////////////////////////
//서버구분코드로 DataSourceType 변경
// M : 내부MCI(MCI) , E : EAI(EAI), F : 외부MCI(FEP)
// 개발은 1,2,3 은 DSG 로 4는 ZSG로 처리 한다.
///////////////////////////////////////////////
String serverType = monitoringContext.getStringProperty(MonitoringContext.EIMS_SYNC_SERVERTYPE, "M=MCI,U=MCU,E=EAI,F=FEP");
HashMap<String,String> serverDstcdMap = new HashMap<String,String>();
Matcher matcher = Pattern.compile("[ ]*([A-Z]+)[ ]*=[ ]*([A-Z]+)[ ]*").matcher(serverType);
while(matcher.find()) {
String key = matcher.group(1).trim();
String value = matcher.group(2).trim();
serverDstcdMap.put(key, value);
}
if (serverDstcdMap.containsKey(eaiSevrDstcd)){
String dataSourceType = serverDstcdMap.get(eaiSevrDstcd);
DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(dataSourceType));
}else{
throw new Exception("Unsupported interface classification code."+eaiSevrDstcd);
}
//
final String fEaiSvcName = eaiSvcName;
transforms = service.selectTransformListForEaiSvcName(new HashMap(){{put("eaiSvcName",fEaiSvcName);}});
if (transforms != null){
for(String transform : transforms){
cnvsnNames += ","+transform;
}
}
/** 업무서비스키 List 불러오기 **/
List<String> bzwkKeyList = service.selectBzwkSvcKeyNameForEaiSvcName(new HashMap(){{put("eaiSvcName",fEaiSvcName);}});
bzwkSvcKeyNames = bzwkKeyList != null? bzwkKeyList : new ArrayList<>();
service.deleteAll(eaiSvcName, bzwkSvcKeyNames, transforms , layouts);
CommonCommand command = null;
if (StringUtils.isNotBlank(eaiSvcName)){
//인터페이스 삭제 동기화
command = new CommonCommand("com.eactive.eai.agent.eaimessage.RemoveEAIMessageCommand",eaiSvcName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("Interface sync error: "+eaiSvcName);
}
//추출키 삭제 동기화
command = new CommonCommand("com.eactive.eai.agent.bizkey.RemoveBizKeyCommand",eaiSvcName+",TR");
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("field extraction key sync error: "+eaiSvcName);
}
command = new CommonCommand("com.eactive.eai.agent.bizkey.RemoveBizKeyCommand",eaiSvcName+",AK");
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("log search key sync error: "+eaiSvcName);
}
//내부표준전문 삭제 동기화
if(bzwkSvcKeyNames != null){
for(String bzwkSvcKeyName : bzwkSvcKeyNames){
command = new CommonCommand("com.ext.eai.agent.stdmessage.RemoveSTDMessageCommand",bzwkSvcKeyName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("Internal standard message sync error: "+bzwkSvcKeyName);
}
}
}
//변환 삭제 동기화
if(transforms != null){
for(String cnvsnName : transforms){
command = new CommonCommand("com.eactive.eai.agent.transformer.RemoveTransformCommand",cnvsnName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("Transform sync error: "+cnvsnName);
}
}
}
}
//레이아웃 삭제 동기화
if(layouts != null){
for(String layout : layouts){
command = new CommonCommand("com.eactive.eai.agent.transformer.RemoveLayoutCommand",layout);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("Layout sync error: "+layout);
}
}
}
sb.append(resultInterface(deployIfId, ver, "True", "Successfully processed(deleted)."));
}catch(Exception e){
logger.error("EIMSSyncController error="+e.getMessage(),e);
sb.append(resultInterface(deployIfId, ver, "False",e.getMessage()));
}
frame.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
frame.append(sb.toString());
//EIMS Log data
DataSourceType dt = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING);
String schemaId = "";
if(dt != null){
DataSourceContextHolder.setDataSourceType(dt);
schemaId =dt.getSchema();
}else{
logger.error("DataSourceType is null");
return null;
}
//HashMap paramMap = new HashMap();
logMap.put("schemaId" , schemaId);
logMap.put("msgDpstHMS" , DateUtil.getDateTimeMilliSecound());
logMap.put("eaiSvcName" , NullControl.addSpace(eaiSvcName));
logMap.put("eaiSevrDstcd" , NullControl.addSpace(eaiSevrDstcd));
logMap.put("cnvsnName" , NullControl.addSpace(cnvsnNames));
logMap.put("loutName" , NullControl.addSpace(loutNames));
logMap.put("reqDstcd" , NullControl.addSpace(buffer.toString()));
logMap.put("resDstcd" , NullControl.addSpace(frame.toString()));
logMap.put("interfaceId" , NullControl.addSpace(deployIfId));
logMap.put("deployId" , NullControl.addSpace(userId));
try{
mmiLogDao.insert(logMap);
}catch(Exception e){
logger.error("db insert error : " + logMap.toString(),e);
}
response.setCharacterEncoding("UTF-8");
ServletOutputStream sos = null;
try {
sos = response.getOutputStream();
sos.write(frame.toString().getBytes("UTF-8"));
} catch( Exception e ) {
logger.error(e.getMessage(),e);
} finally {
if( sos != null ) sos.close();
}
return null;
}
private boolean validate(HashMap<String,Object> map ){
for(String key : map.keySet()){
Object o = map.get(key);
if (o instanceof String){
if("success".equals((String)o)){
;
}else{
return false;
}
}else{
return false;
}
}
return true;
}
private String resultInterface(String sysInfId, String ver, String returnCode, String returnMessage){
StringBuffer sb = new StringBuffer();
sb.append("<Results sysInfId=\""+sysInfId+"\" ver=\""+ver+"\" >");
sb.append("<Result>"+returnCode+"</Result>");
sb.append("<ResultMessage>"+returnMessage+"</ResultMessage>");
sb.append("</Results>");
return sb.toString();
}
private String resultInterfaceDelete(String mmiIfId, String id, String returnCode, String returnMessage){
return "<Interface mmi_if_id=\""+mmiIfId+"\" id=\""+id+"\" return_code=\""+returnCode+"\" return_message=\""+returnMessage+"\" />";
}
private String resultFormatDelete(String mmiIoId, String id, String returnCode, String returnMessage){
return "<Format mmi_io_id=\""+mmiIoId+"\" id=\""+id+"\" return_code=\""+returnCode+"\" return_message=\""+returnMessage+"\" />";
}
private static String streamToString(InputStream is){
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int r;
byte[] data = new byte[1024];
try {
while((r = is.read(data)) != -1){
buffer.write(data,0,r);
}
buffer.flush();
} catch (IOException e) {
logger.error(e.getMessage(),e);
return "";
}
String s = new String(buffer.toByteArray());
return s;
}
}
@@ -0,0 +1,77 @@
package com.eactive.eai.rms.ext.eims;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.eactive.eai.rms.common.base.SqlMapClientTemplateDao;
@Repository("eimsSyncDao")
@SuppressWarnings("unchecked")
public class EIMSSyncDao extends SqlMapClientTemplateDao {
public List<Map<String, Object>> selectHS04(HashMap param) throws Exception {
return (List<Map<String, Object>>)template.queryForList("EIMSSync.selectHS04", param);
}
public void deleteHS04(HashMap<String,Object> std) {
template.delete("EIMSSync.deleteHS04", std);
}
public void deleteHS05(HashMap<String,Object> std) {
template.delete("EIMSSync.deleteHS05", std);
}
public void insertHS04(HashMap<String,Object> std) {
template.insert("EIMSSync.insertHS04", std);
}
public void insertHS05(HashMap<String,Object> std) {
template.insert("EIMSSync.insertHS05", std);
}
public void mergeHE01(HashMap<String,Object> vo) {
template.insert("EIMSSync.mergeHE01", vo);
}
public void mergeHE02(HashMap<String,Object> vo) {
template.insert("EIMSSync.mergeHE02", vo);
}
public Map<String, String> selectAdapterForNickName(Map param) throws Exception {
List<Map<String,String>> list= (List<Map<String,String>>) template.queryForList("EIMSSync.selectAdapterForNickName", param);
if (list == null || list.size() ==0){
return new HashMap<String,String>();
}else if (list.size() == 1){
return list.get(0);
}else {
String nickName = (String)param.get("adptrNickName");
throw new Exception("중복된 nickname("+nickName+")이 존재 합니다.EAI 담당자에게 문의 하세요.");
}
}
public Map<String,String> selectHS05(Map param) throws Exception {
List<Map<String, String>> list = (List<Map<String, String>>)template.queryForList("EIMSSync.selectHS05", param);
Map<String,String> results = new HashMap<String,String>();
for(Map<String,String> map : list){
String key = map.get("BZWKSVCKEYNAME") + "," + map.get("COLUMNNAME");
results.put(key, map.get("COLUMNVALUE"));
}
return results;
}
public List<String> selectTransformListForEaiSvcName(HashMap<String,Object> vo) {
return (List<String>)template.queryForList("EIMSSync.selectTransformListForEaiSvcName", vo);
}
public List<String> selectBzwkSvcKeyNameForEaiSvcName(HashMap<String,Object> vo) {
return (List<String>)template.queryForList("EIMSSync.selectBzwkSvcKeyNameForEaiSvcName", vo);
}
public void deleteHe02SvcPrcssNo(HashMap<String,Object> vo) {
template.delete("EIMSSync.deleteHe02SvcPrcssNo", vo);
}
public int selecAppIsYn(HashMap<String,Object> vo) {
return (Integer) template.queryForObject("EIMSSync.selecAppIsYn", vo);
}
public List<String> selectHS04ForBzwkSvcKeyName(HashMap<String,Object> vo) {
return (List<String>)template.queryForList("EIMSSync.selectHS04ForBzwkSvcKeyName", vo);
}
public List<String> selectInterfaceForSameLayout(HashMap<String,Object> vo) {
return (List<String>)template.queryForList("EIMSSync.selectInterfaceForSameLayout", vo);
}
}
@@ -0,0 +1,741 @@
package com.eactive.eai.rms.ext.eims;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import com.eactive.eai.data.entity.onl.bizkey.BizKey;
import com.eactive.eai.data.entity.onl.messagekey.MessageKey;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutEntity;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutItemEntity;
import com.eactive.eai.rms.common.base.OnlBaseService;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.MessengerPlusSender;
import com.eactive.eai.rms.data.entity.onl.b2bextract.B2bExtractService;
import com.eactive.eai.rms.data.entity.onl.bizkey.BizKeyService;
import com.eactive.eai.rms.data.entity.onl.layout.LayoutService;
import com.eactive.eai.rms.data.entity.onl.messagekey.MessageKeyService;
import com.eactive.eai.rms.data.entity.onl.stdmessage.StandardMessageInfoService;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.manage.rule.layout.LayoutDao;
import com.eactive.eai.rms.onl.manage.rule.transform.TransformDao;
import com.eactive.eai.rms.onl.manage.serviceinfo.bizkey.FieldExtractInfoUIMapper;
import com.eactive.eai.rms.onl.manage.serviceinfo.comm.ChnlInfoIntegrationDao;
import com.eactive.eai.rms.onl.manage.serviceinfo.eaimsg.EaiMsgDao;
@Service("eimsSyncService")
public class EIMSSyncService extends OnlBaseService {
@Autowired
@Qualifier("eimsSyncDao")
private EIMSSyncDao dao;
@Autowired
@Qualifier("transformDao")
private TransformDao transformDao;
@Autowired
@Qualifier("eaiMsgDao")
public EaiMsgDao eaiMsgDao;
@Autowired
@Qualifier("layoutDao")
public LayoutDao layoutDao;
@Autowired
@Qualifier("monitoringContext")
private MonitoringContext monitoringContext;
@Autowired
private ComboService comboService;
@Autowired
private B2bExtractService b2bExtractService;
@Autowired
private ChnlInfoIntegrationDao chnlInfoIntegrationDao;
@Autowired
private StandardMessageInfoService standardMessageInfoService;
@Autowired
private LayoutService layoutService;
@Autowired
private MessageKeyService messageKeyService;
public int mergeLayout(List<HashMap<String,Object>> layoutVos) throws Exception{
for(HashMap<String,Object> vo : layoutVos){
String layout = (String)vo.get("loutName");
//서버구분코드 체크
Optional<LayoutEntity> optionalLayoutEntity = layoutService.findById(layout);
if (layoutService.existsById(layout)){
// String dbEaiSevrDstcd = (String)detail.get("EAISEVRDSTCD");
// String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
// if (!dbEaiSevrDstcd.equals(mmiEaiSevrDstcd)){
// throw new Exception("레이아웃("+layout+") 서버구분코드 오류. EAI DB에 등록("+dbEaiSevrDstcd+")되어 있는값과 EIMS 배포 ("+mmiEaiSevrDstcd+") 값이 다릅니다.");
// }
}else{
String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
if ("9".equals(mmiEaiSevrDstcd)){
throw new Exception("신규 레이아웃 등록시 서버구분코드가 9 인 경우." + layout);
}
}
//vo 의 한글 체크
boolean isDeployHangle= false;
//db 의 한글체크
boolean isDbHangle = false;
if (optionalLayoutEntity.isPresent() && !optionalLayoutEntity.get().getLayoutItemEntities().isEmpty()){
//배포 레이아웃 체크
List<HashMap<String,Object>> list = (List<HashMap<String,Object>>)vo.get("list");
for(HashMap<String,Object> item : list) {
String name = (String)item.get("loutItemName");
if (name.getBytes().length != name.length() ){
isDeployHangle= true;
break;
}
}
//DB 레이아웃 체크
for(LayoutItemEntity item : optionalLayoutEntity.get().getLayoutItemEntities()){
String name = item.getId().getLoutitemname();
if (name.getBytes().length != name.length() ){
isDbHangle= true;
break;
}
}
if (isDeployHangle != isDbHangle){
//EAI 서비스코드가 1개만 존재할때 레이아웃이 다르더라도 패스 2020-10-29 오현석대리요청
//변환까지만 연결된거 무시한다.
List<String> interfaceLists = dao.selectInterfaceForSameLayout(vo);
if (interfaceLists != null && interfaceLists.size() > 1){
if (isDeployHangle){
throw new Exception("배포 된 레이아웃("+layout+") 은 한글로 되어 있습니다. DB에 저장되어 있는 값은 영문 입니다.배포한 레이아웃이 한글이 맞는지 확인하시기 바랍니다. 사용하는 인터페이스 ("+ interfaceLists +")");
}else{
throw new Exception("배포 된 레이아웃("+layout+") 은 영문으로 되어 있습니다. DB에 저장되어 있는 값은 한글 입니다.배포한 레이아웃이 영문이 맞는지 확인하시기 바랍니다. 사용하는 인터페이스 ("+ interfaceLists +")");
}
}
}
}
List<HashMap<String,Object>> list = (List<HashMap<String,Object>>)vo.get("list");
layoutDao.deleteItemAll(vo);
layoutDao.delete(vo);
layoutDao.insert(vo);
for(HashMap<String,Object> item : list) {
layoutDao.insertItem(item);
}
}
return layoutVos.size();
}
public int mergeTransform(List<HashMap<String,Object>> transformVos) throws Exception{
for(HashMap<String,Object> vo : transformVos){
//서버구분코드 체크
HashMap detail =transformDao.selectDetail(vo);
if (detail != null){
// String dbEaiSevrDstcd = (String)detail.get("EAISEVRDSTCD");
// String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
// String cnvsnName = (String)vo.get("cnvsnName");
// if (!dbEaiSevrDstcd.equals(mmiEaiSevrDstcd)){
// throw new Exception("변환("+cnvsnName+") 서버구분코드 오류. EAI DB에 등록("+dbEaiSevrDstcd+")되어 있는값과 EIMS 배포 ("+mmiEaiSevrDstcd+") 값이 다릅니다.");
// }
}else{
String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
if ("9".equals(mmiEaiSevrDstcd)){
throw new Exception("신규 변환 등록시 서버구분코드가 9 인 경우." + (String)vo.get("cnvsnName"));
}
}
transformDao.deleteTransformItem(vo);
transformDao.deleteTransformSourceResult(vo);
transformDao.deleteTransform(vo);
transformDao.insert(vo);
List<HashMap<String,Object>> layouts = (List<HashMap<String,Object>>)vo.get("layouts");
for(HashMap<String,Object>layout : layouts){
transformDao.insertTransformSourceResult(layout);
}
List<HashMap<String,Object>> mappings = (List<HashMap<String,Object>>)vo.get("mappings");
for(HashMap<String,Object> mapping : mappings){
try{
transformDao.insertTransformItem(mapping);
}catch(DuplicateKeyException e){
throw new Exception("변환 항목 중복 오류 " + mapping);
}
}
}
return transformVos.size();
}
public String mergeInterface(HashMap<String,Object> interfaceVo) throws Exception {
HashMap he01 = (HashMap)interfaceVo.get("he01");
String eaiSvcName = (String)he01.get("eaiSvcName");
logger.info ("-1. 내부 표준 전문 INSERT ----------------------------------------------------");
// 1. 내부 표준 전문 INSERT
// 비표준에서 표준으로 가는 경우 표준으로 전환하기 위한 정보 이므로 내부로 갈 때만 처리
//eai 서비스 기준으로 목록 조회
List<Map<String, Object>> listHs04 = dao.selectHS04(new HashMap(){{put("eaiSvcName",eaiSvcName);}});
String[] filters = new String[]{"COMMON_bnkCd"};//현재는 쓰이지 않음
Map<String,String> beforeData = dao.selectHS05(new HashMap(){{put("eaiSvcName",eaiSvcName);put("filters",filters);}});
for(Map map : listHs04){
dao.deleteHS04((HashMap)map);
dao.deleteHS05((HashMap)map);
}
@SuppressWarnings("unchecked")
ArrayList<HashMap<String, Object>> hs04s = (ArrayList<HashMap<String, Object>>)interfaceVo.get("hs04");
if (hs04s != null){
//내부표준전문 업무 서비스키 중복 체크
for(HashMap<String,Object> map : hs04s){
String bzwkSvcKeyName = (String)map.get("bzwkSvcKeyName");
List<String> eaiList = dao.selectHS04ForBzwkSvcKeyName(new HashMap(){{put("bzwkSvcKeyName",bzwkSvcKeyName);}});
if (eaiList != null && eaiList.size() > 0){
String dupEaiSvcName = "";
for(String data : eaiList){
dupEaiSvcName = "," + data;
}
throw new Exception("내부표준전문의 업무서비스키 중복 오류입니다.다른 EAI서비스코드("+dupEaiSvcName+") 에서 서비스키("+bzwkSvcKeyName+") 를 사용하고 있습니다.");
}
}
for(HashMap<String,Object> map : hs04s){
ArrayList<HashMap<String,Object>> hs05s = (ArrayList<HashMap<String,Object>>)map.get("hs05");
dao.insertHS04(map);
for(HashMap<String,Object> submap : hs05s){
String key = submap.get("bzwkSvcKeyName") + "," + submap.get("columnName");
String data = beforeData.get(key);
if (data != null){
submap.put("columnValue", data);
}
dao.insertHS05(submap);
}
}
}
logger.info ("-2. EAI메세지 INSERT -------------------------------------------------------");
// 2. EAI메세지 INSERT
dao.mergeHE01((HashMap<String,Object>)interfaceVo.get("he01"));
eaiSvcNameVali(interfaceVo);
ArrayList<HashMap<String,Object>> he02s = (ArrayList<HashMap<String,Object>>)interfaceVo.get("he02");
for(HashMap<String,Object> map : he02s){
dao.mergeHE02(map);
}
//순서변경 위에서 무조건삭제 하는 방식에서 merge후 he02s가 1건일 경우 2번째 시퀀스 삭제
if(he02s != null && he02s.size() == 1){
//EAI메시지 SERVICE 2번 은 삭제
dao.deleteHe02SvcPrcssNo(new HashMap(){{put("eaiSvcName",eaiSvcName);put("svcPrcssNo",2);}});
}
// logger.info("-3. 참조메시지ID INSERT ----------------------------------------------------");
// 3. 참조메시지ID INSERT
ArrayList<HashMap<String, Object>> ms02s = (ArrayList<HashMap<String, Object>>)interfaceVo.get("ms02");
if (ms02s != null && ms02s.size() > 0 ){
//TransformVo vo = new TransformVo();
//vo.setEaiSvcName(eaiSvcName);
eaiMsgDao.deleteRefForEaiSvcName(new HashMap(){{put("eaiSvcName",eaiSvcName);}});
for(HashMap<String,Object> map : ms02s){
eaiMsgDao.insertRef(map);
}
}
return null;
}
public boolean mergeMessageKey(HashMap<String,Object> interfaceVo, String userId) throws Exception {
//메시지Key
List<String[]> fr04s = (List<String[]>)interfaceVo.get("fr04");
HashMap he01 = (HashMap)interfaceVo.get("he01");
String eaiSvcName = (String)he01.get("eaiSvcName");
String adptrBzwkGroupName = (String)he01.get("gstatSysAdptrBzwkGroupName");
boolean isMessageKeySame = true;
if (fr04s != null && fr04s.size()>0){
//select
List<MessageKey> dbdata = messageKeyService.findByAdptrBzwkGroupNameAndIoDstcd(adptrBzwkGroupName, "I");
isMessageKeySame = messageCheck(fr04s, dbdata);
//쪽지알림
StringBuffer sb = new StringBuffer();
if (!isMessageKeySame){
sb.append("어댑터업무그룹명 : " + adptrBzwkGroupName ).append("<br>");
sb.append("EAI서비스코드 : " + eaiSvcName ).append("<br>");
if (dbdata != null && dbdata.size() > 0 ){
sb.append("현재 설정 정보" ).append("<br>");
sb.append("<table style=\"TEXT-DECORATION: ; WIDTH: 1052px; BACKGROUND-COLOR: #ffffff\" cellSpacing=0 cellPadding=0 width=1052 border=1>");
sb.append("<tr>");
sb.append("<td>메시지 구분코드</td>");
sb.append("<td>입출력 구분코드</td>");
sb.append("<td>그룹 순차번호</td>");
sb.append("<td>필드 처리번호</td>");
sb.append("<td>메시지 필드 시작위치값</td>");
sb.append("<td>메시지 필드 길이</td>");
sb.append("</tr>");
for (MessageKey messageKey : dbdata) {
sb.append("<tr>");
sb.append("<td>" + messageKey.getId().getMsgdstcd() + "</td>");
sb.append("<td>" + messageKey.getId().getIodstcd() + "</td>");
sb.append("<td>" + messageKey.getId().getGroupinorno() + "</td>");
sb.append("<td>" + messageKey.getId().getFldprcssno() + "</td>");
sb.append("<td>" + messageKey.getMsgfldstartsituval() + "</td>");
sb.append("<td>" + messageKey.getMsgfldlen() + "</td>");
sb.append("</tr>");
}
sb.append("</table>");
}
sb.append("요청 설정자 (" + userId + ")").append("<br>");
sb.append("요청 설정 정보 " ).append("<br>");
sb.append("<table style=\"TEXT-DECORATION: ; WIDTH: 1052px; BACKGROUND-COLOR: #ffffff\" cellSpacing=0 cellPadding=0 width=1052 border=1>");
sb.append("<tr>");
//sb.append("<td>메시지 구분코드</td>");
//sb.append("<td>입출력 구분코드</td>");
//sb.append("<td>그룹 순차번호</td>");
sb.append("<td>필드 처리번호</td>");
sb.append("<td>메시지 필드 시작위치값</td>");
sb.append("<td>메시지 필드 길이</td>");
sb.append("</tr>");
for(int i=0;i< fr04s.size();i++){
String[] fr04 = fr04s.get(i);
if (fr04.length == 2){
sb.append("<tr>");
//sb.append("<td>"+m.get("msgDstcd")+"</td>");
//sb.append("<td>"+m.get("ioDstcd")+"</td>");
//sb.append("<td>"+m.get("groupInorNo")+"</td>");
sb.append("<td>"+(i+1)+"</td>");
sb.append("<td>"+fr04[0]+"</td>");
sb.append("<td>"+fr04[1]+"</td>");
sb.append("</tr>");
}
}
MessengerPlusSender sender = MessengerPlusSender.getInstance();
String url = monitoringContext.getStringProperty("rms.messenger.url");
String srvCode = monitoringContext.getStringProperty("rms.messenger.srvCode");
String recipient = monitoringContext.getStringProperty("rms.messenger.recipient");
String send = monitoringContext.getStringProperty("rms.messenger.send");
String senderAlias = monitoringContext.getStringProperty("rms.messenger.senderAlias");
logger.debug("send MessengerPlus data : " + sb.toString());
sender.execute(url, srvCode, recipient, send, "EAI 어댑터 구분필드 추출정보 변경요청", sb.toString(), "", senderAlias);
}
}
return isMessageKeySame;
}
private boolean messageCheck(List<String[]> fr04s, List<MessageKey> selectData) throws Exception{
List<String[]> dbGroup = new ArrayList<String[]>();
HashMap<String,List<String[]>> dbGroups = new HashMap<String,List<String[]>>();
for (MessageKey messageKey : selectData) {
String groupNumber = Integer.toString((Integer) messageKey.getId().getGroupinorno());
if (dbGroups.containsKey(groupNumber)) {
dbGroup = dbGroups.get(groupNumber);
} else {
dbGroup = new ArrayList<String[]>();
dbGroups.put(groupNumber, dbGroup);
}
dbGroup
.add(new String[] { Integer.toString(messageKey.getMsgfldstartsituval()),
Integer.toString(messageKey.getMsgfldlen()) });
}
//false 일 경우 message전송
//check
//신규등록
if (dbGroups.size() == 0 && fr04s.size() >0){
return false;
}
for (String key : dbGroups.keySet()){
dbGroup = dbGroups.get(key);
if (dbGroup.size() == fr04s.size()){
int trueCount = 0;
for(int i=0;i< dbGroup.size() ;i++ ){
if (Arrays.equals(dbGroup.get(i), fr04s.get(i))){
trueCount++;
}
}
if (dbGroup.size()==trueCount){
return true;
}
}
}
return false;
}
@Autowired
private BizKeyService bizKeyService;
@Autowired
private FieldExtractInfoUIMapper fieldExtractInfoUIMapper;
public String mergeTraceKey(HashMap<String,Object> interfaceVo , List<HashMap<String,Object>> tracekeys) throws Exception {
logger.info(" 추적관리필드 INSERT -----------------------------------------------------");
// 4. 추적관리필드 INSERT
HashMap he01 = (HashMap)interfaceVo.get("he01");
final String eaiSvcName = (String)he01.get("eaiSvcName");
bizKeyService.deleteByIdEaiSvcName(eaiSvcName);
if (tracekeys == null || tracekeys.isEmpty()) {
return null;
}
for(HashMap<String,Object> tracekey : tracekeys){
BizKey bizKey = fieldExtractInfoUIMapper.map(tracekey);
bizKeyService.save(bizKey);
}
return null;
}
public boolean transactionEIMSSync( HashMap<String,Object> interfaceVo , List<HashMap<String,Object>> layoutVos, List<HashMap<String,Object>> transformVos, List<HashMap<String,Object>> tracekeys, String userId) throws Exception {
logger.info("-------------------<< transactionEIMSSync >>----------------------------");
logger.debug("{}", interfaceVo);
logger.info("-------------------<< session 값체크>>----------------------------");
boolean isOnline = false;
for ( DataSourceType ds : DataSourceTypeManager.getOnlineDataSourceTypes()){
if (ds.getName().equals(DataSourceContextHolder.getDataSourceType().getName())){
isOnline = true;
break;
}
}
if (!isOnline){
throw new BizException("로그인 오류 (재로그인 하시기 바랍니다.)");
}
mergeLayout(layoutVos);
mergeTransform(transformVos);
mergeInterface(interfaceVo);
mergeTraceKey(interfaceVo, tracekeys);
return mergeMessageKey(interfaceVo, userId);
}
public Map<String,Map<String, String>> selectAdapterForNickName(String src, String tgt, String resSrc) throws Exception {
Map<String, Map<String, String>> result = new HashMap<String,Map<String,String>>();
if (!StringUtils.isEmpty(src)){
Map<String,String> nickname = dao.selectAdapterForNickName(new HashMap(){{put("adptrNickName",src);}});
if (nickname == null || nickname.size()==0){
throw new Exception("어댑터 닉네임 ("+src+")이 존재 하지 않습니다. EAI 담당자에게 문의 하세요.");
}
result.put("SRC", nickname);
}
if (!StringUtils.isEmpty(tgt) && !"DUMMY000".equals(tgt)){
Map<String,String> nickname = dao.selectAdapterForNickName(new HashMap(){{put("adptrNickName",tgt);}});
if (nickname == null || nickname.size()==0){
throw new Exception("어댑터 닉네임 ("+tgt+")이 존재 하지 않습니다. EAI 담당자에게 문의 하세요.");
}
result.put("TGT", nickname);
}
if (!StringUtils.isEmpty(resSrc)){
Map<String,String> nickname = dao.selectAdapterForNickName(new HashMap(){{put("adptrNickName",resSrc);}});
if (nickname == null || nickname.size()==0){
throw new Exception("어댑터 닉네임 ("+resSrc+")이 존재 하지 않습니다. EAI 담당자에게 문의 하세요.");
}
result.put("RES_SRC", nickname);
}
return result;
}
public void deleteInterface( HashMap<String,Object> inter ) throws Exception {
//interface 삭제할 경우
// - interface삭제 (he01,he02,fr01,ms02)
// - altkey,tracekey 삭제 (fr03) interface 기준으로 삭제
// - 내부표준전문 삭제 (hs04,hs05) interface 기준으로 삭제
// - 변환삭제 (tr01,tr02,tr03) interface 기준으로 삭제
logger.info("-------------------<<deleteEIMSSync >>----------------------------");
logger.debug("{}", inter);
logger.info("-------------------<< session 값체크>>----------------------------");
boolean isOnline = false;
for ( DataSourceType ds : DataSourceTypeManager.getOnlineDataSourceTypes()){
if (ds.getName().equals(DataSourceContextHolder.getDataSourceType().getName())){
isOnline = true;
break;
}
}
if (!isOnline){
throw new BizException("로그인 오류 (재로그인 하시기 바랍니다.)");
}
String eaiSvcName = (String)inter.get("eaiSvcName");
HashMap<String,Object> paramMap = new HashMap<String,Object>(){{put("eaiSvcName",eaiSvcName);}};
eaiMsgDao.delete(paramMap);
eaiMsgDao.deleteSvc(paramMap);
eaiMsgDao.deleteRefForEaiSvcName(paramMap);
eaiMsgDao.deleteCondRuleForEaiSvcName(paramMap);
//alterkey, tracekey 삭제
bizKeyService.deleteByIdEaiSvcName(eaiSvcName);
//내부표준전문삭제
List<String> bzwkSvcKeyNames = (List<String>)inter.get("bzwkSvcKeyName");
if (bzwkSvcKeyNames != null) {
for (String bzwkSvcKeyName : bzwkSvcKeyNames) {
standardMessageInfoService.deleteById(bzwkSvcKeyName);
}
}
//변환삭제
List<String> transforms = (List<String>)inter.get("transform");
if (transforms != null){
for(String transform : transforms){
HashMap<String,Object> map = new HashMap<String,Object>(){{put("cnvsnName",transform);}};
//1.delete transform //TR01 삭제
transformDao.deleteTransform(map);
//2.delete transform //TR02 삭제
transformDao.deleteTransformSourceResult(map);
//3.delete transform //TR03 삭제
transformDao.deleteTransformItem(map);
}
}
}
public void deleteLayout(HashMap<String,Object> layouts) throws Exception {
logger.info("-------------------<<deleteLayout >>----------------------------");
logger.debug("{}",layouts);
logger.info("-------------------<< session 값체크>>----------------------------");
boolean isOnline = false;
for ( DataSourceType ds : DataSourceTypeManager.getOnlineDataSourceTypes()){
if (ds.getName().equals(DataSourceContextHolder.getDataSourceType().getName())){
isOnline = true;
break;
}
}
if (!isOnline){
throw new BizException("로그인 오류 (재로그인 하시기 바랍니다.)");
}
String loutName = (String)layouts.get("loutName");
HashMap<String,Object> paramMap = new HashMap<String,Object>(){{put("loutName",loutName);}};
layoutDao.delete(paramMap);
layoutDao.deleteItemAll(paramMap);
}
public void deleteAll( String eaiSvcName, List<String> bzwkSvcKeyNames, List<String> transforms , List<String> layouts ) throws Exception {
logger.info("-------------------<<deleteEIMSSync >>----------------------------");
logger.debug("EIMSSyncService] eaiSvcName ="+eaiSvcName);
for(String bzwkSvcKeyName : bzwkSvcKeyNames){
logger.debug("EIMSSyncService] bzwkSvcKeyName ="+bzwkSvcKeyName);
}
for(String transform : transforms){
logger.debug("EIMSSyncService] transform ="+transform);
}
for(String layout : layouts){
logger.debug("EIMSSyncService] layout ="+layout);
}
logger.info("-------------------<< session 값체크>>----------------------------");
boolean isOnline = false;
for ( DataSourceType ds : DataSourceTypeManager.getOnlineDataSourceTypes()){
if (ds.getName().equals(DataSourceContextHolder.getDataSourceType().getName())){
isOnline = true;
break;
}
}
if (!isOnline){
throw new BizException("온라인 요청이 아닙니다. 확인 하시기 바랍니다.");
}
HashMap<String,Object> paramMap = new HashMap<String,Object>(){{put("eaiSvcName",eaiSvcName);}};
eaiMsgDao.delete(paramMap);
eaiMsgDao.deleteSvc(paramMap);
eaiMsgDao.deleteRefForEaiSvcName(paramMap);
eaiMsgDao.deleteCondRuleForEaiSvcName(paramMap);
//alterkey, tracekey 삭제
bizKeyService.deleteByIdEaiSvcName(eaiSvcName);
//내부표준전문삭제
if (bzwkSvcKeyNames != null) {
for (String bzwkSvcKeyName : bzwkSvcKeyNames) {
standardMessageInfoService.deleteById(bzwkSvcKeyName);
}
}
//변환삭제
if (transforms != null){
for(String transform : transforms){
HashMap<String,Object> map = new HashMap<String,Object>(){{put("cnvsnName",transform);}};
//1.delete transform //TR01 삭제
transformDao.deleteTransform(map);
//2.delete transform //TR02 삭제
transformDao.deleteTransformSourceResult(map);
//3.delete transform //TR03 삭제
transformDao.deleteTransformItem(map);
}
}
//레이아웃삭제
if (layouts != null){
for(String layout : layouts){
HashMap<String,Object> map = new HashMap<String,Object>(){{put("loutName",layout);}};
layoutDao.delete(map);
layoutDao.deleteItemAll(map);
}
}
}
public List<String> selectTransformListForEaiSvcName(HashMap<String,Object> map){
return dao.selectTransformListForEaiSvcName(map);
}
public List<String> selectBzwkSvcKeyNameForEaiSvcName(HashMap<String,Object> map){
return dao.selectBzwkSvcKeyNameForEaiSvcName(map);
}
// public static void main(String[] args) throws Exception{ //취약점 수정
//
// }
public boolean selecAppIsYn(HashMap<String,Object> map){
int count = dao.selecAppIsYn(map);
if (count==0) {
return false;
}else{
return true;
}
}
public void eaiSvcNameVali (HashMap<String,Object> interfaceVo) throws Exception {
/*
20200902
Flow Control -> B2B일 때
모니터링 코드(EIMS_B2B_BZWKDSTCD)에 정의되어 있는 업무구분코드에 서비스코드 앞3자리가 있을 때
라우팅 추출 정보가 없을때
메신저 발송
*/
HashMap he01 = (HashMap)interfaceVo.get("he01");
String eaiSvcName = (String)he01.get("eaiSvcName");
String flowCtrl = (String)he01.get("flowCtrlRoutName"); //플로우컨트롤명
String bzwkDstcd = eaiSvcName.substring(0, 3);//서비스코드 앞 3자리
String eaiSevrTxt = "";
boolean isB2b = false; //플로우컨트롤이 b2b인지
boolean isCode = false; //모니터링 코드에 정의되어 있는지
boolean isRoutCnt = false; //라우팅추출정보가 없을 때
String eaiSevrDstcd = (String)he01.get("eaiSevrDstcd"); //서버구분코드
List<ComboVo> sevrCdList = comboService.getFromCode("INOUT_TYPE");
if (!sevrCdList.isEmpty()) {
for (ComboVo m : sevrCdList) {
if (eaiSevrDstcd.equals(m.getCode())) {
eaiSevrTxt = m.getCodename();
break;
}
}
}
if (flowCtrl.indexOf("B2B")>-1){ //flowControl => B2B일때
isB2b = true;
}
//Monitoring Code에 서비스코드 앞 3자리가 정의되어 있는지
List<ComboVo> bzwkDstcdList = comboService.getMonitoringCodeSortedByIdCode("EIMS_B2B_BZWKDSTCD");
for(ComboVo m : bzwkDstcdList){
if(bzwkDstcd.equals(m.getCodename())){
isCode = true;
break;
}
}
//라우팅추출정보가 없을때
long routCnt = b2bExtractService.count(eaiSvcName);
if(routCnt == 0){
isRoutCnt = true;
}
if (isB2b && isCode && isRoutCnt){
if(!"1".equals(eaiSevrDstcd) && eaiSvcName.endsWith("1")){ //내부가 아니고 서비스코드가 S01 or R01 1로 끝날때 pass
return;
}
//쪽지알림
//라우팅 필드추출 정보 관리에 XXXXXXXX 서비스코드가 미등록 상태입니다.
//EMS - 환경정보 - 서비스정보관리 - 라우팅 필드추출 정보 관리에 신규등록 바랍니다.
StringBuffer sb = new StringBuffer();
sb.append("EAI서비스코드 : " + eaiSvcName ).append("<br>");
sb.append("EAI서버구분 : ["+eaiSevrDstcd+"] " + eaiSevrTxt ).append("<br>");
sb.append("라우팅 추출 정보 관리에 서비스코드("+eaiSvcName+")가 미등록 상태입니다." ).append("<br>");
sb.append("EMS - 환경정보 - 서비스정보관리 - 라우팅 필드추출 정보 관리에 신규등록 바랍니다." ).append("<br>");
MessengerPlusSender sender = MessengerPlusSender.getInstance();
String url = monitoringContext.getStringProperty("rms.messenger.url","http://172.17.179.45/HMemoService");
String srvCode = monitoringContext.getStringProperty("rms.messenger.srvCode","EAI002");
String recipient = monitoringContext.getStringProperty("rms.messenger.recipient","1622512;1562325;2852883;3331839;S010795;");
String send = monitoringContext.getStringProperty("rms.messenger.send","1562325");
String senderAlias = monitoringContext.getStringProperty("rms.messenger.senderAlias","EAI시스템");
logger.debug("send MessengerPlus data : " + sb.toString());
sender.execute(url, srvCode, recipient, send, "라우팅 필드추출정보 등록요청", sb.toString(), "", senderAlias);
}
}
/**
* 엔진 옵션 정보 가져오기
* 1. Queue 정보
* 2. B2B 정보 - 현재는 EIMS에서 하고 있음
* => S2,R2 만 설정해야됨
* 3. FAILOVER 정보 - 전체를 하기로 했음
* => S2,R2 만 설정해야됨
*
* @param serviceType 서버타입
* @param eaiSvcName EAI서비스코드
* @param outBizCd 대외기관코드
* @return
* @throws Exception
*/
public HashMap getEngineOption(String serviceType, String eaiSvcName, String outBizCd) throws Exception{
if (StringUtils.isBlank(outBizCd)){
return new HashMap();
}
String queueFormat = outBizCd + eaiSvcName.substring(eaiSvcName.length()-2);
String b2bFormat = outBizCd ;
String failoverFormat = outBizCd ;
HashMap result = new HashMap();
HashMap m = null;
m = (HashMap)chnlInfoIntegrationDao.selectQueueDetail(new HashMap(){{put("dataDstcd",EIMSParserKey.FC_QUEUE);put("serviceType",serviceType);put("codeName",queueFormat);}});
if (m != null){
String value = (String)m.get("QUEUENAME");
if (StringUtils.isNotBlank(value)){
result.put(EIMSParserKey.FC_QUEUE, value);
}
}
m = (HashMap)chnlInfoIntegrationDao.selectQueueDetail(new HashMap(){{put("dataDstcd",EIMSParserKey.FC_B2B);put("serviceType",serviceType);put("codeName",b2bFormat);}});
if (m != null){
String value = (String)m.get("CODENAME");
if (StringUtils.isNotBlank(value) && (eaiSvcName.endsWith("S2") || eaiSvcName.endsWith("R2") )){
result.put(EIMSParserKey.FC_B2B, "B2BFC");
}
}
m = (HashMap)chnlInfoIntegrationDao.selectQueueDetail(new HashMap(){{put("dataDstcd",EIMSParserKey.FC_FAILOVER);put("serviceType",serviceType);put("codeName",failoverFormat);}});
if (m != null){
String value = (String)m.get("CODENAME");
if (StringUtils.isNotBlank(value) && (eaiSvcName.endsWith("S2") || eaiSvcName.endsWith("R2") )){
result.put(EIMSParserKey.FC_FAILOVER, "1");
}else{
result.put(EIMSParserKey.FC_FAILOVER, "0");
}
}
return result;
}
}
@@ -0,0 +1,221 @@
package com.eactive.eai.rms.ext.kakaocard.cm;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.UUIDGenerator;
import com.eactive.eai.rms.common.cm.CmLogService;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.data.entity.man.cm.CmLogEntity;
import com.eactive.eai.rms.ext.kakaocard.cm.except.CmMoveDirectoryException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public abstract class KakaoCardCmAbstractService implements KakaoCardCmService {
protected static final Logger logger = Logger.getLogger("DYNAMIC_LOGGER");
@Autowired @Qualifier("monitoringContext")
protected MonitoringContext monitoringContext;
@Autowired
protected S3Client s3Client;
@Autowired
protected CmLogService cmLogService;
protected void storeResourceFilesFromAWS_S3(String serviceType, String commitId) throws IOException {
if(System.getProperty("eai.datasource.type").equals("LOCAL")) {
return;
}
String bucketName = monitoringContext.getStringProperty(MonitoringContext.AWS_S3_CM_BUCKET_NAME);
String objectKey = "dat" + File.separator + serviceType + File.separator + serviceType + "-" + commitId + ".zip";
logger.debug("Try to download from bucket: ["+bucketName+"], objectKey: ["+objectKey+"]");
GetObjectRequest getObjectRequest =
GetObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
ResponseInputStream<GetObjectResponse> s3FileStream = s3Client.getObject(getObjectRequest);
String uploadPath =
monitoringContext.getStringProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, CM_DEVELOPER_UPLOAD_PATH_DEFAULT) + serviceType + File.separator + commitId + File.separator;
if (new File(uploadPath).exists()) {
deleteDirectoryRecursively(Paths.get(uploadPath));
}
try (ZipInputStream zis = new ZipInputStream(s3FileStream)) {
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
File destFile = new File(uploadPath, zipEntry.getName());
// 디렉토리인 경우 디렉토리 생성
if (zipEntry.isDirectory()) {
destFile.mkdirs();
} else {
// 파일인 경우 파일 복사
File parentDir = destFile.getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
Files.copy(zis, destFile.toPath());
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected List<String> getAppCodesFromDirectory(String serviceType, String commitId) {
List<String> appCodes = new ArrayList<>();
Path uploadPath = Paths.get(
monitoringContext.getStringProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, CM_DEVELOPER_UPLOAD_PATH_DEFAULT)
+ serviceType + File.separator + commitId);
try (DirectoryStream<Path> onlyDirectory = Files.newDirectoryStream(uploadPath, entry -> Files.isDirectory(entry));) {
for(Path path : onlyDirectory) {
appCodes.add(path.getFileName().toString());
}
if (appCodes.size() == 0) {
throw new RuntimeException("No AppCode Directory In Folder:" + uploadPath.toString());
}
return appCodes;
} catch (IOException e) {
logger.error(e);
throw new RuntimeException(e);
}
}
private void deleteDirectoryRecursively(Path path) throws IOException {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
protected void cmLogging(String afterPath, String serviceType, String appCode, String deployId, String successYn, String rollbackYn, String errorMsg, String deployStartTime, String currentDateTime) throws Exception {
logger.debug("CM작업내용 Logging.. deployId:"+ deployId);
DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING));
CmLogEntity log = new CmLogEntity();
log.setGuid(UUIDGenerator.getUUID());
log.setService_type(serviceType);
log.setAppl_cd(appCode);
log.setDeploy_id(deployId);
log.setSuccess_yn(successYn);
log.setRollback_yn(rollbackYn);
log.setError_msg(errorMsg);
log.setDeploy_time(deployStartTime);
log.setDeploy_end_time(DatetimeUtil.getCurrentDateTime());
cmLogService.insertLog(log, afterPath);
}
/*
* 폴더 이동
* after folder check & move
* 이동순서 uploadFolder => afterFolder => backupFolder
* uploadFolder는 원본데이터, afterFolder는 적용된 데이터(최근꺼만 존재), backupFolder 은 적용된게 여러개일경우(히스토리성)
*/
protected void moveFiles(String uploadPath, String afterPath, String backupPath, String serviceType, String deployId) throws IOException {
/*
* If after exist, after -> backup
*/
File afterFolder = new File(afterPath + File.separator + serviceType + File.separator + deployId);
Path afterFolderPath = Paths.get(afterPath + File.separator + serviceType + File.separator + deployId + File.separator);
logger.info("afterFolder : " + afterFolder.getAbsolutePath() + " , " + afterFolder.exists());
if (afterFolder.exists()) {
File backupFolder = new File(backupPath+ File.separator + serviceType + File.separator+ deployId + "_" + DatetimeUtil.getCurrentTimeMsNoMark(afterFolder.lastModified()));
Path backupFolderPath = Paths.get(backupPath+ File.separator + serviceType + File.separator+ deployId + "_" + DatetimeUtil.getCurrentTimeMsNoMark(afterFolder.lastModified()));
logger.info("backupFolder : " + backupFolder.getAbsolutePath());
try {
if (backupFolder.exists() && backupFolder.isDirectory()){
deleteDirectory(backupFolderPath);
}
Files.createDirectories(backupFolderPath);
Files.move(afterFolderPath, backupFolderPath, StandardCopyOption.REPLACE_EXISTING);
logger.info("move folder success : " + afterFolder.getAbsolutePath() + " to " + backupFolder.getAbsolutePath());
} catch (Exception e) {
logger.error("move folder error : " + afterFolder.getAbsolutePath() + " to " + backupFolder.getAbsolutePath());
throw new CmMoveDirectoryException(e);
}
}
/*
* upload -> after
*/
File uploadFolder = new File(uploadPath + File.separator + serviceType + File.separator + deployId);
Path uploadFolderPath = Paths.get(uploadPath + File.separator + serviceType + File.separator + deployId + File.separator);
logger.info("uploadFolder : " + uploadFolder.getAbsolutePath() + " , "+uploadFolder.exists() );
if (uploadFolder.exists()){
try {
deleteDirectory(afterFolderPath);
Files.createDirectories(afterFolderPath);
Files.move(uploadFolderPath, afterFolderPath, StandardCopyOption.REPLACE_EXISTING);
logger.info("move folder success : " + uploadFolder.getAbsolutePath() + " to " + afterFolder.getAbsolutePath());
} catch (Exception e) {
logger.error("move folder error : " + uploadFolder.getAbsolutePath() + " to " + afterFolder.getAbsolutePath());
throw new CmMoveDirectoryException(e);
}
} else {
logger.error("upload folder does not exist : " + uploadFolder.getAbsolutePath());
throw new CmMoveDirectoryException("upload folder does not exist : " + uploadFolder.getAbsolutePath());
}
}
private void deleteDirectory(Path directory) throws IOException {
if (Files.isDirectory(directory)) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
for (Path path : stream) {
deleteDirectory(path);
}
}
}
Files.delete(directory);
}
}
@@ -0,0 +1,126 @@
package com.eactive.eai.rms.ext.kakaocard.cm;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.rms.bap.loader.service.TransactionBAPServiceImpl;
import com.eactive.eai.rms.common.cm.CmLogService;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.ext.kakaocard.cm.except.CmInsertException;
import com.eactive.eai.rms.onl.common.util.FileWriteUtil;
@Service("kakaoCardCmFepBatchService")
public class KakaoCardCmBapService extends KakaoCardCmAbstractService {
@Autowired @Qualifier("monitoringContext")
private MonitoringContext monitoringContext;
@Autowired @Qualifier("loaderBAPService")
private TransactionBAPServiceImpl loaderService;
@Override
public boolean supportsType(String serviceType) {
return DataSourceTypeManager.BAP.equals(serviceType);
}
@Override
public void startDeploy(String serviceType, String commitId) throws Exception {
final String deployId = commitId;
final String rollbackYn = "N"; // FIXME
final String deployStartTime = DatetimeUtil.getCurrentDateTime();
Properties prop = monitoringContext.getProperties();
String uploadPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, CM_DEVELOPER_UPLOAD_PATH_DEFAULT);
try {
storeResourceFilesFromAWS_S3(serviceType, commitId);
List<String> appCodes = getAppCodesFromDirectory(serviceType, commitId);
this.transactionDeployResources(serviceType, commitId, appCodes);
try {
cmLogging(uploadPath, serviceType, "ALL", deployId, CmLogService.DEPOLY_SUCCESS, rollbackYn, "", deployStartTime, DatetimeUtil.getCurrentDateTime());
} catch (Exception log_e) {
logger.error("CM작업이 정상적으로 종료되었으나, 로깅 중 에러가 발생하였습니다. 해당 에러는 throw되지 않습니다.", log_e);
}
} catch (Exception e) {
/** Error Log **/
try {
cmLogging(uploadPath, serviceType, "ALL", deployId, CmLogService.DEPOLY_FAIL, rollbackYn, e.getMessage(), deployStartTime, DatetimeUtil.getCurrentDateTime());
} catch (Exception log_e) {
logger.error("CM작업의 실패로깅 중 에러가 발생하였습니다. 해당 에러는 throw되지 않습니다.", log_e);
}
throw e;
}
}
@Override
public void transactionDeployResources(String serviceType, String commitId, List<String> appCodes)
throws Exception {
final DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
Properties prop = monitoringContext.getProperties();
final String uploadPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, CM_DEVELOPER_UPLOAD_PATH_DEFAULT);
try {
for (String appCode : appCodes) {
String path_uploaded_servicetype_commitId_app_interface =
uploadPath +
serviceType + File.separator +
commitId + File.separator +
appCode + File.separator +
FileWriteUtil.BAP_CM_DIR + File.separator;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(path_uploaded_servicetype_commitId_app_interface))) {
for (Path item : stream) {
if (Files.isRegularFile(item)) {
loaderService.insertFileInfoLoading(dt, path_uploaded_servicetype_commitId_app_interface, item.getFileName().toString());
}
}
} catch (IOException e) {
throw e;
}
}
} catch (Exception e) {
logger.error("Metadata Deploy INSERT ERROR. ", e);
throw new CmInsertException(e);
}
}
@Override
public void promote(String serviceType, String commitId) {
// TODO Auto-generated method stub
}
@Override
public void rollback(String serviceType, String commitId) {
// TODO Auto-generated method stub
}
}
@@ -0,0 +1,172 @@
package com.eactive.eai.rms.ext.kakaocard.cm;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.rms.common.cm.CmLogService;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.ext.kakaocard.cm.except.CmInsertException;
import com.eactive.eai.rms.ext.kakaocard.cm.except.CmReloadException;
import com.eactive.eai.rms.onl.common.service.AgentUtilService;
import com.eactive.eai.rms.onl.common.util.FileWriteUtil;
import com.eactive.eai.rms.onl.loader.service.TransactionDeployJsonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service("kakaoCardCmEaiBatchService")
public class KakaoCardCmBatService extends KakaoCardCmAbstractService {
private static final Logger logger = LoggerFactory.getLogger("DYNAMIC_LOGGER");
@Autowired @Qualifier("deployJsonServiceBat")
private TransactionDeployJsonService loaderService;
@Autowired @Qualifier("batAgentUtilService")
public AgentUtilService agentUtilService;
private static final Pattern pattern = Pattern.compile("^(.+)\\..+$");
@Override
public boolean supportsType(String serviceType) {
return DataSourceTypeManager.BAT.equals(serviceType);
}
@Override
public void startDeploy(String serviceType, String commitId) throws Exception {
final String deployId = commitId;
final String rollbackYn = "N"; // FIXME
final String deployStartTime = DatetimeUtil.getCurrentDateTime();
Properties prop = monitoringContext.getProperties();
String uploadPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, CM_DEVELOPER_UPLOAD_PATH_DEFAULT);
try {
storeResourceFilesFromAWS_S3(serviceType, commitId);
List<String> appCodes = getAppCodesFromDirectory(serviceType, commitId);
this.transactionDeployResources(serviceType, commitId, appCodes);
try {
cmLogging(uploadPath, serviceType, "ALL", deployId, CmLogService.DEPOLY_SUCCESS, rollbackYn, "", deployStartTime, DatetimeUtil.getCurrentDateTime());
} catch (Exception log_e) {
logger.error("CM작업이 정상적으로 종료되었으나, 로깅 중 에러가 발생하였습니다. 해당 에러는 throw되지 않습니다.", log_e);
}
} catch (Exception e) {
/** Error Log **/
try {
cmLogging(uploadPath, serviceType, "ALL", deployId, CmLogService.DEPOLY_FAIL, rollbackYn, e.getMessage(), deployStartTime, DatetimeUtil.getCurrentDateTime());
} catch (Exception log_e) {
logger.error("CM작업의 실패로깅 중 에러가 발생하였습니다. 해당 에러는 throw되지 않습니다.", log_e);
}
throw e;
}
}
@Override
public void transactionDeployResources(String serviceType, String commitId, List<String> appCodes) throws Exception {
final DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
final Vector<String> allInterfaceList = new Vector<>();
Properties prop = monitoringContext.getProperties();
final String uploadPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, CM_DEVELOPER_UPLOAD_PATH_DEFAULT);
try {
for (String appCode : appCodes) {
String path_uploaded_servicetype_commitId_app_interface =
uploadPath +
serviceType + File.separator +
commitId + File.separator +
appCode + File.separator +
FileWriteUtil.INTERFACE + File.separator;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(path_uploaded_servicetype_commitId_app_interface))) {
for (Path item : stream) {
if (Files.isRegularFile(item)) {
loaderService.insertInterfaceLoading(path_uploaded_servicetype_commitId_app_interface, item.getFileName().toString());
Matcher matcher = pattern.matcher(item.getFileName().toString());
if (matcher.find()) {
allInterfaceList.add(matcher.group(1));
}
}
}
} catch (IOException e) {
throw e;
}
}
} catch (Exception e) {
logger.error("Metadata Deploy INSERT ERROR. ", e);
throw new CmInsertException(e);
}
try {
logger.info("After Metadata deploy, Run ReloadBatchInterfaceJobListCommand with : " + allInterfaceList.toString());
CommonCommand command = new CommonCommand("com.eactive.eai.agent.scheduler.ReloadBatchInterfaceJobListCommand", allInterfaceList);
HashMap<String, Object> returnMap = agentUtilService.broadcast(command);
if (!syncValidate(returnMap)){
throw new Exception("스케쥴 start 오류 " + CommonUtil.getMapString(returnMap, true));
}
} catch (Exception e) {
logger.error("Metadata Deploy RELOAD ERROR. ", e);
throw new CmReloadException(e);
}
}
@Override
public void promote(String serviceType, String commitId) {
// nothing to do
}
@Override
public void rollback(String serviceType, String commitId) {
// nothing to do
}
private boolean syncValidate(HashMap<String,Object> map ){
for(String key : map.keySet()){
Object o = map.get(key);
if (o instanceof String){
if("success".equals((String)o)){
;
}else{
return false;
}
}else{
return false;
}
}
return true;
}
}
@@ -0,0 +1,124 @@
package com.eactive.eai.rms.ext.kakaocard.cm;
import java.nio.charset.StandardCharsets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.spring.BaseController;
@Controller
@RequestMapping({"/deployresource"})
public class KakaoCardCmController extends BaseController {
@Autowired
private KakaoCardCmServiceFactory serviceFactory;
@Autowired
private KakaoCardCmDeploySuffixContextHolder kakaoCardCmDeploySuffixContextHolder;
@GetMapping("/{serviceType}/{commitId}/deployStart.do")
public ResponseEntity<Object> deployStart(@PathVariable String serviceType, @PathVariable String commitId) {
serviceType = serviceType.toUpperCase();
/** Invalid serviceType Error **/
if (!DataSourceTypeManager.getDataSourceTypeNames().contains(serviceType))
return ResponseEntity.internalServerError().contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
.body("Invalid ServiceType: " + serviceType);
try {
DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
DataSourceContextHolder.setDataSourceType(dt);
KakaoCardCmService service = serviceFactory.create(serviceType);
service.startDeploy(serviceType, commitId);
} catch (Exception e) {
logger.error("KakaoCardCmController deployStart Error. serviceType=" + serviceType + ", commitId=" + commitId, e);
return ResponseEntity.internalServerError().contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
.body("KakaoCardCmController deployStart Error. serviceType=" + serviceType + ", commitId=" + commitId + ", error=" + e.getMessage());
} finally {
kakaoCardCmDeploySuffixContextHolder.remove();
}
return ResponseEntity.ok()
.contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
.body("Deploy Complete");
}
@GetMapping("/{serviceType}/{commitId}/promote.do")
public ResponseEntity<Object> promote(@PathVariable String serviceType, @PathVariable String commitId) {
serviceType = serviceType.toUpperCase();
/** Invalid serviceType Error **/
if (!DataSourceTypeManager.getDataSourceTypeNames().contains(serviceType))
return ResponseEntity.internalServerError().contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
.body("Invalid ServiceType: " + serviceType);
try {
DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
DataSourceContextHolder.setDataSourceType(dt);
KakaoCardCmService service = serviceFactory.create(serviceType);
service.promote(serviceType, commitId);
} catch (Exception e) {
logger.error("KakaoCardCmController promote Error. serviceType=" + serviceType + ", commitId=" + commitId, e);
return ResponseEntity.internalServerError().contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
.body("KakaoCardCmController promote Error. serviceType=" + serviceType + ", commitId=" + commitId + ", error=" + e.getMessage());
} finally {
}
return ResponseEntity.ok()
.contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
.body("Promote Complete");
}
@GetMapping("/{serviceType}/{commitId}/rollback.do")
public ResponseEntity<Object> rollback(@PathVariable String serviceType, @PathVariable String commitId) {
serviceType = serviceType.toUpperCase();
/** Invalid serviceType Error **/
if (!DataSourceTypeManager.getDataSourceTypeNames().contains(serviceType))
return ResponseEntity.internalServerError().contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
.body("Invalid ServiceType: " + serviceType);
try {
DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
DataSourceContextHolder.setDataSourceType(dt);
KakaoCardCmService service = serviceFactory.create(serviceType);
service.rollback(serviceType, commitId);
} catch (Exception e) {
logger.error("KakaoCardCmController rollback Error. serviceType=" + serviceType + ", commitId=" + commitId, e);
return ResponseEntity.internalServerError().contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
.body("KakaoCardCmController rollback Error. serviceType=" + serviceType + ", commitId=" + commitId + ", error=" + e.getMessage());
} finally {
}
return ResponseEntity.ok()
.contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
.body("Rollback Complete");
}
}
@@ -0,0 +1,22 @@
package com.eactive.eai.rms.ext.kakaocard.cm;
import org.springframework.stereotype.Component;
@Component
public class KakaoCardCmDeploySuffixContextHolder {
private final ThreadLocal<String> deploySuffixThreadLocal = new ThreadLocal<>();
public void setDeploySuffix(String deploySuffix) {
deploySuffixThreadLocal.set(deploySuffix);
}
public String getDeploySuffix() {
return deploySuffixThreadLocal.get();
}
public void remove() {
deploySuffixThreadLocal.remove();
}
}
@@ -0,0 +1,201 @@
package com.eactive.eai.rms.ext.kakaocard.cm;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.rms.common.cm.CmLogService;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.ext.kakaocard.cm.except.CmInsertException;
import com.eactive.eai.rms.onl.common.util.FileWriteUtil;
import com.eactive.eai.rms.onl.loader.service.TransactionDeployJsonService;
import com.eactive.kakao.rolling.RollingSuffixService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;
@Profile("rolling")
@Service("kakaoCardCmOnlineService")
@Transactional(rollbackOn = Exception.class)
public class KakaoCardCmOnlineService extends KakaoCardCmAbstractService {
public static final String LAYOUT_KEY = "layoutList";
public static final String TRANSFORM_KEY = "transformList";
public static final String ADDI_TRANSFORM_KEY = "addiTransformKey";
public static final String INTERFACE_KEY = "interfaceList";
public static final String INTERFACE_EXT_KEY = "interfaceExtList";
// KakaoCm Deploy : Not send command after MetaData-Deploy
// @Autowired @Qualifier("onlAgentUtilService")
// private AgentUtilService onlAgentUtilService; // GET SERVER INFO FROM DB.TSEAISY02
@Autowired
@Qualifier("deployJsonServiceOnline")
private TransactionDeployJsonService loaderService;
@Autowired
private RollingSuffixService rollingSuffixService;
@Autowired
private KakaoCardCmDeploySuffixContextHolder deploySuffixContextHolder;
@Override
public boolean supportsType(String serviceType) {
return DataSourceTypeManager.getDataSourceType(serviceType).isOnline();
}
public void startDeploy(String serviceType, String commitId) throws Exception {
final String deployId = commitId;
final String rollbackYn = "N"; // FIXME
final String deployStartTime = DatetimeUtil.getCurrentDateTime();
Properties prop = monitoringContext.getProperties();
String uploadPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, CM_DEVELOPER_UPLOAD_PATH_DEFAULT);
try {
storeResourceFilesFromAWS_S3(serviceType, commitId);
List<String> appCodes = getAppCodesFromDirectory(serviceType, commitId);
this.transactionDeployResources(serviceType, commitId, appCodes);
try {
cmLogging(uploadPath, serviceType, "ALL", deployId, CmLogService.DEPOLY_SUCCESS, rollbackYn, "", deployStartTime, DatetimeUtil.getCurrentDateTime());
} catch (Exception log_e) {
logger.error("CM작업이 정상적으로 종료되었으나, 로깅 중 에러가 발생하였습니다. 해당 에러는 throw되지 않습니다.", log_e);
}
} catch (Exception e) {
/** Error Log **/
try {
cmLogging(uploadPath, serviceType, "ALL", deployId, CmLogService.DEPOLY_FAIL, rollbackYn, e.getMessage(), deployStartTime, DatetimeUtil.getCurrentDateTime());
} catch (Exception log_e) {
logger.error("CM작업의 실패로깅 중 에러가 발생하였습니다. 해당 에러는 throw되지 않습니다.", log_e);
}
throw e;
}
}
public void transactionDeployResources(String serviceType, String commitId, List<String> appCodes) throws Exception {
final DataSourceType dt = DataSourceTypeManager.getDataSourceType(serviceType);
final String rollbackYn = "N"; // FIXME
Properties prop = monitoringContext.getProperties();
String uploadPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, CM_DEVELOPER_UPLOAD_PATH_DEFAULT);
rollingSuffixService.insertRollingSuffix(commitId);
deploySuffixContextHolder.setDeploySuffix(rollingSuffixService.getCurrentSuffixByCommitId(commitId));
/** db insert **/
insertCmData(uploadPath, serviceType, appCodes, commitId, rollbackYn, dt);
}
public void promote(String serviceType, String commitId) {
rollingSuffixService.changeCurrentCommitId(commitId);
}
public void rollback(String serviceType, String commitId) {
rollingSuffixService.changeCurrentCommitId(commitId);
try {
final String deployStartTime = DatetimeUtil.getCurrentDateTime();
Properties prop = monitoringContext.getProperties();
String uploadPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH, CM_DEVELOPER_UPLOAD_PATH_DEFAULT);
Path dummyPathForLogging = Paths.get(uploadPath + File.separator + serviceType + File.separator + commitId);
if (Files.notExists(dummyPathForLogging)) {
Files.createDirectories(dummyPathForLogging);
}
cmLogging(uploadPath, serviceType, "ALL", commitId, CmLogService.DEPOLY_SUCCESS, "Y", "Rollback 처리 로그입니다.", deployStartTime, DatetimeUtil.getCurrentDateTime());
} catch (Exception log_e) {
logger.error("CM작업이 정상적으로 종료되었으나, 로깅 중 에러가 발생하였습니다. 해당 에러는 throw되지 않습니다.", log_e);
}
}
public void insertCmData(String uploadPath, String serviceType, List<String> appCodes, String deployId, String rollbackYn, DataSourceType dt) throws Exception {
try {
for (String appCode : appCodes) {
String path = uploadPath + serviceType + File.separator + deployId + File.separator + appCode;
File uploadDir = new File(path);
if (!uploadDir.exists()) {
throw new Exception("폴더존재안함 : " + uploadDir.getAbsolutePath());
}
//layout 식별
File layoutDir = new File(path + File.separator + FileWriteUtil.LAYOUT);
if (layoutDir.exists()) {
insertLayoutFile(dt, layoutDir);
}
//변환 식별
File transformDir = new File(path + File.separator + FileWriteUtil.TRANSFORM);
if (transformDir.exists()) {
insertTransformFile(dt, transformDir);
}
//인터페이스 식별
File interfaceDir = new File(path + File.separator + FileWriteUtil.INTERFACE);
if (interfaceDir.exists()) {
insertInterfaceFile(dt, interfaceDir);
}
}
} catch (Exception e) {
logger.error("Metadata Deploy INSERT ERROR. ", e);
throw new CmInsertException(e);
}
}
private void insertLayoutFile(DataSourceType dt, File layoutDir) throws Exception {
String path = layoutDir.getAbsolutePath() + File.separator;
File subDir = new File(path);
String[] sublistFiles = subDir.list();
if (sublistFiles != null) {
for (String fileName : sublistFiles) {
logger.info("CmService layout : fileName =" + fileName + " , path = " + path);
try {
loaderService.insertLayoutLoading(path, fileName);
} catch (Exception e) {
throw new Exception("Exception FileName : " + fileName + "\n" + e.getMessage(), e);
}
}
}
}
private void insertTransformFile(DataSourceType dt, File transformDir) throws Exception {
String path = transformDir.getAbsolutePath() + File.separator;
File subDir = new File(path);
String[] sublistFiles = subDir.list();
if (sublistFiles != null) {
for (String fileName : sublistFiles) {
logger.info("CmService interface : fileName =" + fileName + " , path = " + path);
loaderService.insertTransformLoading(path, fileName);
}
}
}
private void insertInterfaceFile(DataSourceType dt, File interfaceDir) throws Exception {
String path = interfaceDir.getAbsolutePath() + File.separator;
File subDir = new File(path);
String[] sublistFiles = subDir.list();
if (sublistFiles != null) {
for (String fileName : sublistFiles) {
logger.info("CmService interface : fileName =" + fileName + " , path = " + path);
loaderService.insertInterfaceLoading(path, fileName);
}
}
}
}
@@ -0,0 +1,21 @@
package com.eactive.eai.rms.ext.kakaocard.cm;
import java.util.List;
public interface KakaoCardCmService {
static final String CM_DEVELOPER_UPLOAD_PATH_DEFAULT = "/data001/cm/upload/";
static final String CM_DEVELOPER_AFTER_PATH_DEFAULT = "/data001/cm/after/";
static final String CM_DEVELOPER_BACKUP_PATH_DEFAULT = "/data001/cm/backup/";
boolean supportsType(String serviceType);
void startDeploy(String serviceType, String commitId) throws Exception;
void transactionDeployResources(String serviceType, String commitId, List<String> appCodes) throws Exception;
void promote(String serviceType, String commitId);
void rollback(String serviceType, String commitId);
}
@@ -0,0 +1,20 @@
package com.eactive.eai.rms.ext.kakaocard.cm;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class KakaoCardCmServiceFactory {
@Autowired
private List<KakaoCardCmService> cmServiceList;
public KakaoCardCmService create(String serviceType) {
return cmServiceList.stream()
.filter(service -> service.supportsType(serviceType)).findFirst()
.orElseThrow(() -> new RuntimeException("No Matched Service With ServiceType: " + serviceType));
}
}
@@ -0,0 +1,209 @@
package com.eactive.eai.rms.ext.kakaocard.cm;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
@Controller
@RequestMapping("/deployresource")
public class TempController implements InterceptorSkipController {
@Autowired
private S3Client s3Client;
@Autowired @Qualifier("monitoringContext")
private MonitoringContext monitoringContext;
@RequestMapping("/files.do")
public ResponseEntity<String> temp() {
Properties prop = monitoringContext.getProperties();
String uploadPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_UPLOAD_PATH);
String afterPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_AFTER_PATH);
String backupPath = prop.getProperty(MonitoringContext.CM_DEVELOPER_BACKUP_PATH);
StringBuilder sb = new StringBuilder();
sb.append(" - UPLOAD PATH").append(System.lineSeparator());
sb.append(fileSystemEntryList(Paths.get(uploadPath))).append(System.lineSeparator());
sb.append(" - AFTER PATH").append(System.lineSeparator());
sb.append(fileSystemEntryList(Paths.get(afterPath))).append(System.lineSeparator());
sb.append(" - BACKUP PATH").append(System.lineSeparator());
sb.append(fileSystemEntryList(Paths.get(backupPath))).append(System.lineSeparator());
return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(sb.toString());
}
private String fileSystemEntryList(Path path) {
StringBuilder sb = new StringBuilder();
try {
Files.walkFileTree(path, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
sb.append(dir.toAbsolutePath().toString()).append(System.lineSeparator());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
sb.append(file.toAbsolutePath().toString()).append(System.lineSeparator());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
sb.append("ERROR: " + e.getMessage());
e.printStackTrace();
}
return sb.toString();
}
@RequestMapping("/s3temp/listfiles.do")
public ResponseEntity<Object> listFiles() {
StringBuilder sb = new StringBuilder();
try {
String bucketName = monitoringContext.getStringProperty(MonitoringContext.AWS_S3_CM_BUCKET_NAME);
sb.append("BUCKET : " + bucketName).append(System.lineSeparator());
ListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(1000)
.build();
boolean done = false;
while (!done) {
ListObjectsV2Response listObjResponse = s3Client.listObjectsV2(listObjectsReqManual);
for (S3Object content : listObjResponse.contents()) {
sb.append(content.key()).append(System.lineSeparator());
}
if (listObjResponse.nextContinuationToken() == null) {
done = true;
}
listObjectsReqManual = ListObjectsV2Request.builder()
.bucket(bucketName)
.continuationToken(listObjResponse.nextContinuationToken())
.build();
}
} catch (Exception e) {
e.printStackTrace();
sb.append("ERROR:"+e.getMessage()).append(System.lineSeparator());
}
return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(sb.toString());
}
@RequestMapping("/s3temp/download.do")
public ResponseEntity<Object> temp(String objectKey) {
try {
String bucketName = monitoringContext.getStringProperty(MonitoringContext.AWS_S3_CM_BUCKET_NAME);
GetObjectRequest getObjectRequest = GetObjectRequest.builder().bucket(bucketName).key(objectKey).build();
ResponseBytes<GetObjectResponse> objectAsBytes = s3Client.getObjectAsBytes(getObjectRequest);
return ResponseEntity.ok().header("Content-Disposition", "attachment; filename=TEMP.zip").body(objectAsBytes.asByteArray());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.ok().contentType(new MediaType("text", "plain", StandardCharsets.UTF_8)).body(e.getMessage());
}
}
@RequestMapping("/sessionTest.do")
public ResponseEntity<String> session(Integer startIndex) throws Exception {
Integer url2s = startIndex+1;
URL url = new URL("https://card-ems-"+startIndex+".card-ems.card.svc.cluster.local:8080/monitoring/getId.jsp");
URL url2 = new URL("https://card-ems-"+url2s+".card-ems.card.svc.cluster.local:8080/monitoring/getId.jsp");
return ResponseEntity.ok(new StringBuilder().append(getBody(url)).append(System.lineSeparator()).append(getBody(url2)).toString());
}
private String getBody(URL url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while((line = bufferedReader.readLine()) != null) {
response.append(line);
}
response.append(line);
bufferedReader.close();
return response.toString();
}
// @Autowired @Qualifier("serverService")
// private ServerService serverService;
@RequestMapping("k8sMergeTest.do")
public ResponseEntity<String> test1() {
String result = "";
DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.EAI));
try {
List<Map<String, String>> paramList = new ArrayList<>();
paramList.add(new HashMap<String,String>() {{ put("eaiSevrInstncName", "card-internal-runtime-7f85458c98-cc2z9"); put("sevrLsnPortName", "30510"); put("flovrSevrName", ""); put("hostName", "JOHNCCNS-F6363B"); put("eaiSevrIp", "172.27.176.1"); }});
paramList.add(new HashMap<String,String>() {{ put("eaiSevrInstncName", "newone"); put("sevrLsnPortName", "1234"); put("flovrSevrName", ""); put("hostName", "sunwookPC"); put("eaiSevrIp", "127.0.0.1"); }});
// serverService.transactionMergeServerList(paramList);
result = "success";
} catch (Exception e) {
System.out.println(e);
result = e.getMessage();
}
return ResponseEntity.ok(result);
}
}
@@ -0,0 +1,25 @@
package com.eactive.eai.rms.ext.kakaocard.cm.except;
public class CmInsertException extends RuntimeException {
public CmInsertException() {
super();
}
public CmInsertException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public CmInsertException(String message, Throwable cause) {
super(message, cause);
}
public CmInsertException(String message) {
super(message);
}
public CmInsertException(Throwable cause) {
super(cause);
}
}
@@ -0,0 +1,26 @@
package com.eactive.eai.rms.ext.kakaocard.cm.except;
public class CmMoveDirectoryException extends RuntimeException {
public CmMoveDirectoryException() {
super();
}
public CmMoveDirectoryException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public CmMoveDirectoryException(String message, Throwable cause) {
super(message, cause);
}
public CmMoveDirectoryException(String message) {
super(message);
}
public CmMoveDirectoryException(Throwable cause) {
super(cause);
}
}
@@ -0,0 +1,30 @@
package com.eactive.eai.rms.ext.kakaocard.cm.except;
public class CmReloadException extends RuntimeException {
public CmReloadException() {
super();
// TODO Auto-generated constructor stub
}
public CmReloadException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public CmReloadException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public CmReloadException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public CmReloadException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
@@ -0,0 +1,50 @@
package com.eactive.eai.rms.ext.kakaocard.config;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import software.amazon.awssdk.services.s3.S3Client;
@Configuration
public class AWSConfig {
private static final Logger logger = Logger.getLogger(AWSConfig.class);
@Bean(name = "s3Client")
@Profile("aws")
public S3Client s3Client() {
try {
return S3Client.builder()
// .credentialsProvider(DefaultCredentialsProvider.create()) // KakaoCard Config 설정 필요 없음.
.build();
} catch (Exception e) {
logger.warn("S3Client Bean Not Available.", e);
throw new RuntimeException(e);
}
}
@Bean(name = "s3Client")
@Profile("!aws")
public S3Client mockS3Client() {
return new MockS3Client();
}
}
class MockS3Client implements S3Client {
@Override
public String serviceName() {
return null;
}
@Override
public void close() {
}
}
@@ -0,0 +1,5 @@
package com.eactive.eai.rms.ext.kakaocard.meta;
public class KakaoCardMetaServiceTemp {
}
@@ -0,0 +1,42 @@
package com.eactive.eai.rms.ext.meta.epb;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import com.eactive.eai.rms.common.base.SqlMapClientTemplateDao;
@Repository
public class EpbMetaApplSyncDao extends SqlMapClientTemplateDao implements EpbMetaSyncDao {
protected final Logger logger = Logger.getLogger(EpbMetaApplSyncDao.class);
@Override
public List<EpbMetaVo> selectCdList(HashMap paramMap) throws Exception {
return template.queryForList("EpbMetaSync.selectApplCdList", paramMap);
}
@Override
public Timestamp selectLastUpdateDate(HashMap paramMap) throws Exception {
return (Timestamp) template.queryForObject("EpbMetaSync.selectApplLastUpdateDate", paramMap);
}
@Override
public void insertCodeInfo(EpbMetaVo epbMetaVo) {
template.queryForObject("EpbMetaSync.insertApplCodeInfo", epbMetaVo);
}
@Override
public void updateCodeInfo(EpbMetaVo epbMetaVo) {
template.queryForObject("EpbMetaSync.updateApplCodeInfo", epbMetaVo);
}
@Override
public void mergeAuthToAdmin() {
template.queryForObject("EpbMetaSync.mergeAuthToAdmin");
}
}
@@ -0,0 +1,35 @@
package com.eactive.eai.rms.ext.meta.epb;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.eactive.eai.rms.common.base.SqlMapClientTemplateDao;
@Repository
public class EpbMetaInstSyncDao extends SqlMapClientTemplateDao implements EpbMetaSyncDao {
public List<EpbMetaVo> selectCdList(HashMap paramMap) throws Exception {
return template.queryForList("EpbMetaSync.selectInstCdList", paramMap);
}
public Timestamp selectLastUpdateDate(HashMap paramMap) throws Exception {
return (Timestamp) template.queryForObject("EpbMetaSync.selectInstLastUpdateDate", paramMap);
}
public void insertCodeInfo(EpbMetaVo epbMetaVo) throws Exception {
template.queryForObject("EpbMetaSync.insertInstCodeInfo", epbMetaVo);
}
public void updateCodeInfo(EpbMetaVo epbMetaVo) throws Exception {
template.queryForObject("EpbMetaSync.updateInstCodeInfo", epbMetaVo);
}
@Override
public void mergeAuthToAdmin() {
// nothing to do
}
}
@@ -0,0 +1,22 @@
package com.eactive.eai.rms.ext.meta.epb;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.eactive.eai.rms.common.base.SqlMapClientForMetaTemplateDao;
@Repository
public class EpbMetaSelectDao extends SqlMapClientForMetaTemplateDao {
public List<EpbMetaVo> selectCdList(HashMap map) throws Exception {
return template.queryForList("EpbMetaSelect.selectCdList", map);
}
public Timestamp selectLastUpdateDate(HashMap map) {
return (Timestamp) template.queryForObject("EpbMetaSelect.selectLastUpdateDate", map);
}
}
@@ -0,0 +1,268 @@
package com.eactive.eai.rms.ext.meta.epb;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.HttpUtil;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* 2021. 11. 11
* @author sunwook
*/
@Service("epbMetaSyncService")
public class EpbMetaService extends BaseService {
@Autowired
private MonitoringContext monitoringContext;
@Autowired
private EpbMetaApplSyncDao metaApplSyncDao;
@Autowired
private EpbMetaInstSyncDao metaInstSyncDao;
//@Autowired
//private EpbMetaExtBapSyncDao metaExtBapSyncDao;
private HashMap<String, String> newParamMap(String serviceType, String inputDstCd) {
HashMap result = new HashMap();
result.put("serviceType", serviceType);
result.put("inputDstCd", inputDstCd);
return result;
}
public void sync() throws Exception {
process(new EpbTaskInfo(EpbMetaVo.DOM_ID_APP));
process(new EpbTaskInfo(EpbMetaVo.DOM_ID_EXT));
process(new EpbTaskInfo(EpbMetaVo.DOM_ID_SYS));
process(new EpbTaskInfo(EpbMetaVo.DOM_ID_INST));
//process(new EpbTaskInfo(EpbMetaVo.DOM_ID_EXTBAP));
}
public void process(EpbTaskInfo taskInfo) throws Exception {
for(DataSourceType dataSourceType : taskInfo.getDatasourceList()) {
transactionalSync(taskInfo, dataSourceType);
}
}
private void transactionalSync(EpbTaskInfo taskInfo, DataSourceType dataSourceType) throws Exception {
EpbMetaSyncDao metaSyncDao = taskInfo.getDao();
DataSourceContextHolder.setDataSourceType(dataSourceType);
/** Get LastUpdateDate by (schema + inputDstcd) **/
Timestamp lastTimeStamp = metaSyncDao.selectLastUpdateDate(newParamMap(dataSourceType.getName(), taskInfo.getInputDstcd()));
if(lastTimeStamp == null) { lastTimeStamp = new Timestamp(DatetimeUtil.getLongTimeFormat("yyyyMMddHHmmss", "20000101010101")); } // 2000-01-01 01:01:01 dummyDate
String appLastUpdate = DatetimeUtil.getFormattedDate("yyyyMMddHHmmss", lastTimeStamp);
/** HTTP REST TO EIMS **/
String url = monitoringContext.getStringProperty("eims.address") + "api/epb/v1/smeta/codeInfoList.json?domId=" + taskInfo.getDomId() + "&date=" + appLastUpdate;
String metaCodeListJsonString = HttpUtil.httpCall(url, "GET", "UTF-8");
logger.debug(url + " response : " + metaCodeListJsonString);
if(metaCodeListJsonString == null) {
return;
}
/** JSONArray -> EpbMetoVoList **/
ObjectMapper jacksonMapper = new ObjectMapper();
jacksonMapper.setSerializationInclusion(Include.NON_NULL);
List<EpbMetaVo> metaCodeList = jacksonMapper.readValue(metaCodeListJsonString, new TypeReference<List<EpbMetaVo>>(){});
List<EpbMetaVo> applCodeList = metaSyncDao.selectCdList(newParamMap(dataSourceType.getName(), taskInfo.getInputDstcd()));
metaCodeList.forEach(metaVo -> subStrCodeDesc(metaVo));
/** compare (meta - application) **/
List<EpbMetaVo> whatNewAdded = filterNewAddedList(metaCodeList, applCodeList);
List<EpbMetaVo> whatUpdated = filterUpdatedList(metaCodeList, applCodeList);
if(whatNewAdded.size() == 0 && whatUpdated.size() == 0) {
logger.debug("No New Added And Updated Code");
return;
}
/** insert new added **/
for(EpbMetaVo epbMetaVo : whatNewAdded) {
logger.debug("New Added : " + epbMetaVo.toString());
epbMetaVo.setSchemaId(DataSourceContextHolder.getDataSourceType().getSchema());
epbMetaVo.setInputDstcd(taskInfo.getInputDstcd());
epbMetaVo.setEaiBzwkDstcd(taskInfo.getPrefix() + epbMetaVo.getCodeValidValue());
metaSyncDao.insertCodeInfo(epbMetaVo); // insert CodeInfo
}
/** update updated **/
for(EpbMetaVo epbMetaVo : whatUpdated) {
logger.debug("Updated : " + epbMetaVo.toString());
epbMetaVo.setSchemaId(DataSourceContextHolder.getDataSourceType().getSchema());
epbMetaVo.setInputDstcd(taskInfo.getInputDstcd());
epbMetaVo.setEaiBzwkDstcd(taskInfo.getPrefix() + epbMetaVo.getCodeValidValue());
metaSyncDao.updateCodeInfo(epbMetaVo); // update CodeInfo
}
metaSyncDao.mergeAuthToAdmin();
}
private void subStrCodeDesc(EpbMetaVo metaMetaVo) {
try {
int length = 200;
String codeDesc = metaMetaVo.getCodeDesc();
byte[] bytes = codeDesc.getBytes("UTF-8");
if(bytes.length > length && bytes[bytes.length-1] < 0) {
byte[] destination = new byte[length];
System.arraycopy(bytes, 0, destination, 0, length);
int lastPositive = 0;
for(int i = length-1; i > 0; i--) {
if(destination[i] > 0) {
lastPositive = i;
break;
}
}
int lastIdx = lastPositive + ((length-lastPositive)/3)*3;
byte[] result = new byte[lastIdx+1];
System.arraycopy(destination, 0, result, 0, lastIdx+1);
metaMetaVo.setCodeDesc(new String(result, "UTF-8"));
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
/**
* applCodeList에는 존재하지만, metaCodeList에는 존재하지 않는 MetaVo의 List 반환
*/
private List<EpbMetaVo> filterDeletedList(List<EpbMetaVo> metaCodeList, List<EpbMetaVo> applCodeList) {
return applCodeList.stream()
.filter(
appMetaVo -> metaCodeList.stream().map(metaMetaVo -> metaMetaVo.getCodeValidValue()).noneMatch(Predicate.isEqual(appMetaVo.getCodeValidValue()))
).collect(Collectors.toList());
}
/**
* metaCodeList에는 존재하지만, applCodeList에는 존재하지 않는 MetaVo의 List 반환
*/
private List<EpbMetaVo> filterNewAddedList(List<EpbMetaVo> metaCodeList, List<EpbMetaVo> applCodeList) {
if(applCodeList == null) {
return metaCodeList;
}
return metaCodeList.stream()
.filter(
metaMetaVo -> applCodeList.stream().map(appMetaVo -> appMetaVo.getCodeValidValue()).noneMatch(Predicate.isEqual(metaMetaVo.getCodeValidValue()))
).collect(Collectors.toList());
}
/**
* metaCodeList에 존재하고 applCodeList에 존재하면서, 그 내용이 서로 일치하지 않는 MetaVo의 List 반환
*/
private List<EpbMetaVo> filterUpdatedList(List<EpbMetaVo> metaCodeList, List<EpbMetaVo> applCodeList) {
/** TSAEIRM28은 Desc없음 **/
boolean noDesc = applCodeList.stream().map(epbMetaVo -> Optional.ofNullable(epbMetaVo.getCodeDesc())).noneMatch(optDesc-> optDesc.isPresent());
if(noDesc) {
return filterUpdatedListNoDesc(metaCodeList, applCodeList);
}
return metaCodeList.stream()
.filter(
metaMetaVo -> applCodeList.stream().map(appMetaVo -> appMetaVo.getCodeValidValue()).anyMatch(Predicate.isEqual(metaMetaVo.getCodeValidValue()))
).filter(
metaMetaVo -> applCodeList.stream().noneMatch(appMetaVo -> appMetaVo.equals(metaMetaVo))
).collect(Collectors.toList());
}
/**
* filterUpdatedList와 기능 동일, codeDesc field는 체크안함
*/
private List<EpbMetaVo> filterUpdatedListNoDesc(List<EpbMetaVo> metaCodeList, List<EpbMetaVo> applCodeList) {
return metaCodeList.stream()
.filter(
metaMetaVo -> applCodeList.stream().map(appMetaVo -> appMetaVo.getCodeValidValue()).anyMatch(Predicate.isEqual(metaMetaVo.getCodeValidValue()))
).filter(
metaMetaVo -> applCodeList.stream().noneMatch(appMetaVo -> appMetaVo.equalsNoDesc(metaMetaVo))
).collect(Collectors.toList());
}
/**
* 2021. 12. 03.
* domId별로 process구분
* @author sunwook
*/
private class EpbTaskInfo {
private String domId;
private String inputDstcd;
private String prefix;
private List<DataSourceType> datasourceList;
private EpbMetaSyncDao dao;
private EpbTaskInfo(String domId) throws Exception {
this.domId = domId;
switch(domId) {
case EpbMetaVo.DOM_ID_APP :
this.inputDstcd = EpbMetaVo.INPUTDSTCD_APP;
this.prefix = EpbMetaVo.PREFIX_APP;
this.datasourceList = DataSourceTypeManager.getDynamicDataSourceTypes();
this.dao = metaApplSyncDao;
break;
case EpbMetaVo.DOM_ID_EXT :
this.inputDstcd = EpbMetaVo.INPUTDSTCD_EXT;
this.prefix = EpbMetaVo.PREFIX_EXT;
this.datasourceList = DataSourceTypeManager.getDynamicDataSourceTypes();
this.dao = metaApplSyncDao;
break;
case EpbMetaVo.DOM_ID_SYS :
this.inputDstcd = EpbMetaVo.INPUTDSTCD_SYS;
this.prefix = EpbMetaVo.PREFIX_SYS;
this.datasourceList = DataSourceTypeManager.getDynamicDataSourceTypes();
this.dao = metaApplSyncDao;
break;
case EpbMetaVo.DOM_ID_INST :
this.inputDstcd = EpbMetaVo.INPUTDSTCD_INST;
this.datasourceList = new ArrayList<>();
this.datasourceList.add(DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING));
this.dao = metaInstSyncDao;
break;
case EpbMetaVo.DOM_ID_EXTBAP :
this.datasourceList = new ArrayList<>();
this.datasourceList.add(DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.BAP));
//this.dao = metaExtBapSyncDao;
break;
default :
throw new Exception("지원하지 않는 DomId입니다.");
}
}
public String getDomId() { return domId; }
public String getInputDstcd() { return inputDstcd; }
public String getPrefix() { return prefix; }
public List<DataSourceType> getDatasourceList() { return datasourceList; }
public EpbMetaSyncDao getDao() { return dao; }
}
}
@@ -0,0 +1,15 @@
package com.eactive.eai.rms.ext.meta.epb;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
public interface EpbMetaSyncDao {
public List<EpbMetaVo> selectCdList(HashMap paramMap) throws Exception;
public Timestamp selectLastUpdateDate(HashMap paramMap) throws Exception;
public void insertCodeInfo(EpbMetaVo epbMetaVo) throws Exception;
public void updateCodeInfo(EpbMetaVo epbMetaVo) throws Exception;
public void mergeAuthToAdmin();
}
@@ -0,0 +1,47 @@
package com.eactive.eai.rms.ext.meta.epb;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;
public class EpbMetaSyncJob implements Job {
private static final Logger logger = Logger.getLogger(EpbMetaSyncJob.class);
public void execute(JobExecutionContext context) throws JobExecutionException {
ApplicationContext appContext = null;
try {
appContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
} catch (SchedulerException e1) {
logger.error(e1);
}
if (appContext == null) {
logger.info("[EpbMetaSyncJob.metaSync ]appContext is null");
}
if (appContext.getBean("epbMetaSyncService") == null) {
logger.info("[EpbMetaSyncJob.metaSync ] epbMetaSyncService is null");
}
EpbMetaService service = (EpbMetaService) appContext.getBean("epbMetaSyncService");
logger.info("[EpbMetaSyncJob.metaSync START]----------");
try {
service.sync();
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
logger.info("[EpbMetaSyncJob.metaSync END]----------");
}
}
}
@@ -0,0 +1,268 @@
package com.eactive.eai.rms.ext.meta.epb;
import java.text.ParseException;
import java.util.Date;
import com.eactive.eai.common.util.DatetimeUtil;
public class EpbMetaVo {
public static final String DOM_ID_APP = "D0000004161"; // 어플리케이션 코드
public static final String DOM_ID_EXT = "D0000005289"; // 대외구분코드
public static final String DOM_ID_SYS = "D0000004079"; // 시스템코드
public static final String DOM_ID_INST = "D0000005288"; // 대외연계기관코드
public static final String DOM_ID_EXTBAP = "D0000006211"; // 대외일괄업무코드
public static final String INPUTDSTCD_APP = "APP";
public static final String INPUTDSTCD_EXT = "EXT";
public static final String INPUTDSTCD_SYS = "SYS";
public static final String INPUTDSTCD_INST = "ADPTR_DESC";
public static final String PREFIX_APP = "";
public static final String PREFIX_EXT = "E";
public static final String PREFIX_SYS = "I";
private String eaiBzwkDstcd; // TSEAICM01 APP:XXX, SYS:IXXX, EXT:EXXX
private String inputDstcd; // TSEAICM01 "APP", "EXT", "SYS"
private String domId;
private String codeId;
private String codeDesc;
private String codeValidName;
private String codeValidValue;
private String domEngName;
private String domGroupName;
private String domName;
private Date lastModDtm;
private String stdId;
private String stdName;
private String upperCodeValidName;
private String upperCodeValidValue;
private String useYn;
public String schemaId;
public String getEaiBzwkDstcd() {
return eaiBzwkDstcd;
}
public void setEaiBzwkDstcd(String eaiBzwkDstcd) {
this.eaiBzwkDstcd = eaiBzwkDstcd;
}
public String getInputDstcd() {
return inputDstcd;
}
public void setInputDstcd(String inputDstcd) {
this.inputDstcd = inputDstcd;
}
public String getDomId() {
return domId;
}
public void setDomId(String domId) {
this.domId = domId;
}
public String getCodeId() {
return codeId;
}
public void setCodeId(String codeId) {
this.codeId = codeId;
}
public String getCodeDesc() {
return codeDesc;
}
public void setCodeDesc(String codeDesc) {
this.codeDesc = codeDesc;
}
public String getCodeValidName() {
return codeValidName;
}
public void setCodeValidName(String codeValidName) {
this.codeValidName = codeValidName;
}
public String getCodeValidValue() {
return codeValidValue;
}
public void setCodeValidValue(String codeValidValue) {
this.codeValidValue = codeValidValue;
}
public String getDomEngName() {
return domEngName;
}
public void setDomEngName(String domEngName) {
this.domEngName = domEngName;
}
public String getDomGroupName() {
return domGroupName;
}
public void setDomGroupName(String domGroupName) {
this.domGroupName = domGroupName;
}
public String getDomName() {
return domName;
}
public void setDomName(String domName) {
this.domName = domName;
}
public Date getLastModDtm() {
return lastModDtm;
}
public void setLastModDtm(String lastModDtm) throws ParseException {
if(lastModDtm != null) {
this.lastModDtm = new Date(DatetimeUtil.getLongTimeFormat("yyyyMMddHHmmss", lastModDtm));
} else {
this.lastModDtm = null;
}
}
public String getStdId() {
return stdId;
}
public void setStdId(String stdId) {
this.stdId = stdId;
}
public String getStdName() {
return stdName;
}
public void setStdName(String stdName) {
this.stdName = stdName;
}
public String getUpperCodeValidName() {
return upperCodeValidName;
}
public void setUpperCodeValidName(String upperCodeValidName) {
this.upperCodeValidName = upperCodeValidName;
}
public String getUpperCodeValidValue() {
return upperCodeValidValue;
}
public void setUpperCodeValidValue(String upperCodeValidValue) {
this.upperCodeValidValue = upperCodeValidValue;
}
public String getUseYn() {
return useYn;
}
public void setUseYn(String useYn) {
this.useYn = useYn;
}
public String getSchemaId() {
return schemaId;
}
public void setSchemaId(String schemaId) {
this.schemaId = schemaId;
}
public boolean compareDateEquals(EpbMetaVo epbMetaVo) {
if(this.getLastModDtm() != null) {
return this.getLastModDtm().getTime() == epbMetaVo.getLastModDtm().getTime();
} else {
return false;
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codeDesc == null) ? 0 : codeDesc.hashCode());
result = prime * result + ((codeValidValue == null) ? 0 : codeValidValue.hashCode());
result = prime * result + ((codeValidName == null) ? 0 : codeValidName.hashCode());
result = prime * result + ((lastModDtm == null) ? 0 : lastModDtm.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EpbMetaVo other = (EpbMetaVo) obj;
if (codeDesc == null) {
if (other.codeDesc != null)
return false;
} else if (!codeDesc.equals(other.codeDesc))
return false;
if (codeValidValue == null) {
if (other.codeValidValue != null)
return false;
} else if (!codeValidValue.equals(other.codeValidValue))
return false;
if (codeValidName == null) {
if (other.codeValidName != null)
return false;
} else if (!codeValidName.equals(other.codeValidName))
return false;
if (lastModDtm == null) {
if (other.lastModDtm != null)
return false;
} else if (!this.compareDateEquals((EpbMetaVo) obj))
return false;
return true;
}
public boolean equalsNoDesc(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EpbMetaVo other = (EpbMetaVo) obj;
if (codeValidValue == null) {
if (other.codeValidValue != null)
return false;
} else if (!codeValidValue.equals(other.codeValidValue))
return false;
if (codeValidName == null) {
if (other.codeValidName != null)
return false;
} else if (!codeValidName.equals(other.codeValidName))
return false;
if (lastModDtm == null) {
if (other.lastModDtm != null)
return false;
} else if (!this.compareDateEquals((EpbMetaVo) obj))
return false;
return true;
}
@Override
public String toString() {
return "MetaVo [codeValidValue=" + codeValidValue + ", codeValidName=" + codeValidName + ", codeDesc="
+ codeDesc + ", lastModDtm=" + lastModDtm + ", useYn=" + useYn + "]";
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,94 @@
package com.eactive.eai.rms.ext.mmi;
public interface MMIParserKey {
public static String KBSTANDARD = "K";
//어댑터 위치
public static String SRC = "SRC";
public static String TGT = "TGT";
public static String RES_SRC = "RES_SRC";
//interface 관련
public static String ATTRINFO = "attrinfo";
public static String MMI_IF_ID = "mmi_if_id";
public static String VER = "ver";
public static String INTERFACE_TYPE = "interface_type";
public static String APP_CD = "app_cd";
public static String SYS_INF_CD = "sys_inf_cd";
public static String SYS_INF_NM = "sys_inf_nm";
public static String RES_INF_CD = "res_inf_cd";
public static String EAI_SYS_DSTCD = "eai_sys_dstcd";//내외부구분코드
public static String INF_TYPE = "inf_type"; //1:취급(당발) 2:개벌(타발) 대외거래만 들어옮
public static String SRC_SYS_ID = "src_sys_id";
public static String TRG_SYS_ID = "trg_sys_id";
public static String RES_SRC_SYS_ID = "res_src_sys_id";
public static String SRC_SYS_TYPE = "src_sys_type";
public static String TRG_SYS_TYPE = "trg_sys_type";
//
public static String EXTHE01INFO = "exthe01info";
public static String EAI_SVC_NAME = "eai_svc_name";
public static String FLOW_CTRL_ROUT_NAME = "flow_ctrl_rout_name";
//
public static String EXTHS01INFO = "exths01info";
public static String BZWK_SVC_KEY_NAME = "bzwk_svc_key_name";
public static String COMMON_OGTRAN_RSTR_YN = "common_ogtran_rstr_yn";
//
public static String MSGINFO = "msginfo";
public static String MSG_FLD_START_SITU_VAL = "msg_fld_start_situ_val";
public static String MSG_FLD_LEN = "msg_fld_len";
public static String RESTOPTION = "restOption";
public static String DEPLOY_ID = "deploy_id";
public static String STD_ERR_MPNG = "std_err_mpng";//표준 에러코드 사용여부
//공통
public static String ID = "id";
public static String DESC = "desc";
public static String DEFAULT = "default";
//layout관련
public static String EAI_LAYOUT_CODE = "eai_layout_code";
public static String EAI_APP_CODE = "eai_app_code";
public static String TYPE = "type";
public static String LEN = "len";
public static String SCALE = "scale";
public static String ROWCOUNT = "rowcount";
public static String LOG_KEY = "log_key";
public static String TRAN_KEY = "tran_key";
public static String NO = "no";
public static String DEPTH = "depth";
public static String MAX_CNT = "max_cnt";
public static String MASK = "mask";
public static String CONVERT = "convert";
public static String DISPLAY = "display";
//변환
public static String INPUTMAP = "Inputmap";
public static String FROM = "from";
public static String TO = "to";
public static String LINK = "link";
public static String COLIDX = "colidx";
public static String FUNC = "func";
public static String MPNG_SEQ = "mpng_seq";
//layout 항목 종류
public static String GROUP = "GROUP";
public static String GRID = "GRID";
public static String FLD = "FLD";
public static String COLUMN = "COLUMN";
public static String ATTR = "ATTR";
//삭제관련
//public static String MMI_IF_ID = "mmi_if_id";
public static String MMI_IO_ID = "mmi_io_id";
public static String INTERFACE = "Interface";
public static String FORMAT = "Format";
public static String DELETE_INFO = "Delete_info";
public static String MODID = "modid";
}
@@ -0,0 +1,692 @@
package com.eactive.eai.rms.ext.mmi;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.View;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.common.util.NullControl;
import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;
import com.eactive.eai.rms.common.logging.UserAccessLogger;
import com.eactive.eai.rms.common.mmilog.MMILogDao;
import com.eactive.eai.rms.common.util.StringUtils;
import com.eactive.eai.rms.onl.common.util.DateUtil;
@Controller
public class MMISyncController extends OnlBaseAnnotationController implements InterceptorSkipController {
private static final Logger logger = Logger.getLogger(MMISyncController.class);
@Autowired
@Qualifier("mmiSyncService")
private MMISyncService service;
@Autowired
private MonitoringContext monitoringContext;
@Autowired
@Qualifier("mmiLogDao")
private MMILogDao mmiLogDao;
/**
* 통합인터페이스 시스템(MMI)에서 전문 레이아웃에 대한 INSERT, DELETE 요청
* *
* @param request
* @param response
* @param schema
* @return
* @throws Exception
*/
@RequestMapping(value= "/mmiSync.file", method=RequestMethod.POST)
public View parseMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
UserAccessLogger.log(request, "Message", "L", "cmd=Message");
HashMap<String,String> map = new HashMap<String,String>();
StringBuilder sb = new StringBuilder();
StringBuilder frame = new StringBuilder();
logger.debug("parseMessage content-Type="+request.getContentType());
String mmiIfId = "";
String ver = "";
String eaiSvcName = "";
String eaiSevrDstcd = "";
String cnvsnNames = "";
String loutNames = "";
String userId = "";
HashMap<String,Object> mmiLogMap = new HashMap<String,Object>();
StringBuffer buffer = new StringBuffer();
try{
if (!SystemUtil.isDevServer()){
throw new Exception("개발 서버에서만 동작 합니다. ");
}
for (String key : request.getParameterMap().keySet()){
String [] datas= request.getParameterValues(key);
StringBuffer resultS = new StringBuffer();
for(String data : datas){
resultS.append(data);
}
if (key.startsWith("E_") || key.startsWith("G_") || key.startsWith("FD") || key.startsWith("FM") ){
buffer.append(resultS.toString()).append("\n");
}
if (key.startsWith("FM") ){
cnvsnNames += ","+key;
}
if (key.startsWith("FD")){
loutNames += ","+key;
}
logger.info("receive Data "+key+"="+resultS.toString());
map.put(key, resultS.toString());
}
HashMap<String,Object> inter = null;
HashMap<String,Object> info = null;
for(String key : map.keySet()){
if (key.startsWith("E_") || key.startsWith("G_")){
info = MMIParser.parseInfo(map.get(key));
}
}
if (info == null){
throw new Exception("인터페이스 정보가 존재하지 않습니다.");
}
eaiSvcName = (String)info.get(MMIParserKey.EAI_SVC_NAME);//EAI서비스코드
String eaiBzwkDstcd = (String)info.get(MMIParserKey.APP_CD); //EAI업무구분코드
eaiSevrDstcd = (String)info.get(MMIParserKey.EAI_SYS_DSTCD); //EAI서버구분코드
String interfaceType = (String)info.get(MMIParserKey.INTERFACE_TYPE); //인터페이스유형
mmiIfId = (String)info.get(MMIParserKey.MMI_IF_ID); //
ver = (String)info.get(MMIParserKey.VER); // 버전번호
String srcSysId = (String)info.get(MMIParserKey.SRC_SYS_ID); //소스 시스템ID
String tgtSysId = (String)info.get(MMIParserKey.TRG_SYS_ID); //타겟 시스템ID
String resSrcSysId = (String)info.get(MMIParserKey.RES_SRC_SYS_ID); //응답 소스 시스템ID
String srcSysType = (String)info.get(MMIParserKey.SRC_SYS_TYPE); //소스 시스템 type
String tgtSysType = (String)info.get(MMIParserKey.TRG_SYS_TYPE); //타겟 시스템 type
userId = (String)info.get(MMIParserKey.DEPLOY_ID); //사용자ID
String stdErrMpng = (String)info.get(MMIParserKey.STD_ERR_MPNG); //표준 에러코드 사용여부
///////////////////////////////////////////////
//서버구분코드로 DataSourceType 변경
// 1 : 내부(NSG) , 2 : 대외(DSG), 3 : 공동망(GSG), 4 : DMZ(ZSG), 5 : 오픈뱅킹(ASG)
// 개발은 1,2,3 은 DSG 로 4는 ZSG로 처리 한다.
///////////////////////////////////////////////
String serverType = monitoringContext.getStringProperty(MonitoringContext.MMI_SYNC_SERVERTYPE, "1=DSG,2=DSG,3=DSG,4=ZSG,5=DSG");
HashMap<String,String> serverDstcdMap = new HashMap<String,String>();
Matcher matcher = Pattern.compile("[ ]*([0-9]+)[ ]*=[ ]*([A-Z]+)[ ]*").matcher(serverType);
while(matcher.find()) {
String key = matcher.group(1).trim();
String value = matcher.group(2).trim();
serverDstcdMap.put(key, value);
}
if (serverDstcdMap.containsKey(eaiSevrDstcd)){
String dataSourceType = serverDstcdMap.get(eaiSevrDstcd);
DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(dataSourceType));
}else{
throw new Exception("지원 하지 않는 서버구분코드 입니다."+eaiSevrDstcd);
}
//interface 업무구분코드 valication
boolean isApp = service.selecAppIsYn(new HashMap(){{put("eaiBzwkDstcd",eaiBzwkDstcd);}});
if (!isApp){
throw new Exception("인터페이스 에서 지원 하지 않는 APP CD 입니다." + eaiBzwkDstcd);
}
//변환 업무구분코드 validation
String[] cnvsnNameList = cnvsnNames.split(",");
for(String cnvsnName : cnvsnNameList){
if (!StringUtils.isBlank(cnvsnName) && cnvsnName.length() > 5 ){
String appcode = cnvsnName.substring(2,5);
isApp = service.selecAppIsYn(new HashMap(){{put("eaiBzwkDstcd",appcode);}});
if (!isApp){
throw new Exception("변환 에서 지원 하지 않는 APP CD 입니다. " + appcode);
}
}
}
//layout 업무구분코드 validation
String[] layoutNameList = loutNames.split(",");
for(String layoutName : layoutNameList){
if (!StringUtils.isBlank(layoutName) && layoutName.length() > 5 ){
String appcode = layoutName.substring(2,5);
isApp = service.selecAppIsYn(new HashMap(){{put("eaiBzwkDstcd",appcode);}});
if (!isApp){
throw new Exception("레이아웃 에서 지원 하지 않는 APP CD 입니다. " + appcode);
}
}
}
//adapter validation
if ("A".equals(srcSysType) && "S".equals(tgtSysType) && "S".equals(interfaceType)){
if (StringUtils.isEmpty(srcSysId)){
throw new Exception("소스 어댑터를 선택하지 않았습니다.");
}
if (StringUtils.isEmpty(tgtSysId)){
throw new Exception("타겟 어댑터를 선택하지 않았습니다.");
}
if (StringUtils.isEmpty(resSrcSysId)){
throw new Exception("소스 응답 어댑터를 선택하지 않았습니다.");
}
}else if ("A".equals(srcSysType) && "S".equals(tgtSysType) && "R".equals(interfaceType)){
if (StringUtils.isEmpty(srcSysId)){
throw new Exception("소스 어댑터를 선택하지 않았습니다.");
}
}else{
if (StringUtils.isEmpty(srcSysId)){
throw new Exception("소스 어댑터를 선택하지 않았습니다.");
}
if (StringUtils.isEmpty(tgtSysId)){
throw new Exception("타겟 어댑터를 선택하지 않았습니다.");
}
}
// adapter 파서
Map<String, Map<String, String>> adapters = service.selectAdapterForNickName(srcSysId,tgtSysId,resSrcSysId);
String adptrMsgDstcd = adapters.get(MMIParserKey.SRC).get("ADPTRMSGDSTCD");
// interface 파서
for(String key : map.keySet()){
if (key.startsWith("E_") || key.startsWith("G_")){
inter = MMIParser.parseInterface(map.get(key),adapters);
logger.info("interface parsing " +inter);
}
}
// layout 파서
List<HashMap<String,Object>> layouts = new ArrayList<HashMap<String,Object>>();
for(String key : map.keySet()){
if (key.startsWith("FD")){
if (key.startsWith("FDEAI_") && key.endsWith("_ERR")){
continue;
}
MMIParser.layoutDupValidation(map.get(key));
HashMap<String,Object> layout = MMIParser.parseLayout(map.get(key),eaiSevrDstcd);
layouts.add( layout);
logger.info("layout parsing " + layout);
}
}
//변환 파서
List<HashMap<String,Object>> transforms = new ArrayList<HashMap<String,Object>>();
for(String key : map.keySet()){
if (key.startsWith("FM")){
HashMap<String,Object> transform = MMIParser.parseTransform(map.get(key), eaiBzwkDstcd, eaiSevrDstcd);
transforms.add( transform );
logger.info("transform parsing " + transform);
}
}
MMIParser.validation(srcSysType, tgtSysType, interfaceType,adapters, transforms, layouts, eaiSevrDstcd);
// 변환 을 EAI서비스 코드에 셋팅하는 로직
List<HashMap<String,Object>> he02s = (List<HashMap<String,Object>>)inter.get("he02");
if (he02s != null){
HashMap<String,Object> he02 = (HashMap<String, Object>) he02s.get(0);
if (he02 != null){
//async-async 요청인데 RES로 되어 있는거 보강로직
if ("A".equals(srcSysType) && "A".equals(tgtSysType) && transforms.size()==1) {
String cnvsnName =(String)transforms.get(0).get("cnvsnName");
he02.put("chngEonot" , "1" ); // 변환유무
he02.put("chngMsgIDName" , cnvsnName ); // 변환메시지ID명
}else{
for(String key : map.keySet()){
if (key.startsWith("FM")){
//data sample 변경
// FMEAI_TST0200100EAI_REQ
String cnvsnName = "TRANSFORM_"+ key.substring(2);
if (key.endsWith("_REQ")){
he02.put("chngEonot" , "1" ); // 변환유무
he02.put("chngMsgIDName" , cnvsnName ); // 변환메시지ID명
}else if (key.endsWith("_RES")){
if ("A".equals(srcSysType) && "A".equals(tgtSysType) && "R".equals(interfaceType) ){//Async Async 패턴 응답이 경우
he02.put("chngEonot" , "1" ); // 변환유무
he02.put("chngMsgIDName" , cnvsnName ); // 변환메시지ID명
} else {
he02.put("bascRspnsChngEonot" , "1" ); // 기본응답변환유무
he02.put("bascRspnsChngMsgIDName" , cnvsnName ); // 기본응답변환메시지ID명
}
}else if (key.endsWith("_ERR")){
he02.put("errRspnsChngEonot" , "1" ); // 오류응답변환유무
he02.put("errRspnsChngMsgIDName" , cnvsnName ); // 오류응답변환메시지ID명
}
}
}
}
//표준에러매핑 관련
if ("Y".equals(stdErrMpng)){
//에러변환이 있는경우 표준에러 매핑을 셋팅할수 없음.
if ("1".equals(he02.get("errRspnsChngEonot"))){
throw new Exception("에러 변환을 셋팅한 상태에서는 표준 오류 매핑 사용을 Y 로 셋팅 할수 없습니다.");
}
if ("A".equals(srcSysType) && "S".equals(tgtSysType) && "R".equals(interfaceType)){
throw new Exception("표준에러매핑을 셋팅할수 없는 패턴입니다. 거래패턴 :"+srcSysType +"-" +tgtSysType +" 송수신타입 : "+interfaceType );
}
String srcKesaUseYn = adapters.get(MMIParserKey.SRC).get("KESAUSEYN");
String tgtKesaUseYn = adapters.get(MMIParserKey.TGT).get("KESAUSEYN");
String srcMsgDstcd = adapters.get(MMIParserKey.SRC).get("ADPTRMSGDSTCD");
String tgtMsgDstcd = adapters.get(MMIParserKey.TGT).get("ADPTRMSGDSTCD");
if (!"0".equals(srcKesaUseYn) && !"0".equals(tgtKesaUseYn)){
//Async - Async 응답에서만 셋팅
//Sync - Async 요청에서만셋팅
//Sync - Sync 요청만 있음
//Async - Sync 요청만 있음
String cnvsnName = "";
if ("A".equals(srcSysType) && "A".equals(tgtSysType) && "R".equals(interfaceType)){
cnvsnName = "TRANSFORM_EAI_" + srcMsgDstcd +"TO" + tgtMsgDstcd + "_ERR";
he02.put("errRspnsChngEonot" , "1" ); // 오류응답변환유무
he02.put("errRspnsChngMsgIDName" , cnvsnName ); // 오류응답변환메시지ID명
}else if ("S".equals(srcSysType) && "A".equals(tgtSysType) && "S".equals(interfaceType)){
cnvsnName = "TRANSFORM_EAI_" + tgtMsgDstcd +"TO" + srcMsgDstcd + "_ERR";
he02.put("errRspnsChngEonot" , "1" ); // 오류응답변환유무
he02.put("errRspnsChngMsgIDName" , cnvsnName ); // 오류응답변환메시지ID명
}else if ( "S".equals(tgtSysType) ){
cnvsnName = "TRANSFORM_EAI_" + tgtMsgDstcd +"TO" + srcMsgDstcd + "_ERR";
he02.put("errRspnsChngEonot" , "1" ); // 오류응답변환유무
he02.put("errRspnsChngMsgIDName" , cnvsnName ); // 오류응답변환메시지ID명
}else{
throw new Exception("표준에러매핑을 셋팅할수 없는 패턴입니다. 거래패턴 :"+srcSysType +"-" +tgtSysType +" 송수신타입 : "+interfaceType );
}
}else{
throw new Exception("소스("+srcKesaUseYn+")와 타겟("+tgtKesaUseYn+")이 두개다 kesa가 아닐경우 표준 오류 매핑 사용을 Y 로 셋팅 할수 없습니다.");
}
}
}
logger.info("he02 setting " + he02);
}
///////////////////////
// TR , AK
//////////////////////
List<HashMap<String,Object>> tracekeys = new ArrayList<HashMap<String,Object>>();
// tr , ak 파서
List<String> parseKeys = new ArrayList<String>();
for(String key : map.keySet()){
if (key.startsWith("E_") || key.startsWith("G_")){
parseKeys = MMIParser.parseKey(map.get(key));
logger.info("tr ,ak parsing " +parseKeys);
}
}
//tr ,ak validation
for(String parseKey : parseKeys){
String[] keys = parseKey.split(",");
String keyType = keys[0];
String keyIndex = keys[1];
String layoutFullPath = keys[2];
String layout = layoutFullPath.split("\\.")[0];
if (map.containsKey(layout)){
if (MMIParser.parseKeyValidation(map.get(layout),layoutFullPath)){
tracekeys.add(MMIParser.parseKey2(eaiSvcName, keyType, keyIndex, adptrMsgDstcd,layoutFullPath, eaiSevrDstcd));
}else{
throw new Exception("필드추출정보 혹은 로그조회키 의 Key 패스가 존재하지 않습니다."+layoutFullPath);
}
}else{
throw new Exception("필드추출정보 혹은 로그조회키 의 Key 패스("+layoutFullPath+")가 사용하는 레이아웃이 존재하지 않습니다.전체 배포된 레이아웃("+loutNames+") 목록" );
//tracekeys.add(MMIParser.parseKey2(eaiSvcName, keyType, keyIndex, adptrMsgDstcd,layoutFullPath, eaiSevrDstcd));
}
}
//참조메시지에 대한 정의-20200527 jun's
//1.변환매핑이 없고 로그키(필드추출정보)가 없을 경우 참조메시지ID를 셋팅한다.
//2.저장시에도 아래의 조건 만족하는경우에만 DB에서 DELETE & INSERT 한다.
// => 조건이 안맞을시에는 ms02가 생성이 안되고 ASIS 마이그레이션 데이터가 있더라도 삭제 하지 않는다.
if (transforms.size() == 0 && tracekeys.size() == 0 ){
String refMessage ="";
for(String key : map.keySet()){
if (key.startsWith("FD")){
refMessage = key;
break;
}
}
List<HashMap<String,Object>> ms02s = new ArrayList<HashMap<String,Object>>();
if (!StringUtils.isBlank(refMessage)){
// interface 에 ms02 설정
HashMap<String,Object> ms02 = new HashMap<String,Object>();
ms02.put("EAISVCNAME", eaiSvcName);
ms02.put("SVCPRCSSNO", "1");
ms02.put("REFMSGIDNO", "1");
ms02.put("REFMSGIDNAME", refMessage.substring(2));
ms02s.add(ms02);
}
inter.put("ms02", ms02s);
}
// merge 로직 시작
//boolean isMessageKeySame = service.transactionMMISync(inter, layouts, transforms, tracekeys, userId);
service.transactionMMISync(inter, layouts, transforms, tracekeys, userId);
CommonCommand command = null;
//layout동기화
for(HashMap<String,Object> layout : layouts){
String loutName = (String) layout.get("loutName");
command = new CommonCommand("com.eactive.eai.agent.transformer.ReloadLayoutCommand",loutName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("레이아웃 동기화 오류 "+loutName);
}
}
//변환등기화
for(HashMap<String,Object> transform : transforms){
String cnvsnName = (String)transform.get("cnvsnName");
command = new CommonCommand("com.eactive.eai.agent.transformer.ReloadTransformCommand",cnvsnName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("변환 동기화 오류 "+cnvsnName);
}
}
//인터페이스 동기화
if (!StringUtils.isEmpty(eaiSvcName)){
command = new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageCommand",eaiSvcName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("인터페이스 동기화 오류 "+eaiSvcName);
}
}
//추출키 동기화
if (!StringUtils.isEmpty(eaiSvcName)){
command = new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand",eaiSvcName+",TR");
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("추출키 동기화 오류 "+eaiSvcName);
}
command = new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyCommand",eaiSvcName+",AK");
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("추출키 동기화 오류 "+eaiSvcName);
}
}
//내부표준전문 동기화
if (!StringUtils.isEmpty(eaiSvcName)){
ArrayList<HashMap<String, Object>> hs04s = (ArrayList<HashMap<String, Object>>)inter.get("hs04");
if (hs04s != null){
for(HashMap<String,Object> hs04 : hs04s){
String bzwkSvcKeyName = (String)hs04.get("bzwkSvcKeyName");
command = new CommonCommand("com.eactive.eai.agent.kbmessage.ReloadKBMessageCommand",bzwkSvcKeyName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("내부표준전문 동기화 오류 "+bzwkSvcKeyName);
}
}
}
}
//juns 어댑터 메시지키 동기화 삭제
// //어댑터 메시지키 동기화
// if (!isMessageKeySame){
// List<HashMap<String,Object>> fr04s = (List<HashMap<String,Object>>)inter.get("fr04");
// if (fr04s != null && fr04s.size()>0){
// String adptrBzwkGroupName = (String)fr04s.get(0).get("adptrBzwkGroupName");
// String key = adptrBzwkGroupName +",I";
// command = new CommonCommand("com.eactive.eai.agent.messagekey.ReloadMessageKeyCommand",key);
// if (!validate(agentUtilService.broadcast(command))){
// throw new Exception("어댑터 메시지키 동기화 오류 "+adptrBzwkGroupName);
// }
// }
// }
sb.append(resultInterface(mmiIfId, ver, "SUCCESS", ""));
} catch(Exception e){
logger.error("MMISyncController error="+e.getMessage(),e);
sb.append(resultInterface(mmiIfId, ver, "FAIL",e.getMessage()));
}
frame.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
frame.append("<Deploy>");
frame.append(sb.toString());
frame.append("</Deploy>");
//MMI Log data //취약점소스 수정 2020.08.26
DataSourceType dt = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING);
String schemaId = "";
if(dt != null){
DataSourceContextHolder.setDataSourceType(dt);
schemaId =dt.getSchema();
}else{
logger.error("DataSourceType is null");
return null;
}
//HashMap paramMap = new HashMap();
mmiLogMap.put("schemaId" , schemaId);
mmiLogMap.put("msgDpstHMS" , DateUtil.getDateTimeMilliSecound());
mmiLogMap.put("eaiSvcName" , NullControl.addSpace(eaiSvcName));
mmiLogMap.put("eaiSevrDstcd" , NullControl.addSpace(eaiSevrDstcd));
mmiLogMap.put("cnvsnName" , NullControl.addSpace(cnvsnNames));
mmiLogMap.put("loutName" , NullControl.addSpace(loutNames));
mmiLogMap.put("reqDstcd" , NullControl.addSpace(buffer.toString()));
mmiLogMap.put("resDstcd" , NullControl.addSpace(frame.toString()));
mmiLogMap.put("interfaceId" , NullControl.addSpace(mmiIfId));
mmiLogMap.put("deployId" , NullControl.addSpace(userId));
try{
mmiLogDao.insert(mmiLogMap);
}catch(Exception e){
logger.error("db insert error : " + mmiLogMap.toString(),e);
}
ServletOutputStream sos = null;
try {
sos = response.getOutputStream();
sos.write(frame.toString().getBytes());
} catch( Exception e ) {
//취약점소스 수정 2020.08.24
logger.error(" error", e);
} finally {
if( sos != null ) sos.close();
}
return null;
}
@RequestMapping(value= "/mmiSync.do",params = "cmd=delete", method=RequestMethod.POST)
public View messageDelete(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (true){
throw new Exception("지원 하지 않는 메소드 입니다." );
}
ServletInputStream sis = null;
StringBuilder sb = new StringBuilder();
StringBuilder frame = new StringBuilder();
try{
sis = request.getInputStream();
String data = streamToString(sis);
HashMap<String,Object> map = MMIParser.parseDelete(data);
if (map == null){
throw new Exception ("parsing error");
}
//서버구분코드 필요
String eaiSevrDstcd = "2";
///////////////////////////////////////////////
//서버구분코드로 DataSourceType 변경
// 1 : 내부(NSG) , 2 : 대외(DSG), 3 : 공동망(GSG), 4 : DMZ(ZSG), 5 : 오픈뱅킹(ASG)
// 개발은 1,2,3 은 DSG 로 4는 ZSG로 처리 한다.
///////////////////////////////////////////////
String serverType = monitoringContext.getStringProperty(MonitoringContext.MMI_SYNC_SERVERTYPE, "1=DSG,2=DSG,3=DSG,4=ZSG,5=DSG");
HashMap<String,String> serverDstcdMap = new HashMap<String,String>();
Matcher matcher = Pattern.compile("[ ]*([0-9]+)[ ]*=[ ]*([A-Z]+)[ ]*").matcher(serverType);
while(matcher.find()) {
String key = matcher.group(1).trim();
String value = matcher.group(2).trim();
serverDstcdMap.put(key, value);
}
if (serverDstcdMap.containsKey(eaiSevrDstcd)){
String dataSourceType = serverDstcdMap.get(eaiSevrDstcd);
DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(dataSourceType));
}else{
throw new Exception("지원하지 않는 서버 구분코드 입니다."+eaiSevrDstcd);
}
HashMap<String,Object> inter = (HashMap<String,Object>)map.get("interface");
List<HashMap<String,Object>> layouts = (List<HashMap<String,Object>>)map.get("formats");
if (inter != null ){
//변환 목록 가져오기 - 인터페이스 기준
inter.put("transform", service.selectTransformListForEaiSvcName(inter));
//내부표준 목록 가져오기 - 인터페이스 기준
inter.put("bzwkSvcKeyName", service.selectBzwkSvcKeyNameForEaiSvcName(inter));
}
CommonCommand command = null;
try{
service.deleteInterface(inter);
String eaiSvcName = (String)inter.get("eaiSvcName");
if (!StringUtils.isEmpty(eaiSvcName)){
//인터페이스 동기화
command = new CommonCommand("com.eactive.eai.agent.eaimessage.RemoveEAIMessageCommand",eaiSvcName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("인터페이스 동기화 오류 "+eaiSvcName);
}
//추출키 동기화
command = new CommonCommand("com.eactive.eai.agent.bizkey.RemoveBizKeyCommand",eaiSvcName+",TR");
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("추출키 동기화 오류 "+eaiSvcName);
}
command = new CommonCommand("com.eactive.eai.agent.bizkey.RemoveBizKeyCommand",eaiSvcName+",AK");
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("추출키 동기화 오류 "+eaiSvcName);
}
//내부표준전문 삭제 동기화
List<String> bzwkSvcKeyNames = (List<String>)inter.get("bzwkSvcKeyName");
if (bzwkSvcKeyNames != null){
for(String bzwkSvcKeyName : bzwkSvcKeyNames){
command = new CommonCommand("com.eactive.eai.agent.kbmessage.RemoveKBMessageCommand",bzwkSvcKeyName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("내부표준전문 동기화 오류 "+bzwkSvcKeyName);
}
}
}
//변환 동기화
List<String> transforms = (List<String>)inter.get("transform");
if (transforms != null){
for(String cnvsnName : transforms){
command = new CommonCommand("com.eactive.eai.agent.transformer.RemoveTransformCommand",cnvsnName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("변환 동기화 오류 "+cnvsnName);
}
}
}
}
sb.append(resultInterfaceDelete((String)inter.get("mmiIfId"),(String)inter.get("eaiSvcName"),"SUCCESS",""));
}catch(Exception e){
logger.error("MMISycnControl delete error="+e.getMessage(),e);
sb.append(resultInterfaceDelete((String)inter.get("mmiIfId"),(String)inter.get("eaiSvcName"),"FAIL",e.getMessage()));
}
for(HashMap<String,Object> layout : layouts){
String loutName = (String)layout.get("loutName");
try{
service.deleteLayout(layout);
command = new CommonCommand("com.eactive.eai.agent.transformer.RemoveLayoutCommand",loutName);
if (!validate(agentUtilService.broadcast(command))){
throw new Exception("레이아웃 동기화 오류 "+loutName);
}
sb.append(resultFormatDelete((String)inter.get("mmiIfId"),(String)inter.get("eaiSvcName"),"SUCCESS",""));
}catch(Exception e){
logger.error("MMISycnControl delete error="+e.getMessage(),e);
sb.append(resultFormatDelete((String)inter.get("mmiIfId"),(String)inter.get("eaiSvcName"),"FAIL",e.getMessage()));
}
}
}catch(Exception e){
logger.error(e.getMessage(),e);
sb.append("<error msg=\""+e.getMessage()+"\"/>");
}finally{
if (sis != null) try{sis.close();}catch(Exception e){}
}
frame.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
frame.append("<Deploy>");
frame.append(sb.toString());
frame.append("</Deploy>");
ServletOutputStream sos = null;
try {
sos = response.getOutputStream();
sos.write(frame.toString().getBytes());
} catch( Exception e ) {
logger.error(e.getMessage(),e);
} finally {
if( sos != null ) sos.close();
}
return null;
}
private boolean validate(HashMap<String,Object> map ){
for(String key : map.keySet()){
Object o = map.get(key);
if (o instanceof String){
if("success".equals((String)o)){
;
}else{
return false;
}
}else{
return false;
}
}
return true;
}
private String resultInterface(String mmiIfId, String ver, String returnCode, String returnMessage){
return "<Interface mmi_if_id=\""+mmiIfId+"\" ver=\""+ver+"\" return_code=\""+returnCode+"\" return_message=\""+returnMessage+"\" />";
}
private String resultInterfaceDelete(String mmiIfId, String id, String returnCode, String returnMessage){
return "<Interface mmi_if_id=\""+mmiIfId+"\" id=\""+id+"\" return_code=\""+returnCode+"\" return_message=\""+returnMessage+"\" />";
}
private String resultFormatDelete(String mmiIoId, String id, String returnCode, String returnMessage){
return "<Format mmi_io_id=\""+mmiIoId+"\" id=\""+id+"\" return_code=\""+returnCode+"\" return_message=\""+returnMessage+"\" />";
}
private static String streamToString(InputStream is){
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int r;
byte[] data = new byte[1024];
try {
while((r = is.read(data)) != -1){
buffer.write(data,0,r);
}
buffer.flush();
} catch (IOException e) {
logger.error(e.getMessage(),e);
return "";
}
String s = new String(buffer.toByteArray());
return s;
}
}
@@ -0,0 +1,77 @@
package com.eactive.eai.rms.ext.mmi;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.eactive.eai.rms.common.base.SqlMapClientTemplateDao;
@Repository("mmiSyncDao")
@SuppressWarnings("unchecked")
public class MMISyncDao extends SqlMapClientTemplateDao {
public List<Map<String, Object>> selectHS04(HashMap param) throws Exception {
return (List<Map<String, Object>>)template.queryForList("MMISync.selectHS04", param);
}
public void deleteHS04(HashMap<String,Object> std) {
template.delete("MMISync.deleteHS04", std);
}
public void deleteHS05(HashMap<String,Object> std) {
template.delete("MMISync.deleteHS05", std);
}
public void insertHS04(HashMap<String,Object> std) {
template.insert("MMISync.insertHS04", std);
}
public void insertHS05(HashMap<String,Object> std) {
template.insert("MMISync.insertHS05", std);
}
public void mergeHE01(HashMap<String,Object> vo) {
template.insert("MMISync.mergeHE01", vo);
}
public void mergeHE02(HashMap<String,Object> vo) {
template.insert("MMISync.mergeHE02", vo);
}
public Map<String, String> selectAdapterForNickName(Map param) throws Exception {
List<Map<String,String>> list= (List<Map<String,String>>) template.queryForList("MMISync.selectAdapterForNickName", param);
if (list == null || list.size() ==0){
return new HashMap<String,String>();
}else if (list.size() == 1){
return list.get(0);
}else {
String nickName = (String)param.get("adptrNickName");
throw new Exception("중복된 nickname("+nickName+")이 존재 합니다.EAI 담당자에게 문의 하세요.");
}
}
public Map<String,String> selectHS05(Map param) throws Exception {
List<Map<String, String>> list = (List<Map<String, String>>)template.queryForList("MMISync.selectHS05", param);
Map<String,String> results = new HashMap<String,String>();
for(Map<String,String> map : list){
String key = map.get("BZWKSVCKEYNAME") + "," + map.get("COLUMNNAME");
results.put(key, map.get("COLUMNVALUE"));
}
return results;
}
public List<String> selectTransformListForEaiSvcName(HashMap<String,Object> vo) {
return (List<String>)template.queryForList("MMISync.selectTransformListForEaiSvcName", vo);
}
public List<String> selectBzwkSvcKeyNameForEaiSvcName(HashMap<String,Object> vo) {
return (List<String>)template.queryForList("MMISync.selectBzwkSvcKeyNameForEaiSvcName", vo);
}
public void deleteHe02SvcPrcssNo(HashMap<String,Object> vo) {
template.delete("MMISync.deleteHe02SvcPrcssNo", vo);
}
public int selecAppIsYn(HashMap<String,Object> vo) {
return (Integer) template.queryForObject("MMISync.selecAppIsYn", vo);
}
public List<String> selectHS04ForBzwkSvcKeyName(HashMap<String,Object> vo) {
return (List<String>)template.queryForList("MMISync.selectHS04ForBzwkSvcKeyName", vo);
}
public List<String> selectInterfaceForSameLayout(HashMap<String,Object> vo) {
return (List<String>)template.queryForList("MMISync.selectInterfaceForSameLayout", vo);
}
}
@@ -0,0 +1,618 @@
package com.eactive.eai.rms.ext.mmi;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import com.eactive.eai.data.entity.onl.bizkey.BizKey;
import com.eactive.eai.data.entity.onl.messagekey.MessageKey;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutEntity;
import com.eactive.eai.data.entity.onl.transformer.layout.LayoutItemEntity;
import com.eactive.eai.rms.common.base.OnlBaseService;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.MessengerPlusSender;
import com.eactive.eai.rms.data.entity.onl.b2bextract.B2bExtractService;
import com.eactive.eai.rms.data.entity.onl.bizkey.BizKeyService;
import com.eactive.eai.rms.data.entity.onl.layout.LayoutService;
import com.eactive.eai.rms.data.entity.onl.messagekey.MessageKeyService;
import com.eactive.eai.rms.data.entity.onl.stdmessage.StandardMessageInfoService;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.manage.rule.layout.LayoutDao;
import com.eactive.eai.rms.onl.manage.rule.transform.TransformDao;
import com.eactive.eai.rms.onl.manage.serviceinfo.bizkey.FieldExtractInfoUIMapper;
import com.eactive.eai.rms.onl.manage.serviceinfo.eaimsg.EaiMsgDao;
@Service("mmiSyncService")
public class MMISyncService extends OnlBaseService {
@Autowired
@Qualifier("mmiSyncDao")
private MMISyncDao dao;
@Autowired
@Qualifier("transformDao")
private TransformDao transformDao;
@Autowired
@Qualifier("eaiMsgDao")
public EaiMsgDao eaiMsgDao;
@Autowired
@Qualifier("layoutDao")
public LayoutDao layoutDao;
@Autowired
@Qualifier("monitoringContext")
private MonitoringContext monitoringContext;
@Autowired
private ComboService comboService;
@Autowired
private BizKeyService bizKeyService;
@Autowired
private B2bExtractService b2bExtractService;
@Autowired
private StandardMessageInfoService standardMessageInfoService;
@Autowired
private LayoutService layoutService;
@Autowired
private MessageKeyService messageKeyService;
public int mergeLayout(List<HashMap<String,Object>> layoutVos) throws Exception{
for(HashMap<String,Object> vo : layoutVos){
String layout = (String)vo.get("loutName");
//서버구분코드 체크
Optional<LayoutEntity> optionalLayoutEntity = layoutService.findById(layout);
if (layoutService.existsById(layout)){
String dbEaiSevrDstcd = optionalLayoutEntity.get().getEaisevrdstcd();
String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
if (!dbEaiSevrDstcd.equals(mmiEaiSevrDstcd)){
throw new Exception("레이아웃("+layout+") 서버구분코드 오류. EAI DB에 등록("+dbEaiSevrDstcd+")되어 있는값과 MMI 배포 ("+mmiEaiSevrDstcd+") 값이 다릅니다.");
}
}else{
String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
if ("9".equals(mmiEaiSevrDstcd)){
throw new Exception("신규 레이아웃 등록시 서버구분코드가 9 인 경우." + layout);
}
}
//vo 의 한글 체크
boolean isDeployHangle= false;
//db 의 한글체크
boolean isDbHangle = false;
if (optionalLayoutEntity.isPresent() && !optionalLayoutEntity.get().getLayoutItemEntities().isEmpty()){
//배포 레이아웃 체크
List<HashMap<String,Object>> list = (List<HashMap<String,Object>>)vo.get("list");
for(HashMap<String,Object> item : list) {
String name = (String)item.get("loutItemName");
if (name.getBytes().length != name.length() ){
isDeployHangle= true;
break;
}
}
//DB 레이아웃 체크
for(LayoutItemEntity item : optionalLayoutEntity.get().getLayoutItemEntities()){
String name = item.getId().getLoutitemname();
if (name.getBytes().length != name.length() ){
isDbHangle= true;
break;
}
}
if (isDeployHangle != isDbHangle){
//EAI 서비스코드가 1개만 존재할때 레이아웃이 다르더라도 패스 2020-10-29 오현석대리요청
//변환까지만 연결된거 무시한다.
List<String> interfaceLists = dao.selectInterfaceForSameLayout(vo);
if (interfaceLists != null && interfaceLists.size() > 1){
if (isDeployHangle){
throw new Exception("배포 된 레이아웃("+layout+") 은 한글로 되어 있습니다. DB에 저장되어 있는 값은 영문 입니다.배포한 레이아웃이 한글이 맞는지 확인하시기 바랍니다. 사용하는 인터페이스 ("+ interfaceLists +")");
}else{
throw new Exception("배포 된 레이아웃("+layout+") 은 영문으로 되어 있습니다. DB에 저장되어 있는 값은 한글 입니다.배포한 레이아웃이 영문이 맞는지 확인하시기 바랍니다. 사용하는 인터페이스 ("+ interfaceLists +")");
}
}
}
}
List<HashMap<String,Object>> list = (List<HashMap<String,Object>>)vo.get("list");
layoutDao.deleteItemAll(vo);
layoutDao.delete(vo);
layoutDao.insert(vo);
for(HashMap<String,Object> item : list) {
layoutDao.insertItem(item);
}
}
return layoutVos.size();
}
public int mergeTransform(List<HashMap<String,Object>> transformVos) throws Exception{
for(HashMap<String,Object> vo : transformVos){
//서버구분코드 체크
HashMap detail =transformDao.selectDetail(vo);
if (detail != null){
String dbEaiSevrDstcd = (String)detail.get("EAISEVRDSTCD");
String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
String cnvsnName = (String)vo.get("cnvsnName");
if (!dbEaiSevrDstcd.equals(mmiEaiSevrDstcd)){
throw new Exception("변환("+cnvsnName+") 서버구분코드 오류. EAI DB에 등록("+dbEaiSevrDstcd+")되어 있는값과 MMI 배포 ("+mmiEaiSevrDstcd+") 값이 다릅니다.");
}
}else{
String mmiEaiSevrDstcd = (String)vo.get("eaiSevrDstcd");
if ("9".equals(mmiEaiSevrDstcd)){
throw new Exception("신규 변환 등록시 서버구분코드가 9 인 경우." + (String)vo.get("cnvsnName"));
}
}
transformDao.deleteTransformItem(vo);
transformDao.deleteTransformSourceResult(vo);
transformDao.deleteTransform(vo);
transformDao.insert(vo);
List<HashMap<String,Object>> layouts = (List<HashMap<String,Object>>)vo.get("layouts");
for(HashMap<String,Object>layout : layouts){
transformDao.insertTransformSourceResult(layout);
}
List<HashMap<String,Object>> mappings = (List<HashMap<String,Object>>)vo.get("mappings");
for(HashMap<String,Object> mapping : mappings){
try{
transformDao.insertTransformItem(mapping);
}catch(DuplicateKeyException e){
throw new Exception("변환 항목 중복 오류 " + mapping);
}
}
}
return transformVos.size();
}
public String mergeInterface(HashMap<String,Object> interfaceVo) throws Exception {
HashMap he01 = (HashMap)interfaceVo.get("he01");
String eaiSvcName = (String)he01.get("eaiSvcName");
logger.info ("-1. 내부 표준 전문 INSERT ----------------------------------------------------");
// 1. 내부 표준 전문 INSERT
// 비표준에서 표준으로 가는 경우 표준으로 전환하기 위한 정보 이므로 내부로 갈 때만 처리
//eai 서비스 기준으로 목록 조회
List<Map<String, Object>> listHs04 = dao.selectHS04(new HashMap(){{put("eaiSvcName",eaiSvcName);}});
String[] filters = new String[]{"COMMON_bnkCd","COMMON_chnlDstcd","COMMON_cmpxTranDmndDstcd","COMMON_cnclDstcd","COMMON_groupCoCd","COMMON_mdiaDstcd","COMMON_screnNo","COMMON_sysOperEvirnDstcd"};
Map<String,String> beforeData = dao.selectHS05(new HashMap(){{put("eaiSvcName",eaiSvcName);put("filters",filters);}});
for(Map map : listHs04){
dao.deleteHS04((HashMap)map);
dao.deleteHS05((HashMap)map);
}
@SuppressWarnings("unchecked")
ArrayList<HashMap<String, Object>> hs04s = (ArrayList<HashMap<String, Object>>)interfaceVo.get("hs04");
if (hs04s != null){
//내부표준전문 업무 서비스키 중복 체크
for(HashMap<String,Object> map : hs04s){
String bzwkSvcKeyName = (String)map.get("bzwkSvcKeyName");
List<String> eaiList = dao.selectHS04ForBzwkSvcKeyName(new HashMap(){{put("bzwkSvcKeyName",bzwkSvcKeyName);}});
if (eaiList != null && eaiList.size() > 0){
String dupEaiSvcName = "";
for(String data : eaiList){
dupEaiSvcName = "," + data;
}
throw new Exception("내부표준전문의 업무서비스키 중복 오류입니다.다른 EAI서비스코드("+dupEaiSvcName+") 에서 서비스키("+bzwkSvcKeyName+") 를 사용하고 있습니다.");
}
}
for(HashMap<String,Object> map : hs04s){
ArrayList<HashMap<String,Object>> hs05s = (ArrayList<HashMap<String,Object>>)map.get("hs05");
dao.insertHS04(map);
for(HashMap<String,Object> submap : hs05s){
String key = submap.get("bzwkSvcKeyName") + "," + submap.get("columnName");
String data = beforeData.get(key);
if (data != null){
submap.put("columnValue", data);
}
dao.insertHS05(submap);
}
}
}
logger.info ("-2. EAI메세지 INSERT -------------------------------------------------------");
// 2. EAI메세지 INSERT
dao.mergeHE01((HashMap<String,Object>)interfaceVo.get("he01"));
eaiSvcNameVali(interfaceVo);
ArrayList<HashMap<String,Object>> he02s = (ArrayList<HashMap<String,Object>>)interfaceVo.get("he02");
for(HashMap<String,Object> map : he02s){
dao.mergeHE02(map);
}
//순서변경 위에서 무조건삭제 하는 방식에서 merge후 he02s가 1건일 경우 2번째 시퀀스 삭제
if(he02s != null && he02s.size() == 1){
//EAI메시지 SERVICE 2번 은 삭제
dao.deleteHe02SvcPrcssNo(new HashMap(){{put("eaiSvcName",eaiSvcName);put("svcPrcssNo",2);}});
}
// logger.info("-3. 참조메시지ID INSERT ----------------------------------------------------");
// 3. 참조메시지ID INSERT
ArrayList<HashMap<String, Object>> ms02s = (ArrayList<HashMap<String, Object>>)interfaceVo.get("ms02");
if (ms02s != null && ms02s.size() > 0 ){
//TransformVo vo = new TransformVo();
//vo.setEaiSvcName(eaiSvcName);
eaiMsgDao.deleteRefForEaiSvcName(new HashMap(){{put("eaiSvcName",eaiSvcName);}});
for(HashMap<String,Object> map : ms02s){
eaiMsgDao.insertRef(map);
}
}
return null;
}
public boolean mergeMessageKey(HashMap<String,Object> interfaceVo, String userId) throws Exception {
//메시지Key
List<String[]> fr04s = (List<String[]>)interfaceVo.get("fr04");
HashMap he01 = (HashMap)interfaceVo.get("he01");
String eaiSvcName = (String)he01.get("eaiSvcName");
String adptrBzwkGroupName = (String)he01.get("gstatSysAdptrBzwkGroupName");
boolean isMessageKeySame = true;
if (fr04s != null && fr04s.size()>0){
//select
List<MessageKey> dbdata = messageKeyService.findByAdptrBzwkGroupNameAndIoDstcd(adptrBzwkGroupName, "I");
isMessageKeySame = messageCheck(fr04s, dbdata);
//쪽지알림
StringBuffer sb = new StringBuffer();
if (!isMessageKeySame){
sb.append("어댑터업무그룹명 : " + adptrBzwkGroupName ).append("<br>");
sb.append("EAI서비스코드 : " + eaiSvcName ).append("<br>");
if (dbdata != null && dbdata.size() > 0 ){
sb.append("현재 설정 정보" ).append("<br>");
sb.append("<table style=\"TEXT-DECORATION: ; WIDTH: 1052px; BACKGROUND-COLOR: #ffffff\" cellSpacing=0 cellPadding=0 width=1052 border=1>");
sb.append("<tr>");
sb.append("<td>메시지 구분코드</td>");
sb.append("<td>입출력 구분코드</td>");
sb.append("<td>그룹 순차번호</td>");
sb.append("<td>필드 처리번호</td>");
sb.append("<td>메시지 필드 시작위치값</td>");
sb.append("<td>메시지 필드 길이</td>");
sb.append("</tr>");
for(MessageKey messageKey : dbdata){
sb.append("<tr>");
sb.append("<td>" + messageKey.getId().getMsgdstcd() + "</td>");
sb.append("<td>" + messageKey.getId().getIodstcd() + "</td>");
sb.append("<td>" + messageKey.getId().getGroupinorno() + "</td>");
sb.append("<td>" + messageKey.getId().getFldprcssno() + "</td>");
sb.append("<td>" + messageKey.getMsgfldstartsituval() + "</td>");
sb.append("<td>" + messageKey.getMsgfldlen() + "</td>");
sb.append("</tr>");
}
sb.append("</table>");
}
sb.append("요청 설정자 (" + userId + ")").append("<br>");
sb.append("요청 설정 정보 " ).append("<br>");
sb.append("<table style=\"TEXT-DECORATION: ; WIDTH: 1052px; BACKGROUND-COLOR: #ffffff\" cellSpacing=0 cellPadding=0 width=1052 border=1>");
sb.append("<tr>");
//sb.append("<td>메시지 구분코드</td>");
//sb.append("<td>입출력 구분코드</td>");
//sb.append("<td>그룹 순차번호</td>");
sb.append("<td>필드 처리번호</td>");
sb.append("<td>메시지 필드 시작위치값</td>");
sb.append("<td>메시지 필드 길이</td>");
sb.append("</tr>");
for(int i=0;i< fr04s.size();i++){
String[] fr04 = fr04s.get(i);
if (fr04.length == 2){
sb.append("<tr>");
//sb.append("<td>"+m.get("msgDstcd")+"</td>");
//sb.append("<td>"+m.get("ioDstcd")+"</td>");
//sb.append("<td>"+m.get("groupInorNo")+"</td>");
sb.append("<td>"+(i+1)+"</td>");
sb.append("<td>"+fr04[0]+"</td>");
sb.append("<td>"+fr04[1]+"</td>");
sb.append("</tr>");
}
}
MessengerPlusSender sender = MessengerPlusSender.getInstance();
String url = monitoringContext.getStringProperty("rms.messenger.url");
String srvCode = monitoringContext.getStringProperty("rms.messenger.srvCode");
String recipient = monitoringContext.getStringProperty("rms.messenger.recipient");
String send = monitoringContext.getStringProperty("rms.messenger.send");
String senderAlias = monitoringContext.getStringProperty("rms.messenger.senderAlias");
logger.debug("send MessengerPlus data : " + sb.toString());
sender.execute(url, srvCode, recipient, send, "EAI 어댑터 구분필드 추출정보 변경요청", sb.toString(), "", senderAlias);
}
}
return isMessageKeySame;
}
private boolean messageCheck(List<String[]> fr04s, List<MessageKey> selectData) throws Exception{
List<String[]> dbGroup = new ArrayList<>();
HashMap<String,List<String[]>> dbGroups = new HashMap<>();
for (MessageKey messageKey : selectData) {
String groupNumber = Integer.toString(messageKey.getId().getGroupinorno());
if (dbGroups.containsKey(groupNumber)) {
dbGroup = dbGroups.get(groupNumber);
} else {
dbGroup = new ArrayList<String[]>();
dbGroups.put(groupNumber, dbGroup);
}
dbGroup
.add(new String[] { Integer.toString(messageKey.getMsgfldstartsituval()),
Integer.toString(messageKey.getMsgfldlen()) });
}
//false 일 경우 message전송
//check
//신규등록
if (dbGroups.size() == 0 && fr04s.size() >0){
return false;
}
for (String key : dbGroups.keySet()){
dbGroup = dbGroups.get(key);
if (dbGroup.size() == fr04s.size()){
int trueCount = 0;
for(int i=0;i< dbGroup.size() ;i++ ){
if (Arrays.equals(dbGroup.get(i), fr04s.get(i))){
trueCount++;
}
}
if (dbGroup.size()==trueCount){
return true;
}
}
}
return false;
}
@Autowired
private FieldExtractInfoUIMapper fieldExtractInfoUIMapper;
public String mergeTraceKey(HashMap<String,Object> interfaceVo , List<HashMap<String,Object>> tracekeys) throws Exception {
logger.info(" 추적관리필드 INSERT -----------------------------------------------------");
// 4. 추적관리필드 INSERT
HashMap he01 = (HashMap)interfaceVo.get("he01");
final String eaiSvcName = (String)he01.get("eaiSvcName");
bizKeyService.deleteByIdEaiSvcName(eaiSvcName);
if (tracekeys== null || tracekeys.size()==0){
return null;
}
for (HashMap<String, Object> tracekey : tracekeys) {
BizKey bizKey = fieldExtractInfoUIMapper.map(tracekey);
bizKeyService.save(bizKey);
}
return null;
}
public boolean transactionMMISync( HashMap<String,Object> interfaceVo , List<HashMap<String,Object>> layoutVos, List<HashMap<String,Object>> transformVos, List<HashMap<String,Object>> tracekeys, String userId) throws Exception {
logger.info("-------------------<< transactionMMISync >>----------------------------");
logger.debug("{}",interfaceVo);
logger.info("-------------------<< session 값체크>>----------------------------");
boolean isOnline = false;
for ( DataSourceType ds : DataSourceTypeManager.getOnlineDataSourceTypes()){
if (ds.getName().equals(DataSourceContextHolder.getDataSourceType().getName())){
isOnline = true;
break;
}
}
if (!isOnline){
throw new BizException("로그인 오류 (재로그인 하시기 바랍니다.)");
}
mergeLayout(layoutVos);
mergeTransform(transformVos);
mergeInterface(interfaceVo);
mergeTraceKey(interfaceVo, tracekeys);
return mergeMessageKey(interfaceVo, userId);
}
public Map<String,Map<String, String>> selectAdapterForNickName(String src, String tgt, String resSrc) throws Exception {
Map<String, Map<String, String>> result = new HashMap<String,Map<String,String>>();
if (!StringUtils.isEmpty(src)){
Map<String,String> nickname = dao.selectAdapterForNickName(new HashMap(){{put("adptrNickName",src);}});
if (nickname == null || nickname.size()==0){
throw new Exception("어댑터 닉네임 ("+src+")이 존재 하지 않습니다. EAI 담당자에게 문의 하세요.");
}
result.put("SRC", nickname);
}
if (!StringUtils.isEmpty(tgt) && !"DUMMY000".equals(tgt)){
Map<String,String> nickname = dao.selectAdapterForNickName(new HashMap(){{put("adptrNickName",tgt);}});
if (nickname == null || nickname.size()==0){
throw new Exception("어댑터 닉네임 ("+tgt+")이 존재 하지 않습니다. EAI 담당자에게 문의 하세요.");
}
result.put("TGT", nickname);
}
if (!StringUtils.isEmpty(resSrc)){
Map<String,String> nickname = dao.selectAdapterForNickName(new HashMap(){{put("adptrNickName",resSrc);}});
if (nickname == null || nickname.size()==0){
throw new Exception("어댑터 닉네임 ("+resSrc+")이 존재 하지 않습니다. EAI 담당자에게 문의 하세요.");
}
result.put("RES_SRC", nickname);
}
return result;
}
public void deleteInterface( HashMap<String,Object> inter ) throws Exception {
//interface 삭제할 경우
// - interface삭제 (he01,he02,fr01,ms02)
// - altkey,tracekey 삭제 (fr03) interface 기준으로 삭제
// - 내부표준전문 삭제 (hs04,hs05) interface 기준으로 삭제
// - 변환삭제 (tr01,tr02,tr03) interface 기준으로 삭제
logger.info("-------------------<<deleteMMISync >>----------------------------");
logger.debug("{}",inter);
logger.info("-------------------<< session 값체크>>----------------------------");
boolean isOnline = false;
for ( DataSourceType ds : DataSourceTypeManager.getOnlineDataSourceTypes()){
if (ds.getName().equals(DataSourceContextHolder.getDataSourceType().getName())){
isOnline = true;
break;
}
}
if (!isOnline){
throw new BizException("로그인 오류 (재로그인 하시기 바랍니다.)");
}
String eaiSvcName = (String)inter.get("eaiSvcName");
HashMap<String,Object> paramMap = new HashMap<String,Object>(){{put("eaiSvcName",eaiSvcName);}};
eaiMsgDao.delete(paramMap);
eaiMsgDao.deleteSvc(paramMap);
eaiMsgDao.deleteRefForEaiSvcName(paramMap);
eaiMsgDao.deleteCondRuleForEaiSvcName(paramMap);
//alterkey, tracekey 삭제
bizKeyService.deleteByIdEaiSvcName(eaiSvcName);
//내부표준전문삭제
List<String> bzwkSvcKeyNames = (List<String>)inter.get("bzwkSvcKeyName");
if (bzwkSvcKeyNames != null){
for(String bzwkSvcKeyName : bzwkSvcKeyNames){
standardMessageInfoService.deleteById(bzwkSvcKeyName);
}
}
//변환삭제
List<String> transforms = (List<String>)inter.get("transform");
if (transforms != null){
for(String transform : transforms){
HashMap<String,Object> map = new HashMap<String,Object>(){{put("cnvsnName",transform);}};
//1.delete transform //TR01 삭제
transformDao.deleteTransform(map);
//2.delete transform //TR02 삭제
transformDao.deleteTransformSourceResult(map);
//3.delete transform //TR03 삭제
transformDao.deleteTransformItem(map);
}
}
}
public void deleteLayout(HashMap<String,Object> layouts) throws Exception {
logger.info("-------------------<<deleteLayout >>----------------------------");
logger.debug("{}",layouts);
logger.info("-------------------<< session 값체크>>----------------------------");
boolean isOnline = false;
for ( DataSourceType ds : DataSourceTypeManager.getOnlineDataSourceTypes()){
if (ds.getName().equals(DataSourceContextHolder.getDataSourceType().getName())){
isOnline = true;
break;
}
}
if (!isOnline){
throw new BizException("로그인 오류 (재로그인 하시기 바랍니다.)");
}
String loutName = (String)layouts.get("loutName");
HashMap<String,Object> paramMap = new HashMap<String,Object>(){{put("loutName",loutName);}};
layoutDao.delete(paramMap);
layoutDao.deleteItemAll(paramMap);
}
public List<String> selectTransformListForEaiSvcName(HashMap<String,Object> map){
return dao.selectTransformListForEaiSvcName(map);
}
public List<String> selectBzwkSvcKeyNameForEaiSvcName(HashMap<String,Object> map){
return dao.selectBzwkSvcKeyNameForEaiSvcName(map);
}
// public static void main(String[] args) throws Exception{ //취약점 수정
//
// }
public boolean selecAppIsYn(HashMap<String,Object> map){
int count = dao.selecAppIsYn(map);
if (count==0) {
return false;
}else{
return true;
}
}
public void eaiSvcNameVali (HashMap<String,Object> interfaceVo) throws Exception {
/*
20200902
Flow Control -> B2B일 때
모니터링 코드(MMI_B2B_BZWKDSTCD)에 정의되어 있는 업무구분코드에 서비스코드 앞3자리가 있을 때
라우팅 추출 정보가 없을때
메신저 발송
*/
HashMap he01 = (HashMap)interfaceVo.get("he01");
String eaiSvcName = (String)he01.get("eaiSvcName");
String flowCtrl = (String)he01.get("flowCtrlRoutName"); //플로우컨트롤명
String bzwkDstcd = eaiSvcName.substring(0, 3);//서비스코드 앞 3자리
String eaiSevrTxt = "";
boolean isB2b = false; //플로우컨트롤이 b2b인지
boolean isCode = false; //모니터링 코드에 정의되어 있는지
boolean isRoutCnt = false; //라우팅추출정보가 없을 때
String eaiSevrDstcd = (String)he01.get("eaiSevrDstcd"); //서버구분코드
List<ComboVo> sevrCdList = comboService.getFromCode("INOUT_TYPE");//EAI서버구분코드
if (!sevrCdList.isEmpty()) {
for (ComboVo m : sevrCdList) {
if (eaiSevrDstcd.equals(m.getCode())) {
eaiSevrTxt = m.getCodename();
break;
}
}
}
if (flowCtrl.indexOf("B2B")>-1){ //flowControl => B2B일때
isB2b = true;
}
//Monitoring Code에 서비스코드 앞 3자리가 정의되어 있는지
List<ComboVo> bzwkDstcdList = comboService.getMonitoringCodeSortedByIdCode("MMI_B2B_BZWKDSTCD");
for(ComboVo m : bzwkDstcdList){
if(bzwkDstcd.equals(m.getCodename())){
isCode = true;
break;
}
}
//라우팅추출정보가 없을때
long routCnt = b2bExtractService.count(eaiSvcName);
if(routCnt == 0){
isRoutCnt = true;
}
if (isB2b && isCode && isRoutCnt){
if(!"1".equals(eaiSevrDstcd) && eaiSvcName.endsWith("1")){ //내부가 아니고 서비스코드가 S01 or R01 1로 끝날때 pass
return;
}
//쪽지알림
//라우팅 필드추출 정보 관리에 XXXXXXXX 서비스코드가 미등록 상태입니다.
//EMS - 환경정보 - 서비스정보관리 - 라우팅 필드추출 정보 관리에 신규등록 바랍니다.
StringBuffer sb = new StringBuffer();
sb.append("EAI서비스코드 : " + eaiSvcName ).append("<br>");
sb.append("EAI서버구분 : ["+eaiSevrDstcd+"] " + eaiSevrTxt ).append("<br>");
sb.append("라우팅 추출 정보 관리에 서비스코드("+eaiSvcName+")가 미등록 상태입니다." ).append("<br>");
sb.append("EMS - 환경정보 - 서비스정보관리 - 라우팅 필드추출 정보 관리에 신규등록 바랍니다." ).append("<br>");
MessengerPlusSender sender = MessengerPlusSender.getInstance();
String url = monitoringContext.getStringProperty("rms.messenger.url","http://172.17.179.45/HMemoService");
String srvCode = monitoringContext.getStringProperty("rms.messenger.srvCode","EAI002");
String recipient = monitoringContext.getStringProperty("rms.messenger.recipient","1622512;1562325;2852883;3331839;S010795;");
String send = monitoringContext.getStringProperty("rms.messenger.send","1562325");
String senderAlias = monitoringContext.getStringProperty("rms.messenger.senderAlias","EAI시스템");
logger.debug("send MessengerPlus data : " + sb.toString());
sender.execute(url, srvCode, recipient, send, "라우팅 필드추출정보 등록요청", sb.toString(), "", senderAlias);
}
}
}
@@ -0,0 +1,17 @@
package com.eactive.eai.rms.ext.tran.epb;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.eactive.eai.rms.common.base.SqlMapClientTemplateDao;
@Repository
public class TranResultExtractDao extends SqlMapClientTemplateDao {
public List<String> selectTranResultList(HashMap paramMap) throws Exception {
return template.queryForList("TranResultExtract.selectTranResultList", paramMap);
}
}
@@ -0,0 +1,48 @@
package com.eactive.eai.rms.ext.tran.epb;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;
public class TranResultExtractJob implements Job {
private static final Logger logger = Logger.getLogger(TranResultExtractJob.class);
public void execute(JobExecutionContext context) throws JobExecutionException {
ApplicationContext appContext = null;
try {
appContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
} catch (SchedulerException e1) {
logger.error(e1);
}
if (appContext == null) {
logger.info("[TranResultExtractJob ]appContext is null");
}
if (appContext.getBean("tranResultExtractService") == null) {
logger.info("[TranResultExtractJob ] tranResultExtractService is null");
}
TranResultExtractService service = (TranResultExtractService) appContext.getBean("tranResultExtractService");
logger.info("[TranResultExtractJob START]----------");
try {
service.tranResultExtract();
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
logger.info("[TranResultExtractJob END]----------");
}
}
}
@@ -0,0 +1,120 @@
package com.eactive.eai.rms.ext.tran.epb;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.CommonConstants;
import com.eactive.eai.rms.common.util.CommonUtil;
import com.eactive.eai.rms.onl.common.util.FileWriteUtil;
@Service("tranResultExtractService")
public class TranResultExtractService extends BaseService {
@Autowired
private TranResultExtractDao tranResultExtractDao;
@Autowired
private MonitoringContext monitoringContext;
public void tranResultExtract() throws Exception {
/** TargetDatasource Setting **/
List<DataSourceType> datasourceList = new ArrayList<>();
datasourceList.add(DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.EAI));
datasourceList.add(DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.FEP));
/** YesterDay & TableName **/
String yesterday = CommonUtil.getDiffHourDate(DatetimeUtil.getCurrentDate(), -24, "");
String tranDay = yesterday.substring(0, 8);
String tableName = "TSEAILG1" + DatetimeUtil.getDayOfWeekNum(DatetimeUtil.getLongTimeFormat("yyyyMMddHHmmss", yesterday));
for(DataSourceType datasource : datasourceList) {
DataSourceContextHolder.setDataSourceType(datasource);
logger.debug("Job datasource name : " + datasource.getName());
HashMap paramMap = new HashMap<>();
paramMap.put("serviceType", datasource.getName());
paramMap.put("tableName", tableName);
paramMap.put("tranDay", tranDay);
List<String> tranResultList = tranResultExtractDao.selectTranResultList(paramMap);
logger.debug("Query result : " + tranResultList.toString());
if(tranResultList.size() == 0) { continue; }
String directory = monitoringContext.getStringProperty(MonitoringContext.FILE_PATH_KEY);
/** TODO serverType **/
String serverType = CommonConstants.SERVER_TYPE.equals(CommonConstants.DB_MANAGE_TYPE_S)? CommonConstants.DB_MANAGE_TYPE_T : CommonConstants.SERVER_TYPE;
/** TODO serverType **/
String sendFileName = "IF_TRAN_" + serverType + "_" + datasource.getName() + "_" + tranDay + ".dat";
String sendFileContent = makeSendFileContent(tranResultList);
String checkFileName = sendFileName + ".chk";
String checkFileContent = makeCheckFileContent(sendFileName);
/** validation **/
if(!directory.endsWith("/")) { directory += "/"; }
boolean matches = sendFileName.matches("IF_TRAN_(T|D|P)_(EAI|FEP)_([0-9]{8}).dat");
if(!matches) {
throw new Exception("File Name invaild : " + sendFileName);
}
logger.debug("File directory : " + directory);
logger.debug("Send File name : " + sendFileName);
logger.debug("Send File content : " + sendFileContent);
logger.debug("Check File name : " + checkFileName);
logger.debug("Check File content : " + checkFileContent);
FileWriteUtil.FileWrite(directory, sendFileName, sendFileContent);
FileWriteUtil.FileWrite(directory, checkFileName, checkFileContent);
}
}
private String makeSendFileContent(List<String> tranResultList) {
StringBuilder sb = new StringBuilder();
for(String tranResult : tranResultList) {
sb.append(tranResult);
if(!(tranResultList.indexOf(tranResult) == tranResultList.size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
private String makeCheckFileContent(String sendFileName) {
String sendInterfaceId = monitoringContext.getStringProperty(MonitoringContext.SEND_IF_KEY);
String baseDate = ""; // empty 8
String recNum = ""; // empty 10
String status = "0";
return new StringBuilder()
.append(spacing(sendInterfaceId, 30))
.append(spacing(baseDate, 8))
.append(spacing(recNum, 10))
.append(status)
.append(sendFileName)
.append("@@").toString();
}
private String spacing(String str, int length) {
StringBuilder sb = new StringBuilder();
sb.append(str);
for(int i = str.length(); i < length; i++ ) {
sb.append(" ");
}
return sb.toString();
}
}
@@ -0,0 +1,39 @@
package com.eactive.eai.rms.ext.user.sync;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfiguration {
@Bean
public HttpClient httpClient() {
HttpClient httpClient =
HttpClientBuilder.create()
.setMaxConnTotal(50)
.setMaxConnPerRoute(20)
.build();
return httpClient;
}
@Bean
public HttpComponentsClientHttpRequestFactory factory(HttpClient httpClient) {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
return factory;
}
@Bean
public RestTemplate restTemplate(HttpComponentsClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(factory);
return restTemplate;
}
}