This commit is contained in:
Mauve
2026-09-28 10:28:04 +08:00
parent 5ad104bdd7
commit 3b6f0495a3
94 changed files with 2941 additions and 2975 deletions
@@ -0,0 +1,125 @@
package com.mgm.mcrm.common.config;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApiGatewayConfig {
@Value("${api-gateway.base-url}")
private String serverUrl;
@Value("${api-gateway.request-timeout-ms:60000}")
private int apiRequestTimeout;
//-- Daylight
@Value("${api-gateway.daylight.proxy-path}")
private String daylightProxyPath;
@Value("${api-gateway.daylight.app-id}")
private String daylightAppId;
@Value("${api-gateway.daylight.auth-code}")
private String daylightAppSecret;
@Value("${api-gateway.daylight.system-id}")
private String daylightSystemId;
//-- Opera
@Value("${api-gateway.opera.proxy-path}")
private String operaProxyPath;
@Value("${api-gateway.daylight.app-id}")
private String operaAppId;
@Value("${api-gateway.daylight.auth-code}")
private String operaAppSecret;
//-- ESB MCRM
@Value("${api-gateway.esb-mcrm.proxy-path}")
private String esbMcrmProxyPath;
@Value("${api-gateway.esb-mcrm.app-id}")
private String esbMcrmAppId;
@Value("${api-gateway.esb-mcrm.auth-code}")
private String esbMcrmAppSecret;
//-- ESB Limo
@Value("${api-gateway.esb-limo.proxy-path}")
private String esbLimoProxyPath;
@Value("${api-gateway.esb-limo.app-id}")
private String esbLimoAppId;
@Value("${api-gateway.esb-limo.auth-code}")
private String esbLimoAppSecret;
//-- Limo
@Value("${api-gateway.limo.proxy-path}")
private String limoProxyPath;
@Value("${api-gateway.limo.app-id}")
private String limoAppId;
@Value("${api-gateway.limo.auth-code}")
private String limoAppSecret;
@Value("${api-gateway.limo.main-handle-url}")
private String limoMainHandleUrl;
@Value("${api-gateway.limo.access-account}")
private String limoAccessAccount;
@Value("${api-gateway.limo.access-password}")
private String limoAccessPassword;
@Value("${api-gateway.limo.token-expiry-seconds:60}")
private int limoTokenExpirySeconds;
//-- Notification
@Value("${api-gateway.notification.proxy-path}")
private String notificationProxyPath;
@Value("${api-gateway.notification.app-id}")
private String notificationAppId;
@Value("${api-gateway.notification.auth-code}")
private String notificationAppSecret;
@Bean
public ApiGatewaySetting configApiGateway() {
ApiGatewaySetting config = new ApiGatewaySetting();
config.setBaseUrl(serverUrl);
config.setRequestTimeout(apiRequestTimeout);
config.setDaylightProxyUrl(serverUrl+daylightProxyPath);
config.setDaylightAppId(daylightAppId);
config.setDaylightAppSecret(daylightAppSecret);
config.setDaylightSystemId(daylightSystemId);
config.setOperaProxyUrl(serverUrl+operaProxyPath);
config.setOperaAppId(operaAppId);
config.setOperaAppSecret(operaAppSecret);
config.setEsbMcrmProxyUrl(serverUrl+esbMcrmProxyPath);
config.setEsbMcrmAppId(esbMcrmAppId);
config.setEsbMcrmAppSecret(esbMcrmAppSecret);
config.setEsbLimoProxyUrl(serverUrl+esbLimoProxyPath);
config.setEsbLimoAppId(esbLimoAppId);
config.setEsbLimoAppSecret(esbLimoAppSecret);
config.setLimoProxyUrl(serverUrl+limoProxyPath);
config.setLimoAppId(limoAppId);
config.setLimoAppSecret(limoAppSecret);
config.setLimoMainHandleUrl(limoMainHandleUrl);
config.setLimoAccessAccount(limoAccessAccount);
config.setLimoAccessPassword(limoAccessPassword);
config.setLimoTokenExpirySecond(limoTokenExpirySeconds);
config.setNotificationProxyUrl(serverUrl+notificationProxyPath);
config.setNotificationAppId(notificationAppId);
config.setNotificationAppSecret(notificationAppSecret);
//--
return config;
}
}
@@ -4,11 +4,11 @@ import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.hibernate.autoconfigure.HibernateProperties;
import org.springframework.boot.hibernate.autoconfigure.HibernateSettings;
import org.springframework.boot.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.jpa.autoconfigure.JpaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@@ -51,7 +51,7 @@ public class MGMDataSourceConfig {
@Primary
@Bean(name = "entityManagerFactory") //mrbs实体工厂
public LocalContainerEntityManagerFactoryBean entityManagerFactory (@Qualifier("mgmDataSource") DataSource mgmDataSource,
@Qualifier("mgmJpaProperties") JpaProperties jpaProperties,EntityManagerFactoryBuilder builder) {
@Qualifier("mgmJpaProperties") JpaProperties jpaProperties, EntityManagerFactoryBuilder builder) {
return builder.dataSource(mgmDataSource)
.properties(jpaProperties.getProperties())
.properties(
@@ -4,11 +4,11 @@ import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.hibernate.autoconfigure.HibernateProperties;
import org.springframework.boot.hibernate.autoconfigure.HibernateSettings;
import org.springframework.boot.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.jpa.autoconfigure.JpaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@@ -46,7 +46,7 @@ public class OperaDataSourceConfig {
@Bean(name = "entityManagerFactoryOpera")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryOpera (@Qualifier("operaDataSource") DataSource operaDataSource,
@Qualifier("operaJpaProperties") JpaProperties jpaProperties,EntityManagerFactoryBuilder builder) {
@Qualifier("operaJpaProperties") JpaProperties jpaProperties, EntityManagerFactoryBuilder builder) {
return builder.dataSource(operaDataSource)
.properties(jpaProperties.getProperties())
.properties(
@@ -46,14 +46,13 @@ public class SysCommon {
//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>();
private static final Map<String,AppServerState> appServerStates = new HashMap<String,AppServerState>();
private static final List<String> allowOriginSource = new ArrayList<String>();
private static final List<String> soapServers = new ArrayList<String>();
private static final List<String> httpApiServers = new ArrayList<String>();
private static final List<String> allowIPSource = new ArrayList<String>();
// @Autowired
private static MessageSource messageSource;
@@ -67,7 +66,7 @@ public class SysCommon {
runtime_path = getSystemPath();
}
public static boolean loadSystemConfig() {
public static void loadSystemConfig() {
boolean isLoaded = true;
Properties props = new Properties();
try {
@@ -87,7 +86,6 @@ public class SysCommon {
props.clear();
props = null;
}
return isLoaded;
}
public static void loadSettingsFromDB(List<SysSetting> sysSettings) {
@@ -384,42 +382,8 @@ public class SysCommon {
}
// Load API Config
public static boolean loadAPIConfig(Properties props) {
public static void 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", ""));
@@ -428,7 +392,6 @@ public class SysCommon {
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
@@ -6,53 +6,7 @@ import lombok.Data;
public class APIConfig {
private boolean isLoaded = false;
//-- ESB Server
private String serverUrl_ESB= "";
private String apiKey_ESB="";
private String apiSecret_ESB="";
private int timeout_ESB=0;
private String limoService_ESB="";
private String limoApp_id="";
private String limoApp_key="";
private String serverUrl_ESB_Daylight="";
private String apiKey_ESB_Daylight="";
private String apiSecret_ESB_Daylight="";
private int timeout_ESB_Daylight=0;
//-- OWS Server
private String serverUrl_OWS= "";
private int timeout_OWS=0;
//-- RPA Server
private String serverLoginUrl_RPA= "";
private String apiAccessName_RPA="";
private String apiAccessPassword_RPA="";
private String apiAccessKey_RPA="";
private String serverAddUrl_RPA= "";
private String serverExtensionUrl_RPA= "";
private int timeout_RPA=0;
//-- SSO Server
private String serverUrl_SSO= "";
private String clientId_SSO="";
private String clientSecret_SSO="";
private int timeout_SSO=0;
//-- CallCenter Server
private String serverUrl_CallCenter= "";
private int timeout_CallCenter=0;
//SMS Config
private String tokenUrl_SMS= "";
private String sendUrl_SMS= "";
private String username_SMS= "";
private String password_SMS= "";
private String account_SMS= "";
private String priority_SMS= "";
//SMTP Config
private String port_SMTP= "";
private String host_SMTP= "";
@@ -0,0 +1,32 @@
package com.mgm.mcrm.common.dtos.config;
import lombok.Data;
@Data
public class ApiGatewaySetting {
private String baseUrl;
private int requestTimeout=30000;
private String daylightProxyUrl;
private String daylightSystemId;
private String daylightAppId;
private String daylightAppSecret;
private String operaProxyUrl;
private String operaAppId;
private String operaAppSecret;
private String esbMcrmProxyUrl;
private String esbMcrmAppId;
private String esbMcrmAppSecret;
private String esbLimoProxyUrl;
private String esbLimoAppId;
private String esbLimoAppSecret;
private String limoProxyUrl;
private String limoAppId;
private String limoAppSecret;
private String limoMainHandleUrl;
private String limoAccessAccount;
private String limoAccessPassword;
private int limoTokenExpirySecond;
private String notificationProxyUrl;
private String notificationAppId;
private String notificationAppSecret;
}
@@ -1,25 +1,32 @@
package com.mgm.mcrm.common.dtos.mgm_api;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ApproverRecord {
private String EmployeeId = null;
private String EmployeeName = null;
@JSONField(name = "EmployeeId")
@JsonProperty("employeeId")
private String employeeId = null;
@JSONField(name = "EmployeeName")
@JsonProperty("employeeName")
private String employeeName = null;
public String getEmployeeId() {
return EmployeeId;
return employeeId;
}
public void setEmployeeId(String employeeId) {
EmployeeId = employeeId;
this.employeeId = employeeId;
}
public String getEmployeeName() {
return EmployeeName;
return employeeName;
}
public void setEmployeeName(String employeeName) {
EmployeeName = employeeName;
this.employeeName = employeeName;
}
}
@@ -2,6 +2,8 @@ package com.mgm.mcrm.common.dtos.mgm_api;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
@@ -9,73 +11,117 @@ import java.util.List;
public class ApproverRecordResult {
private String PlayerId = null;
private String BookingType = null;
private String Property = null;
private String RoomCategory = null;
private String StartDate = null;
private String EndDate = null;
private String ApprovalRoutingType = null;
private String ApprovalRoutingMessage = null;
private Object ApproverList;
@JSONField(name = "PlayerId")
private String playerId = null;
@JSONField(name = "BookingType")
private String bookingType = null;
@JSONField(name = "Property")
private String property = null;
@JSONField(name = "RoomCategory")
private String roomCategory = null;
@JSONField(name = "StartDate")
private String startDate = null;
@JSONField(name = "EndDate")
private String endDate = null;
@JSONField(name = "ApprovalRoutingType")
private String approvalRoutingType = null;
@JSONField(name = "ApprovalRoutingMessage")
private String approvalRoutingMessage = null;
@JSONField(name = "ApproverList")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Object approverListRaw;
public String getPlayerId() {
return PlayerId;
return playerId;
}
public void setPlayerId(String playerId) {
PlayerId = playerId;
this.playerId = playerId;
}
public String getBookingType() {
return BookingType;
return bookingType;
}
public void setBookingType(String bookingType) {
BookingType = bookingType;
this.bookingType = bookingType;
}
public String getProperty() {
return Property;
return property;
}
public void setProperty(String property) {
Property = property;
this.property = property;
}
public String getRoomCategory() {
return RoomCategory;
return roomCategory;
}
public void setRoomCategory(String roomCategory) {
RoomCategory = roomCategory;
this.roomCategory = roomCategory;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getApprovalRoutingType() {
return ApprovalRoutingType;
return approvalRoutingType;
}
public void setApprovalRoutingType(String approvalRoutingType) {
ApprovalRoutingType = approvalRoutingType;
this.approvalRoutingType = approvalRoutingType;
}
public String getApprovalRoutingMessage() {
return ApprovalRoutingMessage;
return approvalRoutingMessage;
}
public void setApprovalRoutingMessage(String approvalRoutingMessage) {
ApprovalRoutingMessage = approvalRoutingMessage;
this.approvalRoutingMessage = approvalRoutingMessage;
}
@JSONField(name = "ApproverList")
public void setApproverList(Object approverList) {
this.approverListRaw = approverList;
}
@JsonProperty("approverList")
@JSONField(serialize = false, deserialize = false)
public List<ApproverRecord> getApproverList() {
if (ApproverList == null) {
return parseApproverList(approverListRaw);
}
private static List<ApproverRecord> parseApproverList(Object raw) {
if (raw == null) {
return new ArrayList<ApproverRecord>();
}
if (ApproverList instanceof JSONArray arr) {
if (raw instanceof List<?> list && !list.isEmpty() && list.getFirst() instanceof ApproverRecord) {
List<ApproverRecord> result = new ArrayList<ApproverRecord>();
for (Object item : list) {
result.add((ApproverRecord) item);
}
return result;
}
if (raw instanceof JSONArray arr) {
return arr.toJavaList(ApproverRecord.class);
}
if (ApproverList instanceof String s) {
if (raw instanceof String s) {
s = s.trim();
if (s.isEmpty()) {
return new ArrayList<ApproverRecord>();
@@ -83,20 +129,7 @@ public class ApproverRecordResult {
JSONArray arr = JSONArray.parseArray(s);
return arr == null ? new ArrayList<ApproverRecord>() : arr.toJavaList(ApproverRecord.class);
}
// List/Map 等其它情况:统一转成 JSON 再转回 List<ApproverRecord>
JSONArray arr = JSON.parseArray(JSON.toJSONString(ApproverList));
JSONArray arr = JSON.parseArray(JSON.toJSONString(raw));
return arr == null ? new ArrayList<ApproverRecord>() : arr.toJavaList(ApproverRecord.class);
}
public void setApproverList(List<ApproverRecord> approverList) {
ApproverList = approverList;
}
public void setApproverList(String approverList) {
ApproverList = approverList;
}
public void setApproverList(Object approverList) {
ApproverList = approverList;
}
}
@@ -1,5 +1,7 @@
package com.mgm.mcrm.common.dtos.mgm_api;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.ArrayList;
import java.util.List;
@@ -7,31 +9,34 @@ import java.util.List;
public class ApproverResult {
private String StatusCode = null;
private String StatusDescription=null;
private List<ApproverRecordResult> Records = new ArrayList<ApproverRecordResult>();
@JSONField(name = "StatusCode")
private String statusCode = null;
@JSONField(name = "StatusDescription")
private String statusDescription=null;
@JSONField(name = "Records")
private List<ApproverRecordResult> records = new ArrayList<ApproverRecordResult>();
public String getStatusCode() {
return StatusCode;
return statusCode;
}
public void setStatusCode(String statusCode) {
StatusCode = statusCode;
this.statusCode = statusCode;
}
public String getStatusDescription() {
return StatusDescription;
return statusDescription;
}
public void setStatusDescription(String statusDescription) {
StatusDescription = statusDescription;
this.statusDescription = statusDescription;
}
public List<ApproverRecordResult> getRecords() {
return Records;
return records;
}
public void setRecords(List<ApproverRecordResult> records) {
Records = records;
this.records = records;
}
}
@@ -7,7 +7,7 @@ import java.util.List;
public class TodoDateListRecord {
private String Date = null;
private String date = null;
private List<TodoListRecord> dateRecords = new ArrayList<TodoListRecord>();
public TodoDateListRecord() {
@@ -16,12 +16,12 @@ public class TodoDateListRecord {
public String getDate() {
return Date;
return date;
}
public void setDate(String date) {
Date = date;
this.date = date;
}
@@ -9,7 +9,7 @@ public class TodoDateListResult {
private String statusCode = null;
private String statusDescription=null;
private List<TodoDateListRecord> Records = new ArrayList<TodoDateListRecord>();
private List<TodoDateListRecord> records = new ArrayList<TodoDateListRecord>();
public TodoDateListResult() {
@@ -32,11 +32,11 @@ public class TodoDateListResult {
}
public List<TodoDateListRecord> getRecords() {
return Records;
return records;
}
public void setRecords(List<TodoDateListRecord> records) {
Records = records;
this.records = records;
}
}
@@ -1,33 +1,61 @@
package com.mgm.mcrm.common.dtos.mgm_api;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class TodoListRecord {
private String Date = null;
private String ActionDate = null;
private String OperaConfirmationNo = null;
private Integer PlayerId = null;
private String TierName = null;
private String ChineseName = null;
private String EnglishName = null;
private String Salutation = null;
private Integer HasArrivalRecord = null;
private Integer HasDepartureRecord = null;
private Integer HasInhouseRecord = null;
private Integer HasOthersRecord = null;
private Integer HasLimoRecord = null;
private Integer HasFlightRecord = null;
private String ETA = null;
@JSONField(name = "Date")
private String date = null;
@JSONField(name = "ActionDate")
private String actionDate = null;
@JSONField(name = "OperaConfirmationNo")
private String operaConfirmationNo = null;
@JSONField(name = "PlayerId")
private Integer playerId = null;
@JSONField(name = "TierName")
private String tierName = null;
@JSONField(name = "ChineseName")
private String chineseName = null;
@JSONField(name = "EnglishName")
private String englishName = null;
@JSONField(name = "Salutation")
private String salutation = null;
@JSONField(name = "HasArrivalRecord")
private Integer hasArrivalRecord = null;
@JSONField(name = "HasDepartureRecord")
private Integer hasDepartureRecord = null;
@JSONField(name = "HasInhouseRecord")
private Integer hasInhouseRecord = null;
@JSONField(name = "HasOthersRecord")
private Integer hasOthersRecord = null;
@JSONField(name = "HasLimoRecord")
private Integer hasLimoRecord = null;
@JSONField(name = "HasFlightRecord")
private Integer hasFlightRecord = null;
@JSONField(name = "ETA")
@JsonProperty("eta")
private String eta = null;
private Boolean roomReady = false;
private Boolean isQueue = false;
private Integer BigWinFlag = null;
private Integer BigLossFlag = null;
private Integer NoPlayFlag = null;
private Integer MAId = null;
private String MA = null;
private List<String> Descriptions = null;
@JSONField(name = "BigWinFlag")
private Integer bigWinFlag = null;
@JSONField(name = "BigLossFlag")
private Integer bigLossFlag = null;
@JSONField(name = "NoPlayFlag")
private Integer noPlayFlag = null;
@JSONField(name = "MAId")
@JsonProperty("maId")
private Integer maId = null;
@JSONField(name = "MA")
@JsonProperty("ma")
private String ma = null;
@JSONField(name = "Descriptions")
private List<String> descriptions = null;
public TodoListRecord() {
@@ -36,135 +64,147 @@ public class TodoListRecord {
public String getDate() {
return Date;
return date;
}
public void setDate(String date) {
Date = date;
this.date = date;
}
public String getActionDate() {
return ActionDate;
return actionDate;
}
public void setActionDate(String actionDate) {
ActionDate = actionDate;
this.actionDate = actionDate;
}
public String getOperaConfirmationNo() {
return OperaConfirmationNo;
return operaConfirmationNo;
}
public void setOperaConfirmationNo(String operaConfirmationNo) {
OperaConfirmationNo = operaConfirmationNo;
this.operaConfirmationNo = operaConfirmationNo;
}
public Integer getPlayerId() {
return PlayerId;
return playerId;
}
public void setPlayerId(Integer playerId) {
PlayerId = playerId;
this.playerId = playerId;
}
public String getTierName() {
return TierName;
return tierName;
}
public void setTierName(String tierName) {
TierName = tierName;
this.tierName = tierName;
}
public String getChineseName() {
return ChineseName;
return chineseName;
}
public void setChineseName(String chineseName) {
ChineseName = chineseName;
this.chineseName = chineseName;
}
public String getEnglishName() {
return EnglishName;
return englishName;
}
public void setEnglishName(String englishName) {
EnglishName = englishName;
this.englishName = englishName;
}
public String getSalutation() {
return Salutation;
return salutation;
}
public void setSalutation(String salutation) {
Salutation = salutation;
this.salutation = salutation;
}
public Integer getHasArrivalRecord() {
return HasArrivalRecord;
return hasArrivalRecord;
}
public void setHasArrivalRecord(Integer hasArrivalRecord) {
HasArrivalRecord = hasArrivalRecord;
this.hasArrivalRecord = hasArrivalRecord;
}
public Integer getHasDepartureRecord() {
return HasDepartureRecord;
return hasDepartureRecord;
}
public void setHasDepartureRecord(Integer hasDepartureRecord) {
HasDepartureRecord = hasDepartureRecord;
this.hasDepartureRecord = hasDepartureRecord;
}
public Integer getHasInhouseRecord() {
return HasInhouseRecord;
return hasInhouseRecord;
}
public void setHasInhouseRecord(Integer hasInhouseRecord) {
HasInhouseRecord = hasInhouseRecord;
this.hasInhouseRecord = hasInhouseRecord;
}
public Integer getHasOthersRecord() {
return HasOthersRecord;
return hasOthersRecord;
}
public void setHasOthersRecord(Integer hasOthersRecord) {
HasOthersRecord = hasOthersRecord;
this.hasOthersRecord = hasOthersRecord;
}
public Integer getHasLimoRecord() {
return HasLimoRecord;
return hasLimoRecord;
}
public void setHasLimoRecord(Integer hasLimoRecord) {
HasLimoRecord = hasLimoRecord;
this.hasLimoRecord = hasLimoRecord;
}
public Integer getHasFlightRecord() {
return HasFlightRecord;
return hasFlightRecord;
}
public void setHasFlightRecord(Integer hasFlightRecord) {
HasFlightRecord = hasFlightRecord;
this.hasFlightRecord = hasFlightRecord;
}
@JsonProperty("eta")
public String getEta() {
return eta;
}
@JsonProperty("eta")
public void setEta(String eta) {
this.eta = eta;
}
@JsonIgnore
public String getETA() {
return ETA;
return eta;
}
@JsonIgnore
public void setETA(String eTA) {
ETA = eTA;
this.eta = eTA;
}
public Boolean getRoomReady() {
@@ -184,56 +224,71 @@ public class TodoListRecord {
}
public Integer getBigWinFlag() {
return BigWinFlag;
return bigWinFlag;
}
public void setBigWinFlag(Integer bigWinFlag) {
BigWinFlag = bigWinFlag;
this.bigWinFlag = bigWinFlag;
}
public Integer getBigLossFlag() {
return BigLossFlag;
return bigLossFlag;
}
public void setBigLossFlag(Integer bigLossFlag) {
BigLossFlag = bigLossFlag;
this.bigLossFlag = bigLossFlag;
}
public Integer getNoPlayFlag() {
return NoPlayFlag;
return noPlayFlag;
}
public void setNoPlayFlag(Integer noPlayFlag) {
NoPlayFlag = noPlayFlag;
this.noPlayFlag = noPlayFlag;
}
@JsonProperty("maId")
public Integer getMaId() {
return maId;
}
@JsonIgnore
public Integer getMAId() {
return MAId;
return maId;
}
@com.fasterxml.jackson.annotation.JsonProperty("maId")
public Integer getCalendarMaId() {
return MAId;
public void setMaId(Integer maId) {
this.maId = maId;
}
public void setMAId(Integer mAId) {
MAId = mAId;
this.maId = mAId;
}
@JsonProperty("ma")
public String getMa() {
return ma;
}
@JsonIgnore
public String getMA() {
return MA;
return ma;
}
public void setMa(String ma) {
this.ma = ma;
}
public void setMA(String mA) {
MA = mA;
this.ma = mA;
}
public List<String> getDescriptions() {
return Descriptions;
return descriptions;
}
public void setDescriptions(List<String> descriptions) {
Descriptions = descriptions;
this.descriptions = descriptions;
}
@@ -30,27 +30,23 @@ public class ConfigHeaderFilter implements Filter {
if (response instanceof HttpServletResponse httpServletResponse) {
String origin = ((HttpServletRequest) request).getHeader("Origin");
if (StringUtils.isBlank(origin) && "127.0.0.1".equals(NetworkUtil.getClientIpAddr((HttpServletRequest) request))) {
httpServletResponse.setHeader("Access-Control-Allow-Origin", null);
String sanitizedOrigin = NetworkUtil.sanitizeCRLF(origin);
if (SysCommon.isAllowOriginSource(sanitizedOrigin) || "OPTIONS".equalsIgnoreCase(req.getMethod())) {
httpServletResponse.setHeader("Access-Control-Allow-Origin", sanitizedOrigin);
} else {
String sanitizedOrigin = NetworkUtil.encodePathWithSpring(origin);
if (SysCommon.isAllowOriginSource(sanitizedOrigin)) {
httpServletResponse.setHeader("Access-Control-Allow-Origin", sanitizedOrigin);
} else {
LogUtil.warn(ConfigHeaderFilter.class, "Origin of [" + sanitizedOrigin + "] is not allowed");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "");
log.warn("Blocked request: method={}, uri={}, query={}, origin={}, referer={}, ip={}, xff={}, userAgent={}",
req.getMethod(),
req.getRequestURI(),
req.getQueryString(),
req.getHeader("Origin"),
req.getHeader("Referer"),
req.getRemoteAddr(),
req.getHeader("X-Forwarded-For"),
req.getHeader("User-Agent"));
LogUtil.warn(ConfigHeaderFilter.class, "Origin of [" + sanitizedOrigin + "] is not allowed");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "");
log.warn("Blocked request: method={}, uri={}, query={}, origin={}, referer={}, ip={}, xff={}, userAgent={}",
req.getMethod(),
req.getRequestURI(),
req.getQueryString(),
req.getHeader("Origin"),
req.getHeader("Referer"),
req.getRemoteAddr(),
req.getHeader("X-Forwarded-For"),
req.getHeader("User-Agent"));
return;
}
return;
}
httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,ClientId,Refreshtoken");
@@ -60,7 +60,7 @@ public class BookingScheduleJob {
ArrayList bookIds = new ArrayList();
for(Bookings b:bookings) {
List <GamingData> getGaming = waitlistBookingService.findGamingDataByBookId(b.getId());
if(getGaming==null||getGaming.size()==0) {
if(getGaming==null|| getGaming.isEmpty()) {
bookIds.add(String.valueOf(b.getId()));
}
}
@@ -2,6 +2,7 @@ package com.mgm.mcrm.common.services;
import com.alibaba.fastjson.JSON;
import com.mgm.mcrm.common.dtos.HttpResult;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import com.mgm.mcrm.common.enums.HttpMethods;
import com.mgm.mcrm.common.httpclient.HttpClientExecutor;
import com.mgm.mcrm.common.httpclient.HttpRequestOptions;
@@ -10,12 +11,16 @@ import jakarta.annotation.Resource;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
@@ -37,14 +42,19 @@ public class HttpService {
@Qualifier("httpRequestConfig")
private RequestConfig requestConfig;
@Value("${daylight.url}")
private String daylightUrl;
@Resource
private ApiGatewaySetting apiGatewaySetting;
@Value("${notification_proxy.url}")
private String notificationProxyUrl;
private Header[] supplementDaylightProxySecurity(Header[] headers){
List<Header> newHeaders = (headers == null ? new ArrayList<>() : new ArrayList<>(Arrays.asList(headers)));
newHeaders.add(new BasicHeader("application-id",apiGatewaySetting.getDaylightAppId()));
newHeaders.add(new BasicHeader("Authorization",apiGatewaySetting.getDaylightAppSecret()));
return newHeaders.toArray(new Header[0]);
}
public String sslGet(String url, Header[] headers, Map<String, Object> map) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
// todo 在這裏需要把請求頭的信息插入到數據庫裏
log.info("GET method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(map));
// 使用 HttpConfig 配置 GET 请求(带参数)
@@ -55,7 +65,7 @@ public class HttpService {
.encoding("utf-8")
.client(httpClient);
String result = HttpClientExecutor.get(getConfig, headers);
String result = HttpClientExecutor.get(getConfig, supplementDaylightProxySecurity(headers));
log.info("GET request result size={}", result.length());
return result;
@@ -63,6 +73,7 @@ public class HttpService {
public HttpResult sslGetHttpResult(String url, Header[] headers, Map<String, Object> map) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
// todo 在這裏需要把請求頭的信息插入到數據庫裏
log.info("GET method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(map));
// 使用 HttpConfig 配置 GET 请求(带参数)
@@ -73,8 +84,8 @@ public class HttpService {
.encoding("utf-8")
.client(httpClient);
HttpResult result = HttpClientExecutor.sendAndGetResp(getConfig, headers);
log.info("GET request result size={}", result.getResult().length());
HttpResult result = HttpClientExecutor.sendAndGetResp(getConfig, supplementDaylightProxySecurity(headers));
log.info("GET request result size={}, statusCode={}", result.getResult().length(), result.getStatusCode());
return result;
}
@@ -88,7 +99,9 @@ public class HttpService {
* @return 接口結果的json數據
* @throws Exception 異常
*/
@Deprecated
public String sslPut(String url, Header[] headers, Map<String, Object> map) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
log.info("PUT method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(map));
HttpRequestOptions putConfig = HttpRequestOptions.create()
.url(daylightUrl + url)
@@ -97,7 +110,7 @@ public class HttpService {
.json(JSON.toJSONString(map))
.encoding("utf-8")
.client(httpClient);
String result = HttpClientExecutor.send(putConfig, headers);
String result = HttpClientExecutor.send(putConfig, supplementDaylightProxySecurity(headers));
log.info("PUT request result={}", result);
return result;
@@ -112,7 +125,9 @@ public class HttpService {
* @return 接口結果的json數據
* @throws Exception 異常
*/
@Deprecated
public String sslDelete(String url, Header[] headers, Object requestBody) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
log.info("DELETE method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(requestBody));
HttpRequestOptions deleteConfig = HttpRequestOptions.create()
.url(daylightUrl + url)
@@ -120,7 +135,7 @@ public class HttpService {
.json(JSON.toJSONString(requestBody))
.method(HttpMethods.DELETE)
.client(httpClient);
String result = HttpClientExecutor.send(deleteConfig, headers);
String result = HttpClientExecutor.send(deleteConfig, supplementDaylightProxySecurity(headers));
log.info("DELETE request result={}", result);
return result;
}
@@ -135,6 +150,7 @@ public class HttpService {
* @throws Exception 異常
*/
public HttpResult sslPost(String url, Header[] headers, Object requestBody) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
log.info("POST method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(requestBody));
HttpRequestOptions postConfig = HttpRequestOptions.create()
.url(daylightUrl + url)
@@ -142,9 +158,9 @@ public class HttpService {
.json(JSON.toJSONString(requestBody))
.method(HttpMethods.POST)
.client(httpClient);
HttpResult result = HttpClientExecutor.sendAndPostResp(postConfig, headers);
HttpResult result = HttpClientExecutor.sendAndPostResp(postConfig, supplementDaylightProxySecurity(headers));
// System.out.println("POST 请求结果:\n" + result);
log.info("POST request result size={}", result.getResult().length());
log.info("POST request result size={}, statusCode={}", result.getResult() != null ? result.getResult().length() : null, result.getStatusCode());
return result;
}
@@ -158,6 +174,7 @@ public class HttpService {
* @throws Exception 異常
*/
public HttpResult sslPatch(String url, Header[] headers, Object requestBody) throws Exception {
String daylightUrl=apiGatewaySetting.getDaylightProxyUrl();
log.info("PATCH method, url={}, headers={}, map={}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(requestBody));
HttpRequestOptions patchConfig = HttpRequestOptions.create()
.url(daylightUrl + url)
@@ -166,12 +183,20 @@ public class HttpService {
.method(HttpMethods.PATCH)
.encoding("utf-8")
.client(httpClient);
HttpResult result = HttpClientExecutor.sendAndPatchResp(patchConfig, headers);
log.info("PATCH request result={}", result);
HttpResult result = HttpClientExecutor.sendAndPatchResp(patchConfig, supplementDaylightProxySecurity(headers));
log.info("PATCH request result={}, statusCode={}", result.getResult(), result.getStatusCode());
return result;
}
private Header[] supplementNotificationProxySecurity(Header[] headers){
List<Header> newHeaders = (headers == null ? new ArrayList<>() : new ArrayList<>(Arrays.asList(headers)));
newHeaders.add(new BasicHeader("application-id",apiGatewaySetting.getDaylightAppId()));
newHeaders.add(new BasicHeader("Authorization",apiGatewaySetting.getDaylightAppSecret()));
return newHeaders.toArray(new Header[0]);
}
public HttpResult sslSendNotification(String url, Header[] headers, SendNotificationRequest request) throws Exception {
String notificationProxyUrl=apiGatewaySetting.getNotificationProxyUrl();
log.info("POST method, send notification, url={}, headers={}, map={}", notificationProxyUrl + url, JSON.toJSONString(headers), JSON.toJSONString(request));
HttpRequestOptions postConfig = HttpRequestOptions.create()
.url(notificationProxyUrl + url)
@@ -179,7 +204,7 @@ public class HttpService {
.json(JSON.toJSONString(request))
.method(HttpMethods.POST)
.client(httpClient);
HttpResult result = HttpClientExecutor.sendAndPostResp(postConfig, headers);
HttpResult result = HttpClientExecutor.sendAndPostResp(postConfig, supplementNotificationProxySecurity(headers));
log.info("POST request result={}", result);
return result;
}
@@ -1,468 +0,0 @@
package com.mgm.mcrm.common.services;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.mgm.mcrm.booking.dtos.search.DateRange;
import com.mgm.mcrm.common.constants.SysCommon;
import com.mgm.mcrm.common.dtos.http_util.HttpRequestDefine;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.utils.DateTimeUtil;
import com.mgm.mcrm.common.utils.HttpUtil;
import com.mgm.mcrm.common.utils.LogUtil;
import com.mgm.mcrm.common.utils.mockup.HttpUtilMockup;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class MGMApiService {
public static String ESB_APP_ID = "";
public static String ESB_APP_SECRET = "";
public static String ESB_Server = "";
public static String ESB_ACCESS_TOKEN = null;
public static Date ESB_EXPIRED_TIME = new Date();
private static final String API_GET_ACCESS_TOKEN = "/RequestAccessToken";
private static final String API_GET_PLAYER_PROFILE = "/GetReportingLinePlayerInfo";
private static final String API_CHECK_PLAYER_TPD = "/GetRoomBookingQualificationStatus";
private static final String API_GET_USER_INFO = "/GetLoginUserInfo";
private static final String API_NON_MGM_BOOKING = "/GetNonMGMRoomBookingRecord";
private static final String API_WAITLIST_BOOKING = "/GetRoomBookingWaitList";
private static final String API_CHECK_SECOND_ROOM_TPD = "/GetMultiRoomBookingQualificationStatus";
private static final String API_CHECK_APPROVER = "/CheckApprover";
private static final String API_WAITLIST_DATA = "/GetWaitlistData";
private static final String API_GET_ALL_PLAYER_PROFILE = "/GetPlayerInfo";
private static final String API_GET_TODO_DASHBOARD = "/GetDashboardData";
private static final String API_GET_TODO_DETAIL = "/GetTodolistDetails";
private static final String API_GET_APPROVER_DATA="/RequestWaitlistData";
private static final String API_GET_APPROVER="/RequestRoomBookingApprovalRouting";
private static final String API_GET_TODO_LIST = "/GetTodolist";
private static final String API_REQUEST_ROOM_CALENDAR = "/RequestRoomCalendar";
private static final String API_GET_LIMO_BOOKING_FROM_LEGACY = "/GetLimoBookingFromLegacy";
public HttpResponseResult invokeRequestRoomCalendar(
String playerId,
String property,
String roomType,
String startDate,
String endDate) throws Exception {
return invokeRequestRoomCalendar(playerId, property, roomType, startDate, endDate, 0);
}
public HttpResponseResult invokeRequestRoomCalendar(
String playerId,
String property,
String roomType,
String startDate,
String endDate,
int type) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("Authorization", getAccessToken());
if (StringUtils.isNotBlank(playerId)) {
requestObj.put("PlayerId", playerId);
}
requestObj.put("Property", property);
requestObj.put("RoomType", roomType);
requestObj.put("StartDate", startDate);
requestObj.put("EndDate", endDate);
return invokeESBAPI(ESB_Server, API_REQUEST_ROOM_CALENDAR, requestObj, "POST", requestHeader, type);
}
public HttpResponseResult invokeGetPlayerProfile(
String playerId,
String userId) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestHeader.put("PlayerId", playerId);
requestHeader.put("UserId", userId);
requestObj.put("playerId", playerId);
requestObj.put("userId", userId);
result = this.invokeESBAPI(ESB_Server, API_GET_PLAYER_PROFILE, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeGetAllPlayerProfile(String playerId) throws Exception {
HttpResponseResult result;
String apiLink = SysCommon.mgmApiMockup ? API_GET_PLAYER_PROFILE : API_GET_ALL_PLAYER_PROFILE;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestHeader.put("PlayerId", playerId);
requestObj.put("playerId", playerId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeCheckPlayerTPD(
String playerId,
String roomCate,
List<String> dates,
String bookingType,
String property) throws Exception {
HttpResponseResult result;
String apiLink = API_CHECK_PLAYER_TPD;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestHeader.put("PlayerId", playerId);
requestHeader.put("RoomCategory", roomCate);
requestHeader.put("BookingType", bookingType);
requestHeader.put("Property", property);
requestHeader.put("StartDate", dates.getFirst());
requestHeader.put("EndDate", dates.getLast());
requestObj.put("playerId", playerId);
requestObj.put("roomCategory", roomCate);
requestObj.put("startDate", dates.getFirst());
requestObj.put("endDate", dates.getLast());
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "GET", requestHeader, 1);
return result;
}
public HttpResponseResult invokeGetApprover(String playerId,String bookingType,String property,String roomCategory,String checkInDate,String checkOutDate,String userId) throws Exception {
HttpResponseResult result = null;
String apiLink =API_GET_APPROVER;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<String,String>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("PlayerId", playerId);
requestObj.put("BookingType", bookingType);
requestObj.put("Property", property);
requestObj.put("RoomCategory", roomCategory);
requestObj.put("StartDate", checkInDate);
requestObj.put("EndDate", checkOutDate);
requestObj.put("UserId", userId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetApprovalData(String bookingId) throws Exception {
HttpResponseResult result = null;
String apiLink =API_GET_APPROVER_DATA;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<String,String>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("BookingId", bookingId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeCheckApprover(
String userId,
String userName,
String roomType,
String property) throws Exception {
HttpResponseResult result;
String apiLink = API_CHECK_APPROVER;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
if (!StringUtils.isEmpty(userId)) {
requestObj.put("UserId", userId);
}
if (!StringUtils.isEmpty(userName)) {
requestObj.put("UserName", userName);
}
requestObj.put("RoomCategory", roomType);
requestObj.put("Property", property);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetUserInfo(String userId, String userName) throws Exception {
HttpResponseResult result;
String apiLink = API_GET_USER_INFO;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
if (!StringUtils.isEmpty(userId)) {
requestHeader.put("UserId", userId);
requestObj.put("userId", userId);
}
if (!StringUtils.isEmpty(userName)) {
requestHeader.put("UserName", userName);
requestObj.put("userName", userName);
}
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeNonMGMBooking(String playerId) throws Exception {
HttpResponseResult result;
String apiLink = API_NON_MGM_BOOKING;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestHeader.put("PlayerId", playerId);
requestObj.put("playerId", playerId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeWaitlistBooking(String playerId) throws Exception {
HttpResponseResult result;
String apiLink = API_WAITLIST_BOOKING;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestHeader.put("PlayerId", playerId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeWaitlistData(String bookIds, int categoryType) throws Exception {
HttpResponseResult result;
String apiLink = API_WAITLIST_DATA;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("BookingId", bookIds);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeCheckPlayerSecondTPD(
String playerId,
String roomCate,
List<DateRange> dateRange,
String bookingType,
String property) throws Exception {
HttpResponseResult result;
String apiLink = API_CHECK_SECOND_ROOM_TPD;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("PlayerId", playerId);
requestObj.put("RoomCategory", roomCate);
requestObj.put("BookingType", bookingType);
requestObj.put("Property", property);
requestObj.put("DateRange", dateRange);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
return result;
}
public String getAccessToken() throws Exception {
String token = ESB_ACCESS_TOKEN;
if (SysCommon.mgmApiMockup) return token;
ESB_APP_ID = SysCommon.apiConfig.getApiKey_ESB();
ESB_APP_SECRET = SysCommon.apiConfig.getApiSecret_ESB();
ESB_Server = SysCommon.apiConfig.getServerUrl_ESB();
if (token == null || ESB_EXPIRED_TIME.getTime() < new Date().getTime()) {
String apiLink = API_GET_ACCESS_TOKEN;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("AppId", ESB_APP_ID);
requestObj.put("AppSecret", ESB_APP_SECRET);
HttpResponseResult result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
if (result.getStatusCode() == 200) {
JSONObject resultObj = JSONObject.parseObject(result.getResponseContent());
String status = resultObj.getString("StatusCode");
if (Strings.CS.equals("OK", status)) {
token = resultObj.getString("Token");
ESB_EXPIRED_TIME = DateTimeUtil.getDateFromString(resultObj.getString("ExpireTime"), "yyyy-MM-dd HH:mm:ss");
ESB_ACCESS_TOKEN = token;
} else {
token = null;
ESB_ACCESS_TOKEN = null;
ESB_EXPIRED_TIME = new Date();
}
}
}
return token;
}
public HttpResponseResult invokeGetTodoDashboard(
String userId,
int categoryType) throws Exception {
HttpResponseResult result;
String apiLink = API_GET_TODO_DASHBOARD;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("UserId", userId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeGetTodoDetail(
String playerId,
String todoCategory,
String todoSegment,
String date,
int categoryType) throws Exception {
HttpResponseResult result;
String apiLink = API_GET_TODO_DETAIL;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("PlayerId", playerId);
requestObj.put("TodoCategory", todoCategory);
requestObj.put("TodoSegment", todoSegment);
requestObj.put("Date", date);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeGetLimoBookingFromLegacy(
String playerId
) throws Exception {
HttpResponseResult result = null;
String apiLink = API_GET_LIMO_BOOKING_FROM_LEGACY;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("PlayerId", playerId);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetTodoList(
String userId,
String category,
String type,
Date startDate,
Date endDate,
int categoryType) throws Exception {
HttpResponseResult result;
String apiLink = API_GET_TODO_LIST;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("UserId", userId);
requestObj.put("TodoCategory", category);
requestObj.put("TodoSegment", type);
requestObj.put("StartDate", startDate);
requestObj.put("EndDate", endDate);
result = this.invokeESBAPI(ESB_Server, apiLink, requestObj, "POST", requestHeader, categoryType);
return result;
}
// 如果不设置type,默认call opera
public HttpResponseResult invokeESBAPI(
String serverType,
String requestLink,
JSONObject requestContent,
String requestMethod,
Map<String, String> requestHeader) throws Exception {
return invokeESBAPI(serverType, requestLink, requestContent, requestMethod, requestHeader, 0);
}
/**
*
* @param serverType n
* @param requestLink n
* @param requestContent n
* @param requestMethod n
* @param requestHeader n
* @param type 0 - opera, 1 - daylight
* @return n
* @throws Exception e
*/
public HttpResponseResult invokeESBAPI(
String serverType,
String requestLink,
JSONObject requestContent,
String requestMethod,
Map<String, String> requestHeader,
int type) throws Exception {
String serverUrl;
int timeoutTime;
if (Strings.CS.equals(serverType, ESB_Server)) {
serverUrl = SysCommon.apiConfig.getServerUrl_ESB();
timeoutTime = SysCommon.apiConfig.getTimeout_ESB();
} else {
throw new Exception("Invalid server type");
}
if (type == 1) {
requestLink = "/Daylight" + requestLink;
}
HttpRequestDefine requestDef = new HttpRequestDefine();
String requestUrl = serverUrl + requestLink;
requestDef.setRequestUrl(requestUrl);
requestDef.setRequestMethod(requestMethod);
requestDef.setTimeout(timeoutTime);
requestHeader.put("Content-type", "application/json;charset=utf-8");
requestDef.setHeaders(requestHeader);
if (requestContent != null) {
requestDef.setEntityContent(requestContent.toString());
} else {
requestDef.setEntityContent("");
}
// --
//Get Start,EndTime
long spanTime;
Date startTime = new Date();
Date endTime;
LogUtil.info(MGMApiService.class, "[invokeESBAPI] start request:");
HttpResponseResult httpResult =
SysCommon.mgmApiMockup ?
HttpUtilMockup.processHttpRequest(requestDef) :
HttpUtil.processHttpRequest(requestDef);
httpResult.setRequestContent(requestDef.getEntityContent());
//RefreshEndTime
endTime = new Date();
//Get Spend Time
Gson gson = new Gson();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getRequestUrl:" + gson.toJson(requestDef.getRequestUrl()));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getHeaders:" + gson.toJson(requestDef.getHeaders()));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getRequestMethod:" + gson.toJson(requestDef.getRequestMethod()));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getEntityContent:" + gson.toJson(requestContent));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getStatusCode:" + gson.toJson(httpResult.getStatusCode()));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getErrorMessage:" + gson.toJson(httpResult.getErrorMessage()));
LogUtil.info(MGMApiService.class, "[invokeESBAPI]getResponseContent:" + gson.toJson(httpResult.getResponseContent()));
//Log Spend Time
LogUtil.info(MGMApiService.class, "[invokeESBAPI]SpendTime:" + spanTime + "ms");
return httpResult;
}
}
@@ -2,244 +2,403 @@ package com.mgm.mcrm.common.services;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.mgm.mcrm.booking.dtos.search.DateRange;
import com.mgm.mcrm.common.constants.SysCommon;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import com.mgm.mcrm.common.dtos.http_util.HttpRequestDefine;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.utils.DateTimeUtil;
import com.mgm.mcrm.common.utils.HttpUtil;
import com.mgm.mcrm.common.utils.LogUtil;
import com.mgm.mcrm.common.utils.mockup.HttpUtilMockup;
import com.mgm.mcrm.limo.dtos.request.RequestPlayerEsbBookerRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class MGMEsbApiService {
public static String LIMO_ESB_APP_ID = "";
public static String LIMO_ESB_APP_SECRET = "";
public static String LIMO_ESB_SERVER = "";
public static String LIMO_ESB_ACCESS_TOKEN = "";
public static Date LIMO_ESB_EXPIRED_TIME = new Date();
private final Logger logger = LoggerFactory.getLogger(MGMEsbApiService.class);
public static final String ESB_MCRM_API_TYPE = "ESB_MCRM";
public static final String ESB_LIMO_API_TYPE= "ESB_LIMO";
private static final String API_GET_ACCESS_TOKEN = "/RequestAccessToken";
private static final String API_GET_LIMO_OVERRIDER = "/RequestLimoOverrider";
private static final String API_CHECK_SIMPLE_LIMO_BOOKING_QUALIFICATION_STATUS = "/RequestSimpleLimoBookingQualificationStatus";
private static final String API_CHECK_COMPLEX_LIMO_BOOKING_QUALIFICATION_STATUS = "/RequestComplexLimoBookingQualificationStatus";
private static final String API_REQUEST_EMPLOYEE_INFO = "/RequestEmployeeInfo";
private static final String API_REQUEST_PLAYER_LIMO_BOOKER = "/RequestPlayerLimoBooker";
private static final String API_REQUEST_PLAYER_INFO = "/RequestPlayerInfo";
private static final String API_GET_PLAYER_PROFILE = "/GetReportingLinePlayerInfo";
private static final String API_CHECK_PLAYER_TPD = "/GetRoomBookingQualificationStatus";
private static final String API_GET_USER_INFO = "/GetLoginUserInfo";
private static final String API_NON_MGM_BOOKING = "/GetNonMGMRoomBookingRecord";
private static final String API_WAITLIST_BOOKING = "/GetRoomBookingWaitList";
private static final String API_CHECK_SECOND_ROOM_TPD = "/GetMultiRoomBookingQualificationStatus";
private static final String API_CHECK_APPROVER = "/CheckApprover";
private static final String API_WAITLIST_DATA = "/GetWaitlistData";
private static final String API_GET_ALL_PLAYER_PROFILE = "/GetPlayerInfo";
private static final String API_GET_TODO_DASHBOARD = "/GetDashboardData";
private static final String API_GET_TODO_DETAIL = "/GetTodolistDetails";
private static final String API_GET_APPROVER_DATA="/RequestWaitlistData";
private static final String API_GET_APPROVER="/RequestRoomBookingApprovalRouting";
private static final String API_GET_TODO_LIST = "/GetTodolist";
private static final String API_REQUEST_ROOM_CALENDAR = "/RequestRoomCalendar";
private static final String API_GET_LIMO_BOOKING_FROM_LEGACY = "/GetLimoBookingFromLegacy";
@Autowired
private ApiGatewaySetting apiGatewaySetting;
public HttpResponseResult invokeRequestPlayerLimoBooker(RequestPlayerEsbBookerRequest request) throws Exception {
String apiLink = API_REQUEST_PLAYER_LIMO_BOOKER;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getLimoAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("EmployeeIdOrName", request.getUserId());
requestObj.put("PlayerId", request.getPlayerId());
return this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
public HttpResponseResult invokeRequestRoomCalendar(
String playerId,
String property,
String roomType,
String startDate,
String endDate) throws Exception {
return invokeRequestRoomCalendar(playerId, property, roomType, startDate, endDate, 0);
}
public String getLimoAccessToken() throws Exception {
String token = LIMO_ESB_ACCESS_TOKEN;
if (SysCommon.mgmApiMockup)
return token;
LIMO_ESB_APP_ID = SysCommon.apiConfig.getLimoApp_id();
LIMO_ESB_APP_SECRET = SysCommon.apiConfig.getLimoApp_key();
LIMO_ESB_SERVER = SysCommon.apiConfig.getLimoService_ESB();
if (token == null || LIMO_ESB_EXPIRED_TIME.getTime() < new Date().getTime()) {
String apiLink = API_GET_ACCESS_TOKEN;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("AppId", LIMO_ESB_APP_ID);
requestObj.put("AppSecret", LIMO_ESB_APP_SECRET);
HttpResponseResult result =
this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
if (result.getStatusCode() == 200) {
JSONObject resultObj = JSONObject.parseObject(result.getResponseContent());
String status = resultObj.getString("StatusCode");
if (Strings.CI.equals("OK", status)) {
token = resultObj.getString("Token");
LIMO_ESB_EXPIRED_TIME =
DateTimeUtil.getDateFromString(resultObj.getString("ExpireTime"), "yyyy-MM-dd HH:mm:ss");
LIMO_ESB_ACCESS_TOKEN = token;
} else {
token = null;
LIMO_ESB_ACCESS_TOKEN = null;
LIMO_ESB_EXPIRED_TIME = new Date();
}
}
public HttpResponseResult invokeRequestRoomCalendar(
String playerId,
String property,
String roomType,
String startDate,
String endDate,
int type) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
if (StringUtils.isNotBlank(playerId)) {
requestObj.put("PlayerId", playerId);
}
return token;
requestObj.put("Property", property);
requestObj.put("RoomType", roomType);
requestObj.put("StartDate", startDate);
requestObj.put("EndDate", endDate);
return invokeESBAPI(ESB_MCRM_API_TYPE, API_REQUEST_ROOM_CALENDAR, requestObj, "POST", requestHeader, type);
}
public HttpResponseResult invokeLimoOverrider(
String overriderIdOrName
) throws Exception {
String apiLink = API_GET_LIMO_OVERRIDER;
public HttpResponseResult invokeGetPlayerProfile(
String playerId,
String userId) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("PlayerId", playerId);
requestHeader.put("UserId", userId);
String token = getLimoAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("OverriderIdOrName", "%");
return this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
requestObj.put("playerId", playerId);
requestObj.put("userId", userId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_PLAYER_PROFILE, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeLimoPlayerInfo(
Integer playerId
) throws Exception {
String apiLink = API_REQUEST_PLAYER_INFO;
public HttpResponseResult invokeGetAllPlayerProfile(String playerId) throws Exception {
HttpResponseResult result;
String apiLink = SysCommon.mgmApiMockup ? API_GET_PLAYER_PROFILE : API_GET_ALL_PLAYER_PROFILE;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("PlayerId", playerId);
String token = getLimoAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("PlayerId", playerId);
return this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
requestObj.put("playerId", playerId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, apiLink, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeSimpleLimoBookingQualificationStatus(
Integer playerId,
public HttpResponseResult invokeCheckPlayerTPD(
String playerId,
String roomCate,
List<String> dates,
String bookingType,
String bookingDate
) throws Exception {
String apiLink = API_CHECK_SIMPLE_LIMO_BOOKING_QUALIFICATION_STATUS;
String property) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("PlayerId", playerId);
requestHeader.put("RoomCategory", roomCate);
requestHeader.put("BookingType", bookingType);
requestHeader.put("Property", property);
requestHeader.put("StartDate", dates.getFirst());
requestHeader.put("EndDate", dates.getLast());
String token = getLimoAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("playerId", playerId);
requestObj.put("roomCategory", roomCate);
requestObj.put("startDate", dates.getFirst());
requestObj.put("endDate", dates.getLast());
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_CHECK_PLAYER_TPD, requestObj, "GET", requestHeader, 1);
return result;
}
public HttpResponseResult invokeGetApprover(String playerId,String bookingType,String property,String roomCategory,String checkInDate,String checkOutDate,String userId) throws Exception {
HttpResponseResult result = null;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
requestObj.put("BookingType", bookingType);
requestObj.put("BookingDate", bookingDate);
requestObj.put("Property", property);
requestObj.put("RoomCategory", roomCategory);
requestObj.put("StartDate", checkInDate);
requestObj.put("EndDate", checkOutDate);
requestObj.put("UserId", userId);
return this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_APPROVER, requestObj, "POST", requestHeader, 1);
return result;
}
public HttpResponseResult invokeGetApprovalData(String bookingId, int type) throws Exception {
HttpResponseResult result = null;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<String,String>();
requestObj.put("BookingId", bookingId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_APPROVER_DATA, requestObj, "POST", requestHeader,type);
return result;
}
public HttpResponseResult invokeRequestEmployeeInfo(String employeeId) throws Exception {
String apiLink = API_REQUEST_EMPLOYEE_INFO;
public HttpResponseResult invokeCheckApprover(
String userId,
String userName,
String roomType,
String property) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
String token = getLimoAccessToken();
requestHeader.put("Authorization", token);
requestObj.put("EmployeeId", employeeId);
return this.invokeESBAPI(LIMO_ESB_SERVER, apiLink, requestObj, "POST", requestHeader);
if (!StringUtils.isEmpty(userId)) {
requestObj.put("UserId", userId);
}
if (!StringUtils.isEmpty(userName)) {
requestObj.put("UserName", userName);
}
requestObj.put("RoomCategory", roomType);
requestObj.put("Property", property);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_CHECK_APPROVER, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetUserInfo(String userId, String userName) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
if (!StringUtils.isEmpty(userId)) {
requestHeader.put("UserId", userId);
requestObj.put("userId", userId);
}
if (!StringUtils.isEmpty(userName)) {
requestHeader.put("UserName", userName);
requestObj.put("userName", userName);
}
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_USER_INFO, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeNonMGMBooking(String playerId) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("PlayerId", playerId);
requestObj.put("playerId", playerId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_NON_MGM_BOOKING, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeWaitlistBooking(String playerId) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestHeader.put("PlayerId", playerId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_WAITLIST_BOOKING, requestObj, "GET", requestHeader);
return result;
}
public HttpResponseResult invokeWaitlistData(String bookIds, int categoryType) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("BookingId", bookIds);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_WAITLIST_DATA, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeCheckPlayerSecondTPD(
String playerId,
String roomCate,
List<DateRange> dateRange,
String bookingType,
String property) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
requestObj.put("RoomCategory", roomCate);
requestObj.put("BookingType", bookingType);
requestObj.put("Property", property);
requestObj.put("DateRange", dateRange);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_CHECK_SECOND_ROOM_TPD, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetTodoDashboard(
String userId,
int categoryType) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("UserId", userId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_TODO_DASHBOARD, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeGetTodoDetail(
String playerId,
String todoCategory,
String todoSegment,
String date,
int categoryType) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
requestObj.put("TodoCategory", todoCategory);
requestObj.put("TodoSegment", todoSegment);
requestObj.put("Date", date);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_TODO_DETAIL, requestObj, "POST", requestHeader, categoryType);
return result;
}
public HttpResponseResult invokeGetLimoBookingFromLegacy(
String playerId
) throws Exception {
HttpResponseResult result = null;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_LIMO_BOOKING_FROM_LEGACY, requestObj, "POST", requestHeader);
return result;
}
public HttpResponseResult invokeGetTodoList(
String userId,
String category,
String type,
Date startDate,
Date endDate,
int categoryType) throws Exception {
HttpResponseResult result;
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("UserId", userId);
requestObj.put("TodoCategory", category);
requestObj.put("TodoSegment", type);
requestObj.put("StartDate", startDate);
requestObj.put("EndDate", endDate);
result = this.invokeESBAPI(ESB_MCRM_API_TYPE, API_GET_TODO_LIST, requestObj, "POST", requestHeader, categoryType);
return result;
}
// 如果不设置type,默认call opera
public HttpResponseResult invokeESBAPI(
String serverType,
String esbApiType,
String requestLink,
JSONObject requestContent,
String requestMethod,
Map<String, String> requestHeader) throws Exception {
return invokeESBAPI(esbApiType, requestLink, requestContent, requestMethod, requestHeader, 0);
}
/**
*
* @param esbApiType n
* @param requestLink n
* @param requestContent n
* @param requestMethod n
* @param requestHeader n
* @param type 0 - opera, 1 - daylight
* @return n
* @throws Exception e
*/
public HttpResponseResult invokeESBAPI(
String esbApiType,
String requestLink,
JSONObject requestContent,
String requestMethod,
Map<String, String> requestHeader,
int type) throws Exception {
String serverUrl;
int timeoutTime;
int timeoutTime = apiGatewaySetting.getRequestTimeout();
if (Strings.CS.equals(esbApiType, ESB_MCRM_API_TYPE)) {
serverUrl = apiGatewaySetting.getEsbMcrmProxyUrl();
//-- set proxy authorization
requestHeader.put("application-id", apiGatewaySetting.getEsbMcrmAppId());
requestHeader.put("Authorization", apiGatewaySetting.getEsbMcrmAppSecret());
//--
//Get Spend Time
Gson gson = new Gson();
HttpRequestDefine requestDef = new HttpRequestDefine();
LogUtil.info(MGMEsbApiService.class,"Request Url = "+gson.toJson(requestDef.getRequestUrl())+"serverType: " + serverType+"LIMO_ESB_SERVER"+LIMO_ESB_SERVER);
if (Strings.CS.equals(serverType, LIMO_ESB_SERVER)) {
serverUrl = SysCommon.apiConfig.getLimoService_ESB();
timeoutTime = SysCommon.apiConfig.getTimeout_ESB();
if (type == 1) {
requestLink = "/Daylight" + requestLink;
}
}else if (Strings.CS.equals(esbApiType, ESB_LIMO_API_TYPE)) {
serverUrl = apiGatewaySetting.getEsbLimoProxyUrl();
//-- set proxy authorization
requestHeader.put("application-id", apiGatewaySetting.getEsbLimoAppId());
requestHeader.put("Authorization", apiGatewaySetting.getEsbLimoAppSecret());
//--
} else {
throw new Exception("Invalid server type");
throw new Exception("Invalid ESB Api type");
}
HttpRequestDefine requestDef = new HttpRequestDefine();
String requestUrl = serverUrl + requestLink;
requestDef.setRequestUrl(requestUrl);
requestDef.setRequestMethod(requestMethod);
requestDef.setTimeout(timeoutTime);
requestHeader.put("Content-type", "application/json;charset=utf-8");
requestDef.setHeaders(requestHeader);
if (requestContent != null)
if (requestContent != null) {
requestDef.setEntityContent(requestContent.toString());
else
} else {
requestDef.setEntityContent("");
}
// --
//Get Start,EndTime
long spanTime;
Date startTime = new Date();
LogUtil.info(MGMEsbApiService.class, "[invokeESBAPI] start request:");
HttpResponseResult httpResult = (SysCommon.mgmApiMockup ?
HttpUtilMockup.processHttpRequest(requestDef)
: HttpUtil.processHttpRequest(requestDef));
Date endTime;
logger.info("[invoke {} API] start request:",esbApiType);
HttpResponseResult httpResult =
SysCommon.mgmApiMockup ?
HttpUtilMockup.processHttpRequest(requestDef) :
HttpUtil.processHttpRequest(requestDef);
httpResult.setRequestContent(requestDef.getEntityContent());
//RefreshEndTime
Date endTime = new Date();
endTime = new Date();
//Get Spend Time
Gson gson = new Gson();
spanTime = DateTimeUtil.getTimeSpanSSS(startTime, endTime);
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getRequestUrl:" + gson.toJson(requestDef.getRequestUrl()));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getHeaders:" + gson.toJson(requestDef.getHeaders()));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getRequestMethod:" + gson.toJson(requestDef.getRequestMethod()));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getEntityContent:" + gson.toJson(requestContent));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getStatusCode:" + gson.toJson(httpResult.getStatusCode()));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getErrorMessage:" + gson.toJson(httpResult.getErrorMessage()));
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]getResponseContent:" + gson.toJson(httpResult.getResponseContent()));
logger.info("[invoke {} API]getRequestUrl:{}",esbApiType, gson.toJson(requestDef.getRequestUrl()));
logger.info("[invoke {} API]getHeaders:{}" ,esbApiType, gson.toJson(requestDef.getHeaders()));
logger.info("[invoke {} API]getRequestMethod:{}" ,esbApiType, gson.toJson(requestDef.getRequestMethod()));
logger.info("[invoke {} API]getEntityContent:{}" ,esbApiType, gson.toJson(requestContent));
logger.info("[invoke {} API]getStatusCode:{}" ,esbApiType, gson.toJson(httpResult.getStatusCode()));
logger.info("[invoke {} API]getErrorMessage:{}" ,esbApiType, gson.toJson(httpResult.getErrorMessage()));
logger.info("[invoke {} API]getResponseContent:{}" ,esbApiType, gson.toJson(httpResult.getResponseContent()));
//Log Spend Time
LogUtil.info(MGMEsbApiService.class, "[invokeLimoESBAPI]SpendTime:" + spanTime + "ms");
logger.info("[invoke {} API]SpendTime:{}" ,esbApiType, spanTime + "ms");
return httpResult;
}
}
}
@@ -0,0 +1,91 @@
package com.mgm.mcrm.common.services;
import com.alibaba.fastjson.JSONObject;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.limo.dtos.request.RequestPlayerEsbBookerRequest;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class MGMEsbLimoApiService {
public static final String ESB_LIMO_API_TYPE= "ESB_LIMO";
private static final String API_GET_ACCESS_TOKEN = "/RequestAccessToken";
private static final String API_GET_LIMO_OVERRIDER = "/RequestLimoOverrider";
private static final String API_CHECK_SIMPLE_LIMO_BOOKING_QUALIFICATION_STATUS = "/RequestSimpleLimoBookingQualificationStatus";
private static final String API_CHECK_COMPLEX_LIMO_BOOKING_QUALIFICATION_STATUS = "/RequestComplexLimoBookingQualificationStatus";
private static final String API_REQUEST_EMPLOYEE_INFO = "/RequestEmployeeInfo";
private static final String API_REQUEST_PLAYER_LIMO_BOOKER = "/RequestPlayerLimoBooker";
private static final String API_REQUEST_PLAYER_INFO = "/RequestPlayerInfo";
@Resource
private MGMEsbApiService mgmEsbApiService;
public HttpResponseResult invokeRequestPlayerLimoBooker(RequestPlayerEsbBookerRequest request) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("EmployeeIdOrName", request.getUserId());
requestObj.put("PlayerId", request.getPlayerId());
return mgmEsbApiService.invokeESBAPI(ESB_LIMO_API_TYPE, API_REQUEST_PLAYER_LIMO_BOOKER, requestObj, "POST", requestHeader);
}
public HttpResponseResult invokeLimoOverrider(
String overriderIdOrName
) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("OverriderIdOrName", "%");
return mgmEsbApiService.invokeESBAPI(ESB_LIMO_API_TYPE, API_GET_LIMO_OVERRIDER, requestObj, "POST", requestHeader);
}
public HttpResponseResult invokeLimoPlayerInfo(
Integer playerId
) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
return mgmEsbApiService.invokeESBAPI(ESB_LIMO_API_TYPE, API_REQUEST_PLAYER_INFO, requestObj, "POST", requestHeader);
}
public HttpResponseResult invokeSimpleLimoBookingQualificationStatus(
Integer playerId,
String bookingType,
String bookingDate
) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("PlayerId", playerId);
requestObj.put("BookingType", bookingType);
requestObj.put("BookingDate", bookingDate);
return mgmEsbApiService.invokeESBAPI(ESB_LIMO_API_TYPE, API_CHECK_SIMPLE_LIMO_BOOKING_QUALIFICATION_STATUS, requestObj, "POST", requestHeader);
}
public HttpResponseResult invokeRequestEmployeeInfo(String employeeId) throws Exception {
JSONObject requestObj = new JSONObject();
Map<String, String> requestHeader = new HashMap<>();
requestObj.put("EmployeeId", employeeId);
return mgmEsbApiService.invokeESBAPI(ESB_LIMO_API_TYPE, API_REQUEST_EMPLOYEE_INFO, requestObj, "POST", requestHeader);
}
}
@@ -2,6 +2,7 @@ package com.mgm.mcrm.common.services;
import com.alibaba.fastjson.JSONObject;
import com.mgm.mcrm.common.constants.SysCommon;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import com.mgm.mcrm.common.dtos.http_util.HttpRequestDefine;
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
import com.mgm.mcrm.common.utils.HttpUtil;
@@ -10,11 +11,13 @@ import com.mgm.mcrm.common.utils.mockup.HttpUtilMockup;
import com.mgm.mcrm.limo.dtos.request.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
@@ -22,11 +25,8 @@ import java.util.stream.Collectors;
@Service
public class MGMLimoApiService {
public static String ESB_LIMO_SERVER = "";
public static String ESB_LIMO_ACCESS_TOKEN = null;
public static String ESB_LIMO_APP_ID;
public static String ESB_LIMO_APP_SECRET;
public static Date ESB_LIMO_EXPIRED_TIME = new Date();
public static String LIMO_ACCESS_TOKEN = null;
public static LocalDateTime LIMO_EXPIRED_TIME = LocalDateTime.now();
private static final String API_GET_ACCESS_TOKEN = "GetAccessToken";
private static final String API_GET_TRIP_PRICE = "GetTripPrice";
@@ -42,13 +42,8 @@ public class MGMLimoApiService {
// private static final String API_MAIN_HANDLER_HANDLER = "http://mmlimodevapp01/MCRMAPI/API/MainHandler.ashx ";
@Value("${limo_address}")
private String API_MAIN_HANDLER;
@Value("${limo_getAccessToken_Id}")
private String apiGetAccessTokenId;
@Value("${limo_getAccessToken_pwd}")
private String apiGetAccessTokenPwd;
@Autowired
private ApiGatewaySetting apiGatewaySetting;
public HttpResponseResult invokeGetTripPrice() throws Exception {
@@ -56,11 +51,10 @@ public class MGMLimoApiService {
Map<String, String> requestObj = new HashMap<>();
String token = getLimoAccessToken();
requestObj.put("action", API_GET_TRIP_PRICE);
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
public HttpResponseResult invokeGetLocation(String location) throws Exception {
@@ -68,12 +62,11 @@ public class MGMLimoApiService {
Map<String, String> requestObj = new HashMap<>();
String token = getLimoAccessToken();
requestObj.put("action", API_GET_LOCATION);
requestObj.put("token", token);
requestObj.put("Location", "%");
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
public HttpResponseResult invokeGetCarType() throws Exception {
@@ -85,7 +78,7 @@ public class MGMLimoApiService {
requestObj.put("action", API_GET_CAR_TYPE);
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
@@ -99,7 +92,7 @@ public class MGMLimoApiService {
requestObj.put("action", API_GET_GREET_TYPE);
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
public HttpResponseResult invokeGetBooking(String bookingId) throws Exception {
@@ -107,13 +100,11 @@ public class MGMLimoApiService {
Map<String, String> requestObj = new HashMap<>();
String token = getLimoAccessToken();
if(bookingId != null) requestObj.put("Id",bookingId);
requestObj.put("action", API_GET_BOOKING);
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
public HttpResponseResult getFlightDetails(GetLimoFlightDetailsRequest request) throws Exception {
@@ -131,7 +122,7 @@ public class MGMLimoApiService {
requestObj.put("token", token);
requestObj.put("itemObject", itemObject.toJSONString());
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
public HttpResponseResult getTotalAmount(GetLimoTotalAmountRequest request) throws Exception {
@@ -159,7 +150,7 @@ public class MGMLimoApiService {
requestObj.put("token", token);
requestObj.put("itemObject", itemObject.toJSONString());
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
/** 按 {@code ;} 拆分,去掉空白段;例如 {@code 1;2;3} → [1,2,3] */
@@ -293,7 +284,7 @@ public class MGMLimoApiService {
requestObj.put("itemObject", sb.toString());
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
// ---- Limo format helpers: single-quote + PascalCase + 1/0 for booleans ----
@@ -443,7 +434,7 @@ public class MGMLimoApiService {
requestObj.put("itemObject", sb.toString());
requestObj.put("token", token);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
private static void appendStringUpdate(StringBuilder sb, String fieldName, String value) {
@@ -499,35 +490,28 @@ public class MGMLimoApiService {
requestObj.put("action", API_UPDATE_BOOKING_STATUS);
return this.invokeESBFormUrlEncodedAPI(ESB_LIMO_SERVER, API_MAIN_HANDLER, requestObj, "POST", null);
return this.invokeESBFormUrlEncodedAPI(apiGatewaySetting.getLimoProxyUrl(), apiGatewaySetting.getLimoMainHandleUrl(), requestObj, "POST", null);
}
private String getLimoAccessToken() throws Exception {
String token = ESB_LIMO_ACCESS_TOKEN;
String token = LIMO_ACCESS_TOKEN;
if (SysCommon.mgmApiMockup)
return token;
ESB_LIMO_APP_ID = SysCommon.apiConfig.getApiKey_ESB();
ESB_LIMO_APP_SECRET = SysCommon.apiConfig.getApiSecret_ESB();
ESB_LIMO_SERVER = SysCommon.apiConfig.getServerUrl_ESB();
if (token == null || ESB_LIMO_EXPIRED_TIME.getTime() < new Date().getTime()) {
if (token == null || LIMO_EXPIRED_TIME.isBefore(LocalDateTime.now())) {
String itemObject = String.format(
"{'LoginID':'%s','Password':'%s'}",
apiGetAccessTokenId,
apiGetAccessTokenPwd);
apiGatewaySetting.getLimoAccessAccount(),
apiGatewaySetting.getLimoAccessPassword());
Map<String, String> formData = new HashMap<>();
formData.put("action", API_GET_ACCESS_TOKEN);
formData.put("itemObject", itemObject);
HttpResponseResult result = this.invokeESBFormUrlEncodedAPI(
ESB_LIMO_SERVER,
API_MAIN_HANDLER,
apiGatewaySetting.getLimoProxyUrl(),
apiGatewaySetting.getLimoMainHandleUrl(),
formData,
"POST",
null);
@@ -538,10 +522,12 @@ public class MGMLimoApiService {
if (Strings.CI.equals("200", status)) {
token = resultObj.getString("token");
ESB_LIMO_ACCESS_TOKEN = token;
LIMO_ACCESS_TOKEN = token;
LIMO_EXPIRED_TIME = LocalDateTime.now().plusSeconds(apiGatewaySetting.getLimoTokenExpirySecond());
} else {
token = null;
ESB_LIMO_ACCESS_TOKEN = null;
LIMO_ACCESS_TOKEN = null;
LIMO_EXPIRED_TIME = LocalDateTime.now();
}
}
}
@@ -557,8 +543,12 @@ public class MGMLimoApiService {
Map<String, String> requestHeader) throws Exception {
HttpRequestDefine requestDef = new HttpRequestDefine();
String requestUrl = requestLink;
String requestUrl = serverUrl+requestLink;
Map<String, String> headers = (requestHeader == null ? new HashMap<>() : new HashMap<>(requestHeader));
//-- set proxy authorization
headers.put("application-id", apiGatewaySetting.getLimoAppId());
headers.put("Authorization", apiGatewaySetting.getLimoAppSecret());
//--
String requestBody = buildFormUrlEncodedBody(formData);
requestDef.setRequestUrl(requestUrl);
@@ -589,9 +579,8 @@ public class MGMLimoApiService {
}
String responseContent = httpResult.getResponseContent();
int responseLength = (responseContent == null ? 0 : responseContent.length());
LogUtil.info(MGMLimoApiService.class, "[invokeFormUrlEncodedAPI] Limo action:" + (formData == null ? null : formData.get("action"))
+ " Limo ResponseLength:" + responseLength
+ " Limo Response:" + responseContent
+ " Status=" + httpResult.getStatusCode());
httpResult.setRequestContent(requestBody);
@@ -3,10 +3,18 @@ package com.mgm.mcrm.common.utils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class EncryptUtil {
private static final String AES_TRANSFORMATION = "AES/GCM/NoPadding";
private static final int GCM_IV_LENGTH = 12;
private static final int GCM_TAG_LENGTH = 16;
public static String sha256(String plainString) {
String cipherString = null;
try {
@@ -26,4 +34,43 @@ public class EncryptUtil {
return cipherString;
}
/**
* 与前端 cfgSettingCrypto.normalizeSecret 对齐:去空白、去 UTF-8 BOM,
* 避免 properties 或编辑器带入不可见字符导致与客户端 SHA-256 密钥不一致。
*/
public static String normalizeAllowKey(String secret) {
if (secret == null) {
return null;
}
String s = secret.trim();
if (!s.isEmpty() && s.charAt(0) == '\uFEFF') {
s = s.substring(1);
}
return s;
}
public static String aesEncryptToBase64(String plainText, String secret) {
if (plainText == null || secret == null || secret.isEmpty()) {
return null;
}
try {
secret = normalizeAllowKey(secret);
if (secret == null || secret.isEmpty()) {
return null;
}
byte[] keyBytes = MessageDigest.getInstance("SHA-256").digest(secret.getBytes(StandardCharsets.UTF_8));
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
byte[] iv = new byte[GCM_IV_LENGTH];
new SecureRandom().nextBytes(iv);
Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
GCMParameterSpec gcmSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(iv) + ":" + Base64.getEncoder().encodeToString(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
@@ -773,22 +773,31 @@ public class ExcelUtils {
public static void exportToResponse(ExportDefine reportDef, String reportFileName, Map<String,List<Object>> exportData,Map<String,List<GroupItem>> groupKeys, HttpServletResponse response, HttpServletRequest request) throws Exception {
File file = ExcelUtils.exportEXCEL(reportDef,exportData,groupKeys);
String origin = request.getHeader("Origin");
String sanitizedOrigin = NetworkUtil.encodePathWithSpring(origin);
response.reset();
String basePath = SysCommon.runtime_path + "\\"+SysCommon.runtimeName+"\\tmp\\";
String filePath = file.getCanonicalPath();
basePath = basePath.replace("/", "\\");
filePath = filePath.replace("/", "\\");
if (!filePath.startsWith(basePath)) {
throw new SecurityException("Invalid file path");
}
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Expose-Headers", "Location");
response.setHeader("Access-Control-Expose-Headers", "content-disposition");
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setHeader("content-disposition",
"attachment;filename=" + (StringUtils.isNotBlank(reportFileName)?reportFileName:reportDef.getExportFileName()));
response.getOutputStream().write(FileUtils.readFileToByteArray(file));
ExcelUtils.clearTempFile(file.getName());
if(SysCommon.isAllowOriginSource(sanitizedOrigin)) {
String basePath = SysCommon.runtime_path + "\\"+SysCommon.runtimeName+"\\tmp\\";
String filePath = file.getCanonicalPath();
basePath = basePath.replace("/", "\\");
filePath = filePath.replace("/", "\\");
if (!filePath.startsWith(basePath)) {
throw new SecurityException("Invalid file path");
}
response.setHeader("Access-Control-Allow-Origin",sanitizedOrigin);
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Expose-Headers", "Location");
response.setHeader("Access-Control-Expose-Headers", "content-disposition");
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setHeader("content-disposition",
"attachment;filename=" + (StringUtils.isNotBlank(reportFileName)?reportFileName:reportDef.getExportFileName()));
response.getOutputStream().write(FileUtils.readFileToByteArray(file));
ExcelUtils.clearTempFile(file.getName());
}else {
LogUtil.warn(ExcelUtils.class, "Origin of ["+sanitizedOrigin+"] is not allowed");
errorResponse("Download is not allowed from this site",request,response);
}
}
public static void errorResponse(String errorMessage,HttpServletRequest request, HttpServletResponse response) throws Exception {
//response.setContentType("text/html");
@@ -38,7 +38,9 @@ import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
@@ -51,14 +53,14 @@ public class HttpUtil {
HttpResponseResult responseResult = new HttpResponseResult();
CloseableHttpClient httpclient=null;
CloseableHttpResponse response = null;
String requestUrl =request.getRequestUrl();
if(!NetworkUtil.isValidURL(requestUrl)){
throw new SecurityException("Invalid URL of ["+requestUrl+"]");
String orgRequestUrl =request.getRequestUrl();
if(!NetworkUtil.isValidURL(orgRequestUrl)){
throw new SecurityException("Invalid URL of ["+orgRequestUrl+"]");
}
if (!SysCommon.isAllowApiServer(requestUrl)) {
if (!SysCommon.isAllowApiServer(orgRequestUrl)) {
throw new SecurityException("URL not allowed");
}
requestUrl = NetworkUtil.encodePathWithSpring(requestUrl);
String requestUrl = NetworkUtil.validateAndSanitizeUrl(orgRequestUrl);
try {
//--
RequestConfig.Builder configBuilder = RequestConfig.custom();
@@ -98,18 +100,19 @@ public class HttpUtil {
HttpClientContext context = HttpClientContext.create();
//--
if(Strings.CI.equals("POST", request.getRequestMethod())) {
HttpPost httppost = new HttpPost(requestUrl);
URI url = new URI(requestUrl);
HttpPost httppost = new HttpPost(url);
httppost.setConfig(requestConfig);
if(request.isUpload()!=true) {
if(!request.isUpload()) {
if(request.getHeaders()!=null) {
Map<String, String> headermap = request.getHeaders();
for (Map.Entry<String, String> entry : headermap.entrySet()) {
if(!Strings.CI.equals("Content-Length",entry.getKey())){
httppost.addHeader(entry.getKey(), NetworkUtil.sanitizeHeaderValue(entry.getValue()));
httppost.addHeader(entry.getKey(), NetworkUtil.sanitizeCRLF(entry.getValue()));
}
}
}
httppost.setEntity(new StringEntity(request.getEntityContent(), Charset.forName("UTF-8")));
httppost.setEntity(new StringEntity(request.getEntityContent(), StandardCharsets.UTF_8));
responseResult.setRequestContent(request.getEntityContent());
response = httpclient.execute(httppost,context);
}else {
@@ -128,7 +131,7 @@ public class HttpUtil {
Map<String, String> headermap = request.getHeaders();
for (Map.Entry<String, String> entry : headermap.entrySet()) {
if(!Strings.CI.equals("Content-Length",entry.getKey())){
httpput.addHeader(entry.getKey(), NetworkUtil.sanitizeHeaderValue(entry.getValue()));
httpput.addHeader(entry.getKey(), NetworkUtil.sanitizeCRLF(entry.getValue()));
}
}
}
@@ -147,7 +150,7 @@ public class HttpUtil {
Map<String, String> headermap = request.getHeaders();
for (Map.Entry<String, String> entry : headermap.entrySet()) {
if(!Strings.CI.equals("Content-Length",entry.getKey())){
httpget.addHeader(entry.getKey(), NetworkUtil.sanitizeHeaderValue(entry.getValue()));
httpget.addHeader(entry.getKey(), NetworkUtil.sanitizeCRLF(entry.getValue()));
}
}
}
@@ -6,15 +6,10 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.web.util.UriUtils;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.lang.management.ManagementFactory;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -27,7 +22,19 @@ public class NetworkUtil {
"10.", "192.168.", "172.16.", "172.17.", "172.18.", "172.19.",
"172.20.", "172.21.", "172.22.", "172.23.", "172.24.", "172.25.",
"172.26.", "172.27.", "172.28.", "172.29.", "172.30.", "172.31."
);
private static final Set<String> ALLOWED_PROTOCOLS = new HashSet<>(
Arrays.asList("http", "https")
);
// 禁止的端口
private static final Set<Integer> BLOCKED_PORTS = new HashSet<>(
Arrays.asList(22, 23, 25, 53, 110, 143, 3306, 5432, 6379, 27017)
);
public static void setInternalIpPattern(String patternConfig) {
interalIpPatterns.clear();
@@ -167,13 +174,13 @@ public class NetworkUtil {
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = address.nextElement();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) {// 外网IP
netip = ip.getHostAddress();
ips.add(netip);
finded = true;
break;
} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {// 内网IP
&& !ip.getHostAddress().contains(":")) {// 内网IP
localip = ip.getHostAddress();
ips.add(localip);
}
@@ -188,7 +195,7 @@ public class NetworkUtil {
* @return the real ip
*/
public static String getRealIp() {
return getRealIps().iterator().next();
return Objects.requireNonNull(getRealIps()).getFirst();
}
/**
@@ -202,22 +209,22 @@ public class NetworkUtil {
// 外网IP
String netip = null;
try {
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
// 是否找到外网IP
boolean finded = false;
while (netInterfaces.hasMoreElements() && !finded) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
Enumeration address = ni.getInetAddresses();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = (InetAddress) address.nextElement();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) {
// 外网IP
netip = ip.getHostAddress();
finded = true;
break;
} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {
&& !ip.getHostAddress().contains(":")) {
// 内网IP
localip = ip.getHostAddress();
}
@@ -227,7 +234,7 @@ public class NetworkUtil {
e.printStackTrace();
}
if (netip != null && !"".equals(netip)) {
if (netip != null && !netip.isEmpty()) {
return netip;
} else {
return localip;
@@ -350,10 +357,7 @@ public class NetworkUtil {
if(!"https".equals(scheme) && !"http".equals(scheme)) {
return false;
}
if(host.matches("\\d+\\.\\d+\\.\\d+\\.\\d+")) {
return false;
}
return true;
return !host.matches("\\d+\\.\\d+\\.\\d+\\.\\d+");
} catch (Exception e) {
return false;
}
@@ -378,4 +382,116 @@ public class NetworkUtil {
value= value.replace("\r", "").replace("\n", "");
return UriUtils.encodePath(value, StandardCharsets.UTF_8);
}
public static String sanitizeCRLF(String input){
if(input==null)
return null;
return input.replaceAll("[\r\n]+", "");
}
public static String validateAndSanitizeUrl(String userInputUrl) throws SecurityException {
if (userInputUrl == null || userInputUrl.trim().isEmpty()) {
throw new SecurityException("URL should not be blank");
}
try {
// 1. 解析URL
URL url = new URI(userInputUrl).toURL();
// 2. 验证协议
validateProtocol(url.getProtocol());
// 3. 验证主机名/IP
String host = url.getHost();
validateHost(host);
// 4. 验证端口
int port = url.getPort();
if (port == -1) {
port = url.getDefaultPort();
}
validatePort(port);
// 5. 验证路径(防止路径遍历)
validatePath(url.getPath());
// 6. 返回净化后的URL(标准化)
return sanitizeUrl(url);
} catch (Exception e) {
throw new SecurityException("Invalid URL: " + e.getMessage(), e);
}
}
private static void validateProtocol(String protocol) throws SecurityException {
if (!ALLOWED_PROTOCOLS.contains(protocol.toLowerCase())) {
throw new SecurityException("No support protocol: " + protocol + ", only for HTTP/HTTPS");
}
}
private static void validateHost(String host) throws SecurityException {
if (host == null || host.isEmpty()) {
throw new SecurityException("Host name can not be empty");
}
// 解析IP并验证
try {
InetAddress address = InetAddress.getByName(host);
String ip = address.getHostAddress();
// 检查是否为回环地址(Debug 模式下允许,便于本地联调)
if (address.isLoopbackAddress() && !isDebugMode()) {
throw new SecurityException("Forbit loopback address");
}
} catch (UnknownHostException e) {
throw new SecurityException("Invalid host: " + host);
}
}
private static boolean isDebugMode() {
if (SysCommon.appDebugLog) {
return true;
}
return ManagementFactory.getRuntimeMXBean().getInputArguments().stream()
.anyMatch(arg -> arg.contains("-agentlib:jdwp") || arg.contains("-Xrunjdwp"));
}
private static void validatePort(int port) throws SecurityException {
// 检查是否为禁止端口
if (BLOCKED_PORTS.contains(port)) {
throw new SecurityException("Invalid Port: " + port);
}
}
private static void validatePath(String path) throws SecurityException {
if (path == null) return;
// 防止路径遍历攻击
if (path.contains("..")) {
throw new SecurityException("Invalid path contains '..'");
}
if (path.toLowerCase().contains("://")) {
throw new SecurityException("Invalid path prefix");
}
}
private static String sanitizeUrl(URL url) {
StringBuilder sb = new StringBuilder();
sb.append(url.getProtocol()).append("://");
sb.append(url.getHost());
int port = url.getPort();
if (port != -1 && port != url.getDefaultPort()) {
sb.append(":").append(port);
}
sb.append(url.getPath());
String query = url.getQuery();
if (query != null && !query.isEmpty()) {
sb.append("?").append(query);
}
return sb.toString();
}
}
@@ -1,12 +1,14 @@
package com.mgm.mcrm.common.utils;
import com.mgm.mcrm.common.constants.SysCommon;
import com.mgm.mcrm.common.dtos.config.ApiGatewaySetting;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.soap.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.core5.http.message.BasicHeader;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
@@ -15,6 +17,7 @@ import javax.xml.namespace.QName;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
@@ -37,7 +40,7 @@ public class SOAPUtil {
* 参考---》http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName
*/
public static String getWebServiceSOAP(String url,String action,StringBuffer sendSoapString){
public static String getWebServiceSOAP(String url, String action, StringBuffer sendSoapString, ApiGatewaySetting apiGatewaySetting){
String soap = sendSoapString.toString();
if (soap == null) {
return null;
@@ -58,8 +61,12 @@ public class SOAPUtil {
conn.setRequestProperty("Content-Length",
Integer.toString(soap.length()));
conn.setRequestProperty("Content-Type", "text/xml; charset=GBK");
conn.setConnectTimeout(SysCommon.apiConfig.getTimeout_OWS());
conn.setReadTimeout(SysCommon.apiConfig.getTimeout_OWS());
//-- set proxy auth code
conn.setRequestProperty("application-id",apiGatewaySetting.getOperaAppId());
conn.setRequestProperty("Authorization",apiGatewaySetting.getOperaAppSecret());
//--
conn.setConnectTimeout(apiGatewaySetting.getRequestTimeout());
conn.setReadTimeout(apiGatewaySetting.getRequestTimeout());
// 调用的接口方法是
conn.setRequestProperty("SOAPAction",action);
OutputStream os = conn.getOutputStream();
@@ -88,7 +95,7 @@ public class SOAPUtil {
return null;
}
public static String getWebServiceSOAPUTF(String url,String action,StringBuffer sendSoapString){
public static String getWebServiceSOAPUTF(String url,String action,StringBuffer sendSoapString, ApiGatewaySetting apiGatewaySetting){
String soap = sendSoapString.toString();
if (soap == null) {
return null;
@@ -109,6 +116,10 @@ public class SOAPUtil {
conn.setRequestProperty("Content-Length",
Integer.toString(soap.length()));
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
//-- set proxy auth code
conn.setRequestProperty("application-id",apiGatewaySetting.getOperaAppId());
conn.setRequestProperty("Authorization",apiGatewaySetting.getOperaAppSecret());
//--
// 调用的接口方法是
conn.setRequestProperty("SOAPAction",action);
OutputStream os = conn.getOutputStream();
@@ -153,33 +164,40 @@ public class SOAPUtil {
}
private static final TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
private X509TrustManager defaultTrustManager=null;
{
try {
// 获取 JVM 默认的 TrustManager 作为核心校验逻辑
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init((KeyStore) null); // 使用系统的默认信任库
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
defaultTrustManager = (X509TrustManager) tm;
}
}
}catch(Exception err){
LogUtil.error(SOAPUtil.class,"Default X509TrustManager not found["+err.getMessage()+"]");
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
return defaultTrustManager.getAcceptedIssuers();
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String arg1) throws CertificateException {
if (chain == null || chain.length == 0) {
throw new IllegalArgumentException("No server certificates provided");
}
for (X509Certificate cert : chain) {
cert.checkValidity();
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
defaultTrustManager.checkServerTrusted(chain,authType);
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String arg1) throws CertificateException {
if (chain == null || chain.length == 0) {
throw new CertificateException("No client certificates provided");
}
for (X509Certificate cert : chain) {
cert.checkValidity(); // 检查证书是否在有效期内
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
defaultTrustManager.checkClientTrusted(chain,authType);
}
}};
private static final HostnameVerifier checkSoapServer = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
boolean isServerAllow = SysCommon.isAllowSoapServer(hostname);
@@ -453,7 +453,6 @@ public class SendEmail {
userName = !StringUtils.isEmpty(userName)?userName:"";
String tUser = userId+" "+userName;
String approvalStatus = EumnApprovalStatus.getApprovalStatusByDBValue(book.getApproveStatus());
content2 += "<tr>"+
"<td>"
@@ -562,6 +561,171 @@ public class SendEmail {
return emailObj;
}
public static Email sendCreateR2Y2NewEmail(Bookings book,BookingsView bookView,Email emailObj,String userId,String userName,boolean isOverBook,boolean isConnectRoom,String emailTo) {
String content1 = emailNewApprovalTemp;
try {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
if(StringUtils.isEmpty(mail_smtp_host)) {
mail_smtp_host = SysCommon.apiConfig.getHost_SMTP();
}
mail_port = Integer.valueOf(SysCommon.apiConfig.getPort_SMTP());
if(StringUtils.isEmpty(mail_sender)) {
mail_sender = SysCommon.apiConfig.getUsername_SMTP();
}
if(StringUtils.isEmpty(mail_sender_password)) {
mail_sender_password = SysCommon.apiConfig.getPassword_SMTP();
}
if(!StringUtils.isEmpty(emailTo)) {
mail_to = emailTo;
}else {
mail_to = SysCommon.apiConfig.getSend_to_SMTP();
}
sender.setHost(mail_smtp_host);
sender.setPort(mail_port); // 默认就是25
sender.setUsername(mail_sender);
sender.setPassword(mail_sender_password);//
sender.setDefaultEncoding("UTF-8");
// 配置文件对象
Properties props = new Properties();
props.put("mail.smtp.auth", "false"); // 是否进行验证
Session session = Session.getInstance(props);
sender.setSession(session); // 为发送器指定会话
MimeMessage mail = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mail, true);
String mainTitle;
if(isConnectRoom) {
mainTitle = "[R2/Y2]";
}else if(isOverBook) {
mainTitle = "[Overbook]";
}else {
mainTitle = "[Urgent]";
}
helper.setSubject(mainTitle+"Booking Creation from Mobile CRM APP"); // 标题
helper.setFrom(mail_sender); // 来自
SimpleDateFormat sf = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String RequestDate = sf.format(new Date());
String content2 = "";
String tTime = RequestDate;
userId = !StringUtils.isEmpty(userId)?userId:"";
userName = !StringUtils.isEmpty(userName)?userName:"";
String tUser = userId+" "+userName;
String approvalStatus = EumnApprovalStatus.getApprovalStatusByDBValue(book.getApproveStatus());
content2 += "<tr>"+
"<td>"
+approvalStatus+
"</td> "+
"<td >"
+bookView.getPlayerId()+
"</td> " +
"<td>"
+bookView.getMemberLastName()+
"</td> " +
"<td>"
+(bookView.getMemberTier()!=null?bookView.getMemberTier():"")+
"</td> " +
"<td>"
+(bookView.getPropertyName()!=null?bookView.getPropertyName():"")+
"</td> " +
"<td>"
+(bookView.getRoom()!=null?bookView.getRoom():"")+
"</td> "+
"<td>"
+(bookView.getSharerName()!=null?bookView.getSharerName():"")+
"</td> " +
"<td>"
+"New"+
"</td> "+
"<td>"
+format.format(bookView.getCheckinDate())+
"</td> " +
"<td>"
+format.format(bookView.getCheckoutDate())+
"</td> " +
"<td>"
+(bookView.getBookerTeam()!=null?bookView.getBookerTeam():"")+
"</td> " +
"<td>"
+bookView.getCreatedBy()+
"</td> " +
"<td>"
+bookView.getCreatedByName()+
"</td> " +
"<td>"
+(bookView.getApprovalRemark()!=null?bookView.getApprovalRemark():"")+
"</td> " +
"<td>"
+(bookView.getRemark()!=null?bookView.getRemark():"")+
"</td> " +
"</tr> ";
String mailContent = isConnectRoom?"Please create TT/YY booking for below approved booking<br><br>":"";
content1 = content1.replace("{{tbody}}", content2);
content1 = content1.replace("{{ttime}}", tTime);
content1 = content1.replace("{{tuser}}", tUser);
content1 = content1.replace("{{content}}", mailContent);
helper.setText(content1,true); // 邮件内容,第二个参数指定发送的是HTML格式
JSONObject emailJson = new JSONObject();
emailJson.put("approvalStatus", approvalStatus);
emailJson.put("memberId", bookView.getPlayerId());
emailJson.put("memberName", bookView.getMemberLastName());
emailJson.put("tier", bookView.getMemberTier());
emailJson.put("property", bookView.getPropertyName());
emailJson.put("roomType", bookView.getRoom());
emailJson.put("type", "New");
emailJson.put("checkin", format.format(bookView.getCheckinDate()));
emailJson.put("checkout", format.format(bookView.getCheckoutDate()));
emailJson.put("bookerTeam", bookView.getBookerTeam());
emailJson.put("bookerId", bookView.getCreatedBy());
emailJson.put("bookerName", bookView.getCreatedByName());
emailJson.put("approvalRemark", bookView.getApprovalRemark());
emailJson.put("remark", bookView.getRemark());
emailObj.setSendObject(emailJson.toJSONString());
emailObj.setContent(content1);
emailObj.setSendTo(mail_to);
String[] mailToArr = StringUtils.split(mail_to,";");
if(mailToArr.length>1) {
for (String str : mailToArr) {
helper.setTo(str);
try {
sender.send(mail); // 发送
emailObj.setStatus(1);
} catch (Exception e) {
emailObj.setMessage("Send Email to "+str+" Failed:"+e.getMessage());
emailObj.setStatus(0);
}
}
}else {
helper.setTo(mail_to);
try {
sender.send(mail); // 发送
emailObj.setStatus(1);
LogUtil.info(SendEmail.class, "---mgmEmail.sendApprovalNewEmail--OK!");
} catch (Exception e) {
emailObj.setMessage("Send Email to "+mail_to+" Failed:"+e.getMessage());
emailObj.setStatus(0);
LogUtil.error(SendEmail.class, "---mgmEmail.sendApprovalNewEmail--Failed!"+e.getMessage());
}
}
} catch (Exception e) {
LogUtil.error(SendEmail.class,"---mgmEmail.sendApprovalNewEmail--Exception-->>"+e.getMessage());
emailObj.setMessage(e.getMessage());
emailObj.setStatus(0);
}
return emailObj;
}
public static Email sendApprovalExtendEmail(Bookings book,BookingsView originBook,Email emailObj,String userId,String userName,BookingsView viewBook,boolean isOverBook,String emailTo) {
String content1 = emailApprovalTemp;
@@ -590,7 +754,7 @@ public class SendEmail {
// 配置文件对象
Properties props = new Properties();
props.put("mail.smtp.auth", "false"); // 是否进行验证
props.put("mail.smtp.auth", "true"); // 是否进行验证
Session session = Session.getInstance(props);
sender.setSession(session); // 为发送器指定会话
@@ -623,7 +787,7 @@ public class SendEmail {
changeCheckInDate = viewBook.getCheckinDate()!=null?format.format(viewBook.getCheckinDate()):"";
}
content2 += "<tr>"+
"<td>"
+approvalStatus+
@@ -928,7 +1092,7 @@ public class SendEmail {
MimeMessageHelper helper = new MimeMessageHelper(mail, true);
String subject = emailTemplate.getSubject();
subject = StringUtils.replace(subject, "[TODAY]",DateTimeUtil.getCurrentDate("dd MMM"));
subject = Strings.CI.replace(subject, "[TODAY]", DateTimeUtil.getCurrentDate("dd MMM"));
helper.setSubject(subject); // 标题
helper.setFrom(mail_sender); // 来自