Files
mgm-daylight-mcrm-api-mobile/src/main/java/com/mgm/mcrm/common/constants/SysCommon.java
T
2026-09-15 17:04:06 +08:00

675 lines
24 KiB
Java

package com.mgm.mcrm.common.constants;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.mgm.mcrm.appsetting.models.SysSetting;
import com.mgm.mcrm.authorization.dtos.LoginUserInfo;
import com.mgm.mcrm.authorization.models.SysUser;
import com.mgm.mcrm.booking.services.BookingService;
import com.mgm.mcrm.common.dtos.config.APIConfig;
import com.mgm.mcrm.common.dtos.msg.AppSettingMsgData;
import com.mgm.mcrm.common.dtos.msg.UpdateCfgItem;
import com.mgm.mcrm.common.dtos.system.AppServerState;
import com.mgm.mcrm.common.utils.LogUtil;
import com.mgm.mcrm.common.utils.NetworkUtil;
import com.mgm.mcrm.logging.models.SysLogLogin;
import com.mgm.mcrm.logging.models.SysLogOperation;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.MessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.support.RequestContextUtils;
import java.io.*;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
public class SysCommon {
public static String runtime_path = "";
public static String serverIp="";
public static String serverName="";
public static boolean dbDebugLog = false;
public static boolean apiDebugLog = false;
public static boolean appDebugLog = false;
public static boolean mgmApiMockup =true;
public static boolean jmsRunning=false;
public static String defaultRouter = "welcome";
public static String runtimeName="crm_mobile_runtime";
public static int postTimeOut = 20;
//for stress test
public static int tokenExpMin = 5;
public static int refreshTokenExpDay = 30;
public static String tokenSecret = "SecretKeyWhichShouldBeLongEnoughToBeSecure67848563";
public static APIConfig apiConfig = new APIConfig();
private static Map<String,String> notifyTemplateMap = new HashMap<String,String>();
private static Map<String,AppServerState> appServerStates = new HashMap<String,AppServerState>();
private static List<String> allowOriginSource = new ArrayList<String>();
private static List<String> soapServers = new ArrayList<String>();
private static List<String> httpApiServers = new ArrayList<String>();
private static List<String> allowIPSource = new ArrayList<String>();
// @Autowired
private static MessageSource messageSource;
public static String getSystemPath() {
ApplicationHome h = new ApplicationHome(SysCommon.class);
File f = h.getSource();
return f.getParentFile().toString();
}
public static void initRuntimePath() {
runtime_path = getSystemPath();
}
public static boolean loadSystemConfig() {
boolean isLoaded = true;
Properties props = new Properties();
try {
initRuntimePath();
// load config from appconfig.properties
String configFile = runtime_path + "/crm_mobile_runtime/appconfig.properties";
InputStream inStream = new BufferedInputStream(new FileInputStream(configFile));
props.load(inStream);
//--Server Info
serverIp = NetworkUtil.getInternalIp();
serverName = NetworkUtil.getServerName();
loadAPIConfig(props);
} catch (Exception e) {
isLoaded = false;
LogUtil.error(SysCommon.class, "Load configuration error:" + e.getMessage());
} finally {
props.clear();
props = null;
}
return isLoaded;
}
public static void loadSettingsFromDB(List<SysSetting> sysSettings) {
System.out.println("[SysCommon][loadSettingsFromDB] Load settings from DB, setting size=" + sysSettings.size());
for(int i=0; i<sysSettings.size();i++) {
SysSetting setting = sysSettings.get(i);
if(setting.getSettingKey().equals("DB_DEBUG_LOG")) {
if(setting.getSettingValue().equals("1")) {
dbDebugLog = true;
}else {
dbDebugLog = false;
}
}
if(setting.getSettingKey().equals("API_DEBUG_LOG")) {
if(setting.getSettingValue().equals("1")) {
apiDebugLog = true;
}else {
apiDebugLog = false;
}
}
if(setting.getSettingKey().equals("APP_DEBUG_LOG")) {
if(setting.getSettingValue().equals("1")) {
appDebugLog = true;
}else {
appDebugLog = false;
}
}
if(setting.getSettingKey().equals("APP_MOCK")) {
if(setting.getSettingValue().equals("1")) {
mgmApiMockup = true;
}else {
mgmApiMockup = false;
}
}
if(setting.getSettingKey().equals("DEFAULT_ROUTER")) {
if(StringUtils.isNotBlank(setting.getSettingValue())) {
defaultRouter = setting.getSettingValue();
}
}
if(setting.getSettingKey().equals("POST_TIME_OUT")) {
if(StringUtils.isNotBlank(setting.getSettingValue())) {
postTimeOut = Integer.valueOf(setting.getSettingValue());
}
}
}
System.out.println("[SysCommon][loadSettingsFromDB] Loaded settings, DB_DEBUG_LOG=" + dbDebugLog + ", API_DEBUG_LOG="+apiDebugLog+", APP_DEBUG_LOG="+appDebugLog+", POST_TIME_OUT="+postTimeOut);
}
// --
public static MessageSource getMessageSource() {
return messageSource;
}
public static void setMessageSource(MessageSource messageSource) {
SysCommon.messageSource = messageSource;
}
public static String getMessage(String messageCode, String defaultMessage, HttpServletRequest request) {
return getMessage(messageCode, defaultMessage, resolveLocale(request));
}
public static String getMessage(String messageCode, String[] parasData, HttpServletRequest request) {
return getMessage(messageCode, parasData, resolveLocale(request));
}
public static String getMessage(String messageCode, String defaultMessage, Locale locale) {
return messageSource.getMessage(messageCode, null, defaultMessage, locale);
}
public static String getMessage(String messageCode, String[] parasData, Locale locale) {
return messageSource.getMessage(messageCode, parasData, locale);
}
public static Locale resolveLocale(HttpServletRequest request) {
return RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
}
public static String getStatusMessageByCode(int statusCode, String langType) {
String statusMessage = "";
Locale locale = Locale.US;
if (Strings.CI.equals("TC", langType)) {
locale = Locale.TAIWAN;
} else if (Strings.CI.equals("SC", langType)) {
locale = Locale.CHINA;
}
statusMessage = messageSource.getMessage("common.error_message.error_code_" + statusCode, null, locale);
return statusMessage;
}
public static String getMessageByLangType(String messageCode, String langType) {
String statusMessage = "";
Locale locale = Locale.US;
if (Strings.CI.equals("TC", langType)) {
locale = Locale.TAIWAN;
} else if (Strings.CI.equals("SC", langType)) {
locale = Locale.CHINA;
}
statusMessage = messageSource.getMessage(messageCode, null, locale);
return statusMessage;
}
public static SysLogOperation createLogOperationByRequest(HttpServletRequest request, String eventCode,Object operationObject, Object returnObject,String logMessage,int successFlag,Object oldDataObject) {
SysLogOperation sysLogOper = new SysLogOperation();
SysUser userInfo = (SysUser) request.getAttribute(SysConstants.CURRENT_USER_KEY);
if (userInfo != null) {
SysUser operUser = userInfo;
sysLogOper.setLoginId(operUser.getLoginId());
}
Date now = new Date();
sysLogOper.setOccurTime(now);
sysLogOper.setSortOccurtime(now.getTime());
sysLogOper.setIpAddress(NetworkUtil.getClientIpAddr(request));
sysLogOper.setEventCode(eventCode);
sysLogOper.setLogDesc(logMessage);
sysLogOper.setTagSuccess(successFlag);
//write request body && response body to db when "db debug log" turn on
if (operationObject != null && SysCommon.dbDebugLog) {
try {
String requestContent = "";
if (operationObject instanceof JSONObject || operationObject instanceof String) {
requestContent = operationObject.toString();
} else {
JSONObject contentObject = (JSONObject) JSONObject.toJSON(operationObject);
requestContent = contentObject.toString();
}
String oldContent = "";
if (oldDataObject != null) {
try {
if (oldDataObject instanceof JSONObject || oldDataObject instanceof String) {
oldContent = returnObject.toString();
} else {
JSONObject contentObject = (JSONObject) JSONObject.toJSON(oldDataObject);
oldContent = contentObject.toString();
}
} catch (Exception err) {
System.out.println("Convert old data error:" + err.getMessage());
}
}
requestContent = "Request Data: " + requestContent;
if(!oldContent.equals("")) {
requestContent += "; Old Data:" + oldContent;
}
sysLogOper.setRequestBody(requestContent);
} catch (Exception err) {
System.out.println("Convert request error:" + err.getMessage());
}
}
if (returnObject != null && SysCommon.dbDebugLog) {
try {
String responseContent = "";
if (returnObject instanceof JSONObject || returnObject instanceof String) {
responseContent = returnObject.toString();
} else {
JSONObject contentObject = (JSONObject) JSONObject.toJSON(returnObject);
responseContent = contentObject.toString();
}
sysLogOper.setResponseBody(responseContent);
} catch (Exception err) {
System.out.println("Conver response error:" + err.getMessage());
}
}
return sysLogOper;
}
public static SysLogLogin createLogLoginByRequest(HttpServletRequest request, String eventCode,Object operationObject, Object returnObject,String logMessage,int successFlag,Object oldDataObject) {
SysLogLogin sysLogLogin = new SysLogLogin();
SysUser userInfo = (SysUser) request.getAttribute(SysConstants.CURRENT_USER_KEY);
if (userInfo != null) {
SysUser operUser = userInfo;
sysLogLogin.setLoginId(operUser.getLoginId());
}else {
SysUser operUser = (SysUser)operationObject;
sysLogLogin.setLoginId(operUser.getLoginId());
sysLogLogin.setTransId(operUser.getLoginId());
}
Date now = new Date();
sysLogLogin.setOccurTime(now);
sysLogLogin.setSortOccurtime(now.getTime());
sysLogLogin.setIpAddress(NetworkUtil.getClientIpAddr(request));
sysLogLogin.setEventCode(eventCode);
sysLogLogin.setLogDesc(logMessage);
sysLogLogin.setTagSuccess(successFlag);
//write request body && response body to db when "db debug log" turn on
if (operationObject != null && SysCommon.dbDebugLog) {
try {
String requestContent = "";
if (operationObject instanceof JSONObject || operationObject instanceof String) {
requestContent = operationObject.toString();
} else {
JSONObject contentObject = (JSONObject) JSONObject.toJSON(operationObject);
requestContent = contentObject.toString();
}
String oldContent = "";
if (oldDataObject != null) {
try {
if (oldDataObject instanceof JSONObject || oldDataObject instanceof String) {
oldContent = returnObject.toString();
} else {
JSONObject contentObject = (JSONObject) JSONObject.toJSON(oldDataObject);
oldContent = contentObject.toString();
}
} catch (Exception err) {
System.out.println("Convert old data error:" + err.getMessage());
}
}
requestContent = "Request Data: " + requestContent;
if(!oldContent.equals("")) {
requestContent += "; Old Data:" + oldContent;
}
sysLogLogin.setRequestBody(requestContent);
} catch (Exception err) {
System.out.println("Convert request error:" + err.getMessage());
}
}
if (returnObject != null && SysCommon.dbDebugLog) {
try {
String responseContent = "";
if (returnObject instanceof JSONObject || returnObject instanceof String) {
responseContent = returnObject.toString();
} else {
JSONObject contentObject = (JSONObject) JSONObject.toJSON(returnObject);
responseContent = contentObject.toString();
}
sysLogLogin.setResponseBody(responseContent);
} catch (Exception err) {
System.out.println("Conver response error:" + err.getMessage());
}
}
return sysLogLogin;
}
public static boolean convertBeanDatetimeProperty(Object srcObject, Object targetObject,
String dateTimePropertyName, String dateTimeFormat) {
boolean isSuccess = true;
if (StringUtils.isBlank(dateTimeFormat)) {
dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat dtFormat = new SimpleDateFormat(dateTimeFormat);
Class sourceClass = srcObject.getClass();
Class targetClass = targetObject.getClass();
Field srcPropField = null;
Field targetPropField = null;
try {
srcPropField = sourceClass.getDeclaredField(dateTimePropertyName);
} catch (Exception err) {
srcPropField = null;
}
if (srcPropField == null && sourceClass.getSuperclass() != null) {
try {
srcPropField = sourceClass.getSuperclass().getDeclaredField(dateTimePropertyName);
} catch (Exception err) {
srcPropField = null;
}
}
try {
targetPropField = targetClass.getDeclaredField(dateTimePropertyName);
} catch (Exception err) {
targetPropField = null;
}
if (targetPropField == null && targetClass.getSuperclass() != null) {
try {
targetPropField = targetClass.getSuperclass().getDeclaredField(dateTimePropertyName);
} catch (Exception err) {
targetPropField = null;
}
}
if (srcPropField != null && targetPropField != null) {
srcPropField.setAccessible(true);
targetPropField.setAccessible(true);
try {
Object dateTimeVal = srcPropField.get(srcObject);
if (dateTimeVal != null && StringUtils.isNotBlank(dateTimeVal.toString())) {
Date dateTimeObject = dtFormat.parse(dateTimeVal.toString());
targetPropField.set(targetObject, dateTimeObject);
}
} catch (Exception err) {
isSuccess = false;
}
} else {
isSuccess = false;
}
return isSuccess;
}
public static boolean isSysAdmin(String sysUserId) {
return Strings.CS.equals(SysConstants.SUPER_ADMIN_ID, sysUserId);
}
public static String getRuntime_path() {
return runtime_path;
}
public static void setRuntime_path(String runtime_path) {
SysCommon.runtime_path = runtime_path;
}
// Load API Config
public static boolean loadAPIConfig(Properties props) {
boolean isLoaded = true;
// ESB
SysCommon.apiConfig.setServerUrl_ESB(props.getProperty("esb_server", ""));
SysCommon.apiConfig.setApiKey_ESB(props.getProperty("esb_app_id", ""));
SysCommon.apiConfig.setApiSecret_ESB(props.getProperty("esb_app_secret", ""));
try {
SysCommon.apiConfig.setTimeout_ESB(Integer.parseInt(props.getProperty("esb_request_timeout", "30000")));
} catch (Exception err) {
SysCommon.apiConfig.setTimeout_ESB(0);
}
// OWS
SysCommon.apiConfig.setServerUrl_OWS(props.getProperty("ows_server", ""));
try {
SysCommon.apiConfig.setTimeout_OWS(Integer.parseInt(props.getProperty("ows_request_timeout", "30000")));
} catch (Exception err) {
SysCommon.apiConfig.setTimeout_OWS(0);
}
// RPA
SysCommon.apiConfig.setServerLoginUrl_RPA(props.getProperty("rpa_login_server", ""));
SysCommon.apiConfig.setApiAccessName_RPA(props.getProperty("rpa_username", ""));
SysCommon.apiConfig.setApiAccessPassword_RPA(props.getProperty("rpa_password", ""));
SysCommon.apiConfig.setApiAccessKey_RPA(props.getProperty("rpa_apiKey", ""));
SysCommon.apiConfig.setServerAddUrl_RPA(props.getProperty("rpa_add_server", ""));
SysCommon.apiConfig.setServerExtensionUrl_RPA(props.getProperty("rpa_extension_server", ""));
// SSO
SysCommon.apiConfig.setServerUrl_SSO(props.getProperty("idp_server", ""));
SysCommon.apiConfig.setClientId_SSO(props.getProperty("idp_client_id", ""));
SysCommon.apiConfig.setClientSecret_SSO(props.getProperty("idp_client_secret", ""));
//SMS Config
SysCommon.apiConfig.setTokenUrl_SMS(props.getProperty("sms_token_url", ""));
SysCommon.apiConfig.setSendUrl_SMS(props.getProperty("sms_send_url", ""));
SysCommon.apiConfig.setUsername_SMS(props.getProperty("sms_username", ""));
SysCommon.apiConfig.setPassword_SMS(props.getProperty("sms_password", ""));
SysCommon.apiConfig.setAccount_SMS(props.getProperty("sms_account", ""));
SysCommon.apiConfig.setPriority_SMS(props.getProperty("sms_priority", ""));
//SMS Config
SysCommon.apiConfig.setPort_SMTP(props.getProperty("mail_port", ""));
SysCommon.apiConfig.setHost_SMTP(props.getProperty("mail_smtp_host", ""));
SysCommon.apiConfig.setUsername_SMTP(props.getProperty("mail_sender", ""));
SysCommon.apiConfig.setPassword_SMTP(props.getProperty("mail_sender_password", ""));
SysCommon.apiConfig.setSend_to_SMTP(props.getProperty("mail_send_to", ""));
LogUtil.info(SysCommon.class, "Loaded API config.");
return isLoaded;
}
//-- Path Type 1= Class path 2=Application path 3=URI Path
public static String loadResFileContentByPath(String filePath, int pathType) {
String fileContent = "";
InputStream ifs = null;
BufferedReader bufferedReader = null;
InputStreamReader fileReader = null;
try {
if(pathType==2) {
String applicationPath = SysCommon.runtime_path+"/"+runtimeName;
File dataFile = new File(applicationPath+filePath);
ifs=new FileInputStream(dataFile);
}else {
Resource resource = new ClassPathResource(filePath);
ifs = resource.getInputStream();
}
fileReader = new InputStreamReader(ifs, "UTF-8");
bufferedReader = new BufferedReader(fileReader);
String lineData = null;
int lineCnt =0;
StringBuffer contentBuffer = new StringBuffer();
while ((lineData = bufferedReader.readLine()) != null) {
if(lineCnt>0) {
contentBuffer.append("\n");
}
contentBuffer.append(lineData);
lineCnt++;
}
bufferedReader.close();
fileContent = contentBuffer.toString();
} catch (Exception e) {
//e.printStackTrace();
//LogUtil.error(SysCommon.class, "Get Data File failed:"+e.getMessage());
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if(fileReader!=null) {
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//--
return fileContent;
}
public static AppServerState refreshAppServerState() {
AppServerState currentState = new AppServerState();
currentState.setServerIp(SysCommon.serverIp);
currentState.setHostName(SysCommon.serverName);
currentState.setServerType("MOBILE");
currentState.setApiDebugLog(SysCommon.apiDebugLog);
currentState.setDbDebugLog(SysCommon.dbDebugLog);
currentState.setAppDebugLog(SysCommon.appDebugLog);
appServerStates.put(currentState.getServerType()+"-"+SysCommon.serverIp, currentState);
return currentState;
}
public static void registerServerInfo(AppServerState serverInfo) {
if(serverInfo!=null && (!Strings.CS.equals(serverIp, serverInfo.getServerIp()) || !Strings.CS.equals("MOBILE", serverInfo.getServerType()) )) {
appServerStates.put(serverInfo.getServerType()+"-"+serverInfo.getServerIp(), serverInfo);
}
}
public static AppServerState updateCfgByRequest(AppSettingMsgData updateRequest) {
if(updateRequest!=null) {
List<UpdateCfgItem> cfgItems = updateRequest.getConfigItems();
if(cfgItems!=null) {
for(UpdateCfgItem cfgItem:cfgItems) {
if(Strings.CS.equals("dbDebugLog", cfgItem.getCfgItemKey())) {
SysCommon.dbDebugLog= Boolean.parseBoolean(cfgItem.getCfgItemValue());
}else if(Strings.CS.equals("apiDebugLog", cfgItem.getCfgItemKey())) {
SysCommon.apiDebugLog= Boolean.parseBoolean(cfgItem.getCfgItemValue());
}else if(Strings.CS.equals("appDebugLog", cfgItem.getCfgItemKey())) {
SysCommon.appDebugLog= Boolean.parseBoolean(cfgItem.getCfgItemValue());
}
}
}
}
return refreshAppServerState();
}
public static LoginUserInfo parseUserFromToken(HttpServletRequest request) {
LoginUserInfo loginUser = null;
String token = request.getHeader("Authorization");
if(StringUtils.isNotBlank(token)) {
try {
// token = token.substring(6);
loginUser = parseUserFromToken(token);
}catch(Exception err) {
LogUtil.error(SysCommon.class, "Parse Token failed:"+err.getMessage());
loginUser =null;
}
}
return loginUser;
}
public static LoginUserInfo parseUserFromToken(String tokenContent) {
LoginUserInfo loginUser = null;
if(StringUtils.isNotBlank(tokenContent)) {
try {
tokenContent = tokenContent.replace("Bearer ", "");
DecodedJWT decodeData = JWT.decode(tokenContent);
loginUser = new LoginUserInfo();
String userId = decodeData.getSubject();
if(StringUtils.isNotBlank(userId)) {
loginUser.setId(Long.parseLong(userId));
}else {
loginUser.setId(-1L);
}
loginUser.setLoginId(decodeData.getClaim("login_id").asString());
loginUser.setGroupName(decodeData.getClaim("user_group").asString());
}catch(Exception err) {
LogUtil.error(SysCommon.class, "Parse Token failed:"+err.getMessage());
loginUser =null;
}
}
return loginUser;
}
public static void loadSecurityConfig(String allowOrigins) {
if(allowOrigins!=null) {
String[] serverLists = allowOrigins.split(",");
if(serverLists!=null) {
for(String item:serverLists) {
if(StringUtils.isNotBlank(item)) {
addAllowOriginSource(item.trim());
}
}
}
}
}
public static void addAllowOriginSource(String srcServer) {
allowOriginSource.add(srcServer);
}
public static boolean isAllowOriginSource(String srcServer) {
boolean isAllow = false;
if(StringUtils.isNotBlank(srcServer)) {
for(String allowItem:allowOriginSource) {
if(Strings.CI.startsWith(srcServer, allowItem)) {
isAllow=true;
break;
}
}
}
return isAllow;
}
public static void loadSoapServerConfig(String soapConfig) {
if(soapConfig!=null) {
String[] serverLists = soapConfig.split(",");
if(serverLists!=null) {
for(String item:serverLists) {
if(StringUtils.isNotBlank(item)) {
addSoapServer(item.trim());
}
}
}
}
}
public static void addSoapServer(String srcServer) {
soapServers.add(srcServer);
}
public static boolean isAllowSoapServer(String srcServer) {
boolean isAllow = false;
if(StringUtils.isNotBlank(srcServer)) {
for(String allowItem:soapServers) {
if(Strings.CI.startsWith(srcServer, allowItem)) {
isAllow=true;
break;
}
}
}
return isAllow;
}
public static void loadApiServerConfig(String apiServerConfig) {
if(apiServerConfig!=null) {
String[] serverLists = apiServerConfig.split(",");
if(serverLists!=null) {
for(String item:serverLists) {
if(StringUtils.isNotBlank(item)) {
addApiServer(item.trim());
}
}
}
}
}
public static void addApiServer(String srcServer) {
httpApiServers.add(srcServer);
}
public static boolean isAllowApiServer(String srcServer) {
boolean isAllow = false;
if(StringUtils.isNotBlank(srcServer)) {
for(String allowItem:httpApiServers) {
if(Strings.CI.startsWith(srcServer, allowItem)) {
isAllow=true;
break;
}
}
}
return isAllow;
}
public static void loadAllowIPConfig(String allowIPConfig) {
if(allowIPConfig!=null) {
String[] ipLists = allowIPConfig.split(",");
if(ipLists!=null) {
for(String item:ipLists) {
if(StringUtils.isNotBlank(item)) {
addAllowIP(item.trim());
}
}
}
}
}
public static void addAllowIP(String allowIP) {
allowIPSource.add(allowIP);
}
public static boolean isAllowIPSource(String ip) {
boolean isAllow = false;
if(StringUtils.isNotBlank(ip)) {
for(String allowItem:allowIPSource) {
LogUtil.info(BookingService.class,"[isAllowIPSource]allow item:"+allowItem);
if(Strings.CI.startsWith(ip, allowItem)) {
isAllow=true;
break;
}
}
}
return isAllow;
}
}