init
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
package com.mgm.mcrm.common.annotation.logging;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface OperationLog {
|
||||
public String eventCode();
|
||||
public String actionName();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.mgm.mcrm.common.annotation.security;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target({ElementType.METHOD, ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface AccessToken {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.mgm.mcrm.common.annotation.security;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target({ElementType.METHOD, ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface PassToken {
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.mgm.mcrm.common.config;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
|
||||
/**
|
||||
* @Description: 数据源配置
|
||||
*/
|
||||
@Configuration
|
||||
public class DataSourceConfig {
|
||||
|
||||
@Bean(name = "mgmDataSource")
|
||||
@Qualifier("mgmDataSource")
|
||||
@ConfigurationProperties(prefix = "spring.datasource.mgm")
|
||||
@Primary
|
||||
public DataSource mgmDataSource() {
|
||||
return DataSourceBuilder.create().build();
|
||||
}
|
||||
|
||||
@Bean(name = "operaDataSource")
|
||||
@Qualifier("operaDataSource")
|
||||
@ConfigurationProperties(prefix = "spring.datasource.opera")
|
||||
public DataSource operaDataSource() {
|
||||
return DataSourceBuilder.create().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.mgm.mcrm.common.config;
|
||||
|
||||
import com.mgm.mcrm.common.httpclient.HttpSslSupport;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
|
||||
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
|
||||
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.hc.core5.http.config.Registry;
|
||||
import org.apache.hc.core5.http.config.RegistryBuilder;
|
||||
import org.apache.hc.core5.util.Timeout;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* HttpClient 配置类
|
||||
*
|
||||
* 提供统一的 HttpClient Bean 配置,包括:
|
||||
* - SSL 配置
|
||||
* - 连接池配置
|
||||
* - 请求超时配置
|
||||
*
|
||||
* 配置参数从 application.yml 中读取:
|
||||
* - httpclient.pool.max-total: 连接池最大连接数,默认 100
|
||||
* - httpclient.pool.max-per-route: 每个路由最大连接数,默认 10
|
||||
* - httpclient.timeout.connection-request: 连接请求超时时间(秒),默认 5
|
||||
* - httpclient.timeout.response: 响应超时时间(秒),默认 10
|
||||
* - httpclient.redirects-enabled: 是否启用重定向,默认 false
|
||||
*
|
||||
* @author Aaka
|
||||
*/
|
||||
@Configuration
|
||||
public class HttpClientConfig {
|
||||
|
||||
@Value("${httpclient.pool.max-total:100}")
|
||||
private int maxTotal;
|
||||
|
||||
@Value("${httpclient.pool.max-per-route:30}")
|
||||
private int maxPerRoute;
|
||||
|
||||
@Value("${httpclient.timeout.connection-request:10}")
|
||||
private int connectionRequestTimeout;
|
||||
|
||||
@Value("${httpclient.timeout.response:10}")
|
||||
private int responseTimeout;
|
||||
|
||||
@Value("${httpclient.redirects-enabled:false}")
|
||||
private boolean redirectsEnabled;
|
||||
|
||||
private PoolingHttpClientConnectionManager connectionManager;
|
||||
|
||||
/**
|
||||
* 创建带 SSL 配置的 HttpClient Bean
|
||||
*
|
||||
* @return 配置好的 CloseableHttpClient 实例
|
||||
*/
|
||||
@Bean(name = "httpClientWithSSL")
|
||||
public CloseableHttpClient httpClientWithSSL() {
|
||||
// 使用 SSLs 配置 SSL
|
||||
HttpSslSupport ssls = HttpSslSupport.getInstance();
|
||||
@SuppressWarnings("deprecation")
|
||||
SSLConnectionSocketFactory sslConnFactory = ssls.getSSLCONNSF(HttpSslSupport.SSLProtocolVersion.TLSv1_2);
|
||||
|
||||
// 注意:ConnectionSocketFactory 和 SSLConnectionSocketFactory 在 HttpClient 5 中被标记为 deprecated,
|
||||
// 但这是目前唯一可用的方式,新的 API 尚未稳定
|
||||
@SuppressWarnings("deprecation")
|
||||
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("https", sslConnFactory)
|
||||
.build();
|
||||
|
||||
// 注意:PoolingHttpClientConnectionManager 构造函数在 HttpClient 5 中被标记为 deprecated,
|
||||
// 但这是目前唯一可用的方式
|
||||
@SuppressWarnings("deprecation")
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
|
||||
connManager.setMaxTotal(maxTotal);
|
||||
connManager.setDefaultMaxPerRoute(maxPerRoute);
|
||||
|
||||
this.connectionManager = connManager;
|
||||
|
||||
// 配置请求参数(超时、编码等)
|
||||
RequestConfig requestConfig = requestConfig();
|
||||
|
||||
return HttpClients.custom()
|
||||
.setConnectionManager(connManager)
|
||||
.setDefaultRequestConfig(requestConfig)
|
||||
.setConnectionManagerShared(false)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 RequestConfig Bean
|
||||
*
|
||||
* @return 配置好的 RequestConfig 实例
|
||||
*/
|
||||
@Bean(name = "httpRequestConfig")
|
||||
public RequestConfig requestConfig() {
|
||||
return RequestConfig.custom()
|
||||
.setConnectionRequestTimeout(Timeout.ofSeconds(connectionRequestTimeout))
|
||||
.setResponseTimeout(Timeout.ofSeconds(responseTimeout))
|
||||
.setRedirectsEnabled(redirectsEnabled)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭连接管理器
|
||||
* 在 Spring Bean 销毁时自动调用
|
||||
*/
|
||||
@PreDestroy
|
||||
public void close() {
|
||||
if (connectionManager != null) {
|
||||
connectionManager.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.mgm.mcrm.common.config;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* HTTP 請求頭配置類
|
||||
* 用於自定義 HTTP 請求頭的值
|
||||
*
|
||||
* @author System
|
||||
*/
|
||||
@Data
|
||||
public class HttpHeader {
|
||||
public static final String ACCEPT = "Accept";
|
||||
public static final String ACCEPT_CHARSET = "Accept-Charset";
|
||||
public static final String ACCEPT_ENCODING = "Accept-Encoding";
|
||||
public static final String ACCEPT_LANGUAGE = "Accept-Language";
|
||||
public static final String ACCEPT_RANGES = "Accept-Ranges";
|
||||
public static final String AUTHORIZATION = "Authorization";
|
||||
public static final String CACHE_CONTROL = "Cache-Control";
|
||||
public static final String CONNECTION = "Connection";
|
||||
public static final String COOKIE = "Cookie";
|
||||
public static final String CONTENT_LENGTH = "Content-Length";
|
||||
public static final String CONTENT_TYPE = "Content-Type";
|
||||
public static final String USER_AGENT = "user-agent";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.mgm.mcrm.common.config;
|
||||
|
||||
import java.net.ConnectException;
|
||||
|
||||
import jakarta.jms.ConnectionFactory;
|
||||
import jakarta.jms.ExceptionListener;
|
||||
import jakarta.jms.JMSException;
|
||||
|
||||
import org.apache.activemq.ActiveMQConnectionFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
|
||||
|
||||
import com.mgm.mcrm.common.constants.SysCommon;
|
||||
|
||||
@Configuration
|
||||
public class JMSConfig {
|
||||
|
||||
@Value("${spring.activemq.broker-url}")
|
||||
private String activeMQServer;
|
||||
@Value("${spring.activemq.user}")
|
||||
private String userName;
|
||||
@Value("${spring.activemq.password}")
|
||||
private String password;
|
||||
@Value("${spring.activemq.concurrency}")
|
||||
private String concurrencyCfg="3-10";
|
||||
|
||||
@Bean
|
||||
public ConnectionFactory connectionFactory(){
|
||||
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
|
||||
connectionFactory.setBrokerURL(activeMQServer);
|
||||
connectionFactory.setUserName(userName);
|
||||
connectionFactory.setPassword(password);
|
||||
return connectionFactory;
|
||||
|
||||
}
|
||||
|
||||
@Bean(name = "jmsQueueListenerCF")
|
||||
public DefaultJmsListenerContainerFactory jmsQueueListenerContainerFactory() {
|
||||
DefaultJmsListenerContainerFactory factory =
|
||||
new DefaultJmsListenerContainerFactory();
|
||||
factory.setConnectionFactory(connectionFactory());
|
||||
factory.setConcurrency(concurrencyCfg);
|
||||
factory.setPubSubDomain(false);
|
||||
factory.setRecoveryInterval(20000L);
|
||||
factory.setExceptionListener(new JMSErrorHandler());
|
||||
factory.setSessionAcknowledgeMode(jakarta.jms.Session.CLIENT_ACKNOWLEDGE);
|
||||
factory.setAutoStartup(true);
|
||||
return factory;
|
||||
}
|
||||
@Bean(name = "jmsTopicListenerCF")
|
||||
public DefaultJmsListenerContainerFactory jmsTopicListenerContainerFactory() {
|
||||
DefaultJmsListenerContainerFactory factory =
|
||||
new DefaultJmsListenerContainerFactory();
|
||||
factory.setConnectionFactory(connectionFactory());
|
||||
factory.setConcurrency("1");
|
||||
factory.setPubSubDomain(true);
|
||||
factory.setRecoveryInterval(20000L);
|
||||
factory.setExceptionListener(new JMSErrorHandler());
|
||||
factory.setSessionAcknowledgeMode(jakarta.jms.Session.CLIENT_ACKNOWLEDGE);
|
||||
factory.setAutoStartup(true);
|
||||
return factory;
|
||||
}
|
||||
|
||||
private class JMSErrorHandler implements ExceptionListener {
|
||||
@Override
|
||||
public void onException(JMSException exception) {
|
||||
if(exception.getCause()!=null && exception.getCause() instanceof ConnectException) {
|
||||
SysCommon.jmsRunning=false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.mgm.mcrm.common.config;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
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.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
/**
|
||||
* @Description: 主数据源配置
|
||||
* @date
|
||||
*/
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory",
|
||||
transactionManagerRef = "transactionManager",
|
||||
basePackages = {"com.mgm.mcrm"})
|
||||
public class MGMDataSourceConfig {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("mgmDataSource")
|
||||
private DataSource mrbsDataSource;
|
||||
|
||||
@Primary
|
||||
@Bean(name = "mgmJpaProperties")
|
||||
@ConfigurationProperties(prefix = "spring.jpa.mgm")
|
||||
public JpaProperties jpaProperties() {
|
||||
return new JpaProperties();
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean(name = "entityManager")
|
||||
public EntityManager entityManager( @Qualifier("entityManagerFactory") EntityManagerFactory factory) {
|
||||
return factory.createEntityManager();
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean(name = "entityManagerFactory") //mrbs实体工厂
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory (@Qualifier("mgmDataSource") DataSource mgmDataSource,
|
||||
@Qualifier("mgmJpaProperties") JpaProperties jpaProperties,EntityManagerFactoryBuilder builder) {
|
||||
return builder.dataSource(mgmDataSource)
|
||||
.properties(jpaProperties.getProperties())
|
||||
.properties(
|
||||
new HibernateProperties()
|
||||
.determineHibernateProperties(
|
||||
jpaProperties.getProperties(), new HibernateSettings()))
|
||||
.packages("com.mgm.mcrm") //实体类所在位置
|
||||
.persistenceUnit("mgmPersistenceUnit")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean(name = "transactionManager")
|
||||
public PlatformTransactionManager transactionManager(@Qualifier("entityManagerFactory") EntityManagerFactory factory) {
|
||||
return new JpaTransactionManager(factory);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.mgm.mcrm.common.config;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
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.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
/**
|
||||
* @Description: 副数据源配置
|
||||
* @date
|
||||
*/
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryOpera",
|
||||
transactionManagerRef = "transactionManagerOpera")
|
||||
public class OperaDataSourceConfig {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("operaDataSource")
|
||||
private DataSource operaDataSource;
|
||||
|
||||
@Bean(name = "operaJpaProperties")
|
||||
@ConfigurationProperties(prefix = "spring.jpa.opera")
|
||||
public JpaProperties jpaProperties() {
|
||||
return new JpaProperties();
|
||||
}
|
||||
|
||||
@Bean(name = "entityManagerOpera")
|
||||
public EntityManager entityManager( @Qualifier("entityManagerFactoryOpera") EntityManagerFactory factory) {
|
||||
return factory.createEntityManager();
|
||||
}
|
||||
|
||||
@Bean(name = "entityManagerFactoryOpera")
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactoryOpera (@Qualifier("operaDataSource") DataSource operaDataSource,
|
||||
@Qualifier("operaJpaProperties") JpaProperties jpaProperties,EntityManagerFactoryBuilder builder) {
|
||||
return builder.dataSource(operaDataSource)
|
||||
.properties(jpaProperties.getProperties())
|
||||
.properties(
|
||||
new HibernateProperties()
|
||||
.determineHibernateProperties(
|
||||
jpaProperties.getProperties(), new HibernateSettings()))
|
||||
.packages("com.mgm.mcrm.booking.models") //实体类所在位置
|
||||
.persistenceUnit("operaPersistenceUnit")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean(name = "transactionManagerOpera")
|
||||
public PlatformTransactionManager transactionManagerOpera(@Qualifier("entityManagerFactoryOpera") EntityManagerFactory factory) {
|
||||
return new JpaTransactionManager(factory);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.mgm.mcrm.common.config;
|
||||
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class SwaggerConfig {
|
||||
@Bean
|
||||
public OpenAPI customOpenAPI() {
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("API Document for MGM Daylight application")
|
||||
.version("1.0")
|
||||
.description("API document for MGM Daylight application"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.mgm.mcrm.common.config;
|
||||
|
||||
import com.mgm.mcrm.appsetting.services.SettingService;
|
||||
import com.mgm.mcrm.authorization.filters.JwtAuthFilter;
|
||||
import com.mgm.mcrm.authorization.services.UserTokenService;
|
||||
import com.mgm.mcrm.authorization.utils.JwtTokenUtil;
|
||||
import com.mgm.mcrm.common.filters.ConfigHeaderFilter;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
public class WebFilterConfig {
|
||||
|
||||
@Resource
|
||||
private UserTokenService userTokenService;
|
||||
|
||||
@Resource
|
||||
private SettingService settingService;
|
||||
|
||||
@Value("${mcrm.security.jwt.secret-key}")
|
||||
private String secretKey;
|
||||
|
||||
@Value("${mcrm.security.jwt.api-token-expiration}")
|
||||
private int apiTokenExpiration;
|
||||
|
||||
@Value("${mcrm.security.jwt.mobile-session-expiration}")
|
||||
private int mobileSessionExpiration;
|
||||
|
||||
@Bean
|
||||
public TaskScheduler taskScheduler() {
|
||||
ThreadPoolTaskScheduler scheduling = new ThreadPoolTaskScheduler();
|
||||
scheduling.setPoolSize(10);
|
||||
scheduling.initialize();
|
||||
return scheduling;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<ConfigHeaderFilter> registerHeaderFilter() {
|
||||
FilterRegistrationBean<ConfigHeaderFilter> registration = new FilterRegistrationBean<ConfigHeaderFilter>();
|
||||
registration.setFilter(new ConfigHeaderFilter());
|
||||
registration.addUrlPatterns("/*");
|
||||
registration.setName("ConfigHeaderFilter");
|
||||
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
|
||||
return registration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<JwtAuthFilter> jwtAuthFilter() {
|
||||
JwtTokenUtil.setSecretKey(secretKey);
|
||||
JwtTokenUtil.setAppSessionExpiration(apiTokenExpiration);
|
||||
JwtTokenUtil.setAppSessionExpiration(mobileSessionExpiration);
|
||||
List<String> excludePatterns = Arrays.asList(
|
||||
"/api/system/write_log",
|
||||
"/api/system/sys_setting/get_list",
|
||||
"/api/app/sso/*",
|
||||
"/api/app/booking/mock_cancel",
|
||||
"/api/web/setting/get_setting_by_key",
|
||||
"/swagger*/*",
|
||||
"/v3/**",
|
||||
"/api-docs",
|
||||
"/api-docs/**",
|
||||
"/webjars/**",
|
||||
"/swagger-resources/**"
|
||||
);
|
||||
|
||||
FilterRegistrationBean<JwtAuthFilter> registrationBean = new FilterRegistrationBean<>();
|
||||
JwtAuthFilter filter = new JwtAuthFilter();
|
||||
filter.setUserTokenService(userTokenService);
|
||||
filter.setExcludePatterns(excludePatterns);
|
||||
filter.setSettingService(settingService);
|
||||
registrationBean.setFilter(filter);
|
||||
registrationBean.addUrlPatterns("/*");
|
||||
registrationBean.setOrder(2);
|
||||
registrationBean.setName("RequestJwtFilter");
|
||||
|
||||
return registrationBean;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
package com.mgm.mcrm.common.constants;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.reflect.Field;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import com.mgm.mcrm.authorization.dtos.LoginUserInfo;
|
||||
import com.mgm.mcrm.authorization.models.SysUser;
|
||||
import com.mgm.mcrm.authorization.models.SysUserView;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.springframework.boot.system.ApplicationHome;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.web.servlet.support.RequestContextUtils;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
|
||||
import com.mgm.mcrm.logging.models.SysLogLogin;
|
||||
import com.mgm.mcrm.logging.models.SysLogOperation;
|
||||
import com.mgm.mcrm.appsetting.models.SysSetting;
|
||||
import com.mgm.mcrm.common.dtos.config.APIConfig;
|
||||
import com.mgm.mcrm.common.dtos.msg.AppSettingMsgData;
|
||||
import com.mgm.mcrm.common.dtos.msg.UpdateCfgItem;
|
||||
import com.mgm.mcrm.common.dtos.system.AppServerState;
|
||||
import com.mgm.mcrm.booking.services.BookingService;
|
||||
import com.mgm.mcrm.common.utils.LogUtil;
|
||||
import com.mgm.mcrm.common.utils.NetworkUtil;
|
||||
|
||||
public class SysCommon {
|
||||
|
||||
public static String runtime_path = "";
|
||||
public static String serverIp="";
|
||||
public static String serverName="";
|
||||
public static boolean dbDebugLog = false;
|
||||
public static boolean apiDebugLog = false;
|
||||
public static boolean appDebugLog = false;
|
||||
public static boolean mgmApiMockup =true;
|
||||
public static boolean jmsRunning=false;
|
||||
public static String defaultRouter = "welcome";
|
||||
public static String runtimeName="crm_mobile_runtime";
|
||||
public static int postTimeOut = 20;
|
||||
//for stress test
|
||||
public static int tokenExpMin = 5;
|
||||
public static int refreshTokenExpDay = 30;
|
||||
public static String tokenSecret = "SecretKeyWhichShouldBeLongEnoughToBeSecure67848563";
|
||||
public static APIConfig apiConfig = new APIConfig();
|
||||
private static Map<String,String> notifyTemplateMap = new HashMap<String,String>();
|
||||
private static Map<String,AppServerState> appServerStates = new HashMap<String,AppServerState>();
|
||||
private static List<String> allowOriginSource = new ArrayList<String>();
|
||||
private static List<String> soapServers = new ArrayList<String>();
|
||||
private static List<String> httpApiServers = new ArrayList<String>();
|
||||
private static List<String> allowIPSource = new ArrayList<String>();
|
||||
// @Autowired
|
||||
private static MessageSource messageSource;
|
||||
|
||||
public static String getSystemPath() {
|
||||
ApplicationHome h = new ApplicationHome(SysCommon.class);
|
||||
File f = h.getSource();
|
||||
return f.getParentFile().toString();
|
||||
}
|
||||
|
||||
public static void initRuntimePath() {
|
||||
runtime_path = getSystemPath();
|
||||
}
|
||||
|
||||
public static boolean loadSystemConfig() {
|
||||
boolean isLoaded = true;
|
||||
Properties props = new Properties();
|
||||
try {
|
||||
initRuntimePath();
|
||||
// load config from appconfig.properties
|
||||
String configFile = runtime_path + "/crm_mobile_runtime/appconfig.properties";
|
||||
InputStream inStream = new BufferedInputStream(new FileInputStream(configFile));
|
||||
props.load(inStream);
|
||||
//--Server Info
|
||||
serverIp = NetworkUtil.getInternalIp();
|
||||
serverName = NetworkUtil.getServerName();
|
||||
loadAPIConfig(props);
|
||||
} catch (Exception e) {
|
||||
isLoaded = false;
|
||||
LogUtil.error(SysCommon.class, "Load configuration error:" + e.getMessage());
|
||||
} finally {
|
||||
props.clear();
|
||||
props = null;
|
||||
}
|
||||
return isLoaded;
|
||||
}
|
||||
|
||||
public static void loadSettingsFromDB(List<SysSetting> sysSettings) {
|
||||
System.out.println("[SysCommon][loadSettingsFromDB] Load settings from DB, setting size=" + sysSettings.size());
|
||||
for(int i=0; i<sysSettings.size();i++) {
|
||||
SysSetting setting = sysSettings.get(i);
|
||||
if(setting.getSettingKey().equals("DB_DEBUG_LOG")) {
|
||||
if(setting.getSettingValue().equals("1")) {
|
||||
dbDebugLog = true;
|
||||
}else {
|
||||
dbDebugLog = false;
|
||||
}
|
||||
}
|
||||
if(setting.getSettingKey().equals("API_DEBUG_LOG")) {
|
||||
if(setting.getSettingValue().equals("1")) {
|
||||
apiDebugLog = true;
|
||||
}else {
|
||||
apiDebugLog = false;
|
||||
}
|
||||
}
|
||||
if(setting.getSettingKey().equals("APP_DEBUG_LOG")) {
|
||||
if(setting.getSettingValue().equals("1")) {
|
||||
appDebugLog = true;
|
||||
}else {
|
||||
appDebugLog = false;
|
||||
}
|
||||
}
|
||||
if(setting.getSettingKey().equals("APP_MOCK")) {
|
||||
if(setting.getSettingValue().equals("1")) {
|
||||
mgmApiMockup = true;
|
||||
}else {
|
||||
mgmApiMockup = false;
|
||||
}
|
||||
}
|
||||
if(setting.getSettingKey().equals("DEFAULT_ROUTER")) {
|
||||
if(StringUtils.isNotBlank(setting.getSettingValue())) {
|
||||
defaultRouter = setting.getSettingValue();
|
||||
}
|
||||
}
|
||||
if(setting.getSettingKey().equals("POST_TIME_OUT")) {
|
||||
if(StringUtils.isNotBlank(setting.getSettingValue())) {
|
||||
postTimeOut = Integer.valueOf(setting.getSettingValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("[SysCommon][loadSettingsFromDB] Loaded settings, DB_DEBUG_LOG=" + dbDebugLog + ", API_DEBUG_LOG="+apiDebugLog+", APP_DEBUG_LOG="+appDebugLog+", POST_TIME_OUT="+postTimeOut);
|
||||
}
|
||||
|
||||
// --
|
||||
public static MessageSource getMessageSource() {
|
||||
return messageSource;
|
||||
}
|
||||
|
||||
public static void setMessageSource(MessageSource messageSource) {
|
||||
SysCommon.messageSource = messageSource;
|
||||
}
|
||||
|
||||
public static String getMessage(String messageCode, String defaultMessage, HttpServletRequest request) {
|
||||
return getMessage(messageCode, defaultMessage, resolveLocale(request));
|
||||
}
|
||||
|
||||
public static String getMessage(String messageCode, String[] parasData, HttpServletRequest request) {
|
||||
return getMessage(messageCode, parasData, resolveLocale(request));
|
||||
}
|
||||
|
||||
public static String getMessage(String messageCode, String defaultMessage, Locale locale) {
|
||||
return messageSource.getMessage(messageCode, null, defaultMessage, locale);
|
||||
}
|
||||
|
||||
public static String getMessage(String messageCode, String[] parasData, Locale locale) {
|
||||
return messageSource.getMessage(messageCode, parasData, locale);
|
||||
}
|
||||
|
||||
public static Locale resolveLocale(HttpServletRequest request) {
|
||||
return RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
|
||||
}
|
||||
|
||||
public static String getStatusMessageByCode(int statusCode, String langType) {
|
||||
String statusMessage = "";
|
||||
Locale locale = Locale.US;
|
||||
if (Strings.CI.equals("TC", langType)) {
|
||||
locale = Locale.TAIWAN;
|
||||
} else if (Strings.CI.equals("SC", langType)) {
|
||||
locale = Locale.CHINA;
|
||||
}
|
||||
statusMessage = messageSource.getMessage("common.error_message.error_code_" + statusCode, null, locale);
|
||||
return statusMessage;
|
||||
}
|
||||
|
||||
public static String getMessageByLangType(String messageCode, String langType) {
|
||||
String statusMessage = "";
|
||||
Locale locale = Locale.US;
|
||||
if (Strings.CI.equals("TC", langType)) {
|
||||
locale = Locale.TAIWAN;
|
||||
} else if (Strings.CI.equals("SC", langType)) {
|
||||
locale = Locale.CHINA;
|
||||
}
|
||||
statusMessage = messageSource.getMessage(messageCode, null, locale);
|
||||
return statusMessage;
|
||||
}
|
||||
|
||||
public static SysLogOperation createLogOperationByRequest(HttpServletRequest request, String eventCode,Object operationObject, Object returnObject,String logMessage,int successFlag,Object oldDataObject) {
|
||||
SysLogOperation sysLogOper = new SysLogOperation();
|
||||
SysUser userInfo = (SysUser) request.getAttribute(SysConstants.CURRENT_USER_KEY);
|
||||
if (userInfo != null) {
|
||||
SysUser operUser = userInfo;
|
||||
sysLogOper.setLoginId(operUser.getLoginId());
|
||||
}
|
||||
Date now = new Date();
|
||||
sysLogOper.setOccurTime(now);
|
||||
sysLogOper.setSortOccurtime(now.getTime());
|
||||
sysLogOper.setIpAddress(NetworkUtil.getClientIpAddr(request));
|
||||
sysLogOper.setEventCode(eventCode);
|
||||
sysLogOper.setLogDesc(logMessage);
|
||||
sysLogOper.setTagSuccess(successFlag);
|
||||
//write request body && response body to db when "db debug log" turn on
|
||||
if (operationObject != null && SysCommon.dbDebugLog) {
|
||||
try {
|
||||
String requestContent = "";
|
||||
if (operationObject instanceof JSONObject || operationObject instanceof String) {
|
||||
requestContent = operationObject.toString();
|
||||
} else {
|
||||
JSONObject contentObject = (JSONObject) JSONObject.toJSON(operationObject);
|
||||
requestContent = contentObject.toString();
|
||||
}
|
||||
String oldContent = "";
|
||||
if (oldDataObject != null) {
|
||||
try {
|
||||
if (oldDataObject instanceof JSONObject || oldDataObject instanceof String) {
|
||||
oldContent = returnObject.toString();
|
||||
} else {
|
||||
JSONObject contentObject = (JSONObject) JSONObject.toJSON(oldDataObject);
|
||||
oldContent = contentObject.toString();
|
||||
}
|
||||
} catch (Exception err) {
|
||||
System.out.println("Convert old data error:" + err.getMessage());
|
||||
}
|
||||
}
|
||||
requestContent = "Request Data: " + requestContent;
|
||||
if(!oldContent.equals("")) {
|
||||
requestContent += "; Old Data:" + oldContent;
|
||||
}
|
||||
sysLogOper.setRequestBody(requestContent);
|
||||
} catch (Exception err) {
|
||||
System.out.println("Convert request error:" + err.getMessage());
|
||||
}
|
||||
}
|
||||
if (returnObject != null && SysCommon.dbDebugLog) {
|
||||
try {
|
||||
String responseContent = "";
|
||||
if (returnObject instanceof JSONObject || returnObject instanceof String) {
|
||||
responseContent = returnObject.toString();
|
||||
} else {
|
||||
JSONObject contentObject = (JSONObject) JSONObject.toJSON(returnObject);
|
||||
responseContent = contentObject.toString();
|
||||
}
|
||||
sysLogOper.setResponseBody(responseContent);
|
||||
} catch (Exception err) {
|
||||
System.out.println("Conver response error:" + err.getMessage());
|
||||
}
|
||||
}
|
||||
return sysLogOper;
|
||||
}
|
||||
public static SysLogLogin createLogLoginByRequest(HttpServletRequest request, String eventCode,Object operationObject, Object returnObject,String logMessage,int successFlag,Object oldDataObject) {
|
||||
SysLogLogin sysLogLogin = new SysLogLogin();
|
||||
SysUser userInfo = (SysUser) request.getAttribute(SysConstants.CURRENT_USER_KEY);
|
||||
if (userInfo != null) {
|
||||
SysUser operUser = userInfo;
|
||||
sysLogLogin.setLoginId(operUser.getLoginId());
|
||||
}else {
|
||||
SysUser operUser = (SysUser)operationObject;
|
||||
sysLogLogin.setLoginId(operUser.getLoginId());
|
||||
sysLogLogin.setTransId(operUser.getLoginId());
|
||||
}
|
||||
Date now = new Date();
|
||||
sysLogLogin.setOccurTime(now);
|
||||
sysLogLogin.setSortOccurtime(now.getTime());
|
||||
sysLogLogin.setIpAddress(NetworkUtil.getClientIpAddr(request));
|
||||
sysLogLogin.setEventCode(eventCode);
|
||||
sysLogLogin.setLogDesc(logMessage);
|
||||
sysLogLogin.setTagSuccess(successFlag);
|
||||
//write request body && response body to db when "db debug log" turn on
|
||||
if (operationObject != null && SysCommon.dbDebugLog) {
|
||||
try {
|
||||
String requestContent = "";
|
||||
if (operationObject instanceof JSONObject || operationObject instanceof String) {
|
||||
requestContent = operationObject.toString();
|
||||
} else {
|
||||
JSONObject contentObject = (JSONObject) JSONObject.toJSON(operationObject);
|
||||
requestContent = contentObject.toString();
|
||||
}
|
||||
String oldContent = "";
|
||||
if (oldDataObject != null) {
|
||||
try {
|
||||
if (oldDataObject instanceof JSONObject || oldDataObject instanceof String) {
|
||||
oldContent = returnObject.toString();
|
||||
} else {
|
||||
JSONObject contentObject = (JSONObject) JSONObject.toJSON(oldDataObject);
|
||||
oldContent = contentObject.toString();
|
||||
}
|
||||
} catch (Exception err) {
|
||||
System.out.println("Convert old data error:" + err.getMessage());
|
||||
}
|
||||
}
|
||||
requestContent = "Request Data: " + requestContent;
|
||||
if(!oldContent.equals("")) {
|
||||
requestContent += "; Old Data:" + oldContent;
|
||||
}
|
||||
sysLogLogin.setRequestBody(requestContent);
|
||||
} catch (Exception err) {
|
||||
System.out.println("Convert request error:" + err.getMessage());
|
||||
}
|
||||
}
|
||||
if (returnObject != null && SysCommon.dbDebugLog) {
|
||||
try {
|
||||
String responseContent = "";
|
||||
if (returnObject instanceof JSONObject || returnObject instanceof String) {
|
||||
responseContent = returnObject.toString();
|
||||
} else {
|
||||
JSONObject contentObject = (JSONObject) JSONObject.toJSON(returnObject);
|
||||
responseContent = contentObject.toString();
|
||||
}
|
||||
sysLogLogin.setResponseBody(responseContent);
|
||||
} catch (Exception err) {
|
||||
System.out.println("Conver response error:" + err.getMessage());
|
||||
}
|
||||
}
|
||||
return sysLogLogin;
|
||||
}
|
||||
public static boolean convertBeanDatetimeProperty(Object srcObject, Object targetObject,
|
||||
String dateTimePropertyName, String dateTimeFormat) {
|
||||
boolean isSuccess = true;
|
||||
if (StringUtils.isBlank(dateTimeFormat)) {
|
||||
dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
|
||||
}
|
||||
SimpleDateFormat dtFormat = new SimpleDateFormat(dateTimeFormat);
|
||||
Class sourceClass = srcObject.getClass();
|
||||
Class targetClass = targetObject.getClass();
|
||||
Field srcPropField = null;
|
||||
Field targetPropField = null;
|
||||
try {
|
||||
srcPropField = sourceClass.getDeclaredField(dateTimePropertyName);
|
||||
} catch (Exception err) {
|
||||
srcPropField = null;
|
||||
}
|
||||
if (srcPropField == null && sourceClass.getSuperclass() != null) {
|
||||
try {
|
||||
srcPropField = sourceClass.getSuperclass().getDeclaredField(dateTimePropertyName);
|
||||
} catch (Exception err) {
|
||||
srcPropField = null;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
targetPropField = targetClass.getDeclaredField(dateTimePropertyName);
|
||||
} catch (Exception err) {
|
||||
targetPropField = null;
|
||||
}
|
||||
if (targetPropField == null && targetClass.getSuperclass() != null) {
|
||||
try {
|
||||
targetPropField = targetClass.getSuperclass().getDeclaredField(dateTimePropertyName);
|
||||
} catch (Exception err) {
|
||||
targetPropField = null;
|
||||
}
|
||||
}
|
||||
if (srcPropField != null && targetPropField != null) {
|
||||
srcPropField.setAccessible(true);
|
||||
targetPropField.setAccessible(true);
|
||||
try {
|
||||
Object dateTimeVal = srcPropField.get(srcObject);
|
||||
if (dateTimeVal != null && StringUtils.isNotBlank(dateTimeVal.toString())) {
|
||||
Date dateTimeObject = dtFormat.parse(dateTimeVal.toString());
|
||||
targetPropField.set(targetObject, dateTimeObject);
|
||||
}
|
||||
} catch (Exception err) {
|
||||
isSuccess = false;
|
||||
}
|
||||
} else {
|
||||
isSuccess = false;
|
||||
}
|
||||
return isSuccess;
|
||||
}
|
||||
|
||||
public static boolean isSysAdmin(String sysUserId) {
|
||||
return Strings.CS.equals(SysConstants.SUPER_ADMIN_ID, sysUserId);
|
||||
}
|
||||
|
||||
public static String getRuntime_path() {
|
||||
return runtime_path;
|
||||
}
|
||||
|
||||
public static void setRuntime_path(String runtime_path) {
|
||||
SysCommon.runtime_path = runtime_path;
|
||||
}
|
||||
|
||||
// Load API Config
|
||||
public static boolean loadAPIConfig(Properties props) {
|
||||
boolean isLoaded = true;
|
||||
// ESB
|
||||
SysCommon.apiConfig.setServerUrl_ESB(props.getProperty("esb_server", ""));
|
||||
SysCommon.apiConfig.setApiKey_ESB(props.getProperty("esb_app_id", ""));
|
||||
SysCommon.apiConfig.setApiSecret_ESB(props.getProperty("esb_app_secret", ""));
|
||||
try {
|
||||
SysCommon.apiConfig.setTimeout_ESB(Integer.parseInt(props.getProperty("esb_request_timeout", "30000")));
|
||||
} catch (Exception err) {
|
||||
SysCommon.apiConfig.setTimeout_ESB(0);
|
||||
}
|
||||
// OWS
|
||||
SysCommon.apiConfig.setServerUrl_OWS(props.getProperty("ows_server", ""));
|
||||
try {
|
||||
SysCommon.apiConfig.setTimeout_OWS(Integer.parseInt(props.getProperty("ows_request_timeout", "30000")));
|
||||
} catch (Exception err) {
|
||||
SysCommon.apiConfig.setTimeout_OWS(0);
|
||||
}
|
||||
// RPA
|
||||
SysCommon.apiConfig.setServerLoginUrl_RPA(props.getProperty("rpa_login_server", ""));
|
||||
SysCommon.apiConfig.setApiAccessName_RPA(props.getProperty("rpa_username", ""));
|
||||
SysCommon.apiConfig.setApiAccessPassword_RPA(props.getProperty("rpa_password", ""));
|
||||
SysCommon.apiConfig.setApiAccessKey_RPA(props.getProperty("rpa_apiKey", ""));
|
||||
SysCommon.apiConfig.setServerAddUrl_RPA(props.getProperty("rpa_add_server", ""));
|
||||
SysCommon.apiConfig.setServerExtensionUrl_RPA(props.getProperty("rpa_extension_server", ""));
|
||||
// SSO
|
||||
SysCommon.apiConfig.setServerUrl_SSO(props.getProperty("idp_server", ""));
|
||||
SysCommon.apiConfig.setClientId_SSO(props.getProperty("idp_client_id", ""));
|
||||
SysCommon.apiConfig.setClientSecret_SSO(props.getProperty("idp_client_secret", ""));
|
||||
//SMS Config
|
||||
SysCommon.apiConfig.setTokenUrl_SMS(props.getProperty("sms_token_url", ""));
|
||||
SysCommon.apiConfig.setSendUrl_SMS(props.getProperty("sms_send_url", ""));
|
||||
SysCommon.apiConfig.setUsername_SMS(props.getProperty("sms_username", ""));
|
||||
SysCommon.apiConfig.setPassword_SMS(props.getProperty("sms_password", ""));
|
||||
SysCommon.apiConfig.setAccount_SMS(props.getProperty("sms_account", ""));
|
||||
SysCommon.apiConfig.setPriority_SMS(props.getProperty("sms_priority", ""));
|
||||
//SMS Config
|
||||
SysCommon.apiConfig.setPort_SMTP(props.getProperty("mail_port", ""));
|
||||
SysCommon.apiConfig.setHost_SMTP(props.getProperty("mail_smtp_host", ""));
|
||||
SysCommon.apiConfig.setUsername_SMTP(props.getProperty("mail_sender", ""));
|
||||
SysCommon.apiConfig.setPassword_SMTP(props.getProperty("mail_sender_password", ""));
|
||||
SysCommon.apiConfig.setSend_to_SMTP(props.getProperty("mail_send_to", ""));
|
||||
|
||||
LogUtil.info(SysCommon.class, "Loaded API config.");
|
||||
return isLoaded;
|
||||
}
|
||||
|
||||
//-- Path Type 1= Class path 2=Application path 3=URI Path
|
||||
public static String loadResFileContentByPath(String filePath, int pathType) {
|
||||
String fileContent = "";
|
||||
InputStream ifs = null;
|
||||
BufferedReader bufferedReader = null;
|
||||
InputStreamReader fileReader = null;
|
||||
try {
|
||||
if(pathType==2) {
|
||||
String applicationPath = SysCommon.runtime_path+"/"+runtimeName;
|
||||
File dataFile = new File(applicationPath+filePath);
|
||||
ifs=new FileInputStream(dataFile);
|
||||
}else {
|
||||
Resource resource = new ClassPathResource(filePath);
|
||||
ifs = resource.getInputStream();
|
||||
}
|
||||
fileReader = new InputStreamReader(ifs, "UTF-8");
|
||||
bufferedReader = new BufferedReader(fileReader);
|
||||
String lineData = null;
|
||||
int lineCnt =0;
|
||||
StringBuffer contentBuffer = new StringBuffer();
|
||||
while ((lineData = bufferedReader.readLine()) != null) {
|
||||
if(lineCnt>0) {
|
||||
contentBuffer.append("\n");
|
||||
}
|
||||
contentBuffer.append(lineData);
|
||||
lineCnt++;
|
||||
}
|
||||
bufferedReader.close();
|
||||
fileContent = contentBuffer.toString();
|
||||
} catch (Exception e) {
|
||||
//e.printStackTrace();
|
||||
//LogUtil.error(SysCommon.class, "Get Data File failed:"+e.getMessage());
|
||||
} finally {
|
||||
try {
|
||||
if (bufferedReader != null) {
|
||||
bufferedReader.close();
|
||||
}
|
||||
if(fileReader!=null) {
|
||||
fileReader.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
//--
|
||||
return fileContent;
|
||||
}
|
||||
public static AppServerState refreshAppServerState() {
|
||||
AppServerState currentState = new AppServerState();
|
||||
currentState.setServerIp(SysCommon.serverIp);
|
||||
currentState.setHostName(SysCommon.serverName);
|
||||
currentState.setServerType("MOBILE");
|
||||
currentState.setApiDebugLog(SysCommon.apiDebugLog);
|
||||
currentState.setDbDebugLog(SysCommon.dbDebugLog);
|
||||
currentState.setAppDebugLog(SysCommon.appDebugLog);
|
||||
appServerStates.put(currentState.getServerType()+"-"+SysCommon.serverIp, currentState);
|
||||
return currentState;
|
||||
}
|
||||
|
||||
public static void registerServerInfo(AppServerState serverInfo) {
|
||||
if(serverInfo!=null && (!Strings.CS.equals(serverIp, serverInfo.getServerIp()) || !Strings.CS.equals("MOBILE", serverInfo.getServerType()) )) {
|
||||
appServerStates.put(serverInfo.getServerType()+"-"+serverInfo.getServerIp(), serverInfo);
|
||||
}
|
||||
}
|
||||
|
||||
public static AppServerState updateCfgByRequest(AppSettingMsgData updateRequest) {
|
||||
if(updateRequest!=null) {
|
||||
List<UpdateCfgItem> cfgItems = updateRequest.getConfigItems();
|
||||
if(cfgItems!=null) {
|
||||
for(UpdateCfgItem cfgItem:cfgItems) {
|
||||
if(Strings.CS.equals("dbDebugLog", cfgItem.getCfgItemKey())) {
|
||||
SysCommon.dbDebugLog= Boolean.parseBoolean(cfgItem.getCfgItemValue());
|
||||
}else if(Strings.CS.equals("apiDebugLog", cfgItem.getCfgItemKey())) {
|
||||
SysCommon.apiDebugLog= Boolean.parseBoolean(cfgItem.getCfgItemValue());
|
||||
}else if(Strings.CS.equals("appDebugLog", cfgItem.getCfgItemKey())) {
|
||||
SysCommon.appDebugLog= Boolean.parseBoolean(cfgItem.getCfgItemValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return refreshAppServerState();
|
||||
}
|
||||
|
||||
public static LoginUserInfo parseUserFromToken(HttpServletRequest request) {
|
||||
LoginUserInfo loginUser = null;
|
||||
String token = request.getHeader("Authorization");
|
||||
if(StringUtils.isNotBlank(token)) {
|
||||
try {
|
||||
// token = token.substring(6);
|
||||
loginUser = parseUserFromToken(token);
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(SysCommon.class, "Parse Token failed:"+err.getMessage());
|
||||
loginUser =null;
|
||||
}
|
||||
}
|
||||
return loginUser;
|
||||
}
|
||||
|
||||
public static LoginUserInfo parseUserFromToken(String tokenContent) {
|
||||
LoginUserInfo loginUser = null;
|
||||
if(StringUtils.isNotBlank(tokenContent)) {
|
||||
try {
|
||||
tokenContent = tokenContent.replace("Bearer ", "");
|
||||
|
||||
DecodedJWT decodeData = JWT.decode(tokenContent);
|
||||
loginUser = new LoginUserInfo();
|
||||
String userId = decodeData.getSubject();
|
||||
if(StringUtils.isNotBlank(userId)) {
|
||||
loginUser.setId(Long.parseLong(userId));
|
||||
}else {
|
||||
loginUser.setId(-1L);
|
||||
}
|
||||
loginUser.setLoginId(decodeData.getClaim("login_id").asString());
|
||||
loginUser.setGroupName(decodeData.getClaim("user_group").asString());
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(SysCommon.class, "Parse Token failed:"+err.getMessage());
|
||||
loginUser =null;
|
||||
}
|
||||
}
|
||||
return loginUser;
|
||||
}
|
||||
public static void loadSecurityConfig(String allowOrigins) {
|
||||
if(allowOrigins!=null) {
|
||||
String[] serverLists = allowOrigins.split(",");
|
||||
if(serverLists!=null) {
|
||||
for(String item:serverLists) {
|
||||
if(StringUtils.isNotBlank(item)) {
|
||||
addAllowOriginSource(item.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void addAllowOriginSource(String srcServer) {
|
||||
allowOriginSource.add(srcServer);
|
||||
}
|
||||
|
||||
public static boolean isAllowOriginSource(String srcServer) {
|
||||
boolean isAllow = false;
|
||||
if(StringUtils.isNotBlank(srcServer)) {
|
||||
for(String allowItem:allowOriginSource) {
|
||||
if(Strings.CI.startsWith(srcServer, allowItem)) {
|
||||
isAllow=true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return isAllow;
|
||||
}
|
||||
|
||||
public static void loadSoapServerConfig(String soapConfig) {
|
||||
if(soapConfig!=null) {
|
||||
String[] serverLists = soapConfig.split(",");
|
||||
if(serverLists!=null) {
|
||||
for(String item:serverLists) {
|
||||
if(StringUtils.isNotBlank(item)) {
|
||||
addSoapServer(item.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void addSoapServer(String srcServer) {
|
||||
soapServers.add(srcServer);
|
||||
}
|
||||
|
||||
public static boolean isAllowSoapServer(String srcServer) {
|
||||
boolean isAllow = false;
|
||||
if(StringUtils.isNotBlank(srcServer)) {
|
||||
for(String allowItem:soapServers) {
|
||||
if(Strings.CI.startsWith(srcServer, allowItem)) {
|
||||
isAllow=true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return isAllow;
|
||||
}
|
||||
|
||||
public static void loadApiServerConfig(String apiServerConfig) {
|
||||
if(apiServerConfig!=null) {
|
||||
String[] serverLists = apiServerConfig.split(",");
|
||||
if(serverLists!=null) {
|
||||
for(String item:serverLists) {
|
||||
if(StringUtils.isNotBlank(item)) {
|
||||
addApiServer(item.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void addApiServer(String srcServer) {
|
||||
httpApiServers.add(srcServer);
|
||||
}
|
||||
|
||||
public static boolean isAllowApiServer(String srcServer) {
|
||||
boolean isAllow = false;
|
||||
if(StringUtils.isNotBlank(srcServer)) {
|
||||
for(String allowItem:httpApiServers) {
|
||||
if(Strings.CI.startsWith(srcServer, allowItem)) {
|
||||
isAllow=true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return isAllow;
|
||||
}
|
||||
|
||||
public static void loadAllowIPConfig(String allowIPConfig) {
|
||||
if(allowIPConfig!=null) {
|
||||
String[] ipLists = allowIPConfig.split(",");
|
||||
if(ipLists!=null) {
|
||||
for(String item:ipLists) {
|
||||
if(StringUtils.isNotBlank(item)) {
|
||||
addAllowIP(item.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void addAllowIP(String allowIP) {
|
||||
allowIPSource.add(allowIP);
|
||||
}
|
||||
|
||||
public static boolean isAllowIPSource(String ip) {
|
||||
boolean isAllow = false;
|
||||
if(StringUtils.isNotBlank(ip)) {
|
||||
for(String allowItem:allowIPSource) {
|
||||
LogUtil.info(BookingService.class,"[isAllowIPSource]allow item:"+allowItem);
|
||||
if(Strings.CI.startsWith(ip, allowItem)) {
|
||||
isAllow=true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return isAllow;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.mgm.mcrm.common.constants;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class SysConstants {
|
||||
|
||||
public static final String CURRENT_USER_KEY = "currentUser";
|
||||
public static final String SUPER_ADMIN_ID ="1";
|
||||
|
||||
// cfg_settings
|
||||
public static final String MAX_BOOKING_STAY_DAYS="MAX_BOOKING_STAY_DAYS";
|
||||
public static final String MAX_ADVANCE_BOOKING_DAYS="MAX_ADVANCE_BOOKING_DAYS";
|
||||
public static final String NUM_OF_MULTIPLE_DATE_RANGE="NUM_OF_MULTIPLE_DATE_RANGE";
|
||||
public static final String PROTECTION_PERIOD_CHECKIN="PROTECTION_PERIOD_CHECKIN";
|
||||
public static final String PROTECTION_PERIOD_CHECKOUT="PROTECTION_PERIOD_CHECKOUT";
|
||||
public static final String PROTECT_PERIOD_ENABLE="PROTECT_PERIOD_ENABLE";
|
||||
public static final String MAX_OPERA_BOOKING_DAYS="MAX_OPERA_BOOKING_DAYS";
|
||||
public static final String MGM_EMAIL_ADDRESS="MGM_EMAIL_ADDRESS";
|
||||
public static final String MACAU_IP="MACAU_IP";
|
||||
|
||||
public static final int CMS_TOKEN_TYPE=0;
|
||||
public static final int MOBILE_TOKEN_TYPE=1;
|
||||
|
||||
public static final String PERMISSION_APP_VIEW_BOOKING="10001_01";
|
||||
public static final String PERMISSION_APP_NEW_BOOKING="10001_02";
|
||||
public static final String PERMISSION_APP_TODO_LIST="10001_03";
|
||||
public static final String PERMISSION_APP_DASHBOARD="10001_04";
|
||||
public static final String PERMISSION_APP_APPROVAL="10001_05";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package com.mgm.mcrm.common.dtos;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public class BaseApiResponse<T> {
|
||||
|
||||
@Schema(description = "Indicate API success status")
|
||||
private boolean success = false;
|
||||
|
||||
@Schema(description = "Status Code of response",example="200")
|
||||
private String code;
|
||||
|
||||
@Schema(description = "Description of result")
|
||||
private String message;
|
||||
|
||||
@Schema(description = "Data of response")
|
||||
private T data;
|
||||
|
||||
private String logMessage;
|
||||
|
||||
private Object requestData;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
String dataStr="";
|
||||
try {
|
||||
JSONObject objJson = new JSONObject();
|
||||
objJson.put("success", success);
|
||||
objJson.put("code", success);
|
||||
objJson.put("message", message);
|
||||
objJson.put("data", data);
|
||||
dataStr = objJson.toString();
|
||||
}catch(Exception ignored){
|
||||
|
||||
}
|
||||
return dataStr;
|
||||
}
|
||||
|
||||
/**
|
||||
* 成功响应,默认状态码为 "200",默认消息为空字符串
|
||||
* @return 包含成功状态和默认消息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> ok(){
|
||||
return BaseApiResponse.ok(null,null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 成功响应,默认状态码为 "200",自定义消息
|
||||
* @param message 自定义消息
|
||||
* @return 包含成功状态和自定义消息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> ok(String message){
|
||||
return BaseApiResponse.ok(message, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 成功响应,默认状态码为 "200",自定义数据
|
||||
* 当泛型是String时,调用的是success(String message)方法
|
||||
* @param data 自定义数据
|
||||
* @return 包含成功状态和自定义数据的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> ok(T data){
|
||||
return BaseApiResponse.ok(null, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 成功响应,默认状态码为 "200",自定义消息和数据
|
||||
* @param message 自定义消息
|
||||
* @param data 自定义数据
|
||||
* @return 包含成功状态、自定义消息和数据的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> ok(String message, T data){
|
||||
return build(true, "200", message, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求参数错误
|
||||
* @param message 错误信息
|
||||
* @return 包含错误信息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> badRequestError(String message){
|
||||
return BaseApiResponse.error("400", message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 未登录
|
||||
* @param message 错误信息
|
||||
* @return 包含错误信息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> unauthorizedError(String message){
|
||||
return BaseApiResponse.error("401", message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 没有权限访问
|
||||
* @param message 错误信息
|
||||
* @return 包含错误信息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> forbiddenError(String message){
|
||||
return BaseApiResponse.error("403", message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 找不到资源
|
||||
* @param message 错误信息
|
||||
* @return 包含错误信息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> notFoundError(String message){
|
||||
return BaseApiResponse.error("404", message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 资源冲突,如资源被其他资源使用时 或 资源状态禁用但有其他资源想使用
|
||||
* @param message 错误信息
|
||||
* @return 包含错误信息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> conflictError(String message){
|
||||
return BaseApiResponse.error("409", message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 资源原本存在,但现在已被删除
|
||||
* @param message 错误信息
|
||||
* @return 包含错误信息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> goneError(String message){
|
||||
return BaseApiResponse.error("410", message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务器内部错误
|
||||
* @param message 错误信息
|
||||
* @return 包含错误信息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> internalServerError(String message){
|
||||
return BaseApiResponse.error("500", message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 未实现,表示服务器当前不支持请求所需的功能
|
||||
* @param message 错误信息
|
||||
* @return 包含错误信息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> noImplementedError(String message){
|
||||
return BaseApiResponse.error("501", message);
|
||||
}
|
||||
|
||||
/**
|
||||
* socket连接超时
|
||||
* @param message 错误信息
|
||||
* @return 包含错误信息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> serverUnavailableError(String message){
|
||||
return BaseApiResponse.error("503", message);
|
||||
}
|
||||
|
||||
/**
|
||||
* socket连接超时
|
||||
* @param message 错误信息
|
||||
* @return 包含错误信息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> socketTimeoutError(String message){
|
||||
return BaseApiResponse.error("504", message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义构建错误响应信息
|
||||
* @param code 错误编码
|
||||
* @param message 错误信息
|
||||
* @return 包含错误信息的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> error(String code, String message){
|
||||
return build(false, code, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义构建错误响应信息,只返回数据
|
||||
* @param data 错误数据
|
||||
* @return 包含错误数据的 BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> error(T data){
|
||||
return build(false, null, null, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义构建响应信息
|
||||
* @param code 编码
|
||||
* @param message 信息
|
||||
* @return BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
|
||||
public static <T> BaseApiResponse<T> build(boolean success, String code, String message){
|
||||
return build(success, code, message, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义构建响应信息
|
||||
* @param code 编码
|
||||
* @param message 信息
|
||||
* @return BaseApiResponse 对象
|
||||
* @param <T> 响应数据类型
|
||||
*/
|
||||
|
||||
public static <T> BaseApiResponse<T> build(boolean success, String code, String message, T Data){
|
||||
BaseApiResponse<T> response = new BaseApiResponse<>();
|
||||
response.setSuccess(success);
|
||||
response.setCode(code);
|
||||
response.setMessage(message);
|
||||
response.setData(Data);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否成功响应
|
||||
* @return 是否成功响应
|
||||
*/
|
||||
public boolean checkSuccess(){
|
||||
// 现在成功码只有200,有些地方success会是true,但是code不一定是200,如有需要,另写方案
|
||||
return this.success && "200".equals(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否错误响应
|
||||
* @return 是否错误响应
|
||||
*/
|
||||
public boolean checkFailed(){
|
||||
return !checkSuccess();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将一个BaseApiResponse的信息转换成另一个BaseApiResponse对象,两个对象可能泛型不同,因此不转换Data对象
|
||||
* @param original 转换源
|
||||
* @return 转换结果
|
||||
* @param <T> 结果泛型
|
||||
*/
|
||||
public static <T> BaseApiResponse<T> convert(BaseApiResponse<?> original){
|
||||
return build(original.isSuccess(), original.getCode(), original.getMessage(), null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.mgm.mcrm.common.dtos;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public class BaseQueryRequest {
|
||||
private int startRow = -1;
|
||||
private int endRow = -1;
|
||||
|
||||
public int getPageSize() {
|
||||
validatePageInfo();
|
||||
return pageSize;
|
||||
}
|
||||
|
||||
public int getPageNo() {
|
||||
validatePageInfo();
|
||||
return pageNo;
|
||||
}
|
||||
|
||||
private int pageSize = -1;
|
||||
private int pageNo=-1;
|
||||
private String sortOrder;
|
||||
private boolean pageInfoValidated=false;
|
||||
|
||||
private void validatePageInfo() {
|
||||
if(pageInfoValidated)
|
||||
return;
|
||||
if(pageSize<0){
|
||||
if(startRow>=0 && endRow>=0){
|
||||
pageSize=endRow-startRow;
|
||||
}else{
|
||||
pageSize=20;
|
||||
}
|
||||
}
|
||||
if(pageNo<=0){
|
||||
if(startRow>=0){
|
||||
pageNo = (startRow+1)/pageSize;
|
||||
if(pageNo<0) {
|
||||
pageNo=0;
|
||||
}
|
||||
}else{
|
||||
pageNo=0;
|
||||
}
|
||||
}else{
|
||||
pageNo--;
|
||||
}
|
||||
pageInfoValidated=true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.mgm.mcrm.common.dtos;
|
||||
|
||||
import com.mgm.mcrm.basesetting.property.dtos.response.TokenResponse;
|
||||
|
||||
public class CachedToken {
|
||||
private final TokenResponse token;
|
||||
private final long expireTime;
|
||||
|
||||
public CachedToken(TokenResponse token, long expireTime) {
|
||||
this.token = token;
|
||||
this.expireTime = expireTime;
|
||||
}
|
||||
|
||||
public TokenResponse getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public boolean isExpired() {
|
||||
return System.currentTimeMillis() > expireTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.mgm.mcrm.common.dtos;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class DataTableResult<T> {
|
||||
private List<T> rowData;
|
||||
private int pageSize=10;
|
||||
private long totalRecords=0;
|
||||
private long startRow = 0;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.mgm.mcrm.common.dtos;
|
||||
|
||||
public enum EumnApprovalStatus {
|
||||
|
||||
PendingA("PENDING","PA"),
|
||||
PendingN("PENDING","PN"),
|
||||
Pending("PENDING","P"),
|
||||
PApproved("APPROVED","A"),
|
||||
PRejected("REJECTED","R"),
|
||||
NApproved("APPROVED","N"),
|
||||
EPending("EDIT_PENDING","E"),
|
||||
ERejected("EDIT_REJECTED","D"),
|
||||
EApproved("EDIT_APPROVED","F"),
|
||||
WPending("Pending","W"),
|
||||
WReject("Reject","WR"),
|
||||
WApproved("Approved","WA"),
|
||||
WReserved("Reserved","WF"),
|
||||
WCancelled("Cancelled","WC");
|
||||
|
||||
private String key;
|
||||
private String value;
|
||||
|
||||
private EumnApprovalStatus(String key, String value) {
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public static String getApprovalStatusByDBValue(String value) {
|
||||
EumnApprovalStatus[] objs = values();
|
||||
for (EumnApprovalStatus obj : objs) {
|
||||
if (obj.getValue().equals(value)) {
|
||||
return obj.getKey();
|
||||
}
|
||||
}
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
public static String getDBValueByApprovalStatus(String key) {
|
||||
EumnApprovalStatus[] objs = values();
|
||||
for (EumnApprovalStatus obj : objs) {
|
||||
if (obj.getKey().equals(key)) {
|
||||
return obj.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean isInclude(String value){
|
||||
boolean include = false;
|
||||
for (EumnApprovalStatus e: EumnApprovalStatus.values()){
|
||||
if(e.getValue().equals(value)){
|
||||
include = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return include;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.mgm.mcrm.common.dtos;
|
||||
|
||||
import lombok.Data;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpResponse;
|
||||
import org.apache.hc.core5.http.ProtocolVersion;
|
||||
import org.apache.hc.core5.http.message.StatusLine;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@Data
|
||||
public class HttpResult implements Serializable {
|
||||
/**
|
||||
* 执行结果-body
|
||||
*/
|
||||
private String result;
|
||||
|
||||
/**
|
||||
* 状态码-statusCode
|
||||
*/
|
||||
private int statusCode;
|
||||
|
||||
/**
|
||||
* 状态行-StatusLine
|
||||
*/
|
||||
private StatusLine statusLine;
|
||||
|
||||
/**
|
||||
* 请求头信息
|
||||
*/
|
||||
private Header[] reqHeaders;
|
||||
|
||||
/**
|
||||
* 响应头信息
|
||||
*/
|
||||
private Header[] respHeaders;
|
||||
|
||||
/**
|
||||
* 协议版本
|
||||
*/
|
||||
private ProtocolVersion protocolVersion;
|
||||
|
||||
/**
|
||||
* HttpResponse结果对象
|
||||
*/
|
||||
private HttpResponse resp;
|
||||
|
||||
public HttpResult(HttpResponse resp) {
|
||||
// HttpClient 5 API: 使用 new StatusLine(response) 创建 StatusLine
|
||||
this.statusLine = new StatusLine(resp);
|
||||
// HttpClient 5 API: 使用 getHeaders() 获取所有响应头
|
||||
this.respHeaders = resp.getHeaders();
|
||||
// HttpClient 5 API: 从 StatusLine 获取协议版本
|
||||
this.protocolVersion = this.statusLine.getProtocolVersion();
|
||||
// HttpClient 5 API: 使用 getCode() 获取状态码
|
||||
this.statusCode = resp.getCode();
|
||||
this.resp = resp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从返回的头信息中查询指定头信息
|
||||
*
|
||||
* @param name 头信息名称
|
||||
*/
|
||||
public Header getHeaders(final String name) {
|
||||
Header[] headers = this.resp.getHeaders(name);
|
||||
return headers!=null && headers.length>0?headers[0]:null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.mgm.mcrm.common.dtos;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class RequestDefination {
|
||||
private Map<String, List<String>> requestUrlList;
|
||||
private Map<String, String> sampleJson;
|
||||
public Map<String, List<String>> getRequestUrlList() {
|
||||
return requestUrlList;
|
||||
}
|
||||
public void setRequestUrlList(Map<String, List<String>> requestUrlList) {
|
||||
this.requestUrlList = requestUrlList;
|
||||
}
|
||||
public Map<String, String> getSampleJson() {
|
||||
return sampleJson;
|
||||
}
|
||||
public void setSampleJson(Map<String, String> sampleJson) {
|
||||
this.sampleJson = sampleJson;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package com.mgm.mcrm.common.dtos.config;
|
||||
|
||||
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 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= "";
|
||||
private String username_SMTP= "";
|
||||
private String password_SMTP= "";
|
||||
private String send_to_SMTP= "";
|
||||
|
||||
|
||||
public boolean isLoaded() {
|
||||
return isLoaded;
|
||||
}
|
||||
public void setLoaded(boolean isLoaded) {
|
||||
this.isLoaded = isLoaded;
|
||||
}
|
||||
|
||||
public String getServerUrl_ESB() {
|
||||
return serverUrl_ESB;
|
||||
}
|
||||
public void setServerUrl_ESB(String serverUrl_ESB) {
|
||||
this.serverUrl_ESB = serverUrl_ESB;
|
||||
}
|
||||
public String getApiKey_ESB() {
|
||||
return apiKey_ESB;
|
||||
}
|
||||
public void setApiKey_ESB(String apiKey_ESB) {
|
||||
this.apiKey_ESB = apiKey_ESB;
|
||||
}
|
||||
public String getApiSecret_ESB() {
|
||||
return apiSecret_ESB;
|
||||
}
|
||||
public void setApiSecret_ESB(String apiSecret_ESB) {
|
||||
this.apiSecret_ESB = apiSecret_ESB;
|
||||
}
|
||||
public int getTimeout_ESB() {
|
||||
return timeout_ESB;
|
||||
}
|
||||
public void setTimeout_ESB(int timeout_ESB) {
|
||||
this.timeout_ESB = timeout_ESB;
|
||||
}
|
||||
public String getServerLoginUrl_RPA() {
|
||||
return serverLoginUrl_RPA;
|
||||
}
|
||||
public void setServerLoginUrl_RPA(String serverLoginUrl_RPA) {
|
||||
this.serverLoginUrl_RPA = serverLoginUrl_RPA;
|
||||
}
|
||||
public String getApiAccessName_RPA() {
|
||||
return apiAccessName_RPA;
|
||||
}
|
||||
public void setApiAccessName_RPA(String apiAccessName_RPA) {
|
||||
this.apiAccessName_RPA = apiAccessName_RPA;
|
||||
}
|
||||
public String getApiAccessPassword_RPA() {
|
||||
return apiAccessPassword_RPA;
|
||||
}
|
||||
public void setApiAccessPassword_RPA(String apiAccessPassword_RPA) {
|
||||
this.apiAccessPassword_RPA = apiAccessPassword_RPA;
|
||||
}
|
||||
public String getApiAccessKey_RPA() {
|
||||
return apiAccessKey_RPA;
|
||||
}
|
||||
public void setApiAccessKey_RPA(String apiAccessKey_RPA) {
|
||||
this.apiAccessKey_RPA = apiAccessKey_RPA;
|
||||
}
|
||||
public String getServerAddUrl_RPA() {
|
||||
return serverAddUrl_RPA;
|
||||
}
|
||||
public void setServerAddUrl_RPA(String serverAddUrl_RPA) {
|
||||
this.serverAddUrl_RPA = serverAddUrl_RPA;
|
||||
}
|
||||
public String getServerExtensionUrl_RPA() {
|
||||
return serverExtensionUrl_RPA;
|
||||
}
|
||||
public void setServerExtensionUrl_RPA(String serverExtensionUrl_RPA) {
|
||||
this.serverExtensionUrl_RPA = serverExtensionUrl_RPA;
|
||||
}
|
||||
public int getTimeout_RPA() {
|
||||
return timeout_RPA;
|
||||
}
|
||||
public void setTimeout_RPA(int timeout_RPA) {
|
||||
this.timeout_RPA = timeout_RPA;
|
||||
}
|
||||
public String getServerUrl_SSO() {
|
||||
return serverUrl_SSO;
|
||||
}
|
||||
public void setServerUrl_SSO(String serverUrl_SSO) {
|
||||
this.serverUrl_SSO = serverUrl_SSO;
|
||||
}
|
||||
|
||||
public String getClientId_SSO() {
|
||||
return clientId_SSO;
|
||||
}
|
||||
public void setClientId_SSO(String clientId_SSO) {
|
||||
this.clientId_SSO = clientId_SSO;
|
||||
}
|
||||
public String getClientSecret_SSO() {
|
||||
return clientSecret_SSO;
|
||||
}
|
||||
public void setClientSecret_SSO(String clientSecret_SSO) {
|
||||
this.clientSecret_SSO = clientSecret_SSO;
|
||||
}
|
||||
public int getTimeout_SSO() {
|
||||
return timeout_SSO;
|
||||
}
|
||||
public void setTimeout_SSO(int timeout_SSO) {
|
||||
this.timeout_SSO = timeout_SSO;
|
||||
}
|
||||
public String getServerUrl_CallCenter() {
|
||||
return serverUrl_CallCenter;
|
||||
}
|
||||
public void setServerUrl_CallCenter(String serverUrl_CallCenter) {
|
||||
this.serverUrl_CallCenter = serverUrl_CallCenter;
|
||||
}
|
||||
public int getTimeout_CallCenter() {
|
||||
return timeout_CallCenter;
|
||||
}
|
||||
public void setTimeout_CallCenter(int timeout_CallCenter) {
|
||||
this.timeout_CallCenter = timeout_CallCenter;
|
||||
}
|
||||
public String getTokenUrl_SMS() {
|
||||
return tokenUrl_SMS;
|
||||
}
|
||||
public void setTokenUrl_SMS(String tokenUrl_SMS) {
|
||||
this.tokenUrl_SMS = tokenUrl_SMS;
|
||||
}
|
||||
public String getSendUrl_SMS() {
|
||||
return sendUrl_SMS;
|
||||
}
|
||||
public void setSendUrl_SMS(String sendUrl_SMS) {
|
||||
this.sendUrl_SMS = sendUrl_SMS;
|
||||
}
|
||||
public String getUsername_SMS() {
|
||||
return username_SMS;
|
||||
}
|
||||
public void setUsername_SMS(String username_SMS) {
|
||||
this.username_SMS = username_SMS;
|
||||
}
|
||||
public String getPassword_SMS() {
|
||||
return password_SMS;
|
||||
}
|
||||
public void setPassword_SMS(String password_SMS) {
|
||||
this.password_SMS = password_SMS;
|
||||
}
|
||||
public String getAccount_SMS() {
|
||||
return account_SMS;
|
||||
}
|
||||
public void setAccount_SMS(String account_SMS) {
|
||||
this.account_SMS = account_SMS;
|
||||
}
|
||||
public String getPriority_SMS() {
|
||||
return priority_SMS;
|
||||
}
|
||||
public void setPriority_SMS(String priority_SMS) {
|
||||
this.priority_SMS = priority_SMS;
|
||||
}
|
||||
public String getServerUrl_OWS() {
|
||||
return serverUrl_OWS;
|
||||
}
|
||||
public void setServerUrl_OWS(String serverUrl_OWS) {
|
||||
this.serverUrl_OWS = serverUrl_OWS;
|
||||
}
|
||||
public int getTimeout_OWS() {
|
||||
return timeout_OWS;
|
||||
}
|
||||
public void setTimeout_OWS(int timeout_OWS) {
|
||||
this.timeout_OWS = timeout_OWS;
|
||||
}
|
||||
public String getPort_SMTP() {
|
||||
return port_SMTP;
|
||||
}
|
||||
public void setPort_SMTP(String port_SMTP) {
|
||||
this.port_SMTP = port_SMTP;
|
||||
}
|
||||
public String getHost_SMTP() {
|
||||
return host_SMTP;
|
||||
}
|
||||
public void setHost_SMTP(String host_SMTP) {
|
||||
this.host_SMTP = host_SMTP;
|
||||
}
|
||||
public String getUsername_SMTP() {
|
||||
return username_SMTP;
|
||||
}
|
||||
public void setUsername_SMTP(String username_SMTP) {
|
||||
this.username_SMTP = username_SMTP;
|
||||
}
|
||||
public String getPassword_SMTP() {
|
||||
return password_SMTP;
|
||||
}
|
||||
public void setPassword_SMTP(String password_SMTP) {
|
||||
this.password_SMTP = password_SMTP;
|
||||
}
|
||||
public String getSend_to_SMTP() {
|
||||
return send_to_SMTP;
|
||||
}
|
||||
public void setSend_to_SMTP(String send_to_SMTP) {
|
||||
this.send_to_SMTP = send_to_SMTP;
|
||||
}
|
||||
|
||||
public String getServerUrl_ESB_Daylight() {
|
||||
return serverUrl_ESB_Daylight;
|
||||
}
|
||||
|
||||
public void setServerUrl_ESB_Daylight(String serverUrl_ESB_Daylight) {
|
||||
this.serverUrl_ESB_Daylight = serverUrl_ESB_Daylight;
|
||||
}
|
||||
|
||||
public String getApiKey_ESB_Daylight() {
|
||||
return apiKey_ESB_Daylight;
|
||||
}
|
||||
|
||||
public void setApiKey_ESB_Daylight(String apiKey_ESB_Daylight) {
|
||||
this.apiKey_ESB_Daylight = apiKey_ESB_Daylight;
|
||||
}
|
||||
|
||||
public String getApiSecret_ESB_Daylight() {
|
||||
return apiSecret_ESB_Daylight;
|
||||
}
|
||||
|
||||
public void setApiSecret_ESB_Daylight(String apiSecret_ESB_Daylight) {
|
||||
this.apiSecret_ESB_Daylight = apiSecret_ESB_Daylight;
|
||||
}
|
||||
|
||||
public int getTimeout_ESB_Daylight() {
|
||||
return timeout_ESB_Daylight;
|
||||
}
|
||||
|
||||
public void setTimeout_ESB_Daylight(int timeout_ESB_Daylight) {
|
||||
this.timeout_ESB_Daylight = timeout_ESB_Daylight;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.mgm.mcrm.common.dtos.data_import;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ValidateResult {
|
||||
private int resultCount=0;
|
||||
private int passedCount=0;
|
||||
private int failedCount=0;
|
||||
private boolean success=false;
|
||||
private List resultRows;
|
||||
private List groupItems=null;
|
||||
public int getResultCount() {
|
||||
return resultCount;
|
||||
}
|
||||
public void setResultCount(int resultCount) {
|
||||
this.resultCount = resultCount;
|
||||
}
|
||||
public int getPassedCount() {
|
||||
return passedCount;
|
||||
}
|
||||
public void setPassedCount(int passedCount) {
|
||||
this.passedCount = passedCount;
|
||||
}
|
||||
public int getFailedCount() {
|
||||
return failedCount;
|
||||
}
|
||||
public void setFailedCount(int failedCount) {
|
||||
this.failedCount = failedCount;
|
||||
}
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
public void setSuccess(boolean success) {
|
||||
this.success = success;
|
||||
}
|
||||
public List getResultRows() {
|
||||
return resultRows;
|
||||
}
|
||||
public void setResultRows(List resultRows) {
|
||||
this.resultRows = resultRows;
|
||||
}
|
||||
public List getGroupItems() {
|
||||
return groupItems;
|
||||
}
|
||||
public void setGroupItems(List groupItems) {
|
||||
this.groupItems = groupItems;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.mgm.mcrm.common.dtos.data_import.booking;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class OtherBookingImportRow {
|
||||
|
||||
private boolean validatePassed=false;
|
||||
private String errorMessage;
|
||||
|
||||
private Long otherRoomStatusId;
|
||||
private Long otherFollowUpStatusId;
|
||||
private Long propertyId;
|
||||
private Long roomId;
|
||||
private Long bookingTypeId;
|
||||
private Long marketCodeId;
|
||||
private Long segmentId;
|
||||
private Long souceCodeId;
|
||||
private String otherRoomStatusName;
|
||||
private String otherFollowUpStatusName;
|
||||
private String propertyName;
|
||||
private String roomName;
|
||||
private String bookingTypeName;
|
||||
private String marketCodeName;
|
||||
private String segmentName;
|
||||
private String checkinDate;
|
||||
private String checkoutDate;
|
||||
private String playerId;
|
||||
private String bookerId;
|
||||
private String approverId;
|
||||
private String sharer;
|
||||
private String remark;
|
||||
private String sharerList;
|
||||
private String confirmationNo;
|
||||
private String playerName;
|
||||
private String sourceCodeName;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_export;
|
||||
|
||||
public class ColumnDefine {
|
||||
private String columnHeader;
|
||||
private String dataType;
|
||||
private String attrName;
|
||||
private int columnWidth=0;
|
||||
|
||||
public String getColumnHeader() {
|
||||
return columnHeader;
|
||||
}
|
||||
public void setColumnHeader(String columnHeader) {
|
||||
this.columnHeader = columnHeader;
|
||||
}
|
||||
public String getDataType() {
|
||||
return dataType;
|
||||
}
|
||||
public void setDataType(String dataType) {
|
||||
this.dataType = dataType;
|
||||
}
|
||||
public String getAttrName() {
|
||||
return attrName;
|
||||
}
|
||||
public void setAttrName(String attrName) {
|
||||
this.attrName = attrName;
|
||||
}
|
||||
public int getColumnWidth() {
|
||||
return columnWidth;
|
||||
}
|
||||
public void setColumnWidth(int columnWidth) {
|
||||
this.columnWidth = columnWidth;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_export;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class DataElement {
|
||||
private int offsetRow=0;
|
||||
private int offsetCol=0;
|
||||
private int elementType=0;
|
||||
private boolean isShowHeader=false;
|
||||
private String objClassName;
|
||||
private String headerAlign="center";
|
||||
private String headerColor="";
|
||||
private String textAlign="left";
|
||||
private String textColor="";
|
||||
private List<ColumnDefine> columnDefs;
|
||||
private List blockData;
|
||||
|
||||
public int getElementType() {
|
||||
return elementType;
|
||||
}
|
||||
public void setElementType(int elementType) {
|
||||
this.elementType = elementType;
|
||||
}
|
||||
public List<ColumnDefine> getColumnDefs() {
|
||||
return columnDefs;
|
||||
}
|
||||
public void setColumnDefs(List<ColumnDefine> columnDefs) {
|
||||
this.columnDefs = columnDefs;
|
||||
}
|
||||
|
||||
public boolean isShowHeader() {
|
||||
return isShowHeader;
|
||||
}
|
||||
public void setShowHeader(boolean isShowHeader) {
|
||||
this.isShowHeader = isShowHeader;
|
||||
}
|
||||
public int getOffsetRow() {
|
||||
return offsetRow;
|
||||
}
|
||||
public void setOffsetRow(int offsetRow) {
|
||||
this.offsetRow = offsetRow;
|
||||
}
|
||||
public int getOffsetCol() {
|
||||
return offsetCol;
|
||||
}
|
||||
public void setOffsetCol(int offsetCol) {
|
||||
this.offsetCol = offsetCol;
|
||||
}
|
||||
public String getObjClassName() {
|
||||
return objClassName;
|
||||
}
|
||||
public void setObjClassName(String objClassName) {
|
||||
this.objClassName = objClassName;
|
||||
}
|
||||
public String getHeaderAlign() {
|
||||
return headerAlign;
|
||||
}
|
||||
public void setHeaderAlign(String headerAlign) {
|
||||
this.headerAlign = headerAlign;
|
||||
}
|
||||
public String getHeaderColor() {
|
||||
return headerColor;
|
||||
}
|
||||
public void setHeaderColor(String headerColor) {
|
||||
this.headerColor = headerColor;
|
||||
}
|
||||
public String getTextAlign() {
|
||||
return textAlign;
|
||||
}
|
||||
public void setTextAlign(String textAlign) {
|
||||
this.textAlign = textAlign;
|
||||
}
|
||||
public String getTextColor() {
|
||||
return textColor;
|
||||
}
|
||||
public void setTextColor(String textColor) {
|
||||
this.textColor = textColor;
|
||||
}
|
||||
public List getBlockData() {
|
||||
return blockData;
|
||||
}
|
||||
public void setBlockData(List blockData) {
|
||||
this.blockData = blockData;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_export;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ExportDefination {
|
||||
private List<ExportSheet> exportPages;
|
||||
private String exportFileName;
|
||||
|
||||
public List<ExportSheet> getExportPages() {
|
||||
return exportPages;
|
||||
}
|
||||
|
||||
public void setExportPages(List<ExportSheet> exportPages) {
|
||||
this.exportPages = exportPages;
|
||||
}
|
||||
|
||||
public String getExportFileName() {
|
||||
return exportFileName;
|
||||
}
|
||||
|
||||
public void setExportFileName(String exportFileName) {
|
||||
this.exportFileName = exportFileName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_export;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ExportSheet {
|
||||
private String sheetName;
|
||||
private List<DataElement> dataElements;
|
||||
|
||||
public ExportSheet() {
|
||||
|
||||
}
|
||||
|
||||
public String getSheetName() {
|
||||
return sheetName;
|
||||
}
|
||||
public void setSheetName(String sheetName) {
|
||||
this.sheetName = sheetName;
|
||||
}
|
||||
public List<DataElement> getDataElements() {
|
||||
return dataElements;
|
||||
}
|
||||
public void setDataElements(List<DataElement> dataElements) {
|
||||
this.dataElements = dataElements;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ColumnDefine {
|
||||
private String columnHeader;
|
||||
private String columnType="SINGLE";
|
||||
private String dataType="String";
|
||||
private String attrName;
|
||||
private String groupName;
|
||||
private String textAlign;
|
||||
private String formatVal;
|
||||
private String groupKeyAttrName;
|
||||
private boolean checkHeader=false;
|
||||
private int columnWidth=0;
|
||||
private int columnIndex=0;
|
||||
private int headerRowIdx=0;
|
||||
private List<ColumnDefine> groupColumns=null;
|
||||
|
||||
public String getColumnHeader() {
|
||||
return columnHeader;
|
||||
}
|
||||
public void setColumnHeader(String columnHeader) {
|
||||
this.columnHeader = columnHeader;
|
||||
}
|
||||
public String getDataType() {
|
||||
return dataType;
|
||||
}
|
||||
public void setDataType(String dataType) {
|
||||
this.dataType = dataType;
|
||||
}
|
||||
public String getAttrName() {
|
||||
return attrName;
|
||||
}
|
||||
public void setAttrName(String attrName) {
|
||||
this.attrName = attrName;
|
||||
}
|
||||
public int getColumnWidth() {
|
||||
return columnWidth;
|
||||
}
|
||||
public void setColumnWidth(int columnWidth) {
|
||||
this.columnWidth = columnWidth;
|
||||
}
|
||||
public int getColumnIndex() {
|
||||
return columnIndex;
|
||||
}
|
||||
public void setColumnIndex(int columnIndex) {
|
||||
this.columnIndex = columnIndex;
|
||||
}
|
||||
public String getColumnType() {
|
||||
return columnType;
|
||||
}
|
||||
public void setColumnType(String columnType) {
|
||||
this.columnType = columnType;
|
||||
}
|
||||
public String getTextAlign() {
|
||||
return textAlign;
|
||||
}
|
||||
public void setTextAlign(String textAlign) {
|
||||
this.textAlign = textAlign;
|
||||
}
|
||||
public String getFormatVal() {
|
||||
return formatVal;
|
||||
}
|
||||
public void setFormatVal(String formatVal) {
|
||||
this.formatVal = formatVal;
|
||||
}
|
||||
public boolean isCheckHeader() {
|
||||
return checkHeader;
|
||||
}
|
||||
public void setCheckHeader(boolean checkHeader) {
|
||||
this.checkHeader = checkHeader;
|
||||
}
|
||||
public int getHeaderRowIdx() {
|
||||
return headerRowIdx;
|
||||
}
|
||||
public void setHeaderRowIdx(int headerRowIdx) {
|
||||
this.headerRowIdx = headerRowIdx;
|
||||
}
|
||||
public List<ColumnDefine> getGroupColumns() {
|
||||
return groupColumns;
|
||||
}
|
||||
public void setGroupColumns(List<ColumnDefine> groupColumns) {
|
||||
this.groupColumns = groupColumns;
|
||||
}
|
||||
public String getGroupName() {
|
||||
return groupName;
|
||||
}
|
||||
public void setGroupName(String groupName) {
|
||||
this.groupName = groupName;
|
||||
}
|
||||
public String getGroupKeyAttrName() {
|
||||
return groupKeyAttrName;
|
||||
}
|
||||
public void setGroupKeyAttrName(String groupKeyAttrName) {
|
||||
this.groupKeyAttrName = groupKeyAttrName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_model;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.List;
|
||||
|
||||
public class ColumnGroupInfo {
|
||||
|
||||
private String groupName;
|
||||
private int colStartIndex=0;
|
||||
private Field groupDataField=null;
|
||||
private Field keyField=null;
|
||||
private Class<?> groupDataType=null;
|
||||
private List<GroupItem> groupItems=null;
|
||||
private List<RowFieldInfo> groupColumns;
|
||||
public String getGroupName() {
|
||||
return groupName;
|
||||
}
|
||||
public void setGroupName(String groupName) {
|
||||
this.groupName = groupName;
|
||||
}
|
||||
public int getColStartIndex() {
|
||||
return colStartIndex;
|
||||
}
|
||||
public void setColStartIndex(int colStartIndex) {
|
||||
this.colStartIndex = colStartIndex;
|
||||
}
|
||||
public List<RowFieldInfo> getGroupColumns() {
|
||||
return groupColumns;
|
||||
}
|
||||
public void setGroupColumns(List<RowFieldInfo> groupColumns) {
|
||||
this.groupColumns = groupColumns;
|
||||
}
|
||||
public Field getGroupDataField() {
|
||||
return groupDataField;
|
||||
}
|
||||
public void setGroupDataField(Field groupDataField) {
|
||||
this.groupDataField = groupDataField;
|
||||
}
|
||||
public Class getGroupDataType() {
|
||||
return groupDataType;
|
||||
}
|
||||
public void setGroupDataType(Class groupDataType) {
|
||||
this.groupDataType = groupDataType;
|
||||
}
|
||||
public List<GroupItem> getGroupItems() {
|
||||
return groupItems;
|
||||
}
|
||||
public void setGroupItems(List<GroupItem> groupItems) {
|
||||
this.groupItems = groupItems;
|
||||
}
|
||||
public Field getKeyField() {
|
||||
return keyField;
|
||||
}
|
||||
public void setKeyField(Field keyField) {
|
||||
this.keyField = keyField;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class DataBlock {
|
||||
private int offsetRow=0;
|
||||
private int offsetCol=0;
|
||||
private int elementType=0;
|
||||
private int headerRowNum=1;
|
||||
private boolean isShowHeader=false;
|
||||
private String objClassName;
|
||||
private String headerAlign="center";
|
||||
private String headerColor="";
|
||||
private String textAlign="left";
|
||||
private String textColor="";
|
||||
private String headerTextColor="";
|
||||
private String blockName="";
|
||||
private List<ColumnDefine> columnDefs;
|
||||
|
||||
|
||||
public int getElementType() {
|
||||
return elementType;
|
||||
}
|
||||
public void setElementType(int elementType) {
|
||||
this.elementType = elementType;
|
||||
}
|
||||
public List<ColumnDefine> getColumnDefs() {
|
||||
return columnDefs;
|
||||
}
|
||||
public void setColumnDefs(List<ColumnDefine> columnDefs) {
|
||||
this.columnDefs = columnDefs;
|
||||
}
|
||||
|
||||
public boolean isShowHeader() {
|
||||
return isShowHeader;
|
||||
}
|
||||
public void setShowHeader(boolean isShowHeader) {
|
||||
this.isShowHeader = isShowHeader;
|
||||
}
|
||||
public int getOffsetRow() {
|
||||
return offsetRow;
|
||||
}
|
||||
public void setOffsetRow(int offsetRow) {
|
||||
this.offsetRow = offsetRow;
|
||||
}
|
||||
public int getOffsetCol() {
|
||||
return offsetCol;
|
||||
}
|
||||
public void setOffsetCol(int offsetCol) {
|
||||
this.offsetCol = offsetCol;
|
||||
}
|
||||
public String getObjClassName() {
|
||||
return objClassName;
|
||||
}
|
||||
public void setObjClassName(String objClassName) {
|
||||
this.objClassName = objClassName;
|
||||
}
|
||||
public String getHeaderAlign() {
|
||||
return headerAlign;
|
||||
}
|
||||
public void setHeaderAlign(String headerAlign) {
|
||||
this.headerAlign = headerAlign;
|
||||
}
|
||||
public String getHeaderColor() {
|
||||
return headerColor;
|
||||
}
|
||||
public void setHeaderColor(String headerColor) {
|
||||
this.headerColor = headerColor;
|
||||
}
|
||||
public String getTextAlign() {
|
||||
return textAlign;
|
||||
}
|
||||
public void setTextAlign(String textAlign) {
|
||||
this.textAlign = textAlign;
|
||||
}
|
||||
public String getTextColor() {
|
||||
return textColor;
|
||||
}
|
||||
public void setTextColor(String textColor) {
|
||||
this.textColor = textColor;
|
||||
}
|
||||
public String getBlockName() {
|
||||
return blockName;
|
||||
}
|
||||
public void setBlockName(String blockName) {
|
||||
this.blockName = blockName;
|
||||
}
|
||||
public String getHeaderTextColor() {
|
||||
return headerTextColor;
|
||||
}
|
||||
public void setHeaderTextColor(String headerTextColor) {
|
||||
this.headerTextColor = headerTextColor;
|
||||
}
|
||||
public int getHeaderRowNum() {
|
||||
return headerRowNum;
|
||||
}
|
||||
public void setHeaderRowNum(int headerRowNum) {
|
||||
this.headerRowNum = headerRowNum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ExportDefine {
|
||||
private String exportName;
|
||||
private List<SheetDefine> exportPages;
|
||||
private String exportFileName;
|
||||
|
||||
public List<SheetDefine> getExportPages() {
|
||||
return exportPages;
|
||||
}
|
||||
|
||||
public void setExportPages(List<SheetDefine> exportPages) {
|
||||
this.exportPages = exportPages;
|
||||
}
|
||||
|
||||
public String getExportFileName() {
|
||||
return exportFileName;
|
||||
}
|
||||
|
||||
public void setExportFileName(String exportFileName) {
|
||||
this.exportFileName = exportFileName;
|
||||
}
|
||||
|
||||
public String getExportName() {
|
||||
return exportName;
|
||||
}
|
||||
|
||||
public void setExportName(String exportName) {
|
||||
this.exportName = exportName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_model;
|
||||
|
||||
public class GroupItem {
|
||||
|
||||
private String itemText;
|
||||
private String itemKey;
|
||||
private int headerIndex=-1;
|
||||
|
||||
public String getItemText() {
|
||||
return itemText;
|
||||
}
|
||||
public void setItemText(String itemText) {
|
||||
this.itemText = itemText;
|
||||
}
|
||||
public String getItemKey() {
|
||||
return itemKey;
|
||||
}
|
||||
public void setItemKey(String itemKey) {
|
||||
this.itemKey = itemKey;
|
||||
}
|
||||
public int getHeaderIndex() {
|
||||
return headerIndex;
|
||||
}
|
||||
public void setHeaderIndex(int headerIndex) {
|
||||
this.headerIndex = headerIndex;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ImportDefine {
|
||||
private String importName;
|
||||
private List<SheetDefine> importPages;
|
||||
private String importFileName;
|
||||
|
||||
public List<SheetDefine> getImportPages() {
|
||||
return importPages;
|
||||
}
|
||||
|
||||
public void setImportPages(List<SheetDefine> exportPages) {
|
||||
this.importPages = exportPages;
|
||||
}
|
||||
|
||||
public String getImportFileName() {
|
||||
return importFileName;
|
||||
}
|
||||
|
||||
public void setImportFileName(String importFileName) {
|
||||
this.importFileName = importFileName;
|
||||
}
|
||||
|
||||
public String getImportName() {
|
||||
return importName;
|
||||
}
|
||||
|
||||
public void setImportName(String importName) {
|
||||
this.importName = importName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_model;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
|
||||
|
||||
public class RowFieldInfo {
|
||||
private String fieldKey;
|
||||
private Field dataField=null;
|
||||
private String columnHeader="";
|
||||
private int headerRowIdx=-1;
|
||||
private int colIndex=0;
|
||||
private String dateFormat;
|
||||
private String dataType="String";
|
||||
private boolean checkHeader=false;
|
||||
private XSSFCellStyle fieldStyle=null;
|
||||
|
||||
public String getFieldKey() {
|
||||
return fieldKey;
|
||||
}
|
||||
public void setFieldKey(String fieldKey) {
|
||||
this.fieldKey = fieldKey;
|
||||
}
|
||||
public Field getDataField() {
|
||||
return dataField;
|
||||
}
|
||||
public void setDataField(Field dataField) {
|
||||
this.dataField = dataField;
|
||||
}
|
||||
public int getColIndex() {
|
||||
return colIndex;
|
||||
}
|
||||
public void setColIndex(int colIndex) {
|
||||
this.colIndex = colIndex;
|
||||
}
|
||||
public XSSFCellStyle getFieldStyle() {
|
||||
return fieldStyle;
|
||||
}
|
||||
public void setFieldStyle(XSSFCellStyle fieldStyle) {
|
||||
this.fieldStyle = fieldStyle;
|
||||
}
|
||||
public boolean isCheckHeader() {
|
||||
return checkHeader;
|
||||
}
|
||||
public void setCheckHeader(boolean checkHeader) {
|
||||
this.checkHeader = checkHeader;
|
||||
}
|
||||
public String getColumnHeader() {
|
||||
return columnHeader;
|
||||
}
|
||||
public void setColumnHeader(String columnHeader) {
|
||||
this.columnHeader = columnHeader;
|
||||
}
|
||||
public int getHeaderRowIdx() {
|
||||
return headerRowIdx;
|
||||
}
|
||||
public void setHeaderRowIdx(int headerRowIdx) {
|
||||
this.headerRowIdx = headerRowIdx;
|
||||
}
|
||||
public String getDateFormat() {
|
||||
return dateFormat;
|
||||
}
|
||||
public void setDateFormat(String dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
}
|
||||
public String getDataType() {
|
||||
return dataType;
|
||||
}
|
||||
public void setDataType(String dataType) {
|
||||
this.dataType = dataType;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.mgm.mcrm.common.dtos.excel_model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class SheetDefine {
|
||||
private String sheetName;
|
||||
private int sheetIndx=0;
|
||||
private List<DataBlock> dataElements;
|
||||
|
||||
public String getSheetName() {
|
||||
return sheetName;
|
||||
}
|
||||
public void setSheetName(String sheetName) {
|
||||
this.sheetName = sheetName;
|
||||
}
|
||||
public List<DataBlock> getDataElements() {
|
||||
return dataElements;
|
||||
}
|
||||
public void setDataElements(List<DataBlock> dataElements) {
|
||||
this.dataElements = dataElements;
|
||||
}
|
||||
public int getSheetIndx() {
|
||||
return sheetIndx;
|
||||
}
|
||||
public void setSheetIndx(int sheetIndx) {
|
||||
this.sheetIndx = sheetIndx;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.mgm.mcrm.common.dtos.http_util;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.hc.client5.http.auth.CredentialsProvider;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
|
||||
public class HttpRequestDefine {
|
||||
|
||||
private String requestUrl;
|
||||
private String requestMethod="GET";
|
||||
private int timeout=0;
|
||||
private String entityContent="";
|
||||
private String requestCharSet ="UTF-8";
|
||||
private String responseCharSet = "UTF-8";
|
||||
private boolean isUpload =false;
|
||||
private MultipartFile uploadFile = null;
|
||||
private String fileParaName;
|
||||
private CredentialsProvider credentials=null;
|
||||
private HttpEntity requestEntity;
|
||||
|
||||
private Map<String,String> headers;
|
||||
|
||||
public String getRequestUrl() {
|
||||
return requestUrl;
|
||||
}
|
||||
public void setRequestUrl(String requestUrl) {
|
||||
this.requestUrl = requestUrl;
|
||||
}
|
||||
public String getRequestMethod() {
|
||||
return requestMethod;
|
||||
}
|
||||
public void setRequestMethod(String requestMethod) {
|
||||
this.requestMethod = requestMethod;
|
||||
}
|
||||
public int getTimeout() {
|
||||
return timeout;
|
||||
}
|
||||
public void setTimeout(int timeout) {
|
||||
this.timeout = timeout;
|
||||
}
|
||||
public Map<String, String> getHeaders() {
|
||||
return headers;
|
||||
}
|
||||
public void setHeaders(Map<String, String> headers) {
|
||||
this.headers = headers;
|
||||
}
|
||||
public String getEntityContent() {
|
||||
return entityContent;
|
||||
}
|
||||
public void setEntityContent(String entityContent) {
|
||||
this.entityContent = entityContent;
|
||||
}
|
||||
public String getRequestCharSet() {
|
||||
return requestCharSet;
|
||||
}
|
||||
public void setRequestCharSet(String requestCharSet) {
|
||||
this.requestCharSet = requestCharSet;
|
||||
}
|
||||
public String getResponseCharSet() {
|
||||
return responseCharSet;
|
||||
}
|
||||
public void setResponseCharSet(String responseCharSet) {
|
||||
this.responseCharSet = responseCharSet;
|
||||
}
|
||||
|
||||
public boolean isUpload() {
|
||||
return isUpload;
|
||||
}
|
||||
public void setUpload(boolean isUpload) {
|
||||
this.isUpload = isUpload;
|
||||
}
|
||||
public MultipartFile getUploadFile() {
|
||||
return uploadFile;
|
||||
}
|
||||
public void setUploadFile(MultipartFile uploadFile) {
|
||||
this.uploadFile = uploadFile;
|
||||
}
|
||||
public String getFileParaName() {
|
||||
return fileParaName;
|
||||
}
|
||||
public void setFileParaName(String fileParaName) {
|
||||
this.fileParaName = fileParaName;
|
||||
}
|
||||
public CredentialsProvider getCredentials() {
|
||||
return credentials;
|
||||
}
|
||||
public void setCredentials(CredentialsProvider credentials) {
|
||||
this.credentials = credentials;
|
||||
}
|
||||
public HttpEntity getRequestEntity() {
|
||||
return requestEntity;
|
||||
}
|
||||
public void setRequestEntity(HttpEntity requestEntity) {
|
||||
this.requestEntity = requestEntity;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.mgm.mcrm.common.dtos.http_util;
|
||||
|
||||
import org.apache.hc.client5.http.cookie.Cookie;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class HttpResponseResult {
|
||||
|
||||
private int statusCode;
|
||||
private String responseContent;
|
||||
private String errorMessage;
|
||||
private String requestUrl;
|
||||
private String requestContent;
|
||||
private String requestTime;
|
||||
private String responseTime;
|
||||
private Date requestTimeVal;
|
||||
private Date responseTimeVal;
|
||||
private List<Cookie> cookies;
|
||||
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
public void setStatusCode(int statusCode) {
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
public String getResponseContent() {
|
||||
return responseContent;
|
||||
}
|
||||
public void setResponseContent(String responseContent) {
|
||||
this.responseContent = responseContent;
|
||||
}
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
public void setMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
public String getRequestUrl() {
|
||||
return requestUrl;
|
||||
}
|
||||
public void setRequestUrl(String requestUrl) {
|
||||
this.requestUrl = requestUrl;
|
||||
}
|
||||
public String getRequestContent() {
|
||||
return requestContent;
|
||||
}
|
||||
public void setRequestContent(String requestContent) {
|
||||
this.requestContent = requestContent;
|
||||
}
|
||||
public Date getRequestTimeVal() {
|
||||
return requestTimeVal;
|
||||
}
|
||||
public void setRequestTimeVal(Date requestTimeVal) {
|
||||
this.requestTimeVal = requestTimeVal;
|
||||
}
|
||||
public Date getResponseTimeVal() {
|
||||
return responseTimeVal;
|
||||
}
|
||||
public void setResponseTimeVal(Date responseTimeVal) {
|
||||
this.responseTimeVal = responseTimeVal;
|
||||
}
|
||||
public String getRequestTime() {
|
||||
return requestTime;
|
||||
}
|
||||
public void setRequestTime(String requestTime) {
|
||||
this.requestTime = requestTime;
|
||||
}
|
||||
public String getResponseTime() {
|
||||
return responseTime;
|
||||
}
|
||||
public void setResponseTime(String responseTime) {
|
||||
this.responseTime = responseTime;
|
||||
}
|
||||
public List<Cookie> getCookies() {
|
||||
return cookies;
|
||||
}
|
||||
public void setCookies(List<Cookie> cookies) {
|
||||
this.cookies = cookies;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import com.mgm.mcrm.approval.models.ApprovalGamingData;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class ApprovalGamingDataResult implements Serializable {
|
||||
|
||||
private String statusCode = null;
|
||||
private String statusDescription=null;
|
||||
private List<ApprovalGamingData> Records = null;
|
||||
|
||||
|
||||
public String getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
public void setStatusCode(String statusCode) {
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
|
||||
public String getStatusDescription() {
|
||||
return statusDescription;
|
||||
}
|
||||
|
||||
public void setStatusDescription(String statusDescription) {
|
||||
this.statusDescription = statusDescription;
|
||||
}
|
||||
|
||||
public List<ApprovalGamingData> getRecords() {
|
||||
return Records;
|
||||
}
|
||||
|
||||
public void setRecords(List<ApprovalGamingData> records) {
|
||||
Records = records;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
|
||||
public class ApproverRecord {
|
||||
|
||||
|
||||
private String EmployeeId = null;
|
||||
private String EmployeeName = null;
|
||||
|
||||
public String getEmployeeId() {
|
||||
return EmployeeId;
|
||||
}
|
||||
|
||||
public void setEmployeeId(String employeeId) {
|
||||
EmployeeId = employeeId;
|
||||
}
|
||||
|
||||
public String getEmployeeName() {
|
||||
return EmployeeName;
|
||||
}
|
||||
|
||||
public void setEmployeeName(String employeeName) {
|
||||
EmployeeName = employeeName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
|
||||
import java.util.ArrayList;
|
||||
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;
|
||||
|
||||
|
||||
public String getPlayerId() {
|
||||
return PlayerId;
|
||||
}
|
||||
|
||||
public void setPlayerId(String playerId) {
|
||||
PlayerId = playerId;
|
||||
}
|
||||
|
||||
public String getBookingType() {
|
||||
return BookingType;
|
||||
}
|
||||
|
||||
public void setBookingType(String bookingType) {
|
||||
BookingType = bookingType;
|
||||
}
|
||||
|
||||
public String getProperty() {
|
||||
return Property;
|
||||
}
|
||||
|
||||
public void setProperty(String property) {
|
||||
Property = property;
|
||||
}
|
||||
|
||||
public String getRoomCategory() {
|
||||
return RoomCategory;
|
||||
}
|
||||
|
||||
public void setRoomCategory(String roomCategory) {
|
||||
RoomCategory = roomCategory;
|
||||
}
|
||||
|
||||
public String getApprovalRoutingType() {
|
||||
return ApprovalRoutingType;
|
||||
}
|
||||
|
||||
public void setApprovalRoutingType(String approvalRoutingType) {
|
||||
ApprovalRoutingType = approvalRoutingType;
|
||||
}
|
||||
|
||||
public String getApprovalRoutingMessage() {
|
||||
return ApprovalRoutingMessage;
|
||||
}
|
||||
|
||||
public void setApprovalRoutingMessage(String approvalRoutingMessage) {
|
||||
ApprovalRoutingMessage = approvalRoutingMessage;
|
||||
}
|
||||
|
||||
public List<ApproverRecord> getApproverList() {
|
||||
if (ApproverList == null) {
|
||||
return new ArrayList<ApproverRecord>();
|
||||
}
|
||||
if (ApproverList instanceof JSONArray arr) {
|
||||
return arr.toJavaList(ApproverRecord.class);
|
||||
}
|
||||
if (ApproverList instanceof String s) {
|
||||
s = s.trim();
|
||||
if (s.isEmpty()) {
|
||||
return new ArrayList<ApproverRecord>();
|
||||
}
|
||||
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));
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class ApproverResult {
|
||||
|
||||
|
||||
private String StatusCode = null;
|
||||
private String StatusDescription=null;
|
||||
private List<ApproverRecordResult> Records = new ArrayList<ApproverRecordResult>();
|
||||
|
||||
public String getStatusCode() {
|
||||
return StatusCode;
|
||||
}
|
||||
|
||||
public void setStatusCode(String statusCode) {
|
||||
StatusCode = statusCode;
|
||||
}
|
||||
|
||||
public String getStatusDescription() {
|
||||
return StatusDescription;
|
||||
}
|
||||
|
||||
public void setStatusDescription(String statusDescription) {
|
||||
StatusDescription = statusDescription;
|
||||
}
|
||||
|
||||
public List<ApproverRecordResult> getRecords() {
|
||||
return Records;
|
||||
}
|
||||
|
||||
public void setRecords(List<ApproverRecordResult> records) {
|
||||
Records = records;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class CheckApproverResult {
|
||||
|
||||
private String statusCode = null;
|
||||
private String statusDescription="";
|
||||
private String userId;
|
||||
private String userName;
|
||||
private String property;
|
||||
private String roomCategory;
|
||||
private String roomType;
|
||||
private String isApprover;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
|
||||
public class ItemRecord {
|
||||
|
||||
private String ItemRecordDescription = null;
|
||||
|
||||
public ItemRecord() {
|
||||
|
||||
}
|
||||
|
||||
|
||||
public String getItemRecordDescription() {
|
||||
return ItemRecordDescription;
|
||||
}
|
||||
|
||||
public void setItemRecordDescription(String itemRecordDescription) {
|
||||
ItemRecordDescription = itemRecordDescription;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class NonMGMBookingApiResult {
|
||||
|
||||
private String statusCode;
|
||||
private String statusDescription;
|
||||
private List<NonMGMBookingRecord> records;
|
||||
public String getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
public void setStatusCode(String statusCode) {
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
public String getStatusDescription() {
|
||||
return statusDescription;
|
||||
}
|
||||
public void setStatusDescription(String statusDescription) {
|
||||
this.statusDescription = statusDescription;
|
||||
}
|
||||
public List<NonMGMBookingRecord> getRecords() {
|
||||
return records;
|
||||
}
|
||||
public void setRecords(List<NonMGMBookingRecord> records) {
|
||||
this.records = records;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
public class NonMGMBookingRecord {
|
||||
|
||||
private String confirmationNumber;
|
||||
private String property;
|
||||
private String roomTypeStatusCode;
|
||||
private String checkInDate;
|
||||
private String checkOutDate;
|
||||
private String createdBy;
|
||||
private String createdOn;
|
||||
|
||||
public String getConfirmationNumber() {
|
||||
return confirmationNumber;
|
||||
}
|
||||
public void setConfirmationNumber(String confirmationNumber) {
|
||||
this.confirmationNumber = confirmationNumber;
|
||||
}
|
||||
public String getProperty() {
|
||||
return property;
|
||||
}
|
||||
public void setProperty(String property) {
|
||||
this.property = property;
|
||||
}
|
||||
public String getRoomTypeStatusCode() {
|
||||
return roomTypeStatusCode;
|
||||
}
|
||||
public void setRoomTypeStatusCode(String roomTypeStatusCode) {
|
||||
this.roomTypeStatusCode = roomTypeStatusCode;
|
||||
}
|
||||
public String getCheckInDate() {
|
||||
return checkInDate;
|
||||
}
|
||||
public void setCheckInDate(String checkInDate) {
|
||||
this.checkInDate = checkInDate;
|
||||
}
|
||||
public String getCheckOutDate() {
|
||||
return checkOutDate;
|
||||
}
|
||||
public void setCheckOutDate(String checkOutDate) {
|
||||
this.checkOutDate = checkOutDate;
|
||||
}
|
||||
public String getCreatedBy() {
|
||||
return createdBy;
|
||||
}
|
||||
public void setCreatedBy(String createdBy) {
|
||||
this.createdBy = createdBy;
|
||||
}
|
||||
public String getCreatedOn() {
|
||||
return createdOn;
|
||||
}
|
||||
public void setCreatedOn(String createdOn) {
|
||||
this.createdOn = createdOn;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class PlayerProfileEntry {
|
||||
|
||||
private String statusCode = null;
|
||||
private String statusDescription = "";
|
||||
private String playerId;
|
||||
private String userId;
|
||||
private String tierName;
|
||||
private String tierId;
|
||||
private String chineseName;
|
||||
private String englishName;
|
||||
private String salutation;
|
||||
private Integer codedFlag;
|
||||
private String name;
|
||||
private String playerPhone;
|
||||
private String phoneType;
|
||||
private String birthday;
|
||||
private String country;
|
||||
private String state;
|
||||
private String passport;
|
||||
private String language;
|
||||
private List<Integer> nameIds = new ArrayList<>();
|
||||
private String profileId;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
import com.mgm.mcrm.player.dtos.PlayerTPD;
|
||||
|
||||
|
||||
public class PlayerTPDApiResult {
|
||||
|
||||
private String statusCode = null;
|
||||
private String statusDescription="";
|
||||
private List<PlayerTPD> records;
|
||||
private int status;
|
||||
private List<JSONObject> dates=new ArrayList<JSONObject>();
|
||||
|
||||
public PlayerTPDApiResult() {
|
||||
|
||||
}
|
||||
|
||||
public String getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
public void setStatusCode(String statusCode) {
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
|
||||
public String getStatusDescription() {
|
||||
return statusDescription;
|
||||
}
|
||||
|
||||
public void setStatusDescription(String statusDescription) {
|
||||
this.statusDescription = statusDescription;
|
||||
}
|
||||
|
||||
public List<PlayerTPD> getRecords() {
|
||||
return records;
|
||||
}
|
||||
|
||||
public void setRecords(List<PlayerTPD> records) {
|
||||
this.records = records;
|
||||
}
|
||||
|
||||
public int getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public List<JSONObject> getDates() {
|
||||
return dates;
|
||||
}
|
||||
|
||||
public void setDates(List<JSONObject> dates) {
|
||||
this.dates = dates;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
|
||||
public class TodoDashboardRecord {
|
||||
|
||||
private Integer UserId=null;
|
||||
private String UserSegment=null;
|
||||
private String Type = null;
|
||||
private Integer Identifier = null;
|
||||
private String ItemName=null;
|
||||
private Integer Level=null;
|
||||
private Double CurrentValue = null;
|
||||
private Double TargetValue = null;
|
||||
|
||||
public TodoDashboardRecord() {
|
||||
|
||||
}
|
||||
|
||||
public Integer getUserId() {
|
||||
return UserId;
|
||||
}
|
||||
|
||||
|
||||
public void setUserId(Integer userId) {
|
||||
UserId = userId;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return Type;
|
||||
}
|
||||
|
||||
public void setType(String Type) {
|
||||
this.Type = Type;
|
||||
}
|
||||
|
||||
public Integer getIdentifier() {
|
||||
return Identifier;
|
||||
}
|
||||
|
||||
public void setIdentifier(Integer identifier) {
|
||||
Identifier = identifier;
|
||||
}
|
||||
|
||||
public String getItemName() {
|
||||
return ItemName;
|
||||
}
|
||||
|
||||
public void setItemName(String itemName) {
|
||||
ItemName = itemName;
|
||||
}
|
||||
|
||||
public String getUserSegment() {
|
||||
return UserSegment;
|
||||
}
|
||||
|
||||
public void setUserSegment(String userSegment) {
|
||||
UserSegment = userSegment;
|
||||
}
|
||||
|
||||
public Integer getLevel() {
|
||||
return Level;
|
||||
}
|
||||
|
||||
public void setLevel(Integer level) {
|
||||
Level = level;
|
||||
}
|
||||
|
||||
public Double getCurrentValue() {
|
||||
return CurrentValue;
|
||||
}
|
||||
|
||||
public void setCurrentValue(Double currentValue) {
|
||||
CurrentValue = currentValue;
|
||||
}
|
||||
|
||||
public Double getTargetValue() {
|
||||
return TargetValue;
|
||||
}
|
||||
|
||||
public void setTargetValue(Double targetValue) {
|
||||
TargetValue = targetValue;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Data
|
||||
public class TodoDashboardResult {
|
||||
|
||||
private String statusCode = null;
|
||||
private String statusDescription=null;
|
||||
private List<TodoDashboardRecord> records = new ArrayList<TodoDashboardRecord>();
|
||||
|
||||
public TodoDashboardResult() {
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class TodoDateListRecord {
|
||||
|
||||
|
||||
private String Date = null;
|
||||
private List<TodoListRecord> dateRecords = new ArrayList<TodoListRecord>();
|
||||
|
||||
public TodoDateListRecord() {
|
||||
|
||||
}
|
||||
|
||||
|
||||
public String getDate() {
|
||||
return Date;
|
||||
}
|
||||
|
||||
|
||||
public void setDate(String date) {
|
||||
Date = date;
|
||||
}
|
||||
|
||||
|
||||
public List<TodoListRecord> getDateRecords() {
|
||||
return dateRecords;
|
||||
}
|
||||
|
||||
|
||||
public void setDateRecords(List<TodoListRecord> dateRecords) {
|
||||
this.dateRecords = dateRecords;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class TodoDateListResult {
|
||||
|
||||
|
||||
private String statusCode = null;
|
||||
private String statusDescription=null;
|
||||
private List<TodoDateListRecord> Records = new ArrayList<TodoDateListRecord>();
|
||||
|
||||
public TodoDateListResult() {
|
||||
|
||||
}
|
||||
|
||||
public String getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
public void setStatusCode(String statusCode) {
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
|
||||
public String getStatusDescription() {
|
||||
return statusDescription;
|
||||
}
|
||||
|
||||
public void setStatusDescription(String statusDescription) {
|
||||
this.statusDescription = statusDescription;
|
||||
}
|
||||
|
||||
public List<TodoDateListRecord> getRecords() {
|
||||
return Records;
|
||||
}
|
||||
|
||||
public void setRecords(List<TodoDateListRecord> records) {
|
||||
Records = records;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
|
||||
public class TodoDetailDescription {
|
||||
|
||||
|
||||
private String ItemRecordType = null;
|
||||
private Integer ItemRecordId = null;
|
||||
private String ItemRecordDescription = null;
|
||||
|
||||
public TodoDetailDescription() {
|
||||
|
||||
}
|
||||
|
||||
public String getItemRecordType() {
|
||||
return ItemRecordType;
|
||||
}
|
||||
|
||||
public void setItemRecordType(String itemRecordType) {
|
||||
ItemRecordType = itemRecordType;
|
||||
}
|
||||
|
||||
public Integer getItemRecordId() {
|
||||
return ItemRecordId;
|
||||
}
|
||||
|
||||
public void setItemRecordId(Integer itemRecordId) {
|
||||
ItemRecordId = itemRecordId;
|
||||
}
|
||||
|
||||
public String getItemRecordDescription() {
|
||||
return ItemRecordDescription;
|
||||
}
|
||||
|
||||
public void setItemRecordDescription(String itemRecordDescription) {
|
||||
ItemRecordDescription = itemRecordDescription;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
@Data
|
||||
public class TodoDetailResult {
|
||||
|
||||
private String StatusCode = null;
|
||||
private String StatusDescription=null;
|
||||
private Integer PlayerId = null;
|
||||
private Date Date = null;
|
||||
private String TierName = null;
|
||||
private String ChineseName = null;
|
||||
private String EnglishName = null;
|
||||
private String Salutation = null;
|
||||
private String Location=null;
|
||||
private String ActivePrgId=null;
|
||||
private Integer PrgTO=null;
|
||||
private Integer PrgWin=null;
|
||||
private Double TORIPercentage=null;
|
||||
private Integer FrontMoney=null;
|
||||
private Integer TTO=null;
|
||||
|
||||
@JsonProperty("01CompBalance")
|
||||
private Integer ComBalance=null;
|
||||
|
||||
private String R3MTO=null;
|
||||
private String R3MTOD=null;
|
||||
private String R3MWin=null;
|
||||
private String R3MTPD=null;
|
||||
private String R3MTheo = null;
|
||||
private String R3MRIPercentage=null;
|
||||
private String R6MTO=null;
|
||||
private String R6MTOD=null;
|
||||
private String R6MWin=null;
|
||||
private String R6MTPD=null;
|
||||
private String R6MTheo = null;
|
||||
private String R6MRIPercentage=null;
|
||||
private Integer ExpComm=null;
|
||||
private Integer NetCreditOutstanding=null;
|
||||
private Integer UnsettledExpenses=null;
|
||||
private Integer TodayTo=null;
|
||||
private Integer TodayTPD=null;
|
||||
private Integer TodayWin=null;
|
||||
private Integer TodayTheo = null;
|
||||
private Integer TripWin=null;
|
||||
private Integer TripTPD=null;
|
||||
private Integer TripTheo = null;
|
||||
private Double TripRIPercentage=null;
|
||||
private Integer YesterdayTO=null;
|
||||
private Integer YesterdayWin=null;
|
||||
private Integer YesterdayPlayHour=null;
|
||||
private Integer AveragePlayHour = null;
|
||||
private List<TodoDetailDescription> Descriptions = new ArrayList<TodoDetailDescription>();
|
||||
public TodoDetailResult() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
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;
|
||||
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;
|
||||
|
||||
public TodoListRecord() {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public String getDate() {
|
||||
return Date;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void setDate(String date) {
|
||||
Date = date;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public String getActionDate() {
|
||||
return ActionDate;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void setActionDate(String actionDate) {
|
||||
ActionDate = actionDate;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public String getOperaConfirmationNo() {
|
||||
return OperaConfirmationNo;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void setOperaConfirmationNo(String operaConfirmationNo) {
|
||||
OperaConfirmationNo = operaConfirmationNo;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public Integer getPlayerId() {
|
||||
return PlayerId;
|
||||
}
|
||||
|
||||
public void setPlayerId(Integer playerId) {
|
||||
PlayerId = playerId;
|
||||
}
|
||||
|
||||
public String getTierName() {
|
||||
return TierName;
|
||||
}
|
||||
|
||||
public void setTierName(String tierName) {
|
||||
TierName = tierName;
|
||||
}
|
||||
|
||||
public String getChineseName() {
|
||||
return ChineseName;
|
||||
}
|
||||
|
||||
public void setChineseName(String chineseName) {
|
||||
ChineseName = chineseName;
|
||||
}
|
||||
|
||||
public String getEnglishName() {
|
||||
return EnglishName;
|
||||
}
|
||||
|
||||
public void setEnglishName(String englishName) {
|
||||
EnglishName = englishName;
|
||||
}
|
||||
|
||||
public String getSalutation() {
|
||||
return Salutation;
|
||||
}
|
||||
|
||||
public void setSalutation(String salutation) {
|
||||
Salutation = salutation;
|
||||
}
|
||||
|
||||
public Integer getHasArrivalRecord() {
|
||||
return HasArrivalRecord;
|
||||
}
|
||||
|
||||
public void setHasArrivalRecord(Integer hasArrivalRecord) {
|
||||
HasArrivalRecord = hasArrivalRecord;
|
||||
}
|
||||
|
||||
public Integer getHasDepartureRecord() {
|
||||
return HasDepartureRecord;
|
||||
}
|
||||
|
||||
public void setHasDepartureRecord(Integer hasDepartureRecord) {
|
||||
HasDepartureRecord = hasDepartureRecord;
|
||||
}
|
||||
|
||||
public Integer getHasInhouseRecord() {
|
||||
return HasInhouseRecord;
|
||||
}
|
||||
|
||||
public void setHasInhouseRecord(Integer hasInhouseRecord) {
|
||||
HasInhouseRecord = hasInhouseRecord;
|
||||
}
|
||||
|
||||
public Integer getHasOthersRecord() {
|
||||
return HasOthersRecord;
|
||||
}
|
||||
|
||||
public void setHasOthersRecord(Integer hasOthersRecord) {
|
||||
HasOthersRecord = hasOthersRecord;
|
||||
}
|
||||
|
||||
public Integer getHasLimoRecord() {
|
||||
return HasLimoRecord;
|
||||
}
|
||||
|
||||
public void setHasLimoRecord(Integer hasLimoRecord) {
|
||||
HasLimoRecord = hasLimoRecord;
|
||||
}
|
||||
|
||||
public Integer getHasFlightRecord() {
|
||||
return HasFlightRecord;
|
||||
}
|
||||
|
||||
public void setHasFlightRecord(Integer hasFlightRecord) {
|
||||
HasFlightRecord = hasFlightRecord;
|
||||
}
|
||||
|
||||
public String getETA() {
|
||||
return ETA;
|
||||
}
|
||||
|
||||
public void setETA(String eTA) {
|
||||
ETA = eTA;
|
||||
}
|
||||
|
||||
public Boolean getRoomReady() {
|
||||
return roomReady;
|
||||
}
|
||||
|
||||
public void setRoomReady(Boolean roomReady) {
|
||||
this.roomReady = roomReady;
|
||||
}
|
||||
|
||||
public Boolean getIsQueue() {
|
||||
return isQueue;
|
||||
}
|
||||
|
||||
public void setIsQueue(Boolean isQueue) {
|
||||
this.isQueue = isQueue;
|
||||
}
|
||||
|
||||
public Integer getBigWinFlag() {
|
||||
return BigWinFlag;
|
||||
}
|
||||
|
||||
public void setBigWinFlag(Integer bigWinFlag) {
|
||||
BigWinFlag = bigWinFlag;
|
||||
}
|
||||
|
||||
public Integer getBigLossFlag() {
|
||||
return BigLossFlag;
|
||||
}
|
||||
|
||||
public void setBigLossFlag(Integer bigLossFlag) {
|
||||
BigLossFlag = bigLossFlag;
|
||||
}
|
||||
|
||||
public Integer getNoPlayFlag() {
|
||||
return NoPlayFlag;
|
||||
}
|
||||
|
||||
public void setNoPlayFlag(Integer noPlayFlag) {
|
||||
NoPlayFlag = noPlayFlag;
|
||||
}
|
||||
|
||||
public Integer getMAId() {
|
||||
return MAId;
|
||||
}
|
||||
|
||||
public void setMAId(Integer mAId) {
|
||||
MAId = mAId;
|
||||
}
|
||||
|
||||
public String getMA() {
|
||||
return MA;
|
||||
}
|
||||
|
||||
public void setMA(String mA) {
|
||||
MA = mA;
|
||||
}
|
||||
|
||||
public List<String> getDescriptions() {
|
||||
return Descriptions;
|
||||
}
|
||||
|
||||
public void setDescriptions(List<String> descriptions) {
|
||||
Descriptions = descriptions;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class TodoListResult {
|
||||
|
||||
|
||||
private String statusCode = null;
|
||||
private String statusDescription=null;
|
||||
private List<TodoListRecord> Records = new ArrayList<TodoListRecord>();
|
||||
|
||||
public TodoListResult() {
|
||||
|
||||
}
|
||||
|
||||
public String getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
public void setStatusCode(String statusCode) {
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
|
||||
public String getStatusDescription() {
|
||||
return statusDescription;
|
||||
}
|
||||
|
||||
public void setStatusDescription(String statusDescription) {
|
||||
this.statusDescription = statusDescription;
|
||||
}
|
||||
|
||||
public List<TodoListRecord> getRecords() {
|
||||
return Records;
|
||||
}
|
||||
|
||||
public void setRecords(List<TodoListRecord> records) {
|
||||
Records = records;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UserInfoApiRecord {
|
||||
|
||||
private String statusCode = null;
|
||||
private String statusDescription="";
|
||||
private String userId;
|
||||
private String userName;
|
||||
private String property;
|
||||
private String division;
|
||||
private String department;
|
||||
private String section;
|
||||
private String block;
|
||||
private Long propertyId;
|
||||
private Long divisionId;
|
||||
private Long departmentId;
|
||||
private Long sectionId;
|
||||
private Long blockId;
|
||||
private Long teamStructureId;
|
||||
private boolean canViewBooking=false;
|
||||
private boolean canNewBooking=false;
|
||||
private boolean canViewTodoList=false;
|
||||
private boolean canViewDashboard=false;
|
||||
private boolean canViewApproval=false;
|
||||
private String groupName;
|
||||
private String phone;
|
||||
private boolean loginTag;
|
||||
|
||||
public UserInfoApiRecord() {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class UserInfoApiResult {
|
||||
|
||||
private String statusCode;
|
||||
private String statusDescription;
|
||||
private List<UserInfoApiRecord> records;
|
||||
public String getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
public void setStatusCode(String statusCode) {
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
public String getStatusDescription() {
|
||||
return statusDescription;
|
||||
}
|
||||
public void setStatusDescription(String statusDescription) {
|
||||
this.statusDescription = statusDescription;
|
||||
}
|
||||
public List<UserInfoApiRecord> getRecords() {
|
||||
return records;
|
||||
}
|
||||
public void setRecords(List<UserInfoApiRecord> records) {
|
||||
this.records = records;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class WaitlistBookingApiResult {
|
||||
|
||||
private String statusCode;
|
||||
private String statusDescription;
|
||||
private List<WaitlistBookingRecord> records;
|
||||
public String getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
public void setStatusCode(String statusCode) {
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
public String getStatusDescription() {
|
||||
return statusDescription;
|
||||
}
|
||||
public void setStatusDescription(String statusDescription) {
|
||||
this.statusDescription = statusDescription;
|
||||
}
|
||||
public List<WaitlistBookingRecord> getRecords() {
|
||||
return records;
|
||||
}
|
||||
public void setRecords(List<WaitlistBookingRecord> records) {
|
||||
this.records = records;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
public class WaitlistBookingRecord {
|
||||
|
||||
private String playerId;
|
||||
private String bookingId;
|
||||
private String bookingStatus;
|
||||
|
||||
public String getPlayerId() {
|
||||
return playerId;
|
||||
}
|
||||
public void setPlayerId(String playerId) {
|
||||
this.playerId = playerId;
|
||||
}
|
||||
public String getBookingId() {
|
||||
return bookingId;
|
||||
}
|
||||
public void setBookingId(String bookingId) {
|
||||
this.bookingId = bookingId;
|
||||
}
|
||||
public String getBookingStatus() {
|
||||
return bookingStatus;
|
||||
}
|
||||
public void setBookingStatus(String bookingStatus) {
|
||||
this.bookingStatus = bookingStatus;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class WaitlistDataApiResult {
|
||||
|
||||
private String statusCode;
|
||||
private String statusDescription;
|
||||
private List<WaitlistDataRecord> records;
|
||||
public String getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
public void setStatusCode(String statusCode) {
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
public String getStatusDescription() {
|
||||
return statusDescription;
|
||||
}
|
||||
public void setStatusDescription(String statusDescription) {
|
||||
this.statusDescription = statusDescription;
|
||||
}
|
||||
public List<WaitlistDataRecord> getRecords() {
|
||||
return records;
|
||||
}
|
||||
public void setRecords(List<WaitlistDataRecord> records) {
|
||||
this.records = records;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.mgm.mcrm.common.dtos.mgm_api;
|
||||
|
||||
public class WaitlistDataRecord {
|
||||
|
||||
private String bookingId;
|
||||
private String playerId;
|
||||
private String overlapBooking;
|
||||
private String mABooking;
|
||||
private String r3TheoWin;
|
||||
private String r3TPD;
|
||||
private String r3ActualWin;
|
||||
private String r6TheoWin;
|
||||
private String r6TPD;
|
||||
private String r6ActualWin;
|
||||
private String r12TheoWin;
|
||||
private String r12TPD;
|
||||
private String r12ActualWin;
|
||||
private String finalSegment;
|
||||
private String tripTheoProfit;
|
||||
private String dailyTheoProfit;
|
||||
private String playerType;
|
||||
private String rankingByPlayer;
|
||||
private String bookerTeam;
|
||||
private String currentTripTheoWinAmount;
|
||||
private String last2DayTheoWinAmount;
|
||||
public String getBookingId() {
|
||||
return bookingId;
|
||||
}
|
||||
public void setBookingId(String bookingId) {
|
||||
this.bookingId = bookingId;
|
||||
}
|
||||
public String getPlayerId() {
|
||||
return playerId;
|
||||
}
|
||||
public void setPlayerId(String playerId) {
|
||||
this.playerId = playerId;
|
||||
}
|
||||
public String getOverlapBooking() {
|
||||
return overlapBooking;
|
||||
}
|
||||
public void setOverlapBooking(String overlapBooking) {
|
||||
this.overlapBooking = overlapBooking;
|
||||
}
|
||||
public String getmABooking() {
|
||||
return mABooking;
|
||||
}
|
||||
public void setmABooking(String mABooking) {
|
||||
this.mABooking = mABooking;
|
||||
}
|
||||
public String getR3TheoWin() {
|
||||
return r3TheoWin;
|
||||
}
|
||||
public void setR3TheoWin(String r3TheoWin) {
|
||||
this.r3TheoWin = r3TheoWin;
|
||||
}
|
||||
public String getR3TPD() {
|
||||
return r3TPD;
|
||||
}
|
||||
public void setR3TPD(String r3tpd) {
|
||||
r3TPD = r3tpd;
|
||||
}
|
||||
public String getR3ActualWin() {
|
||||
return r3ActualWin;
|
||||
}
|
||||
public void setR3ActualWin(String r3ActualWin) {
|
||||
this.r3ActualWin = r3ActualWin;
|
||||
}
|
||||
public String getR6TheoWin() {
|
||||
return r6TheoWin;
|
||||
}
|
||||
public void setR6TheoWin(String r6TheoWin) {
|
||||
this.r6TheoWin = r6TheoWin;
|
||||
}
|
||||
public String getR6TPD() {
|
||||
return r6TPD;
|
||||
}
|
||||
public void setR6TPD(String r6tpd) {
|
||||
r6TPD = r6tpd;
|
||||
}
|
||||
public String getR6ActualWin() {
|
||||
return r6ActualWin;
|
||||
}
|
||||
public void setR6ActualWin(String r6ActualWin) {
|
||||
this.r6ActualWin = r6ActualWin;
|
||||
}
|
||||
public String getR12TheoWin() {
|
||||
return r12TheoWin;
|
||||
}
|
||||
public void setR12TheoWin(String r12TheoWin) {
|
||||
this.r12TheoWin = r12TheoWin;
|
||||
}
|
||||
public String getR12TPD() {
|
||||
return r12TPD;
|
||||
}
|
||||
public void setR12TPD(String r12tpd) {
|
||||
r12TPD = r12tpd;
|
||||
}
|
||||
public String getR12ActualWin() {
|
||||
return r12ActualWin;
|
||||
}
|
||||
public void setR12ActualWin(String r12ActualWin) {
|
||||
this.r12ActualWin = r12ActualWin;
|
||||
}
|
||||
public String getFinalSegment() {
|
||||
return finalSegment;
|
||||
}
|
||||
public void setFinalSegment(String finalSegment) {
|
||||
this.finalSegment = finalSegment;
|
||||
}
|
||||
public String getTripTheoProfit() {
|
||||
return tripTheoProfit;
|
||||
}
|
||||
public void setTripTheoProfit(String tripTheoProfit) {
|
||||
this.tripTheoProfit = tripTheoProfit;
|
||||
}
|
||||
public String getDailyTheoProfit() {
|
||||
return dailyTheoProfit;
|
||||
}
|
||||
public void setDailyTheoProfit(String dailyTheoProfit) {
|
||||
this.dailyTheoProfit = dailyTheoProfit;
|
||||
}
|
||||
public String getPlayerType() {
|
||||
return playerType;
|
||||
}
|
||||
public void setPlayerType(String playerType) {
|
||||
this.playerType = playerType;
|
||||
}
|
||||
public String getRankingByPlayer() {
|
||||
return rankingByPlayer;
|
||||
}
|
||||
public void setRankingByPlayer(String rankingByPlayer) {
|
||||
this.rankingByPlayer = rankingByPlayer;
|
||||
}
|
||||
public String getBookerTeam() {
|
||||
return bookerTeam;
|
||||
}
|
||||
public void setBookerTeam(String bookerTeam) {
|
||||
this.bookerTeam = bookerTeam;
|
||||
}
|
||||
public String getCurrentTripTheoWinAmount() {
|
||||
return currentTripTheoWinAmount;
|
||||
}
|
||||
public void setCurrentTripTheoWinAmount(String currentTripTheoWinAmount) {
|
||||
this.currentTripTheoWinAmount = currentTripTheoWinAmount;
|
||||
}
|
||||
public String getLast2DayTheoWinAmount() {
|
||||
return last2DayTheoWinAmount;
|
||||
}
|
||||
public void setLast2DayTheoWinAmount(String last2DayTheoWinAmount) {
|
||||
this.last2DayTheoWinAmount = last2DayTheoWinAmount;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.mgm.mcrm.common.dtos.msg;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class AppSettingMsgData {
|
||||
private String serverType;
|
||||
private List<UpdateCfgItem> configItems;
|
||||
public String getServerType() {
|
||||
return serverType;
|
||||
}
|
||||
public void setServerType(String serverType) {
|
||||
this.serverType = serverType;
|
||||
}
|
||||
public List<UpdateCfgItem> getConfigItems() {
|
||||
return configItems;
|
||||
}
|
||||
public void setConfigItems(List<UpdateCfgItem> configItems) {
|
||||
this.configItems = configItems;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.mgm.mcrm.common.dtos.msg;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class JMSTextMessage {
|
||||
private String msgType;
|
||||
private Date sendTime = new Date();
|
||||
private String msgContent;
|
||||
public String getMsgType() {
|
||||
return msgType;
|
||||
}
|
||||
public void setMsgType(String msgType) {
|
||||
this.msgType = msgType;
|
||||
}
|
||||
public Date getSendTime() {
|
||||
return sendTime;
|
||||
}
|
||||
public void setSendTime(Date sendTime) {
|
||||
this.sendTime = sendTime;
|
||||
}
|
||||
public String getMsgContent() {
|
||||
return msgContent;
|
||||
}
|
||||
public void setMsgContent(String msgContent) {
|
||||
this.msgContent = msgContent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.mgm.mcrm.common.dtos.msg;
|
||||
|
||||
public class UpdateCfgItem {
|
||||
private String cfgItemKey;
|
||||
private String cfgItemValue;
|
||||
public String getCfgItemKey() {
|
||||
return cfgItemKey;
|
||||
}
|
||||
public void setCfgItemKey(String cfgItemKey) {
|
||||
this.cfgItemKey = cfgItemKey;
|
||||
}
|
||||
public String getCfgItemValue() {
|
||||
return cfgItemValue;
|
||||
}
|
||||
public void setCfgItemValue(String cfgItemValue) {
|
||||
this.cfgItemValue = cfgItemValue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.mgm.mcrm.common.dtos.system;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class AppServerState {
|
||||
|
||||
private String serverIp="";
|
||||
private String hostName="";
|
||||
private String serverType="";
|
||||
private boolean dbDebugLog=false;
|
||||
private boolean apiDebugLog=false;
|
||||
private boolean appDebugLog=false;
|
||||
private Date lastUpdateTime=new Date();
|
||||
public String getServerIp() {
|
||||
return serverIp;
|
||||
}
|
||||
public void setServerIp(String serverIp) {
|
||||
this.serverIp = serverIp;
|
||||
}
|
||||
public String getHostName() {
|
||||
return hostName;
|
||||
}
|
||||
public void setHostName(String hostName) {
|
||||
this.hostName = hostName;
|
||||
}
|
||||
public boolean isDbDebugLog() {
|
||||
return dbDebugLog;
|
||||
}
|
||||
public void setDbDebugLog(boolean dbDebugLog) {
|
||||
this.dbDebugLog = dbDebugLog;
|
||||
}
|
||||
public boolean isApiDebugLog() {
|
||||
return apiDebugLog;
|
||||
}
|
||||
public void setApiDebugLog(boolean apiDebugLog) {
|
||||
this.apiDebugLog = apiDebugLog;
|
||||
}
|
||||
public boolean isAppDebugLog() {
|
||||
return appDebugLog;
|
||||
}
|
||||
public void setAppDebugLog(boolean appDebugLog) {
|
||||
this.appDebugLog = appDebugLog;
|
||||
}
|
||||
public Date getLastUpdateTime() {
|
||||
return lastUpdateTime;
|
||||
}
|
||||
public void setLastUpdateTime(Date lastUpdateTime) {
|
||||
this.lastUpdateTime = lastUpdateTime;
|
||||
}
|
||||
public String getServerType() {
|
||||
return serverType;
|
||||
}
|
||||
public void setServerType(String serverType) {
|
||||
this.serverType = serverType;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.mgm.mcrm.common.dtos.system;
|
||||
|
||||
public class ResFileResult {
|
||||
private boolean success=false;
|
||||
private String fileName;
|
||||
private String filePath;
|
||||
private String errorMessage;
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
public void setSuccess(boolean success) {
|
||||
this.success = success;
|
||||
}
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
public void setFileName(String fileName) {
|
||||
this.fileName = fileName;
|
||||
}
|
||||
public String getFilePath() {
|
||||
return filePath;
|
||||
}
|
||||
public void setFilePath(String filePath) {
|
||||
this.filePath = filePath;
|
||||
}
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
public void setMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.mgm.mcrm.common.dtos.system;
|
||||
|
||||
import com.mgm.mcrm.authorization.models.SysRouter;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.sql.Date;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class RouterPages implements Serializable {
|
||||
|
||||
private List<SysRouter> pages;
|
||||
|
||||
public List<SysRouter> getPages() {
|
||||
return pages;
|
||||
}
|
||||
|
||||
public void setPages(List<SysRouter> pages) {
|
||||
this.pages = pages;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.mgm.mcrm.common.enums;
|
||||
|
||||
public enum DeliveryReceiptState {
|
||||
|
||||
ESME_ROK(0, "Ok - Message Acceptable"),
|
||||
|
||||
ESME_RINVMSGLEN(1, "Invalid Message Length"),
|
||||
|
||||
ESME_RINVCMDLEN(2, "Invalid Command Length"),
|
||||
|
||||
ESME_RINVCMDID(3, "Invalid Command ID"),
|
||||
|
||||
ESME_RINVBNDSTS(4, "Invalid bind status"),
|
||||
|
||||
ESME_RALYBND(5, "Bind attempted when already bound"),
|
||||
|
||||
ESME_RINVPRTFLG(6, "Invalid priority flag"),
|
||||
|
||||
ESME_RINVREGDLVFLG(7, "Invalid registered-delivery flag"),
|
||||
|
||||
ESME_RSYSERR(8, "SMSC system error"),
|
||||
|
||||
ESME_RINVSRCADR(9, "Invalid source address"),
|
||||
|
||||
ESME_RINVDSTADR(11, "Invalid destination address"),
|
||||
|
||||
ESME_RINVMSGID(12, "Invalid message-id"),
|
||||
|
||||
NOT_FOUND(000, "Couldn't resolve.Ask admin to add.");
|
||||
|
||||
private int value;
|
||||
private String description;
|
||||
|
||||
DeliveryReceiptState(int value, String description) {
|
||||
this.value = value;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public static DeliveryReceiptState getDescription(int value) {
|
||||
for (DeliveryReceiptState item : values()) {
|
||||
if (item.value() == value) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
return NOT_FOUND;
|
||||
}
|
||||
|
||||
public int value() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public String description() {
|
||||
return description;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.mgm.mcrm.common.enums;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
public enum EnumBookingStatus {
|
||||
|
||||
DUE_IN("DUE IN", "DUE_IN"),
|
||||
DUE_IN_UNDERSCORE("DUE_IN", "DUE_IN"),
|
||||
DUEIN("DUEIN", "DUE_IN"),
|
||||
RESERVED("RESERVED", "RESERVED"),
|
||||
RESERVE("Reserved", "RESERVED"),
|
||||
CHECKEDIN("Checked in", "CHECKED_IN"),
|
||||
CHECKED_IN("CHECKED IN", "CHECKED_IN"),
|
||||
CHECKED_IN_UNDERSCORE("CHECKED_IN", "CHECKED_IN"),
|
||||
CHECK_IN("CHECK_IN", "CHECKED_IN"),
|
||||
CHECK_IN_IN_HOUSE("CHECK_IN(IN_HOUSE)", "CHECKED_IN"),
|
||||
CHECKED_OUT("CHECKED OUT", "CHECKED_OUT"),
|
||||
CHECKED_OUT_UNDERSCORE("CHECKED_OUT", "CHECKED_OUT"),
|
||||
INHOUSE("INHOUSE", "CHECKED_IN"),
|
||||
IN_HOUSE("IN-HOUSE", "CHECKED_IN"),
|
||||
IN_HOUSE_UNDERSCORE("IN_HOUSE", "CHECKED_IN"),
|
||||
IN("IN", "CHECKED_IN"),
|
||||
IH("IH", "CHECKED_IN"),
|
||||
DUE_OUT("DUE OUT", "DUE_OUT"),
|
||||
DUE_OUT_UNDERSCORE("DUE_OUT", "DUE_OUT"),
|
||||
DUEOUT("DUEOUT", "DUE_OUT"),
|
||||
CANCELED("CANCELED", "CANCELED"),
|
||||
CANCELLED("CANCELLED", "CANCELED");
|
||||
|
||||
@Getter
|
||||
private final String key;
|
||||
@Getter
|
||||
private final String value;
|
||||
|
||||
EnumBookingStatus(String key, String value) {
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public static String getStatusByDaylightStatus(String key) {
|
||||
if (key == null) {
|
||||
return "UNKNOWN";
|
||||
}
|
||||
String normalizedKey = key.trim();
|
||||
EnumBookingStatus[] objs = values();
|
||||
for (EnumBookingStatus obj : objs) {
|
||||
if (obj.getKey().equalsIgnoreCase(normalizedKey)) {
|
||||
return obj.getValue();
|
||||
}
|
||||
}
|
||||
String compactKey = normalizeStatusKey(normalizedKey);
|
||||
for (EnumBookingStatus obj : objs) {
|
||||
String compactObjKey = normalizeStatusKey(obj.getKey());
|
||||
if (compactObjKey.equalsIgnoreCase(compactKey)) {
|
||||
return obj.getValue();
|
||||
}
|
||||
}
|
||||
if (compactKey.contains("CHECKIN") || compactKey.contains("INHOUSE")) {
|
||||
return "CHECKED_IN";
|
||||
}
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
private static String normalizeStatusKey(String key) {
|
||||
return key == null ? "" : key.replaceAll("[^A-Za-z0-9]", "");
|
||||
}
|
||||
|
||||
public static boolean isInclude(String value) {
|
||||
boolean include = false;
|
||||
for (EnumBookingStatus e : EnumBookingStatus.values()) {
|
||||
if (e.getValue().equals(value)) {
|
||||
include = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return include;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.mgm.mcrm.common.enums;
|
||||
|
||||
|
||||
/**
|
||||
* 枚举HttpMethods方法
|
||||
*
|
||||
* @author Anka
|
||||
*/
|
||||
public enum HttpMethods {
|
||||
|
||||
/**
|
||||
* 求获取Request-URI所标识的资源
|
||||
*/
|
||||
GET(0, "GET"),
|
||||
|
||||
/**
|
||||
* 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。
|
||||
* POST请求可能会导致新的资源的建立和/或已有资源的修改
|
||||
*/
|
||||
POST(1, "POST"),
|
||||
|
||||
/**
|
||||
* 向服务器索要与GET请求相一致的响应,只不过响应体将不会被返回。
|
||||
* 这一方法可以在不必传输整个响应内容的情况下,就可以获取包含在响应消息头中的元信息
|
||||
* 只获取响应信息报头
|
||||
*/
|
||||
HEAD(2, "HEAD"),
|
||||
|
||||
/**
|
||||
* 向指定资源位置上传其最新内容(全部更新,操作幂等)
|
||||
*/
|
||||
PUT (3, "PUT"),
|
||||
|
||||
/**
|
||||
* 请求服务器删除Request-URI所标识的资源
|
||||
*/
|
||||
DELETE (4, "DELETE"),
|
||||
|
||||
/**
|
||||
* 请求服务器回送收到的请求信息,主要用于测试或诊断
|
||||
*/
|
||||
TRACE(5, "TRACE"),
|
||||
|
||||
/**
|
||||
* 向指定资源位置上传其最新内容(部分更新,非幂等)
|
||||
*/
|
||||
PATCH (6, "PATCH"),
|
||||
|
||||
/**
|
||||
* 返回服务器针对特定资源所支持的HTTP请求方法。
|
||||
* 也可以利用向Web服务器发送'*'的请求来测试服务器的功能性
|
||||
*/
|
||||
OPTIONS (7, "OPTIONS"),
|
||||
|
||||
// /**
|
||||
// * HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器
|
||||
// */
|
||||
// CONNECT(99, "CONNECT"),
|
||||
;
|
||||
|
||||
private int code;
|
||||
private String name;
|
||||
|
||||
private HttpMethods(int code, String name){
|
||||
this.code = code;
|
||||
this.name = name;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.mgm.mcrm.common.filters;
|
||||
|
||||
import com.mgm.mcrm.common.constants.SysCommon;
|
||||
import com.mgm.mcrm.common.utils.LogUtil;
|
||||
import com.mgm.mcrm.common.utils.NetworkUtil;
|
||||
import jakarta.servlet.*;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Slf4j
|
||||
public class ConfigHeaderFilter implements Filter {
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
|
||||
HttpServletRequest req = (HttpServletRequest) request;
|
||||
|
||||
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);
|
||||
} 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"));
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
|
||||
httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,ClientId,Refreshtoken");
|
||||
httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
|
||||
httpServletResponse.addHeader("Access-Control-Max-Age", "3600");
|
||||
httpServletResponse.addHeader("Access-Control-Expose-Headers", "MacauIP, IsInternal");
|
||||
|
||||
if (request.isSecure()) {
|
||||
httpServletResponse.setHeader("Strict-Transport-Security",
|
||||
"max-age=86400; includeSubDomains; preload");
|
||||
}
|
||||
httpServletResponse.setHeader("X-Frame-Options", "SAMEORIGIN");
|
||||
httpServletResponse.setHeader("X-Content-Type-Options", "nosniff");
|
||||
httpServletResponse.setHeader("Content-Security-Policy",
|
||||
"default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; " +
|
||||
"style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; " +
|
||||
"connect-src 'self'; media-src 'self'; object-src 'none'; frame-src 'self'");
|
||||
httpServletResponse.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
|
||||
httpServletResponse.setHeader("X-XSS-Protection", "1; mode=block");
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
package com.mgm.mcrm.common.httpclient;
|
||||
|
||||
import com.mgm.mcrm.common.dtos.HttpResult;
|
||||
import com.mgm.mcrm.common.enums.HttpMethods;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPatch;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.apache.hc.core5.http.NameValuePair;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* HTTP 客户端工具类(基于 Apache HttpClient 5)
|
||||
*
|
||||
* 提供便捷的 HTTP 请求方法,支持:
|
||||
* - GET、POST、PUT、DELETE 请求
|
||||
* - 自定义请求头和参数
|
||||
* - Cookie 管理
|
||||
* - 详细响应信息获取
|
||||
*
|
||||
* 使用示例:
|
||||
* <pre>
|
||||
* // 配置请求
|
||||
* HttpConfig config = HttpConfig.custom()
|
||||
* .url("https://api.example.com/data")
|
||||
* .timeout(requestConfig)
|
||||
* .map(params)
|
||||
* .encoding("utf-8")
|
||||
* .client(httpClient);
|
||||
*
|
||||
* // 配置请求头
|
||||
* Header[] headers = HttpHeaderUtil.custom()
|
||||
* .userAgent("MyApp")
|
||||
* .build();
|
||||
*
|
||||
* // 执行 GET 请求
|
||||
* String result = HttpClientUtil.get(config, headers);
|
||||
*
|
||||
* // 执行 POST 请求
|
||||
* String result = HttpClientUtil.post(config, headers);
|
||||
*
|
||||
* // 获取详细响应信息
|
||||
* HttpResult httpResult = HttpClientUtil.sendAndGetResp(config, headers);
|
||||
* </pre>
|
||||
*
|
||||
* @author Aaka
|
||||
*/
|
||||
public class HttpClientExecutor {
|
||||
|
||||
private HttpClientExecutor() {
|
||||
// 工具类,禁止实例化
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 GET 请求
|
||||
*
|
||||
* @param config HTTP 请求配置
|
||||
* @param headers 请求头数组(可选,可为 null)
|
||||
* @return 响应体字符串
|
||||
* @throws Exception 请求执行异常
|
||||
*/
|
||||
public static String get(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
return executeGet(config, headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 POST 请求
|
||||
*
|
||||
* @param config HTTP 请求配置
|
||||
* @param headers 请求头数组(可选,可为 null)
|
||||
* @return 响应体字符串
|
||||
* @throws Exception 请求执行异常
|
||||
*/
|
||||
public static String post(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
return executePost(config, headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行通用请求(根据 HttpConfig 中的 method 自动选择)
|
||||
*
|
||||
* @param config HTTP 请求配置
|
||||
* @param headers 请求头数组(可选,可为 null)
|
||||
* @return 响应体字符串
|
||||
* @throws Exception 请求执行异常
|
||||
*/
|
||||
public static String send(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
return execute(config, headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行请求并返回详细响应信息
|
||||
*
|
||||
* @param config HTTP 请求配置
|
||||
* @param headers 请求头数组(可选,可为 null)
|
||||
* @return HttpResult 包含完整的响应信息(状态码、响应头、响应体等)
|
||||
* @throws Exception 请求执行异常
|
||||
*/
|
||||
public static HttpResult sendAndGetResp(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
return executeAndGetResp(config, headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行请求并返回详细响应信息
|
||||
*
|
||||
* @param config HTTP 请求配置
|
||||
* @param headers 请求头数组(可选,可为 null)
|
||||
* @return HttpResult 包含完整的响应信息(状态码、响应头、响应体等)
|
||||
* @throws Exception 请求执行异常
|
||||
*/
|
||||
public static HttpResult sendAndPostResp(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
return executePostRes(config, headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 PATCH 请求并返回详细响应信息
|
||||
*
|
||||
* @param config HTTP 请求配置
|
||||
* @param headers 请求头数组(可选,可为 null)
|
||||
* @return HttpResult 包含完整的响应信息(状态码、响应头、响应体等)
|
||||
* @throws Exception 请求执行异常
|
||||
*/
|
||||
public static HttpResult sendAndPatchResp(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
return executePatchRes(config, headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 GET 请求(内部方法)
|
||||
*/
|
||||
private static String executeGet(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
String url = config.url();
|
||||
List<NameValuePair> nvps = new ArrayList<>();
|
||||
// 1. 先解析 URL 中原本就带的查询参数(如果有)
|
||||
// 2. 再把 HttpConfig.map() 里的参数也加入到 nvps 中
|
||||
// 对于 GET 请求,这些参数应该拼到 URL 上,而不是放到 body 里
|
||||
Map<String, Object> map = config.map();
|
||||
if (map != null && !map.isEmpty()) {
|
||||
url = HttpEntityBuilder.checkHasParas(url, nvps, config.inenc());
|
||||
// 这里主要是为了复用参数编码逻辑,返回的 entity 我们不用
|
||||
HttpEntityBuilder.map2HttpEntity(nvps, map, config.inenc());
|
||||
}
|
||||
|
||||
// 3. 如果 nvps 中有参数,手动构建查询字符串
|
||||
// 注意:某些服务器(如接口测试工具)可能期望参数值中的特殊字符(如 == 和 ;)不被编码
|
||||
// 因此我们只对参数名进行编码,参数值保持原样或只编码必要的字符
|
||||
if (!nvps.isEmpty()) {
|
||||
StringBuilder queryBuilder = new StringBuilder();
|
||||
for (int i = 0; i < nvps.size(); i++) {
|
||||
NameValuePair nvp = nvps.get(i);
|
||||
if (i > 0) {
|
||||
queryBuilder.append("&");
|
||||
}
|
||||
try {
|
||||
// 只对参数名进行编码
|
||||
String encodedName = encodeQueryParam(nvp.getName(), config.inenc());
|
||||
// 参数值保持原样,不进行编码(与接口测试工具行为一致)
|
||||
// 如果参数值中包含需要编码的字符(如中文、空格等),可以在这里添加编码逻辑
|
||||
String paramValue = nvp.getValue();
|
||||
queryBuilder.append(encodedName).append("=").append(paramValue);
|
||||
} catch (Exception ex) {
|
||||
// 如果编码失败,使用原始值
|
||||
queryBuilder.append(nvp.getName()).append("=").append(nvp.getValue());
|
||||
}
|
||||
}
|
||||
String query = queryBuilder.toString();
|
||||
if (url.contains("?")) {
|
||||
url = url + "&" + query;
|
||||
} else {
|
||||
url = url + "?" + query;
|
||||
}
|
||||
}
|
||||
// System.out.println(url);
|
||||
HttpGet httpGet = new HttpGet(url);
|
||||
setHeaders(httpGet, headers);
|
||||
setRequestConfig(httpGet, config);
|
||||
|
||||
// 如果配置了 context,使用 context 执行请求以支持 Cookie
|
||||
// 注意:execute 方法在 HttpClient 5 中被标记为 deprecated,但这是目前推荐的方式
|
||||
CloseableHttpResponse response;
|
||||
if (config.context() != null) {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(httpGet, config.context());
|
||||
response = tempResponse;
|
||||
} else {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(httpGet);
|
||||
response = tempResponse;
|
||||
}
|
||||
try (response) {
|
||||
return extractResponseBody(response, config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 POST 请求(内部方法)
|
||||
*/
|
||||
private static String executePost(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
String url = config.url();
|
||||
List<NameValuePair> nvps = new ArrayList<>();
|
||||
url = HttpEntityBuilder.checkHasParas(url, nvps, config.inenc());
|
||||
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
setHeaders(httpPost, headers);
|
||||
setRequestConfig(httpPost, config);
|
||||
|
||||
// 设置请求体
|
||||
Map<String, Object> map = config.map();
|
||||
if (map != null && !map.isEmpty()) {
|
||||
HttpEntity entity = HttpEntityBuilder.map2HttpEntity(nvps, map, config.inenc());
|
||||
httpPost.setEntity(entity);
|
||||
}
|
||||
|
||||
// 如果配置了 context,使用 context 执行请求以支持 Cookie
|
||||
// 注意:execute 方法在 HttpClient 5 中被标记为 deprecated,但这是目前推荐的方式
|
||||
CloseableHttpResponse response;
|
||||
if (config.context() != null) {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(httpPost, config.context());
|
||||
response = tempResponse;
|
||||
} else {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(httpPost);
|
||||
response = tempResponse;
|
||||
}
|
||||
try (response) {
|
||||
return extractResponseBody(response, config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 POST 请求(内部方法)
|
||||
*/
|
||||
private static HttpResult executePostRes(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
String url = config.url();
|
||||
List<NameValuePair> nvps = new ArrayList<>();
|
||||
url = HttpEntityBuilder.checkHasParas(url, nvps, config.inenc());
|
||||
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
setHeaders(httpPost, headers);
|
||||
setRequestConfig(httpPost, config);
|
||||
|
||||
// 设置请求体
|
||||
Map<String, Object> map = config.map();
|
||||
if (map != null && !map.isEmpty()) {
|
||||
HttpEntity entity = HttpEntityBuilder.map2HttpEntity(nvps, map, config.inenc());
|
||||
httpPost.setEntity(entity);
|
||||
}
|
||||
|
||||
// 如果配置了 context,使用 context 执行请求以支持 Cookie
|
||||
// 注意:execute 方法在 HttpClient 5 中被标记为 deprecated,但这是目前推荐的方式
|
||||
CloseableHttpResponse response;
|
||||
if (config.context() != null) {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(httpPost, config.context());
|
||||
response = tempResponse;
|
||||
} else {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(httpPost);
|
||||
response = tempResponse;
|
||||
}
|
||||
try (response) {
|
||||
return buildHttpResult(response, config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 PATCH 请求(内部方法)
|
||||
*/
|
||||
private static HttpResult executePatchRes(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
String url = config.url();
|
||||
List<NameValuePair> nvps = new ArrayList<>();
|
||||
url = HttpEntityBuilder.checkHasParas(url, nvps, config.inenc());
|
||||
|
||||
HttpPatch httpPatch = new HttpPatch(url);
|
||||
setHeaders(httpPatch, headers);
|
||||
setRequestConfig(httpPatch, config);
|
||||
|
||||
// 设置请求体
|
||||
Map<String, Object> map = config.map();
|
||||
if (map != null && !map.isEmpty()) {
|
||||
HttpEntity entity = HttpEntityBuilder.map2HttpEntity(nvps, map, config.inenc());
|
||||
httpPatch.setEntity(entity);
|
||||
}
|
||||
|
||||
// 如果配置了 context,使用 context 执行请求以支持 Cookie
|
||||
// 注意:execute 方法在 HttpClient 5 中被标记为 deprecated,但这是目前推荐的方式
|
||||
CloseableHttpResponse response;
|
||||
if (config.context() != null) {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(httpPatch, config.context());
|
||||
response = tempResponse;
|
||||
} else {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(httpPatch);
|
||||
response = tempResponse;
|
||||
}
|
||||
try (response) {
|
||||
return buildHttpResult(response, config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行通用请求(根据 HttpMethods 自动选择)(内部方法)
|
||||
*/
|
||||
private static String execute(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
HttpMethods method = config.method();
|
||||
String url = config.url();
|
||||
List<NameValuePair> nvps = new ArrayList<>();
|
||||
url = HttpEntityBuilder.checkHasParas(url, nvps, config.inenc());
|
||||
|
||||
ClassicHttpRequest request = createRequest(method, url);
|
||||
setHeaders(request, headers);
|
||||
setRequestConfig(request, config);
|
||||
|
||||
// 设置请求体(仅 POST 和 PUT)
|
||||
Map<String, Object> map = config.map();
|
||||
if (map != null && !map.isEmpty() && (request instanceof HttpPost || request instanceof HttpPut)) {
|
||||
HttpEntity entity = HttpEntityBuilder.map2HttpEntity(nvps, map, config.inenc());
|
||||
if (request instanceof HttpPost) {
|
||||
((HttpPost) request).setEntity(entity);
|
||||
} else if (request instanceof HttpPut) {
|
||||
((HttpPut) request).setEntity(entity);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果配置了 context,使用 context 执行请求以支持 Cookie
|
||||
// 注意:execute 方法在 HttpClient 5 中被标记为 deprecated,但这是目前推荐的方式
|
||||
CloseableHttpResponse response;
|
||||
if (config.context() != null) {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(request, config.context());
|
||||
response = tempResponse;
|
||||
} else {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(request);
|
||||
response = tempResponse;
|
||||
}
|
||||
try (response) {
|
||||
return extractResponseBody(response, config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行请求并返回详细响应信息(内部方法)
|
||||
*/
|
||||
private static HttpResult executeAndGetResp(HttpRequestOptions config, Header[] headers) throws Exception {
|
||||
String url = config.url();
|
||||
List<NameValuePair> nvps = new ArrayList<>();
|
||||
// 1. 先解析 URL 中原本就带的查询参数(如果有)
|
||||
url = HttpEntityBuilder.checkHasParas(url, nvps, config.inenc());
|
||||
|
||||
// 2. 再把 HttpConfig.map() 里的参数也加入到 nvps 中
|
||||
// 对于 GET 请求,这些参数应该拼到 URL 上,而不是放到 body 里
|
||||
Map<String, Object> map = config.map();
|
||||
if (map != null && !map.isEmpty()) {
|
||||
// 这里主要是为了复用参数编码逻辑,返回的 entity 我们不用
|
||||
HttpEntityBuilder.map2HttpEntity(nvps, map, config.inenc());
|
||||
}
|
||||
|
||||
// 3. 如果 nvps 中有参数,手动构建查询字符串
|
||||
// 注意:某些服务器(如接口测试工具)可能期望参数值中的特殊字符(如 == 和 ;)不被编码
|
||||
// 因此我们只对参数名进行编码,参数值保持原样或只编码必要的字符
|
||||
if (!nvps.isEmpty()) {
|
||||
StringBuilder queryBuilder = new StringBuilder();
|
||||
for (int i = 0; i < nvps.size(); i++) {
|
||||
NameValuePair nvp = nvps.get(i);
|
||||
if (i > 0) {
|
||||
queryBuilder.append("&");
|
||||
}
|
||||
try {
|
||||
// 只对参数名进行编码
|
||||
String encodedName = encodeQueryParam(nvp.getName(), config.inenc());
|
||||
// 参数值保持原样,不进行编码(与接口测试工具行为一致)
|
||||
// 如果参数值中包含需要编码的字符(如中文、空格等),可以在这里添加编码逻辑
|
||||
String paramValue = nvp.getValue();
|
||||
queryBuilder.append(encodedName).append("=").append(paramValue);
|
||||
} catch (Exception ex) {
|
||||
// 如果编码失败,使用原始值
|
||||
queryBuilder.append(nvp.getName()).append("=").append(nvp.getValue());
|
||||
}
|
||||
}
|
||||
String query = queryBuilder.toString();
|
||||
if (url.contains("?")) {
|
||||
url = url + "&" + query;
|
||||
} else {
|
||||
url = url + "?" + query;
|
||||
}
|
||||
}
|
||||
// System.out.println(url);
|
||||
HttpGet httpGet = new HttpGet(url);
|
||||
setHeaders(httpGet, headers);
|
||||
setRequestConfig(httpGet, config);
|
||||
|
||||
// 如果配置了 context,使用 context 执行请求以支持 Cookie
|
||||
// 注意:execute 方法在 HttpClient 5 中被标记为 deprecated,但这是目前推荐的方式
|
||||
CloseableHttpResponse response;
|
||||
if (config.context() != null) {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(httpGet, config.context());
|
||||
response = tempResponse;
|
||||
} else {
|
||||
@SuppressWarnings("deprecation")
|
||||
CloseableHttpResponse tempResponse = (CloseableHttpResponse) config.client().execute(httpGet);
|
||||
response = tempResponse;
|
||||
}
|
||||
try (response) {
|
||||
return buildHttpResult(response, config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 HTTP 请求对象
|
||||
*/
|
||||
private static ClassicHttpRequest createRequest(HttpMethods method, String url) {
|
||||
switch (method) {
|
||||
case GET:
|
||||
return new HttpGet(url);
|
||||
case POST:
|
||||
return new HttpPost(url);
|
||||
case PUT:
|
||||
return new HttpPut(url);
|
||||
case DELETE:
|
||||
return new HttpDelete(url);
|
||||
default:
|
||||
return new HttpGet(url);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置请求头
|
||||
*/
|
||||
private static void setHeaders(ClassicHttpRequest request, Header[] headers) {
|
||||
if (headers != null) {
|
||||
for (Header header : headers) {
|
||||
request.addHeader(header.getName(), header.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置请求配置
|
||||
*/
|
||||
private static void setRequestConfig(ClassicHttpRequest request, HttpRequestOptions config) {
|
||||
if (config.requestConfig() == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (request instanceof HttpGet) {
|
||||
((HttpGet) request).setConfig(config.requestConfig());
|
||||
} else if (request instanceof HttpPost) {
|
||||
((HttpPost) request).setConfig(config.requestConfig());
|
||||
} else if (request instanceof HttpPut) {
|
||||
((HttpPut) request).setConfig(config.requestConfig());
|
||||
} else if (request instanceof HttpPatch) {
|
||||
((HttpPatch) request).setConfig(config.requestConfig());
|
||||
} else if (request instanceof HttpDelete) {
|
||||
((HttpDelete) request).setConfig(config.requestConfig());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取响应体内容
|
||||
*/
|
||||
private static String extractResponseBody(CloseableHttpResponse response, HttpRequestOptions config) throws Exception {
|
||||
HttpEntity entity = response.getEntity();
|
||||
if (entity == null) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
String result = EntityUtils.toString(entity, Charset.forName(config.outenc()));
|
||||
return result;
|
||||
} finally {
|
||||
EntityUtils.consume(entity);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建 HttpResult 对象
|
||||
*/
|
||||
private static HttpResult buildHttpResult(CloseableHttpResponse response, HttpRequestOptions config) throws Exception {
|
||||
// 直接使用 HttpResult 构造函数,自动设置状态行、响应头、协议版本和状态码
|
||||
HttpResult result = new HttpResult(response);
|
||||
|
||||
// 读取响应体内容
|
||||
HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
String responseBody = EntityUtils.toString(entity, Charset.forName(config.outenc()));
|
||||
result.setResult(responseBody);
|
||||
EntityUtils.consume(entity);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 编码查询参数名(只编码参数名,不编码参数值)
|
||||
* 这样可以保持与接口测试工具的行为一致
|
||||
*
|
||||
* @param param 参数名
|
||||
* @param encoding 编码格式
|
||||
* @return 编码后的参数名
|
||||
*/
|
||||
private static String encodeQueryParam(String param, String encoding) {
|
||||
if (param == null) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
// 只对参数名进行标准 URL 编码
|
||||
return java.net.URLEncoder.encode(param, encoding).replace("+", "%20");
|
||||
} catch (java.io.UnsupportedEncodingException e) {
|
||||
return param;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.mgm.mcrm.common.httpclient;
|
||||
|
||||
import org.apache.hc.client5.http.cookie.BasicCookieStore;
|
||||
import org.apache.hc.client5.http.cookie.CookieStore;
|
||||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||
|
||||
public class HttpCookieContext {
|
||||
/**
|
||||
* 使用httpcontext,用于设置和携带Cookie
|
||||
*/
|
||||
private HttpClientContext context ;
|
||||
|
||||
/**
|
||||
* 储存Cookie
|
||||
*/
|
||||
private CookieStore cookieStore;
|
||||
|
||||
public static HttpCookieContext custom(){
|
||||
return new HttpCookieContext();
|
||||
}
|
||||
|
||||
private HttpCookieContext(){
|
||||
this.context = new HttpClientContext();
|
||||
this.cookieStore = new BasicCookieStore();
|
||||
this.context.setCookieStore(cookieStore);
|
||||
}
|
||||
|
||||
public HttpClientContext getContext() {
|
||||
return context;
|
||||
}
|
||||
|
||||
public HttpCookieContext setContext(HttpClientContext context) {
|
||||
this.context = context;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CookieStore getCookieStore() {
|
||||
return cookieStore;
|
||||
}
|
||||
|
||||
public HttpCookieContext setCookieStore(CookieStore cookieStore) {
|
||||
this.cookieStore = cookieStore;
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
package com.mgm.mcrm.common.httpclient;
|
||||
|
||||
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
|
||||
import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
|
||||
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.apache.hc.core5.http.HttpHeaders;
|
||||
import org.apache.hc.core5.http.NameValuePair;
|
||||
import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
|
||||
import org.apache.hc.core5.http.io.entity.FileEntity;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.message.BasicHeader;
|
||||
import org.apache.hc.core5.http.message.BasicNameValuePair;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
|
||||
public class HttpEntityBuilder {
|
||||
|
||||
//传入参数特定类型
|
||||
public static final String ENTITY_STRING="$ENTITY_STRING$";
|
||||
public static final String ENTITY_JSON="$ENTITY_JSON$";
|
||||
public static final String ENTITY_FILE="$ENTITY_FILEE$";
|
||||
public static final String ENTITY_BYTES="$ENTITY_BYTES$";
|
||||
public static final String ENTITY_INPUTSTREAM="$ENTITY_INPUTSTREAM$";
|
||||
public static final String ENTITY_SERIALIZABLE="$ENTITY_SERIALIZABLE$";
|
||||
public static final String ENTITY_MULTIPART="$ENTITY_MULTIPART$";
|
||||
private static final List<String> SPECIAL_ENTITIY = Arrays.asList(ENTITY_STRING, ENTITY_JSON, ENTITY_BYTES, ENTITY_FILE, ENTITY_INPUTSTREAM, ENTITY_SERIALIZABLE, ENTITY_MULTIPART);
|
||||
|
||||
/**
|
||||
* 是否开启debug,
|
||||
*/
|
||||
private static boolean debug = false;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(HttpEntityBuilder.class);
|
||||
|
||||
|
||||
/**
|
||||
* 检测url是否含有参数,如果有,则把参数加到参数列表中
|
||||
*
|
||||
* @param url 资源地址
|
||||
* @param nvps 参数列表
|
||||
* @param encoding 编码
|
||||
* @return 返回去掉参数的url
|
||||
* @throws UnsupportedEncodingException 不支持的编码异常
|
||||
*/
|
||||
public static String checkHasParas(String url, List<NameValuePair> nvps, String encoding) throws UnsupportedEncodingException {
|
||||
// 检测url中是否存在参数
|
||||
if (url.contains("?") && url.indexOf("?") < url.indexOf("=")) {
|
||||
String[] paras = url.substring(url.indexOf("?") + 1).split("&");
|
||||
for (String para : paras) {
|
||||
int pos = para.indexOf("=");
|
||||
if (pos >= 0) {
|
||||
nvps.add(new BasicNameValuePair(para.substring(0, pos), para.substring(pos + 1)));
|
||||
} else {
|
||||
nvps.add(new BasicNameValuePair(para, ""));
|
||||
}
|
||||
}
|
||||
url = url.substring(0, url.indexOf("?"));
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 参数转换,将map中的参数,转到参数列表中
|
||||
*
|
||||
* @param nvps 参数列表
|
||||
* @param map 参数列表(map)
|
||||
* @param encoding 编码
|
||||
* @return 返回HttpEntity
|
||||
* @throws UnsupportedEncodingException 不支持的编码异常
|
||||
*/
|
||||
public static HttpEntity map2HttpEntity(List<NameValuePair> nvps, Map<String, Object> map, String encoding) throws UnsupportedEncodingException {
|
||||
HttpEntity entity = null;
|
||||
if(map!=null && map.size()>0){
|
||||
boolean isSpecial = false;
|
||||
// 拼接参数
|
||||
for (Entry<String, Object> entry : map.entrySet()) {
|
||||
if(SPECIAL_ENTITIY.contains(entry.getKey())){//判断是否在之中
|
||||
isSpecial = true;
|
||||
if(ENTITY_STRING.equals(entry.getKey())){//string
|
||||
entity = new StringEntity(String.valueOf(entry.getValue()), Charset.forName(encoding));
|
||||
break;
|
||||
}else if(ENTITY_JSON.equals(entry.getKey())){//json
|
||||
ContentType jsonContentType;
|
||||
|
||||
entity = new StringEntity(String.valueOf(entry.getValue()), Charset.forName(encoding));
|
||||
String contentType = "application/json";
|
||||
if (encoding != null && !encoding.trim().isEmpty()) {
|
||||
// 创建带有编码的JSON ContentType
|
||||
jsonContentType = ContentType.APPLICATION_JSON.withCharset(Charset.forName(encoding));
|
||||
}else {
|
||||
// 使用默认的JSON ContentType(通常UTF-8)
|
||||
jsonContentType = ContentType.APPLICATION_JSON;
|
||||
}
|
||||
// 创建实体时直接传入ContentType
|
||||
entity = new StringEntity(String.valueOf(entry.getValue()), jsonContentType);
|
||||
break;
|
||||
}else if(ENTITY_BYTES.equals(entry.getKey())){//file
|
||||
byte[] data = (byte[]) entry.getValue();
|
||||
entity = new ByteArrayEntity(data, ContentType.APPLICATION_OCTET_STREAM);
|
||||
break;
|
||||
}else if(ENTITY_FILE.equals(entry.getKey())){//file
|
||||
if(File.class.isAssignableFrom(entry.getValue().getClass())){
|
||||
entity = new FileEntity((File)entry.getValue(), ContentType.APPLICATION_OCTET_STREAM);
|
||||
}else if(entry.getValue().getClass()==String.class){
|
||||
entity = new FileEntity(new File((String) entry.getValue()), ContentType.create("text/plain", "UTF-8"));
|
||||
}
|
||||
break;
|
||||
}else if(ENTITY_INPUTSTREAM.equals(entry.getKey())){//inputstream
|
||||
// entity = new InputStreamEntity();
|
||||
break;
|
||||
}else if(ENTITY_SERIALIZABLE.equals(entry.getKey())){//serializeable
|
||||
// entity = new SerializableEntity()
|
||||
break;
|
||||
}else if(ENTITY_MULTIPART.equals(entry.getKey())){//MultipartEntityBuilder
|
||||
File[] files = null;
|
||||
if(File.class.isAssignableFrom(entry.getValue().getClass().getComponentType())){
|
||||
files=(File[])entry.getValue();
|
||||
}else if(entry.getValue().getClass().getComponentType()==String.class){
|
||||
String[] names = (String[]) entry.getValue();
|
||||
files = new File[names.length];
|
||||
for (int i = 0; i < names.length; i++) {
|
||||
files[i] = new File(names[i]);
|
||||
}
|
||||
}
|
||||
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.setCharset(Charset.forName(encoding));// 设置请求的编码格式
|
||||
builder.setMode(HttpMultipartMode.LEGACY);// 设置浏览器兼容模式
|
||||
int count = 0;
|
||||
for (File file : files) {
|
||||
// //把文件转换成流对象FileBody
|
||||
// FileBody fileBody = new FileBody(file);
|
||||
// builder.addPart(String.valueOf(map.get(ENTITY_MULTIPART+".name")) + count++, fileBody);
|
||||
builder.addBinaryBody(String.valueOf(map.get(ENTITY_MULTIPART+".name")) + count++,file);
|
||||
}
|
||||
boolean forceRemoveContentTypeCharset = (boolean)map.get(ENTITY_MULTIPART+".rmCharset");
|
||||
Map<String, Object> m = new HashMap<String, Object>();
|
||||
m.putAll(map);
|
||||
m.remove(ENTITY_MULTIPART);
|
||||
m.remove(ENTITY_MULTIPART+".name");
|
||||
m.remove(ENTITY_MULTIPART+".rmCharset");
|
||||
Iterator<Entry<String, Object>> iterator = m.entrySet().iterator();
|
||||
// 发送的数据
|
||||
while (iterator.hasNext()) {
|
||||
Entry<String, Object> e = iterator.next();
|
||||
builder.addTextBody(e.getKey(), String.valueOf(e.getValue()), ContentType.create("text/plain", encoding));
|
||||
}
|
||||
entity = builder.build();// 生成 HTTP POST 实体
|
||||
|
||||
//强制去除contentType中的编码设置,否则,在某些情况下会导致上传失败
|
||||
if(forceRemoveContentTypeCharset){
|
||||
removeContentTypeCharset(encoding, entity);
|
||||
}
|
||||
break;
|
||||
}else {
|
||||
nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
|
||||
}
|
||||
}else{
|
||||
nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
|
||||
}
|
||||
}
|
||||
if(!isSpecial) {
|
||||
entity = new UrlEncodedFormEntity(nvps, Charset.forName(encoding));
|
||||
}
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除content-type中的charset
|
||||
*
|
||||
* @param encoding 编码
|
||||
* @param entity 请求参数及数据信息
|
||||
*/
|
||||
private static void removeContentTypeCharset(String encoding, HttpEntity entity) {
|
||||
try {
|
||||
Class<?> clazz = entity.getClass();
|
||||
Field field = clazz.getDeclaredField("contentType");
|
||||
field.setAccessible(true); //将字段的访问权限设为true:即去除private修饰符的影响
|
||||
if(Modifier.isFinal(field.getModifiers())){
|
||||
Field modifiersField = Field.class.getDeclaredField("modifiers"); //去除final修饰符的影响,将字段设为可修改的
|
||||
modifiersField.setAccessible(true);
|
||||
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
|
||||
}
|
||||
BasicHeader o = (BasicHeader) field.get(entity);
|
||||
field.set(entity, new BasicHeader(HttpHeaders.CONTENT_TYPE, o.getValue().replace("; charset="+encoding,"")));
|
||||
} catch (NoSuchFieldException e) {
|
||||
HttpEntityBuilder.exception(e);
|
||||
} catch (SecurityException e) {
|
||||
HttpEntityBuilder.exception(e);
|
||||
} catch (IllegalArgumentException e) {
|
||||
HttpEntityBuilder.exception(e);
|
||||
} catch (IllegalAccessException e) {
|
||||
HttpEntityBuilder.exception(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 生成参数
|
||||
* 参数格式:k1=v1&k2=v2
|
||||
*
|
||||
* @param paras 参数列表
|
||||
* @return 返回参数列表(map)
|
||||
*/
|
||||
public static Map<String,Object> buildParas(String paras){
|
||||
String[] p = paras.split("&");
|
||||
String[][] ps = new String[p.length][2];
|
||||
int pos = 0;
|
||||
for (int i = 0; i < p.length; i++) {
|
||||
pos = p[i].indexOf("=");
|
||||
ps[i][0]=p[i].substring(0,pos);
|
||||
ps[i][1]=p[i].substring(pos+1);
|
||||
pos = 0;
|
||||
}
|
||||
return buildParas(ps);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成参数
|
||||
* 参数类型:{{"k1","v1"},{"k2","v2"}}
|
||||
*
|
||||
* @param paras 参数列表
|
||||
* @return 返回参数列表(map)
|
||||
*/
|
||||
public static Map<String,Object> buildParas(String[][] paras){
|
||||
// 创建参数队列
|
||||
Map<String,Object> map = new HashMap<String, Object>();
|
||||
for (String[] para: paras) {
|
||||
map.put(para[0], para[1]);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印消息
|
||||
*
|
||||
* @param msg 消息
|
||||
*/
|
||||
public static void info(String msg){
|
||||
if(debug){
|
||||
log.info(msg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印消息和异常堆栈
|
||||
*
|
||||
* @param msg 异常消息
|
||||
* @param t 异常
|
||||
*/
|
||||
public static void infoException(String msg, Throwable t){
|
||||
if(debug){
|
||||
log.info(msg,t);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印错误消息
|
||||
*
|
||||
* @param msg 异常消息
|
||||
*/
|
||||
public static void error(String msg){
|
||||
log.error(msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印错误消息和异常堆栈
|
||||
*
|
||||
* @param msg 异常消息
|
||||
* @param t 异常
|
||||
*/
|
||||
public static void errorException(String msg, Throwable t){
|
||||
log.error(msg, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印异常堆栈
|
||||
*
|
||||
* @param t 异常
|
||||
*/
|
||||
public static void exception(Throwable t){
|
||||
log.error(String.valueOf(t));
|
||||
}
|
||||
|
||||
/**
|
||||
* 开启打印日志
|
||||
*/
|
||||
public static void debug() {
|
||||
debug(true);
|
||||
}
|
||||
/**
|
||||
* 开启或关闭打印日志
|
||||
* @param debug 是否开启debug
|
||||
*/
|
||||
public static void debug(boolean debug) {
|
||||
HttpEntityBuilder.debug = debug;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,697 @@
|
||||
package com.mgm.mcrm.common.httpclient;
|
||||
|
||||
|
||||
import com.mgm.mcrm.common.config.HttpHeader;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.message.BasicHeader;
|
||||
|
||||
import java.net.URLConnection;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* http 发送参数
|
||||
*
|
||||
* @author Aaka
|
||||
*/
|
||||
public class HttpHeaderBuilder {
|
||||
|
||||
private HttpHeaderBuilder() {};
|
||||
|
||||
public static HttpHeaderBuilder custom() {
|
||||
return new HttpHeaderBuilder();
|
||||
}
|
||||
|
||||
//记录head头信息
|
||||
private Map<String, Header> headerMaps = new HashMap<String, Header>();
|
||||
|
||||
/**
|
||||
* 自定义header头信息
|
||||
*
|
||||
* @param key header-key
|
||||
* @param value header-value
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder other(String key, String value) {
|
||||
headerMaps.put(key, new BasicHeader(key, value));
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* 指定客户端能够接收的内容类型
|
||||
* 例如:Accept: text/plain, text/html
|
||||
*
|
||||
* @param accept accept
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder accept(String accept) {
|
||||
headerMaps.put(HttpReqHead.ACCEPT,
|
||||
new BasicHeader(HttpReqHead.ACCEPT, accept));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 浏览器可以接受的字符编码集
|
||||
* 例如:Accept-Charset: iso-8859-5
|
||||
*
|
||||
* @param acceptCharset accept-charset
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder acceptCharset(String acceptCharset) {
|
||||
headerMaps.put(HttpReqHead.ACCEPT_CHARSET,
|
||||
new BasicHeader(HttpReqHead.ACCEPT_CHARSET, acceptCharset));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定浏览器可以支持的web服务器返回内容压缩编码类型
|
||||
* 例如:Accept-Encoding: compress, gzip
|
||||
*
|
||||
* @param acceptEncoding accept-encoding
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder acceptEncoding(String acceptEncoding) {
|
||||
headerMaps.put(HttpReqHead.ACCEPT_ENCODING,
|
||||
new BasicHeader(HttpReqHead.ACCEPT_ENCODING, acceptEncoding));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 浏览器可接受的语言
|
||||
* 例如:Accept-Language: en,zh
|
||||
*
|
||||
* @param acceptLanguage accept-language
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder acceptLanguage(String acceptLanguage) {
|
||||
headerMaps.put(HttpReqHead.ACCEPT_LANGUAGE,
|
||||
new BasicHeader(HttpReqHead.ACCEPT_LANGUAGE, acceptLanguage));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 可以请求网页实体的一个或者多个子范围字段
|
||||
* 例如:Accept-Ranges: bytes
|
||||
*
|
||||
* @param acceptRanges accept-ranges
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder acceptRanges(String acceptRanges) {
|
||||
headerMaps.put(HttpReqHead.ACCEPT_RANGES,
|
||||
new BasicHeader(HttpReqHead.ACCEPT_RANGES, acceptRanges));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP授权的授权证书
|
||||
* 例如:Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
|
||||
*
|
||||
* @param authorization authorization
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder authorization(String authorization) {
|
||||
headerMaps.put(HttpReqHead.AUTHORIZATION,
|
||||
new BasicHeader(HttpReqHead.AUTHORIZATION, authorization));
|
||||
return this;
|
||||
}
|
||||
|
||||
public HttpHeaderBuilder ac_property_id(String ac_property_id) {
|
||||
headerMaps.put(HttpReqHead.AC_PROPERTY_ID,
|
||||
new BasicHeader(HttpReqHead.AC_PROPERTY_ID, ac_property_id));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定请求和响应遵循的缓存机制
|
||||
* 例如:Cache-Control: no-cache
|
||||
*
|
||||
* @param cacheControl cache-control
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder cacheControl(String cacheControl) {
|
||||
headerMaps.put(HttpReqHead.CACHE_CONTROL,
|
||||
new BasicHeader(HttpReqHead.CACHE_CONTROL, cacheControl));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 表示是否需要持久连接(HTTP 1.1默认进行持久连接)
|
||||
* 例如:Connection: close 短链接; Connection: keep-alive 长连接
|
||||
*
|
||||
* @param connection connection
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder connection(String connection) {
|
||||
headerMaps.put(HttpReqHead.CONNECTION,
|
||||
new BasicHeader(HttpReqHead.CONNECTION, connection));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP请求发送时,会把保存在该请求域名下的所有cookie值一起发送给web服务器
|
||||
* 例如:Cookie: $Version=1; Skin=new;
|
||||
*
|
||||
* @param cookie cookie
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder cookie(String cookie) {
|
||||
headerMaps.put(HttpReqHead.COOKIE,
|
||||
new BasicHeader(HttpReqHead.COOKIE, cookie));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求内容长度
|
||||
* 例如:Content-Length: 348
|
||||
*
|
||||
* @param contentLength content-length
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder contentLength(String contentLength) {
|
||||
headerMaps.put(HttpReqHead.CONTENT_LENGTH,
|
||||
new BasicHeader(HttpReqHead.CONTENT_LENGTH, contentLength));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求的与实体对应的MIME信息
|
||||
* 例如:Content-Type: application/x-www-form-urlencoded
|
||||
*
|
||||
* @param contentType content-type
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder contentType(String contentType) {
|
||||
headerMaps.put(HttpReqHead.CONTENT_TYPE,
|
||||
new BasicHeader(HttpReqHead.CONTENT_TYPE, contentType));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求发送的日期和时间
|
||||
* 例如:Date: Tue, 15 Nov 2010 08:12:31 GMT
|
||||
*
|
||||
* @param date date
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder date(String date) {
|
||||
headerMaps.put(HttpReqHead.DATE,
|
||||
new BasicHeader(HttpReqHead.DATE, date));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求的特定的服务器行为
|
||||
* 例如:Expect: 100-continue
|
||||
*
|
||||
* @param expect expect
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder expect(String expect) {
|
||||
headerMaps.put(HttpReqHead.EXPECT,
|
||||
new BasicHeader(HttpReqHead.EXPECT, expect));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发出请求的用户的Email
|
||||
* 例如:From: user@email.com
|
||||
*
|
||||
* @param from from
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder from(String from) {
|
||||
headerMaps.put(HttpReqHead.FROM,
|
||||
new BasicHeader(HttpReqHead.FROM, from));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定请求的服务器的域名和端口号
|
||||
* 例如:Host: blog.csdn.net
|
||||
*
|
||||
* @param host host
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder host(String host) {
|
||||
headerMaps.put(HttpReqHead.HOST,
|
||||
new BasicHeader(HttpReqHead.HOST, host));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 只有请求内容与实体相匹配才有效
|
||||
* 例如:If-Match: “737060cd8c284d8af7ad3082f209582d”
|
||||
*
|
||||
* @param ifMatch if-match
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder ifMatch(String ifMatch) {
|
||||
headerMaps.put(HttpReqHead.IF_MATCH,
|
||||
new BasicHeader(HttpReqHead.IF_MATCH, ifMatch));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果请求的部分在指定时间之后被修改则请求成功,未被修改则返回304代码
|
||||
* 例如:If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT
|
||||
*
|
||||
* @param ifModifiedSince if-modified-Since
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder ifModifiedSince(String ifModifiedSince) {
|
||||
headerMaps.put(HttpReqHead.IF_MODIFIED_SINCE,
|
||||
new BasicHeader(HttpReqHead.IF_MODIFIED_SINCE, ifModifiedSince));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果内容未改变返回304代码,参数为服务器先前发送的Etag,与服务器回应的Etag比较判断是否改变
|
||||
* 例如:If-None-Match: “737060cd8c284d8af7ad3082f209582d”
|
||||
*
|
||||
* @param ifNoneMatch if-none-match
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder ifNoneMatch(String ifNoneMatch) {
|
||||
headerMaps.put(HttpReqHead.IF_NONE_MATCH,
|
||||
new BasicHeader(HttpReqHead.IF_NONE_MATCH, ifNoneMatch));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果实体未改变,服务器发送客户端丢失的部分,否则发送整个实体。参数也为Etag
|
||||
* 例如:If-Range: “737060cd8c284d8af7ad3082f209582d”
|
||||
*
|
||||
* @param ifRange if-range
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder ifRange(String ifRange) {
|
||||
headerMaps.put(HttpReqHead.IF_RANGE,
|
||||
new BasicHeader(HttpReqHead.IF_RANGE, ifRange));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 只在实体在指定时间之后未被修改才请求成功
|
||||
* 例如:If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT
|
||||
*
|
||||
* @param ifUnmodifiedSince if-unmodified-since
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder ifUnmodifiedSince(String ifUnmodifiedSince) {
|
||||
headerMaps.put(HttpReqHead.IF_UNMODIFIED_SINCE,
|
||||
new BasicHeader(HttpReqHead.IF_UNMODIFIED_SINCE, ifUnmodifiedSince));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 限制信息通过代理和网关传送的时间
|
||||
* 例如:Max-Forwards: 10
|
||||
*
|
||||
* @param maxForwards max-forwards
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder maxForwards(String maxForwards) {
|
||||
headerMaps.put(HttpReqHead.MAX_FORWARDS,
|
||||
new BasicHeader(HttpReqHead.MAX_FORWARDS, maxForwards));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用来包含实现特定的指令
|
||||
* 例如:Pragma: no-cache
|
||||
*
|
||||
* @param pragma pragma
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder pragma(String pragma) {
|
||||
headerMaps.put(HttpReqHead.PRAGMA,
|
||||
new BasicHeader(HttpReqHead.PRAGMA, pragma));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接到代理的授权证书
|
||||
* 例如:Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
|
||||
*
|
||||
* @param proxyAuthorization proxy-authorization
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder proxyAuthorization(String proxyAuthorization) {
|
||||
headerMaps.put(HttpReqHead.PROXY_AUTHORIZATION,
|
||||
new BasicHeader(HttpReqHead.PROXY_AUTHORIZATION, proxyAuthorization));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 只请求实体的一部分,指定范围
|
||||
* 例如:Range: bytes=500-999
|
||||
*
|
||||
* @param range range
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder range(String range) {
|
||||
headerMaps.put(HttpReqHead.RANGE,
|
||||
new BasicHeader(HttpReqHead.RANGE, range));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 先前网页的地址,当前请求网页紧随其后,即来路
|
||||
* 例如:Referer: http://www.zcmhi.com/archives/71.html
|
||||
*
|
||||
* @param referer referer
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder referer(String referer) {
|
||||
headerMaps.put(HttpReqHead.REFERER,
|
||||
new BasicHeader(HttpReqHead.REFERER, referer));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户端愿意接受的传输编码,并通知服务器接受接受尾加头信息
|
||||
* 例如:TE: trailers,deflate;q=0.5
|
||||
*
|
||||
* @param te te
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder te(String te) {
|
||||
headerMaps.put(HttpReqHead.TE,
|
||||
new BasicHeader(HttpReqHead.TE, te));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 向服务器指定某种传输协议以便服务器进行转换(如果支持)
|
||||
* 例如:Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
|
||||
*
|
||||
* @param upgrade upgrade
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder upgrade(String upgrade) {
|
||||
headerMaps.put(HttpReqHead.UPGRADE,
|
||||
new BasicHeader(HttpReqHead.UPGRADE, upgrade));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* User-Agent的内容包含发出请求的用户信息
|
||||
*
|
||||
* @param userAgent user-agent
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder userAgent(String userAgent) {
|
||||
headerMaps.put(HttpReqHead.USER_AGENT,
|
||||
new BasicHeader(HttpReqHead.USER_AGENT, userAgent));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关于消息实体的警告信息
|
||||
* 例如:Warn: 199 Miscellaneous warning
|
||||
*
|
||||
* @param warning warning
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder warning(String warning) {
|
||||
headerMaps.put(HttpReqHead.WARNING,
|
||||
new BasicHeader(HttpReqHead.WARNING, warning));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知中间网关或代理服务器地址,通信协议
|
||||
* 例如:Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
|
||||
*
|
||||
* @param via via
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpHeaderBuilder via(String via) {
|
||||
headerMaps.put(HttpReqHead.VIA,
|
||||
new BasicHeader(HttpReqHead.VIA, via));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置此HTTP连接的持续时间(超时时间)
|
||||
* 例如:Keep-Alive: 300
|
||||
*
|
||||
* @param keepAlive keep-alive
|
||||
* @return 返回当前对象
|
||||
|
||||
*/
|
||||
public HttpHeaderBuilder keepAlive(String keepAlive) {
|
||||
headerMaps.put(HttpReqHead.KEEP_ALIVE,
|
||||
new BasicHeader(HttpReqHead.KEEP_ALIVE, keepAlive));
|
||||
return this;
|
||||
}
|
||||
|
||||
public String accept() {
|
||||
return get(HttpReqHead.ACCEPT);
|
||||
}
|
||||
|
||||
public String acceptCharset() {
|
||||
return get(HttpReqHead.ACCEPT_CHARSET);
|
||||
}
|
||||
|
||||
public String acceptEncoding() {
|
||||
return get(HttpReqHead.ACCEPT_ENCODING);
|
||||
}
|
||||
|
||||
public String acceptLanguage() {
|
||||
return get(HttpReqHead.ACCEPT_LANGUAGE);
|
||||
}
|
||||
|
||||
public String acceptRanges() {
|
||||
return get(HttpReqHead.ACCEPT_RANGES);
|
||||
}
|
||||
|
||||
public String authorization() {
|
||||
return get(HttpReqHead.AUTHORIZATION);
|
||||
}
|
||||
|
||||
public String cacheControl() {
|
||||
return get(HttpReqHead.CACHE_CONTROL);
|
||||
}
|
||||
|
||||
public String connection() {
|
||||
return get(HttpReqHead.CONNECTION);
|
||||
}
|
||||
|
||||
public String cookie() {
|
||||
return get(HttpReqHead.COOKIE);
|
||||
}
|
||||
|
||||
public String contentLength() {
|
||||
return get(HttpReqHead.CONTENT_LENGTH);
|
||||
}
|
||||
|
||||
public String contentType() {
|
||||
return get(HttpReqHead.CONTENT_TYPE);
|
||||
}
|
||||
|
||||
public String date() {
|
||||
return get(HttpReqHead.DATE);
|
||||
}
|
||||
|
||||
public String expect() {
|
||||
return get(HttpReqHead.EXPECT);
|
||||
}
|
||||
|
||||
public String from() {
|
||||
return get(HttpReqHead.FROM);
|
||||
}
|
||||
|
||||
public String host() {
|
||||
return get(HttpReqHead.HOST);
|
||||
}
|
||||
|
||||
public String ifMatch() {
|
||||
return get(HttpReqHead.IF_MATCH);
|
||||
}
|
||||
|
||||
public String ifModifiedSince() {
|
||||
return get(HttpReqHead.IF_MODIFIED_SINCE);
|
||||
}
|
||||
|
||||
public String ifNoneMatch() {
|
||||
return get(HttpReqHead.IF_NONE_MATCH);
|
||||
}
|
||||
|
||||
public String ifRange() {
|
||||
return get(HttpReqHead.IF_RANGE);
|
||||
}
|
||||
|
||||
public String ifUnmodifiedSince() {
|
||||
return get(HttpReqHead.IF_UNMODIFIED_SINCE);
|
||||
}
|
||||
|
||||
public String maxForwards() {
|
||||
return get(HttpReqHead.MAX_FORWARDS);
|
||||
}
|
||||
|
||||
public String pragma() {
|
||||
return get(HttpReqHead.PRAGMA);
|
||||
}
|
||||
|
||||
public String proxyAuthorization() {
|
||||
return get(HttpReqHead.PROXY_AUTHORIZATION);
|
||||
}
|
||||
|
||||
public String referer() {
|
||||
return get(HttpReqHead.REFERER);
|
||||
}
|
||||
|
||||
public String te() {
|
||||
return get(HttpReqHead.TE);
|
||||
}
|
||||
|
||||
public String upgrade() {
|
||||
return get(HttpReqHead.UPGRADE);
|
||||
}
|
||||
|
||||
public String userAgent() {
|
||||
return get(HttpReqHead.USER_AGENT);
|
||||
}
|
||||
|
||||
public String via() {
|
||||
return get(HttpReqHead.VIA);
|
||||
}
|
||||
|
||||
public String warning() {
|
||||
return get(HttpReqHead.WARNING);
|
||||
}
|
||||
|
||||
public String keepAlive() {
|
||||
return get(HttpReqHead.KEEP_ALIVE);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取head信息
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private String get(String headName) {
|
||||
if (headerMaps.containsKey(headName)) {
|
||||
return headerMaps.get(headName).getValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回header头信息
|
||||
*
|
||||
* @return 返回构建的header头信息数组
|
||||
*/
|
||||
public Header[] build() {
|
||||
Header[] headers = new Header[headerMaps.size()];
|
||||
int i = 0;
|
||||
for (Header header : headerMaps.values()) {
|
||||
headers[i] = header;
|
||||
i++;
|
||||
}
|
||||
headerMaps.clear();
|
||||
headerMaps = null;
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Http头信息
|
||||
*
|
||||
* @author arron
|
||||
* @date 2015年11月9日 上午11:29:04
|
||||
* @version 1.0
|
||||
*/
|
||||
private static class HttpReqHead {
|
||||
public static final String ACCEPT = "Accept";
|
||||
public static final String ACCEPT_CHARSET = "Accept-Charset";
|
||||
public static final String ACCEPT_ENCODING = "Accept-Encoding";
|
||||
public static final String ACCEPT_LANGUAGE = "Accept-Language";
|
||||
public static final String ACCEPT_RANGES = "Accept-Ranges";
|
||||
public static final String AUTHORIZATION = "Authorization";
|
||||
public static final String AC_PROPERTY_ID = "AC-Property-Id";
|
||||
public static final String CACHE_CONTROL = "Cache-Control";
|
||||
public static final String CONNECTION = "Connection";
|
||||
public static final String COOKIE = "Cookie";
|
||||
public static final String CONTENT_LENGTH = "Content-Length";
|
||||
public static final String CONTENT_TYPE = "Content-Type";
|
||||
public static final String DATE= "Date";
|
||||
public static final String EXPECT = "Expect";
|
||||
public static final String FROM = "From";
|
||||
public static final String HOST = "Host";
|
||||
public static final String IF_MATCH = "If-Match";
|
||||
public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
|
||||
public static final String IF_NONE_MATCH = "If-None-Match";
|
||||
public static final String IF_RANGE = "If-Range";
|
||||
public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
|
||||
public static final String KEEP_ALIVE = "Keep-Alive";
|
||||
public static final String MAX_FORWARDS = "Max-Forwards";
|
||||
public static final String PRAGMA = "Pragma";
|
||||
public static final String PROXY_AUTHORIZATION = "Proxy-Authorization";
|
||||
public static final String RANGE = "Range";
|
||||
public static final String REFERER = "Referer";
|
||||
public static final String TE = "TE";
|
||||
public static final String UPGRADE = "Upgrade";
|
||||
public static final String USER_AGENT = "User-Agent";
|
||||
public static final String VIA = "Via";
|
||||
public static final String WARNING = "Warning";
|
||||
}
|
||||
|
||||
/**
|
||||
* 常用头信息配置
|
||||
*
|
||||
* @author arron
|
||||
* @version 1.0
|
||||
*/
|
||||
public static class Headers{
|
||||
public static final String APP_FORM_URLENCODED="application/x-www-form-urlencoded";
|
||||
public static final String TEXT_PLAIN="text/plain";
|
||||
public static final String TEXT_HTML="text/html";
|
||||
public static final String TEXT_XML="text/xml";
|
||||
public static final String TEXT_JSON="text/json";
|
||||
public static final String CONTENT_CHARSET_ISO_8859_1 = StandardCharsets.ISO_8859_1.name();
|
||||
public static final String CONTENT_CHARSET_UTF8 = StandardCharsets.UTF_8.name();
|
||||
public static final String DEF_PROTOCOL_CHARSET = StandardCharsets.US_ASCII.name();
|
||||
public static final String CONN_CLOSE = "close";
|
||||
public static final String KEEP_ALIVE = "keep-alive";
|
||||
public static final String EXPECT_CONTINUE = "100-continue";
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public static Map<String, String> getDefaultHeaders(URLConnection connection) {
|
||||
Map<String, String> defaultHeaders = new HashMap<>();
|
||||
defaultHeaders.put(HttpHeader.ACCEPT, "*/*");
|
||||
defaultHeaders.put(HttpHeader.CONNECTION, "Keep-Alive");
|
||||
defaultHeaders.put(HttpHeader.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
|
||||
defaultHeaders.put(HttpHeader.ACCEPT_CHARSET, "utf-8");
|
||||
return defaultHeaders;
|
||||
}
|
||||
|
||||
/**
|
||||
* 設置請求頭到連接對象
|
||||
*
|
||||
* @param conn URL連接對象
|
||||
* @param contentType 內容類型
|
||||
* @param headers HTTP 請求頭 Map(可選,如果為 null 或空則使用默認值)
|
||||
*/
|
||||
public static void setRequestHeaders(URLConnection conn, String contentType, Map<String, String> headers) {
|
||||
Map<String, String> defaultHeaders = getDefaultHeaders(conn);
|
||||
// 如果傳入了自定義 headers,則合併(自定義的優先)
|
||||
if (headers != null && !headers.isEmpty()) {
|
||||
defaultHeaders.putAll(headers);
|
||||
}
|
||||
// 設置所有請求頭
|
||||
for (Map.Entry<String, String> entry : defaultHeaders.entrySet()) {
|
||||
conn.setRequestProperty(entry.getKey(), entry.getValue());
|
||||
}
|
||||
// Content-Type 優先級最高,如果指定了則覆蓋
|
||||
if (contentType != null) {
|
||||
conn.setRequestProperty("Content-Type", contentType);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.mgm.mcrm.common.httpclient;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* HTTP 参数构建器
|
||||
*
|
||||
* 用于构建 HTTP 请求参数(查询字符串、请求体等)。
|
||||
*
|
||||
* @author Aaka
|
||||
*/
|
||||
public class HttpParameterBuilder {
|
||||
private static final Logger log = LoggerFactory.getLogger(HttpParameterBuilder.class);
|
||||
|
||||
/**
|
||||
* 將參數 Map 轉換為查詢字符串(用於 GET 請求)
|
||||
*
|
||||
* @param params 參數 Map
|
||||
* @return 查詢字符串,格式為 name1=value1&name2=value2
|
||||
*/
|
||||
public static String buildQueryString(Map<String, Object> params) {
|
||||
if (params == null || params.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return params.entrySet().stream()
|
||||
.filter(entry -> entry.getKey() != null && entry.getValue() != null)
|
||||
.map(entry -> {
|
||||
try {
|
||||
String key = URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8);
|
||||
String value = URLEncoder.encode(String.valueOf(entry.getValue()), StandardCharsets.UTF_8);
|
||||
return key + "=" + value;
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to encode parameter: {}={}", entry.getKey(), entry.getValue(), e);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(java.util.Objects::nonNull)
|
||||
.collect(Collectors.joining("&"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 將參數 Map 轉換為請求體字符串
|
||||
*
|
||||
* @param params 參數 Map
|
||||
* @param contentType 內容類型
|
||||
* @return 請求體字符串
|
||||
*/
|
||||
public static String buildRequestBody(Map<String, Object> params, String contentType) {
|
||||
if (params == null || params.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
// 如果是 JSON 格式
|
||||
if (contentType != null && contentType.contains("application/json")) {
|
||||
// 使用 FastJSON 將 Map 轉換為 JSON 字符串
|
||||
return JSON.toJSONString(params);
|
||||
} else {
|
||||
// 默認使用 form-urlencoded 格式
|
||||
return buildQueryString(params);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
package com.mgm.mcrm.common.httpclient;
|
||||
|
||||
import com.mgm.mcrm.common.enums.HttpMethods;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.entity.mime.Header;
|
||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
||||
import org.apache.hc.core5.util.Timeout;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpRequestOptions {
|
||||
|
||||
private HttpRequestOptions(){};
|
||||
|
||||
/**
|
||||
* 获取实例
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public static HttpRequestOptions create(){
|
||||
return new HttpRequestOptions();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* HttpClient对象
|
||||
*/
|
||||
private HttpClient client;
|
||||
|
||||
/**
|
||||
* Header头信息
|
||||
*/
|
||||
private Header[] headers;
|
||||
|
||||
/**
|
||||
* 是否返回response的headers
|
||||
*/
|
||||
private boolean isReturnRespHeaders;
|
||||
|
||||
/**
|
||||
* 请求方法
|
||||
*/
|
||||
private HttpMethods method=HttpMethods.POST;
|
||||
|
||||
/**
|
||||
* 请求方法名称
|
||||
*/
|
||||
private String methodName;
|
||||
|
||||
/**
|
||||
* 用于cookie操作
|
||||
*/
|
||||
private HttpContext context;
|
||||
|
||||
// private Map<String, Object> map;
|
||||
|
||||
/**
|
||||
* 以json格式作为输入参数
|
||||
*/
|
||||
private String json;
|
||||
|
||||
/**
|
||||
* 输入输出编码
|
||||
*/
|
||||
private String encoding= Charset.defaultCharset().displayName();
|
||||
|
||||
/**
|
||||
* 输入编码
|
||||
*/
|
||||
private String inenc;
|
||||
|
||||
/**
|
||||
* 输出编码
|
||||
*/
|
||||
private String outenc;
|
||||
|
||||
/**
|
||||
* 设置RequestConfig
|
||||
*/
|
||||
private RequestConfig requestConfig;
|
||||
|
||||
/**
|
||||
* 解决多线程下载时,strean被close的问题
|
||||
*/
|
||||
private static final ThreadLocal<OutputStream> outs = new ThreadLocal<OutputStream>();
|
||||
|
||||
/**
|
||||
* 解决多线程处理时,url被覆盖问题
|
||||
*/
|
||||
private static final ThreadLocal<String> urls = new ThreadLocal<String>();
|
||||
|
||||
/**
|
||||
* 解决多线程处理时,url被覆盖问题
|
||||
*/
|
||||
private static final ThreadLocal<Map<String,Object>> maps = new ThreadLocal<Map<String,Object>>();
|
||||
|
||||
/**
|
||||
* @param client HttpClient对象
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions client(HttpClient client) {
|
||||
this.client = client;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param url 资源url
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions url(String url) {
|
||||
urls.set(url);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param headers Header头信息
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions headers(Header[] headers) {
|
||||
this.headers = headers;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Header头信息(是否返回response中的headers)
|
||||
*
|
||||
* @param headers Header头信息
|
||||
* @param isReturnRespHeaders 是否返回response中的headers
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions headers(Header[] headers, boolean isReturnRespHeaders) {
|
||||
this.headers = headers;
|
||||
this.isReturnRespHeaders=isReturnRespHeaders;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param method 请求方法
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions method(HttpMethods method) {
|
||||
this.method = method;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param methodName 请求方法
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions methodName(String methodName) {
|
||||
this.methodName = methodName;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param context cookie操作相关
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions context(HttpContext context) {
|
||||
this.context = context;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param map 传递参数
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions map(Map<String, Object> map) {
|
||||
// synchronized (getClass()) {
|
||||
// if(this.map==null || map==null){
|
||||
// this.map = map;
|
||||
// }else {
|
||||
// this.map.putAll(map);;
|
||||
// }
|
||||
// }
|
||||
Map<String, Object> m = maps.get();
|
||||
if(m == null || map.isEmpty()){
|
||||
m = map;
|
||||
}else {
|
||||
m.putAll(map);
|
||||
}
|
||||
maps.set(m);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param json 以json格式字符串作为参数
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions json(String json) {
|
||||
this.json = json;
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put(HttpEntityBuilder.ENTITY_JSON, json);
|
||||
maps.set(map);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param filePaths 待上传文件所在路径
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions files(String[] filePaths) {
|
||||
return files(filePaths, "file");
|
||||
}
|
||||
/**
|
||||
* 上传文件时用到
|
||||
* @param filePaths 待上传文件所在路径
|
||||
* @param inputName 即file input 标签的name值,默认为file
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions files(String[] filePaths, String inputName) {
|
||||
return files(filePaths, inputName, false);
|
||||
}
|
||||
/**
|
||||
* 上传文件时用到
|
||||
* @param filePaths 待上传文件所在路径
|
||||
* @param inputName 即file input 标签的name值,默认为file
|
||||
* @param forceRemoveContentTypeChraset 是否强制一处content-type中设置的编码类型
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions files(String[] filePaths, String inputName, boolean forceRemoveContentTypeChraset) {
|
||||
// synchronized (getClass()) {
|
||||
// if(this.map==null){
|
||||
// this.map= new HashMap<String, Object>();
|
||||
// }
|
||||
// }
|
||||
// map.put(Utils.ENTITY_MULTIPART, filePaths);
|
||||
// map.put(Utils.ENTITY_MULTIPART+".name", inputName);
|
||||
// map.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset);
|
||||
|
||||
Map<String, Object> m = maps.get();
|
||||
if(m.isEmpty()){
|
||||
m = new HashMap<String, Object>();
|
||||
}
|
||||
m.put(HttpEntityBuilder.ENTITY_MULTIPART, filePaths);
|
||||
m.put(HttpEntityBuilder.ENTITY_MULTIPART+".name", inputName);
|
||||
m.put(HttpEntityBuilder.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset);
|
||||
maps.set(m);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param encoding 输入输出编码
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions encoding(String encoding) {
|
||||
//设置输入输出
|
||||
inenc(encoding);
|
||||
outenc(encoding);
|
||||
this.encoding = encoding;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param inenc 输入编码
|
||||
*/
|
||||
public void inenc(String inenc) {
|
||||
this.inenc = inenc;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param outenc 输出编码
|
||||
*/
|
||||
public void outenc(String outenc) {
|
||||
this.outenc = outenc;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param out 输出流对象
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions out(OutputStream out) {
|
||||
outs.set(out);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置超时时间
|
||||
*
|
||||
* @param timeout 超市时间,单位-毫秒
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions timeout(int timeout){
|
||||
return timeout(timeout, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置超时时间以及是否允许网页重定向(自动跳转 302)
|
||||
*
|
||||
* @param timeout 超时时间,单位-毫秒
|
||||
* @param redirectEnable 自动跳转
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions timeout(int timeout, boolean redirectEnable){
|
||||
// 配置请求的超时设置
|
||||
// 注意:HttpClient 5 中需要使用 Timeout 对象,而不是直接的 int 值
|
||||
Timeout timeoutValue = Timeout.ofMilliseconds(timeout);
|
||||
RequestConfig config = RequestConfig.custom()
|
||||
.setConnectionRequestTimeout(timeoutValue)
|
||||
.setResponseTimeout(timeoutValue)
|
||||
.setRedirectsEnabled(redirectEnable)
|
||||
.build();
|
||||
return timeout(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置代理、超时时间、允许网页重定向等
|
||||
*
|
||||
* @param requestConfig 超时时间,单位-毫秒
|
||||
* @return 返回当前对象
|
||||
*/
|
||||
public HttpRequestOptions timeout(RequestConfig requestConfig){
|
||||
this.requestConfig = requestConfig;
|
||||
return this;
|
||||
}
|
||||
|
||||
public HttpClient client() {
|
||||
return client;
|
||||
}
|
||||
|
||||
public Header[] headers() {
|
||||
return headers;
|
||||
}
|
||||
public boolean isReturnRespHeaders() {
|
||||
return isReturnRespHeaders;
|
||||
}
|
||||
|
||||
public String url() {
|
||||
return urls.get();
|
||||
}
|
||||
|
||||
public HttpMethods method() {
|
||||
return method;
|
||||
}
|
||||
|
||||
public String methodName() {
|
||||
return methodName;
|
||||
}
|
||||
|
||||
public HttpContext context() {
|
||||
return context;
|
||||
}
|
||||
|
||||
public Map<String, Object> map() {
|
||||
// return map;
|
||||
return maps.get();
|
||||
}
|
||||
|
||||
public String json() {
|
||||
return json;
|
||||
}
|
||||
|
||||
public String encoding() {
|
||||
return encoding;
|
||||
}
|
||||
|
||||
public String inenc() {
|
||||
return inenc == null ? encoding : inenc;
|
||||
}
|
||||
|
||||
public String outenc() {
|
||||
return outenc == null ? encoding : outenc;
|
||||
}
|
||||
|
||||
public OutputStream out() {
|
||||
return outs.get();
|
||||
}
|
||||
|
||||
public RequestConfig requestConfig() {
|
||||
return requestConfig;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package com.mgm.mcrm.common.httpclient;
|
||||
|
||||
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.hc.core5.ssl.SSLContexts;
|
||||
|
||||
import javax.net.ssl.*;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.CertificateException;
|
||||
|
||||
/**
|
||||
* SSL 工具类(基于 HttpClient 5)
|
||||
*
|
||||
* 提供:
|
||||
* - 信任所有证书的 SSLSocketFactory
|
||||
* - 信任所有证书的 SSLConnectionSocketFactory
|
||||
*
|
||||
* 注意:默认实现信任所有证书,仅适用于内部系统或测试环境。
|
||||
*
|
||||
* @author Anka
|
||||
* @version 2.0 (client5)
|
||||
*/
|
||||
public class HttpSslSupport {
|
||||
private static final SSLHandler SIMPLE_VERIFIER = new SSLHandler();
|
||||
|
||||
private static SSLSocketFactory sslFactory;
|
||||
// 注意:SSLConnectionSocketFactory 在 HttpClient 5 中被标记为 deprecated,
|
||||
// 但这是目前唯一可用的方式,新的 API 尚未稳定
|
||||
@SuppressWarnings("deprecation")
|
||||
private static SSLConnectionSocketFactory sslConnFactory;
|
||||
|
||||
private static final HttpSslSupport INSTANCE = new HttpSslSupport();
|
||||
|
||||
private SSLContext sc;
|
||||
|
||||
public static HttpSslSupport getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public static HttpSslSupport custom() {
|
||||
return new HttpSslSupport();
|
||||
}
|
||||
|
||||
/**
|
||||
* 重写 X509TrustManager 和 HostnameVerifier,信任所有证书与主机名。
|
||||
* 仅推荐在内部环境或调试场景使用。
|
||||
*/
|
||||
private static class SSLHandler implements X509TrustManager, HostnameVerifier {
|
||||
|
||||
@Override
|
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||||
return new java.security.cert.X509Certificate[]{};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(java.security.cert.X509Certificate[] chain,
|
||||
String authType) throws CertificateException {
|
||||
// 信任所有服务器证书
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkClientTrusted(java.security.cert.X509Certificate[] chain,
|
||||
String authType) throws CertificateException {
|
||||
// 信任所有客户端证书
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(String paramString, SSLSession paramSSLSession) {
|
||||
// 信任所有主机名
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取默认 HostnameVerifier(信任所有主机名)
|
||||
*/
|
||||
public static HostnameVerifier getVerifier() {
|
||||
return SIMPLE_VERIFIER;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取信任所有证书的 {@link SSLSocketFactory}
|
||||
*/
|
||||
public synchronized SSLSocketFactory getSSLSF(SSLProtocolVersion sslpv) {
|
||||
if (sslFactory != null) {
|
||||
return sslFactory;
|
||||
}
|
||||
try {
|
||||
SSLContext context = getSSLContext(sslpv);
|
||||
context.init(null, new TrustManager[]{SIMPLE_VERIFIER}, null);
|
||||
sslFactory = context.getSocketFactory();
|
||||
return sslFactory;
|
||||
} catch (KeyManagementException e) {
|
||||
throw new RuntimeException("初始化 SSLSocketFactory 失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取信任所有证书的 {@link SSLConnectionSocketFactory}(HttpClient5)
|
||||
*
|
||||
* 注意:SSLConnectionSocketFactory 在 HttpClient 5 中被标记为 deprecated,
|
||||
* 但这是目前唯一可用的方式,新的 API 尚未稳定
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public synchronized SSLConnectionSocketFactory getSSLCONNSF(SSLProtocolVersion sslpv) {
|
||||
if (sslConnFactory != null) {
|
||||
return sslConnFactory;
|
||||
}
|
||||
try {
|
||||
SSLContext context = getSSLContext(sslpv);
|
||||
context.init(null, new TrustManager[]{SIMPLE_VERIFIER}, new java.security.SecureRandom());
|
||||
sslConnFactory = new SSLConnectionSocketFactory(context, SIMPLE_VERIFIER);
|
||||
return sslConnFactory;
|
||||
} catch (KeyManagementException e) {
|
||||
throw new RuntimeException("初始化 SSLConnectionSocketFactory 失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用自定义证书(trustStore)初始化 SSLContext
|
||||
*/
|
||||
public HttpSslSupport customSSL(String keyStorePath, String keyStorepass) {
|
||||
FileInputStream instream = null;
|
||||
try {
|
||||
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||
instream = new FileInputStream(new File(keyStorePath));
|
||||
trustStore.load(instream, keyStorepass.toCharArray());
|
||||
// 相信自己的 CA 和所有自签名证书
|
||||
this.sc = SSLContexts.custom()
|
||||
.loadTrustMaterial(trustStore, (chain, authType) -> true)
|
||||
.build();
|
||||
return this;
|
||||
} catch (KeyManagementException | KeyStoreException |
|
||||
NoSuchAlgorithmException | CertificateException | IOException e) {
|
||||
throw new RuntimeException("初始化自定义 SSLContext 失败", e);
|
||||
} finally {
|
||||
if (instream != null) {
|
||||
try {
|
||||
instream.close();
|
||||
} catch (IOException ignore) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取(或创建)指定协议版本的 {@link SSLContext}
|
||||
*/
|
||||
public SSLContext getSSLContext(SSLProtocolVersion sslpv) {
|
||||
try {
|
||||
if (this.sc == null) {
|
||||
this.sc = SSLContext.getInstance(sslpv.getName());
|
||||
}
|
||||
return this.sc;
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException("不支持的 SSL 协议版本: " + sslpv.getName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 支持的 SSL/TLS 协议版本枚举
|
||||
*/
|
||||
public enum SSLProtocolVersion {
|
||||
SSL("SSL"),
|
||||
SSLv3("SSLv3"),
|
||||
TLSv1("TLSv1"),
|
||||
TLSv1_1("TLSv1.1"),
|
||||
TLSv1_2("TLSv1.2"),
|
||||
TLSv1_3("TLSv1.3");
|
||||
|
||||
private final String name;
|
||||
|
||||
SSLProtocolVersion(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public static SSLProtocolVersion find(String name) {
|
||||
for (SSLProtocolVersion pv : SSLProtocolVersion.values()) {
|
||||
if (pv.getName().equalsIgnoreCase(name)) {
|
||||
return pv;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("未支持当前 SSL 版本号:" + name);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.mgm.mcrm.common.interceptor;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import com.mgm.mcrm.common.dtos.BaseApiResponse;
|
||||
import jakarta.annotation.Resource;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.Signature;
|
||||
import org.aspectj.lang.annotation.AfterReturning;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import com.mgm.mcrm.common.constants.SysCommon;
|
||||
import com.mgm.mcrm.common.annotation.logging.OperationLog;
|
||||
import com.mgm.mcrm.logging.models.SysLogOperation;
|
||||
import com.mgm.mcrm.logging.models.SysLogLogin;
|
||||
import com.mgm.mcrm.logging.services.SysLogOperationService;
|
||||
import com.mgm.mcrm.logging.services.SysLogLoginService;
|
||||
import com.mgm.mcrm.common.utils.LogUtil;
|
||||
|
||||
@Aspect // 表示一个切面bean
|
||||
@Component // bean容器的组件注解。虽然放在contrller包里,但它不是控制器。如果注入service,但我们又没有放在service包里
|
||||
@Order(3) // 有多个日志时,ORDER可以定义切面的执行顺序(数字越大,前置越后执行,后置越前执行)
|
||||
public class ControllerLogAspector {
|
||||
@Resource
|
||||
private SysLogOperationService sysLogOperationService;
|
||||
@Resource
|
||||
private SysLogLoginService sysLogLoginService;
|
||||
//定义切入点
|
||||
/*1、execution 表达式主体
|
||||
2、第1个* 表示返回值类型 *表示所有类型
|
||||
3、包名 com.*.*.controller下
|
||||
4、第4个* 类名,com.*.*.controller包下所有类
|
||||
5、第5个* 方法名,com.*.*.controller包下所有类所有方法
|
||||
6、(..) 表示方法参数,..表示任何参数
|
||||
*/
|
||||
@Pointcut("execution(public * com.mgm.mcrm..*.*Controller.*(..))")
|
||||
public void ControllerLog() {
|
||||
|
||||
}
|
||||
|
||||
@Before("ControllerLog()")
|
||||
public void doBefore(JoinPoint joinPoint) {
|
||||
}
|
||||
|
||||
@AfterReturning(returning="returnObject", pointcut= "ControllerLog()")
|
||||
public void doAfterReturn(JoinPoint joinPoint, Object returnObject) {
|
||||
try {
|
||||
//--獲得調用的方法以及參數類型
|
||||
Signature invokeSignature = joinPoint.getSignature();
|
||||
String methodName = invokeSignature.getName();
|
||||
Class[] parameterTypes = ((MethodSignature)invokeSignature).getMethod().getParameterTypes();
|
||||
Method invokeMmethod = invokeSignature.getDeclaringType().getMethod(methodName,parameterTypes);
|
||||
boolean isLogController = invokeMmethod.isAnnotationPresent(OperationLog.class);
|
||||
//--檢測到需要寫DBLog的注釋
|
||||
if(isLogController) {
|
||||
OperationLog operLogTag = invokeMmethod.getAnnotation(OperationLog.class);
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
Object invokeObject=null;
|
||||
Object resultObject=null;
|
||||
Object oldDataObject = null;
|
||||
boolean isRunSuccess=true;
|
||||
String sLogMessage = "";
|
||||
if(returnObject instanceof BaseApiResponse processResult) {
|
||||
isRunSuccess = processResult.isSuccess();
|
||||
invokeObject = processResult.getRequestData();
|
||||
resultObject = processResult.getData();
|
||||
oldDataObject = processResult.getRequestData();
|
||||
sLogMessage = processResult.getLogMessage();
|
||||
}else {
|
||||
resultObject = returnObject;
|
||||
}
|
||||
if(invokeObject==null) {
|
||||
invokeObject = request.getParameterMap();
|
||||
}
|
||||
if(!SysCommon.dbDebugLog) {
|
||||
invokeObject = null;
|
||||
resultObject = null;
|
||||
oldDataObject = null;
|
||||
}
|
||||
int successFlag = 1;
|
||||
if(!isRunSuccess) {
|
||||
successFlag = 0;
|
||||
}
|
||||
// 如果log有内容,則寫入DB log
|
||||
if(StringUtils.isNotBlank(sLogMessage)) {
|
||||
if("login".equalsIgnoreCase(operLogTag.actionName())) {
|
||||
SysLogLogin logLogin = SysCommon.createLogLoginByRequest(request, operLogTag.eventCode(),invokeObject,resultObject,sLogMessage,successFlag,oldDataObject);
|
||||
sysLogLoginService.save(logLogin);
|
||||
}else {
|
||||
SysLogOperation logOperation = SysCommon.createLogOperationByRequest(request, operLogTag.eventCode(),invokeObject,resultObject,sLogMessage,successFlag,oldDataObject);
|
||||
sysLogOperationService.save(logOperation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ControllerLogAspector.class, "[ControllerLogAspector][doAfterReturn] " + err.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@AfterReturning("ControllerLog()")
|
||||
public void doAfter(JoinPoint joinPoint) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.mgm.mcrm.common.jms;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.springframework.jms.annotation.JmsListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
|
||||
import com.mgm.mcrm.common.constants.SysCommon;
|
||||
import com.mgm.mcrm.common.dtos.msg.AppSettingMsgData;
|
||||
import com.mgm.mcrm.common.dtos.msg.JMSTextMessage;
|
||||
import com.mgm.mcrm.common.dtos.system.AppServerState;
|
||||
import com.mgm.mcrm.common.services.SysServerStateService;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AppControlMsgConsumer {
|
||||
@Resource
|
||||
private SysServerStateService serverStateService;
|
||||
|
||||
@JmsListener(destination = "${app_ctrl_topic}", containerFactory = "jmsTopicListenerCF")
|
||||
public void receive(String msg){
|
||||
JMSTextMessage msgObject = null;
|
||||
|
||||
try {
|
||||
|
||||
msgObject = JSONObject.parseObject(msg, JMSTextMessage.class);
|
||||
|
||||
if(Strings.CS.equals("SYNC_SERVER_STATE", msgObject.getMsgType())) {
|
||||
|
||||
AppServerState serverInfo =
|
||||
JSONObject.parseObject(msgObject.getMsgContent(), AppServerState.class);
|
||||
|
||||
if(serverInfo != null) {
|
||||
SysCommon.registerServerInfo(serverInfo);
|
||||
}
|
||||
|
||||
} else if(Strings.CS.equals("UPD_MOBILE_CFG", msgObject.getMsgType())) {
|
||||
|
||||
AppSettingMsgData updateRequest =
|
||||
JSONObject.parseObject(msgObject.getMsgContent(), AppSettingMsgData.class);
|
||||
|
||||
serverStateService.updateCfgByRequest(updateRequest);
|
||||
|
||||
} else if(Strings.CS.equals("REQ_SYNC_SERVER_STATE", msgObject.getMsgType())) {
|
||||
|
||||
serverStateService.notifyCurrentState();
|
||||
}
|
||||
|
||||
} catch(Exception err) {
|
||||
|
||||
log.error("Process JMS message failed. msgType={}, message={}", msgObject != null ? msgObject.getMsgType() : "UNKNOWN", msg, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.mgm.mcrm.common.jms;
|
||||
|
||||
import org.apache.activemq.command.ActiveMQTopic;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jms.core.JmsTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
|
||||
import com.mgm.mcrm.common.dtos.msg.JMSTextMessage;
|
||||
import com.mgm.mcrm.common.utils.LogUtil;
|
||||
|
||||
@Component
|
||||
public class AppControlMsgSender {
|
||||
|
||||
@Value("${app_ctrl_topic}")
|
||||
private String ctrlTopicName;
|
||||
private ActiveMQTopic ctrlTopic=null;
|
||||
|
||||
@Autowired
|
||||
private JmsTemplate jmsTemplate;
|
||||
|
||||
private ActiveMQTopic getTopic() {
|
||||
return this.ctrlTopic==null?new ActiveMQTopic(ctrlTopicName):this.ctrlTopic;
|
||||
}
|
||||
|
||||
public void sendMessage(String message) {
|
||||
jmsTemplate.convertAndSend(getTopic(), message);
|
||||
}
|
||||
|
||||
public boolean sendMessage(String msgType, Object msgData) {
|
||||
boolean result =false;
|
||||
try {
|
||||
JMSTextMessage msg = new JMSTextMessage();
|
||||
msg.setMsgType(msgType);
|
||||
msg.setMsgContent(msgData==null?"":JSON.toJSONString(msgData));
|
||||
String message = JSON.toJSONString(msg);
|
||||
jmsTemplate.convertAndSend(getTopic(), message);
|
||||
result=true;
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(AppControlMsgSender.class, "Send JMS Failed:"+err.getMessage());
|
||||
result=false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.mgm.mcrm.common.jms;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.mgm.mcrm.booking.dtos.BookingDto;
|
||||
import com.mgm.mcrm.booking.models.Bookings;
|
||||
import jakarta.annotation.Resource;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.jms.annotation.JmsListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
|
||||
import com.mgm.mcrm.booking.repositories.BookingDao;
|
||||
import com.mgm.mcrm.common.dtos.msg.JMSTextMessage;
|
||||
import com.mgm.mcrm.booking.services.BookingService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class BookingControlMsgConsumer {
|
||||
@Resource
|
||||
private BookingService bookingService;
|
||||
@Resource
|
||||
private BookingDao bookingDao;
|
||||
|
||||
@JmsListener(destination = "${book_ctrl_queue}", containerFactory = "jmsQueueListenerCF")
|
||||
public void receive(String msg){
|
||||
|
||||
JMSTextMessage msgObject = null;
|
||||
|
||||
try {
|
||||
|
||||
msgObject = JSONObject.parseObject(msg, JMSTextMessage.class);
|
||||
|
||||
String msgType = msgObject.getMsgType();
|
||||
if("CREATE_DAYLIGHT_BOOKING".equals(msgType)) {
|
||||
Bookings booking =
|
||||
JSONObject.parseObject(msgObject.getMsgContent(), Bookings.class);
|
||||
bookingService.callDaylightUpsertReservation(
|
||||
booking,
|
||||
"CREATE_BOOKING"
|
||||
);
|
||||
} else if("CREATE_OPERA_BOOKING".equals(msgType)) {
|
||||
Bookings booking =
|
||||
JSONObject.parseObject(msgObject.getMsgContent(), Bookings.class);
|
||||
|
||||
bookingService.callOWSCreateBooking(booking);
|
||||
} else if("EDIT_BOOKING".equals(msgType)) {
|
||||
Bookings booking =
|
||||
JSONObject.parseObject(msgObject.getMsgContent(), Bookings.class);
|
||||
bookingService.callOWSEditBooking(booking);
|
||||
} else if("WAITLIST_BOOKING".equals(msgType)) {
|
||||
bookingService.finishWaitlistBooking();
|
||||
} else if("SYNC_MERGE_BOOKING".equals(msgType)) {
|
||||
|
||||
List<BookingDto> syncBookings = null;
|
||||
try {
|
||||
syncBookings =
|
||||
JSON.parseArray(
|
||||
msgObject.getMsgContent(),
|
||||
BookingDto.class
|
||||
);
|
||||
} catch(Exception err){
|
||||
log.error("Convert sync booking data error", err);
|
||||
}
|
||||
|
||||
bookingService.updateMergeBookingToDb_Optimize(syncBookings);
|
||||
}
|
||||
} catch(Exception err) {
|
||||
|
||||
try {
|
||||
if(msgObject != null
|
||||
&& "CREATE_DAYLIGHT_BOOKING".equals(msgObject.getMsgType())) {
|
||||
|
||||
Bookings booking =
|
||||
JSONObject.parseObject(
|
||||
msgObject.getMsgContent(),
|
||||
Bookings.class
|
||||
);
|
||||
|
||||
bookingDao.updateProcessStatus(
|
||||
booking.getId(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
} catch(Exception updateErr){
|
||||
|
||||
log.error("Update booking process status failed", updateErr);
|
||||
}
|
||||
|
||||
log.error("Process booking JMS message failed. msgType={}, message={}", msgObject != null ? msgObject.getMsgType() : "UNKNOWN", msg, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.mgm.mcrm.common.jms;
|
||||
|
||||
import org.apache.activemq.command.ActiveMQQueue;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jms.core.JmsTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
|
||||
import com.mgm.mcrm.common.dtos.msg.JMSTextMessage;
|
||||
import com.mgm.mcrm.common.utils.LogUtil;
|
||||
|
||||
@Component
|
||||
public class BookingControlMsgSender {
|
||||
|
||||
@Value("${book_ctrl_queue}")
|
||||
private String ctrlQueueName;
|
||||
|
||||
private ActiveMQQueue ctrlQueue = null;
|
||||
|
||||
@Autowired
|
||||
private JmsTemplate jmsTemplate;
|
||||
|
||||
private ActiveMQQueue getQueue() {
|
||||
if (ctrlQueue == null) {
|
||||
ctrlQueue = new ActiveMQQueue(ctrlQueueName);
|
||||
}
|
||||
return ctrlQueue;
|
||||
}
|
||||
|
||||
public void sendMessage(String message) {
|
||||
jmsTemplate.convertAndSend(getQueue(), message);
|
||||
}
|
||||
|
||||
public boolean sendMessage(String msgType, Object msgData) {
|
||||
|
||||
try {
|
||||
JMSTextMessage msg = new JMSTextMessage();
|
||||
msg.setMsgType(msgType);
|
||||
msg.setMsgContent(msgData == null ? "" : JSON.toJSONString(msgData));
|
||||
String message = JSON.toJSONString(msg);
|
||||
jmsTemplate.convertAndSend(getQueue(), message);
|
||||
return true;
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(BookingControlMsgSender.class, "Send JMS Failed:" + err.getMessage());
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.mgm.mcrm.common.listener;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.context.event.ApplicationStartedEvent;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.mgm.mcrm.common.constants.SysCommon;
|
||||
import com.mgm.mcrm.common.jms.AppControlMsgSender;
|
||||
import com.mgm.mcrm.appsetting.models.SysSetting;
|
||||
import com.mgm.mcrm.common.dtos.system.AppServerState;
|
||||
import com.mgm.mcrm.appsetting.services.SysSettingService;
|
||||
import com.mgm.mcrm.common.utils.ExcelUtils;
|
||||
import com.mgm.mcrm.common.utils.NetworkUtil;
|
||||
|
||||
@Component
|
||||
public class ConfigListener implements ApplicationListener<ApplicationStartedEvent> {
|
||||
@Value("${internal_network_pattern}")
|
||||
private String internalIpPattern;
|
||||
@Value("${allow_origin}")
|
||||
private String allowOrigins;
|
||||
@Value("${soap_servers}")
|
||||
private String soapServers;
|
||||
@Value("${http_api_servers}")
|
||||
private String httpApiServers;
|
||||
@Value("${allow_ip}")
|
||||
private String allowIP;
|
||||
@Resource
|
||||
private SysSettingService sysSettingService;
|
||||
@Autowired
|
||||
private AppControlMsgSender ctrlMsgSender;
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(ApplicationStartedEvent event) {
|
||||
|
||||
MessageSource i18nMessage = (MessageSource)event.getApplicationContext().getBean("messageSource");
|
||||
SysCommon.setMessageSource(i18nMessage);
|
||||
SysCommon.initRuntimePath();
|
||||
SysCommon.loadSystemConfig();
|
||||
// load settings from DB
|
||||
List<SysSetting> sysSettings = sysSettingService.getSysSettingsAll();
|
||||
SysCommon.loadSettingsFromDB(sysSettings);
|
||||
SysCommon.loadSecurityConfig(allowOrigins);
|
||||
SysCommon.loadSoapServerConfig(soapServers);
|
||||
SysCommon.loadApiServerConfig(httpApiServers);
|
||||
SysCommon.loadAllowIPConfig(allowIP);
|
||||
ExcelUtils.loadExcelDefines();
|
||||
if(ctrlMsgSender!=null) {
|
||||
AppServerState serverState = SysCommon.refreshAppServerState();
|
||||
SysCommon.jmsRunning = ctrlMsgSender.sendMessage("REQ_SYNC_SERVER_STATE",serverState);
|
||||
}
|
||||
NetworkUtil.setInternalIpPattern(internalIpPattern);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.mgm.mcrm.common.schedule;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.mgm.mcrm.common.constants.SysCommon;
|
||||
import com.mgm.mcrm.common.services.SysServerStateService;
|
||||
|
||||
@Component
|
||||
public class AppSystemScheduleJob {
|
||||
|
||||
@Autowired
|
||||
private SysServerStateService serverStateService;
|
||||
|
||||
@Scheduled(fixedDelay = 60000)
|
||||
public void notifyServerState() {
|
||||
try {
|
||||
if(StringUtils.isNotBlank(SysCommon.serverIp)) {
|
||||
serverStateService.notifyCurrentState();
|
||||
}
|
||||
}catch(Exception err) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.mgm.mcrm.common.schedule;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import com.mgm.mcrm.appsetting.models.CfgSettings;
|
||||
import com.mgm.mcrm.booking.models.Bookings;
|
||||
import com.mgm.mcrm.booking.models.GamingData;
|
||||
import com.mgm.mcrm.booking.services.BookingService;
|
||||
import jakarta.annotation.Resource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.mgm.mcrm.booking.repositories.BookingDao;
|
||||
import com.mgm.mcrm.booking.repositories.GamingDataDao;
|
||||
import com.mgm.mcrm.common.jms.BookingControlMsgSender;
|
||||
//import com.mgm.mcrm.booking.services.BookingService;
|
||||
import com.mgm.mcrm.notification.services.EmailTemplateService;
|
||||
import com.mgm.mcrm.appsetting.services.SettingService;
|
||||
import com.mgm.mcrm.booking.services.WaitlistBookingService;
|
||||
import com.mgm.mcrm.common.utils.DateTimeUtil;
|
||||
|
||||
@Component
|
||||
public class BookingScheduleJob {
|
||||
@Autowired
|
||||
private BookingControlMsgSender ctrlMsgSender;
|
||||
@Resource
|
||||
private WaitlistBookingService waitlistBookingService;
|
||||
@Resource
|
||||
private SettingService settingService;
|
||||
@Resource
|
||||
private BookingService bookingService;
|
||||
|
||||
@Scheduled(fixedDelay = 300000)
|
||||
public void expiryWaitlistBooking() {
|
||||
try {
|
||||
CfgSettings cutoffStartTime = settingService.getSettingByKey("VIEW_YESTERDAY_TODOLIST_START");
|
||||
String cutoffStartTimeValue = cutoffStartTime.getKeyValues();
|
||||
CfgSettings cutoffEndTime = settingService.getSettingByKey("VIEW_YESTERDAY_TODOLIST_END");
|
||||
String cutoffEndTimeValue = cutoffEndTime.getKeyValues();
|
||||
Date curoffDate = DateTimeUtil.getTodoYesterdayDay(cutoffStartTimeValue, cutoffEndTimeValue);
|
||||
Date currentDate = DateTimeUtil.getCurrentDateTime("yyyy-MM-dd");
|
||||
|
||||
if(curoffDate.getTime() == currentDate.getTime()) {
|
||||
List<Bookings> bookList = waitlistBookingService.getExpiryWaitlistBooking();
|
||||
while(!bookList.isEmpty()) {
|
||||
Bookings book = bookList.getFirst();
|
||||
waitlistBookingService.expiryWaitlistBooking(book);
|
||||
bookList = waitlistBookingService.getExpiryWaitlistBooking();
|
||||
}
|
||||
|
||||
}
|
||||
}catch(Exception err) {
|
||||
err.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 120000)
|
||||
public void syncGamingData() {
|
||||
try {
|
||||
List<Bookings> bookings = waitlistBookingService.getPendingWaitlistBooking();
|
||||
if(bookings.size()>0) {
|
||||
ArrayList bookIds = new ArrayList();
|
||||
for(Bookings b:bookings) {
|
||||
List <GamingData> getGaming = waitlistBookingService.findGamingDataByBookId(b.getId());
|
||||
if(getGaming==null||getGaming.size()==0) {
|
||||
bookIds.add(String.valueOf(b.getId()));
|
||||
}
|
||||
}
|
||||
if(bookIds.size()>0) {
|
||||
String bookId = String.join(";", bookIds);
|
||||
List<GamingData> gamingData = waitlistBookingService.syncWaitlistData(bookId);
|
||||
}
|
||||
}
|
||||
|
||||
}catch(Exception err) {
|
||||
err.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 3000)
|
||||
public void finishFailedBooking() {
|
||||
try {
|
||||
List<Bookings> bookings = bookingService.getFailedBooking();
|
||||
while(!bookings.isEmpty()) {
|
||||
Bookings book = bookings.getFirst();
|
||||
int res = bookingService.updateProcessStatus(book.getId());
|
||||
if(res>0) {
|
||||
if(book.getRevisionOf()!=null) {
|
||||
ctrlMsgSender.sendMessage("EDIT_BOOKING", book);
|
||||
}else {
|
||||
if("DAYLIGHT".equals(book.getCategory())) {
|
||||
ctrlMsgSender.sendMessage("CREATE_DAYLIGHT_BOOKING", book);
|
||||
}else{
|
||||
ctrlMsgSender.sendMessage("CREATE_OPERA_BOOKING", book);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
bookings = bookingService.getFailedBooking();
|
||||
}
|
||||
}catch(Exception err) {
|
||||
err.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package com.mgm.mcrm.common.services;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.mgm.mcrm.common.dtos.HttpResult;
|
||||
import com.mgm.mcrm.common.enums.HttpMethods;
|
||||
import com.mgm.mcrm.common.httpclient.HttpClientExecutor;
|
||||
import com.mgm.mcrm.common.httpclient.HttpRequestOptions;
|
||||
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.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.Map;
|
||||
|
||||
/**
|
||||
* 請求服務
|
||||
*
|
||||
* @author Aaka
|
||||
*/
|
||||
@Service
|
||||
public class HttpService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(HttpService.class);
|
||||
|
||||
|
||||
@Resource
|
||||
@Qualifier("httpClientWithSSL")
|
||||
private CloseableHttpClient httpClient;
|
||||
|
||||
@Resource
|
||||
@Qualifier("httpRequestConfig")
|
||||
private RequestConfig requestConfig;
|
||||
|
||||
@Value("${daylight.url}")
|
||||
private String daylightUrl;
|
||||
|
||||
public String sslGet(String url, Header[] headers, Map<String, Object> map) throws Exception {
|
||||
|
||||
// todo 在這裏需要把請求頭的信息插入到數據庫裏
|
||||
log.info("======sslGet======url:{}===========headers:{} =============== map:{}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(map));
|
||||
// 使用 HttpConfig 配置 GET 请求(带参数)
|
||||
HttpRequestOptions getConfig = HttpRequestOptions.create()
|
||||
.url(daylightUrl + url)
|
||||
.timeout(requestConfig)
|
||||
.map(map)
|
||||
.encoding("utf-8")
|
||||
.client(httpClient);
|
||||
|
||||
String result = HttpClientExecutor.get(getConfig, headers);
|
||||
log.info("====== GET request result:{}", result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String sslGetNoLog(String url, Header[] headers, Map<String, Object> map) throws Exception {
|
||||
|
||||
// todo 在這裏需要把請求頭的信息插入到數據庫裏
|
||||
log.info("======sslGet======url:{}===========headers:{} =============== map:{}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(map));
|
||||
// 使用 HttpConfig 配置 GET 请求(带参数)
|
||||
HttpRequestOptions getConfig = HttpRequestOptions.create()
|
||||
.url(daylightUrl + url)
|
||||
.timeout(requestConfig)
|
||||
.map(map)
|
||||
.encoding("utf-8")
|
||||
.client(httpClient);
|
||||
|
||||
String result = HttpClientExecutor.get(getConfig, headers);
|
||||
log.info("====== GET request result size={}", result.length());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public HttpResult sslGetHttpResult(String url, Header[] headers, Map<String, Object> map) throws Exception {
|
||||
|
||||
// todo 在這裏需要把請求頭的信息插入到數據庫裏
|
||||
log.info("======sslGet======url:{}===========headers:{} =============== map:{}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(map));
|
||||
// 使用 HttpConfig 配置 GET 请求(带参数)
|
||||
HttpRequestOptions getConfig = HttpRequestOptions.create()
|
||||
.url(daylightUrl + url)
|
||||
.timeout(requestConfig)
|
||||
.map(map)
|
||||
.encoding("utf-8")
|
||||
.client(httpClient);
|
||||
|
||||
HttpResult result = HttpClientExecutor.sendAndGetResp(getConfig, headers);
|
||||
log.info("====== GET request result:{}", result.getResult());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 HttpConfig 配置 PUT 请求
|
||||
*
|
||||
* @param url 請求路徑
|
||||
* @param headers 請求頭
|
||||
* @param map 請求參數
|
||||
* @return 接口結果的json數據
|
||||
* @throws Exception 異常
|
||||
*/
|
||||
public String sslPut(String url, Header[] headers, Map<String, Object> map) throws Exception {
|
||||
log.info("======sslPut======url:{}===========headers:{} =============== map:{}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(map));
|
||||
HttpRequestOptions putConfig = HttpRequestOptions.create()
|
||||
.url(daylightUrl + url)
|
||||
.timeout(requestConfig)
|
||||
.method(HttpMethods.PUT)
|
||||
.json(JSON.toJSONString(map))
|
||||
.encoding("utf-8")
|
||||
.client(httpClient);
|
||||
String result = HttpClientExecutor.send(putConfig, headers);
|
||||
log.info("====== PUT request result:{}", result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 HttpConfig 配置 Delete 请求
|
||||
*
|
||||
* @param url 請求路徑
|
||||
* @param headers 請求頭
|
||||
* @param requestBody 請求參數
|
||||
* @return 接口結果的json數據
|
||||
* @throws Exception 異常
|
||||
*/
|
||||
public String sslDelete(String url, Header[] headers, Object requestBody) throws Exception {
|
||||
log.info("======sslDelete======url:{}===========headers:{} =============== map:{}", daylightUrl + url, JSON.toJSONString(headers), JSON.toJSONString(requestBody));
|
||||
HttpRequestOptions deleteConfig = HttpRequestOptions.create()
|
||||
.url(daylightUrl + url)
|
||||
.timeout(requestConfig)
|
||||
.json(JSON.toJSONString(requestBody))
|
||||
.method(HttpMethods.DELETE)
|
||||
.client(httpClient);
|
||||
String result = HttpClientExecutor.send(deleteConfig, headers);
|
||||
log.info("====== DELETE request result:{}", result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 HttpConfig 配置 Post 请求
|
||||
*
|
||||
* @param url 請求路徑
|
||||
* @param headers 請求頭
|
||||
* @param requestBody request 数据
|
||||
* @return 接口結果的json數據
|
||||
* @throws Exception 異常
|
||||
*/
|
||||
public HttpResult sslPost(String url, Header[] headers, Object requestBody) throws Exception {
|
||||
log.info("======sslCreatePost======url:{}===========headers:{}", daylightUrl + url, JSON.toJSONString(headers));
|
||||
HttpRequestOptions postConfig = HttpRequestOptions.create()
|
||||
.url(daylightUrl + url)
|
||||
.timeout(requestConfig)
|
||||
.json(JSON.toJSONString(requestBody))
|
||||
.method(HttpMethods.POST)
|
||||
.client(httpClient);
|
||||
HttpResult result = HttpClientExecutor.sendAndPostResp(postConfig, headers);
|
||||
// System.out.println("POST 请求结果:\n" + result);
|
||||
log.info("====== POST request result:{}", result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 HttpConfig 配置 PATCH 请求(JSON 请求体)
|
||||
*
|
||||
* @param url 請求路徑
|
||||
* @param headers 請求頭
|
||||
* @param requestBody request 数据
|
||||
* @return 接口結果的json數據
|
||||
* @throws Exception 異常
|
||||
*/
|
||||
public HttpResult sslPatch(String url, Header[] headers, Object requestBody) throws Exception {
|
||||
log.info("======sslCreatePatch======url:{}===========headers:{}", daylightUrl + url, JSON.toJSONString(headers));
|
||||
HttpRequestOptions patchConfig = HttpRequestOptions.create()
|
||||
.url(daylightUrl + url)
|
||||
.timeout(requestConfig)
|
||||
.json(JSON.toJSONString(requestBody))
|
||||
.method(HttpMethods.PATCH)
|
||||
.encoding("utf-8")
|
||||
.client(httpClient);
|
||||
HttpResult result = HttpClientExecutor.sendAndPatchResp(patchConfig, headers);
|
||||
log.info("====== PATCH request result:{}", result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 HttpConfig 配置 Delete 请求
|
||||
*
|
||||
* @param url 請求路徑
|
||||
* @param headers 請求頭
|
||||
* @param map Cancel数据
|
||||
* @return 接口結果的json數據
|
||||
* @throws Exception 異常
|
||||
*/
|
||||
public HttpResult sslCancelPost(String url, Header[] headers, Map<String, Object> map) throws Exception {
|
||||
log.info("======sslCancelPost======url:{}===========headers:{}", daylightUrl + url, JSON.toJSONString(headers));
|
||||
HttpRequestOptions postConfig = HttpRequestOptions.create()
|
||||
.url(daylightUrl + url)
|
||||
.timeout(requestConfig)
|
||||
.json(JSON.toJSONString(map))
|
||||
.method(HttpMethods.POST)
|
||||
.client(httpClient);
|
||||
HttpResult result = HttpClientExecutor.sendAndPostResp(postConfig, headers);
|
||||
// System.out.println("POST 请求结果:\n" + result);
|
||||
log.info("====== POST request result:{}", result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
package com.mgm.mcrm.common.services;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.mgm.mcrm.basesetting.property.dtos.response.TokenResponse;
|
||||
import com.mgm.mcrm.common.dtos.CachedToken;
|
||||
import com.mgm.mcrm.common.dtos.HttpResult;
|
||||
import com.mgm.mcrm.common.enums.HttpMethods;
|
||||
import com.mgm.mcrm.common.httpclient.HttpClientExecutor;
|
||||
import com.mgm.mcrm.common.httpclient.HttpRequestOptions;
|
||||
import com.mgm.mcrm.common.httpclient.HttpHeaderBuilder;
|
||||
import com.mgm.mcrm.common.httpclient.HttpSslSupport;
|
||||
import com.mgm.mcrm.common.utils.LogUtil;
|
||||
import jakarta.annotation.Resource;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
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.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class HttpTokenService {
|
||||
@Resource
|
||||
private HttpService httpService;
|
||||
|
||||
@Resource
|
||||
@Qualifier("httpClientWithSSL")
|
||||
private CloseableHttpClient httpClient;
|
||||
|
||||
@Resource
|
||||
@Qualifier("httpRequestConfig")
|
||||
private RequestConfig requestConfig;
|
||||
|
||||
@Value("${token.url}")
|
||||
private String tokenUrl;
|
||||
|
||||
@Value("${token.username}")
|
||||
private String username;
|
||||
|
||||
@Value("${token.password}")
|
||||
private String password;
|
||||
|
||||
@Value("${token.grant-type}")
|
||||
private String grantType;
|
||||
|
||||
@Value("${token.client-id}")
|
||||
private String clientId;
|
||||
|
||||
@Value("${token.client-secret}")
|
||||
private String clientSecret;
|
||||
|
||||
// Token 缓存,key 为 url,value 为缓存的 token 信息
|
||||
private final ConcurrentHashMap<String, CachedToken> tokenCache = new ConcurrentHashMap<>();
|
||||
|
||||
// Token 过期时间:800 毫秒
|
||||
private static final long TOKEN_EXPIRE_TIME_MS = 80000;
|
||||
// 重试间隔时间:1秒
|
||||
private static final long RETRY_DELAY_MS = 1000;
|
||||
|
||||
public TokenResponse getToken() throws Exception {
|
||||
String url = "/connect/token";
|
||||
// 1. 先检查缓存
|
||||
CachedToken cachedToken = tokenCache.get(url);
|
||||
|
||||
if (cachedToken != null && !cachedToken.isExpired()) {
|
||||
// 缓存未过期,直接返回
|
||||
LogUtil.info(HttpTokenService.class, "=========get token from cache"+cachedToken.getToken());
|
||||
return cachedToken.getToken();
|
||||
}
|
||||
if (cachedToken != null && cachedToken.isExpired()) {
|
||||
// 緩存過期,重新获取 token(使用 username/password)
|
||||
// 注意:这里不使用 refresh_token,因为需要保存 refresh_token 才能使用
|
||||
// 如果后续需要支持 refresh_token,需要修改逻辑
|
||||
log.info("Cached token expired, will get new token");
|
||||
String re = byToken(url);
|
||||
if (re == null || re.contains("\"error\"")) {
|
||||
log.error("Failed to get new token after cache expired, response: {}", re);
|
||||
throw new Exception("Failed to get new token: " + re);
|
||||
}
|
||||
TokenResponse tokenResponse = JSON.parseObject(re, TokenResponse.class);
|
||||
if (tokenResponse == null || tokenResponse.getAccess_token() == null) {
|
||||
log.error("Invalid token response after cache expired: {}", re);
|
||||
throw new Exception("Invalid token response: " + re);
|
||||
}
|
||||
long expireTime = System.currentTimeMillis() + TOKEN_EXPIRE_TIME_MS;
|
||||
tokenCache.put(url, new CachedToken(tokenResponse, expireTime));
|
||||
LogUtil.info(HttpTokenService.class, "=========get new token after cache expired");
|
||||
return tokenResponse;
|
||||
}
|
||||
String re = byToken(url);
|
||||
if (re == null || re.contains("\"error\"")) {
|
||||
log.error("Failed to get token, response: {}", re);
|
||||
throw new Exception("Failed to get token: " + re);
|
||||
}
|
||||
TokenResponse tokenResponse = JSON.parseObject(re, TokenResponse.class);
|
||||
if (tokenResponse == null || tokenResponse.getAccess_token() == null) {
|
||||
log.error("Invalid token response: {}", re);
|
||||
throw new Exception("Invalid token response: " + re);
|
||||
}
|
||||
// 3. 将新获取的 token 放入缓存
|
||||
long expireTime = System.currentTimeMillis() + TOKEN_EXPIRE_TIME_MS;
|
||||
tokenCache.put(url, new CachedToken(tokenResponse, expireTime));
|
||||
|
||||
return tokenResponse;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 构建请求头
|
||||
*/
|
||||
private Header[] buildHeaders() {
|
||||
return HttpHeaderBuilder.custom()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建请求参数 Map
|
||||
*/
|
||||
private Map<String, Object> buildTokenRequestParams() {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("username", username);
|
||||
map.put("password", password);
|
||||
map.put("grant_type", grantType);
|
||||
map.put("client_id", clientId);
|
||||
map.put("client_secret", clientSecret);
|
||||
|
||||
// 验证关键参数不为空
|
||||
if (clientId == null || clientId.trim().isEmpty()) {
|
||||
log.error("client_id is null or empty!");
|
||||
}
|
||||
if (clientSecret == null || clientSecret.trim().isEmpty()) {
|
||||
log.error("client_secret is null or empty!");
|
||||
}
|
||||
if (grantType == null || grantType.trim().isEmpty()) {
|
||||
log.error("grant_type is null or empty!");
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查响应是否有效(包含有效的 access_token)
|
||||
*/
|
||||
private boolean isValidTokenResponse(String response) {
|
||||
if (response == null || response.trim().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// 检查是否包含错误信息
|
||||
if (response.contains("\"error\"")) {
|
||||
log.warn("Token response contains error: {}", response);
|
||||
return false;
|
||||
}
|
||||
|
||||
TokenResponse tokenResponse = JSON.parseObject(response, TokenResponse.class);
|
||||
return tokenResponse != null && tokenResponse.getAccess_token() != null
|
||||
&& !tokenResponse.getAccess_token().trim().isEmpty();
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to parse token response: {}", response, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否是认证相关的错误(不应该重试)
|
||||
*/
|
||||
private boolean isAuthenticationError(String response) {
|
||||
if (response == null) {
|
||||
return false;
|
||||
}
|
||||
// 检查常见的认证错误
|
||||
return response.contains("\"error\"") && (
|
||||
response.contains("invalid_client") ||
|
||||
response.contains("invalid_grant") ||
|
||||
response.contains("unauthorized_client") ||
|
||||
response.contains("unsupported_grant_type")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 token 请求(带重试机制)
|
||||
* 如果第一次失败(网络错误或临时错误),等待1秒后重试一次
|
||||
* 如果是业务错误(如 invalid_client),不重试
|
||||
*/
|
||||
private String sendTokenRequestWithRetry(String url) {
|
||||
// 第一次尝试
|
||||
RequestResult firstResult = sendTokenRequestWithDetails(url);
|
||||
String token = firstResult.responseBody;
|
||||
|
||||
// 记录第一次请求是否到达服务器
|
||||
log.info("First attempt - ReachedServer: {}, StatusCode: {}, Response: {}",
|
||||
firstResult.reachedServer, firstResult.statusCode,
|
||||
token != null && token.length() > 100 ? token.substring(0, 100) + "..." : token);
|
||||
|
||||
// 检查响应是否有效
|
||||
if (!isValidTokenResponse(token)) {
|
||||
// 如果响应包含认证错误信息(如 invalid_client),不重试
|
||||
if (isAuthenticationError(token)) {
|
||||
Map<String, Object> params = buildTokenRequestParams();
|
||||
log.error("Token request failed with authentication error, will not retry. URL: {}, StatusCode: {}, ReachedServer: {}, Error: {}, params:{}",
|
||||
url, firstResult.statusCode, firstResult.reachedServer, token,
|
||||
params);
|
||||
return token;
|
||||
}
|
||||
|
||||
// 如果是其他错误(非认证错误),也不重试
|
||||
if (token != null && token.contains("\"error\"")) {
|
||||
Map<String, Object> params = buildTokenRequestParams();
|
||||
log.error("Token request failed with error response, will not retry. URL: {}, StatusCode: {}, ReachedServer: {}, Error: {}, params:{}",
|
||||
url, firstResult.statusCode, firstResult.reachedServer, token,
|
||||
params);
|
||||
return token;
|
||||
}
|
||||
|
||||
// 判断是否需要重试
|
||||
// 只有在请求未到达服务器(网络错误)时才重试
|
||||
if (!firstResult.reachedServer) {
|
||||
log.warn("First attempt did not reach server, will retry after {} ms. URL: {}, Exception: {}",
|
||||
RETRY_DELAY_MS, url,
|
||||
firstResult.exception != null ? firstResult.exception.getMessage() : "Unknown error");
|
||||
|
||||
try {
|
||||
Thread.sleep(RETRY_DELAY_MS);
|
||||
|
||||
// 重试时重新构建参数,确保参数是全新的
|
||||
RequestResult retryResult = sendTokenRequestWithDetails(url);
|
||||
String retryToken = retryResult.responseBody;
|
||||
|
||||
log.info("Retry attempt - ReachedServer: {}, StatusCode: {}, Response: {}",
|
||||
retryResult.reachedServer, retryResult.statusCode,
|
||||
retryToken != null && retryToken.length() > 100 ? retryToken.substring(0, 100) + "..." : retryToken);
|
||||
|
||||
// 如果重试时也返回错误,记录详细信息
|
||||
if (retryToken != null && retryToken.contains("\"error\"")) {
|
||||
log.error("Retry also failed with error. URL: {}, First attempt (ReachedServer: {}, StatusCode: {}), Retry (ReachedServer: {}, StatusCode: {}), Error: {}",
|
||||
url, firstResult.reachedServer, firstResult.statusCode,
|
||||
retryResult.reachedServer, retryResult.statusCode, retryToken);
|
||||
}
|
||||
|
||||
if (isValidTokenResponse(retryToken)) {
|
||||
log.info("Successfully retrieved token from url: {} on retry", url);
|
||||
return retryToken;
|
||||
} else {
|
||||
log.error("Failed to retrieve token from url: {} after retry. First (ReachedServer: {}), Retry (ReachedServer: {}, StatusCode: {})",
|
||||
url, firstResult.reachedServer, retryResult.reachedServer, retryResult.statusCode);
|
||||
return retryToken; // 返回重试的结果,即使失败
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.error("Thread interrupted while waiting for retry", e);
|
||||
return token; // 返回第一次的结果
|
||||
}
|
||||
} else {
|
||||
// 请求到达了服务器但返回了无效响应,不重试
|
||||
log.warn("Request reached server but returned invalid response, will not retry. URL: {}, StatusCode: {}, Response: {}",
|
||||
url, firstResult.statusCode, token);
|
||||
return token;
|
||||
}
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求结果包装类
|
||||
*/
|
||||
private static class RequestResult {
|
||||
String responseBody;
|
||||
Integer statusCode;
|
||||
boolean reachedServer;
|
||||
Exception exception;
|
||||
|
||||
RequestResult(String responseBody, Integer statusCode, boolean reachedServer, Exception exception) {
|
||||
this.responseBody = responseBody;
|
||||
this.statusCode = statusCode;
|
||||
this.reachedServer = reachedServer;
|
||||
this.exception = exception;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 token 请求(单次),返回详细结果包括状态码
|
||||
*/
|
||||
private RequestResult sendTokenRequestWithDetails(String url) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
try {
|
||||
Map<String, Object> params = buildTokenRequestParams();
|
||||
Header[] headers = buildHeaders();
|
||||
|
||||
// 构建完整的 URL
|
||||
String fullUrl = tokenUrl + url;
|
||||
|
||||
log.debug("Sending token request to url: {}, with params: client_id={}, grant_type={}",
|
||||
fullUrl, params.get("client_id"), params.get("grant_type"));
|
||||
|
||||
// 使用 HttpClientUtil.sendPostAndGetResp 获取详细响应信息(包括状态码)
|
||||
HttpRequestOptions postFormConfig = HttpRequestOptions.create()
|
||||
.url(fullUrl)
|
||||
.timeout(requestConfig)
|
||||
.method(HttpMethods.POST)
|
||||
.map(params)
|
||||
.encoding("utf-8")
|
||||
.client(httpClient);
|
||||
|
||||
HttpResult httpResult = HttpClientExecutor.sendAndPostResp(postFormConfig, headers);
|
||||
|
||||
long duration = System.currentTimeMillis() - startTime;
|
||||
int statusCode = httpResult.getStatusCode();
|
||||
String responseBody = httpResult.getResult();
|
||||
|
||||
// 判断请求是否到达服务器
|
||||
// 如果有 HTTP 状态码(即使是错误码如 400, 401, 500),说明请求到达了服务器
|
||||
boolean reachedServer = (statusCode > 0);
|
||||
|
||||
log.info("Token request completed - URL: {}, StatusCode: {}, ReachedServer: {}, Duration: {}ms, Response: {},header:{}",
|
||||
fullUrl, statusCode, reachedServer, duration,
|
||||
responseBody != null && responseBody.length() > 200
|
||||
? responseBody.substring(0, 200) + "..." : responseBody,headers);
|
||||
|
||||
return new RequestResult(responseBody, statusCode, reachedServer, null);
|
||||
|
||||
} catch (Exception e) {
|
||||
long duration = System.currentTimeMillis() - startTime;
|
||||
log.error("Failed to retrieve token from url: {}, Duration: {}ms, Exception: {}",
|
||||
tokenUrl + url, duration, e.getMessage(), e);
|
||||
|
||||
// 根据异常类型判断是否到达服务器
|
||||
boolean reachedServer = isServerReachableException(e);
|
||||
|
||||
return new RequestResult(null, null, reachedServer, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断异常类型,确定请求是否可能到达了服务器
|
||||
*/
|
||||
private boolean isServerReachableException(Exception e) {
|
||||
if (e == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String exceptionMessage = e.getMessage();
|
||||
String exceptionClass = e.getClass().getName();
|
||||
|
||||
// 如果异常信息包含 HTTP 状态码相关的内容,可能到达了服务器
|
||||
if (exceptionMessage != null && (
|
||||
exceptionMessage.contains("status") ||
|
||||
exceptionMessage.contains("HTTP") ||
|
||||
exceptionMessage.contains("400") ||
|
||||
exceptionMessage.contains("401") ||
|
||||
exceptionMessage.contains("403") ||
|
||||
exceptionMessage.contains("500")
|
||||
)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 连接超时、DNS 解析失败等异常,说明未到达服务器
|
||||
if (exceptionClass.contains("ConnectTimeoutException") ||
|
||||
exceptionClass.contains("SocketTimeoutException") ||
|
||||
exceptionClass.contains("UnknownHostException") ||
|
||||
exceptionClass.contains("NoRouteToHostException") ||
|
||||
exceptionMessage != null && (
|
||||
exceptionMessage.contains("timeout") ||
|
||||
exceptionMessage.contains("Connection refused") ||
|
||||
exceptionMessage.contains("Name or service not known")
|
||||
)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 其他异常,默认认为可能到达了服务器(保守判断)
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 token 请求(单次)- 兼容旧接口
|
||||
*/
|
||||
private String sendTokenRequest(String url) {
|
||||
RequestResult result = sendTokenRequestWithDetails(url);
|
||||
return result.responseBody;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取新 token(带重试)
|
||||
*/
|
||||
private String byToken(String url) {
|
||||
return sendTokenRequestWithRetry(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试用的 main 函数 - 循环请求测试
|
||||
* 参数写死,直接运行即可
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
// 写死的测试参数
|
||||
String testUrl = "/connect/token";
|
||||
int loopCount = 200; // 循环次数
|
||||
long intervalMs = 100; // 每次请求间隔(毫秒)
|
||||
|
||||
System.out.println("========== 开始 Token 请求循环测试 ==========");
|
||||
System.out.println("URL: " + testUrl);
|
||||
System.out.println("循环次数: " + loopCount);
|
||||
System.out.println("请求间隔: " + intervalMs + "ms");
|
||||
System.out.println("=============================================\n");
|
||||
|
||||
// 手动创建必要的依赖对象
|
||||
CloseableHttpClient httpClient = createHttpClient();
|
||||
RequestConfig requestConfig = createRequestConfig();
|
||||
HttpService httpService = createHttpService(httpClient, requestConfig);
|
||||
|
||||
// 创建 HttpTokenService 实例
|
||||
HttpTokenService tokenService = new HttpTokenService();
|
||||
|
||||
// 手动设置参数(写死的配置)
|
||||
tokenService.tokenUrl = "https://eu1.api.uat.development.abovecloud.io";
|
||||
tokenService.username = "mcrm.ifc@MGMDEV";
|
||||
tokenService.password = "Shiji@123";
|
||||
tokenService.grantType = "password";
|
||||
tokenService.clientId = "3rd.willtech_technology";
|
||||
tokenService.clientSecret = "HJIvAynCSCqvjEe8MC9K";
|
||||
|
||||
// 设置依赖对象
|
||||
tokenService.httpClient = httpClient;
|
||||
tokenService.requestConfig = requestConfig;
|
||||
tokenService.httpService = httpService;
|
||||
|
||||
int successCount = 0;
|
||||
int failCount = 0;
|
||||
long totalTime = 0;
|
||||
|
||||
try {
|
||||
for (int i = 1; i <= loopCount; i++) {
|
||||
try {
|
||||
System.out.println("---------- 第 " + i + " 次请求 ----------");
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
// 调用 getToken 方法
|
||||
TokenResponse tokenResponse = tokenService.getToken();
|
||||
|
||||
long duration = System.currentTimeMillis() - startTime;
|
||||
totalTime += duration;
|
||||
|
||||
if (tokenResponse != null && tokenResponse.getAccess_token() != null) {
|
||||
successCount++;
|
||||
String tokenPreview = tokenResponse.getAccess_token().length() > 20
|
||||
? tokenResponse.getAccess_token().substring(0, 20) + "..."
|
||||
: tokenResponse.getAccess_token();
|
||||
System.out.println("✓ 请求成功 - 耗时: " + duration + "ms");
|
||||
System.out.println(" AccessToken: " + tokenPreview);
|
||||
} else {
|
||||
failCount++;
|
||||
System.out.println("✗ 请求失败 - 响应为空或无效");
|
||||
}
|
||||
|
||||
// 如果不是最后一次,等待
|
||||
if (i < loopCount) {
|
||||
System.out.println("等待 " + intervalMs + "ms 后进行下一次请求...\n");
|
||||
Thread.sleep(intervalMs);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
failCount++;
|
||||
System.err.println("✗ 第 " + i + " 次请求异常: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
|
||||
if (i < loopCount) {
|
||||
try {
|
||||
Thread.sleep(intervalMs);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// 关闭 HttpClient
|
||||
if (httpClient != null) {
|
||||
httpClient.close();
|
||||
}
|
||||
}
|
||||
|
||||
// 输出统计
|
||||
System.out.println("\n=============================================");
|
||||
System.out.println("========== Token 请求测试完成 ==========");
|
||||
System.out.println("总请求次数: " + loopCount);
|
||||
System.out.println("成功次数: " + successCount);
|
||||
System.out.println("失败次数: " + failCount);
|
||||
if (loopCount > 0) {
|
||||
System.out.println("成功率: " + String.format("%.2f%%", (successCount * 100.0 / loopCount)));
|
||||
System.out.println("平均耗时: " + (totalTime / loopCount) + "ms");
|
||||
}
|
||||
System.out.println("总耗时: " + totalTime + "ms");
|
||||
System.out.println("=============================================");
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动创建 HttpClient
|
||||
*/
|
||||
private static CloseableHttpClient createHttpClient() {
|
||||
try {
|
||||
HttpSslSupport ssls = HttpSslSupport.getInstance();
|
||||
@SuppressWarnings("deprecation")
|
||||
org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory sslConnFactory =
|
||||
ssls.getSSLCONNSF(HttpSslSupport.SSLProtocolVersion.TLSv1_2);
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
org.apache.hc.core5.http.config.Registry<org.apache.hc.client5.http.socket.ConnectionSocketFactory> registry =
|
||||
org.apache.hc.core5.http.config.RegistryBuilder.<org.apache.hc.client5.http.socket.ConnectionSocketFactory>create()
|
||||
.register("https", sslConnFactory)
|
||||
.build();
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager connManager =
|
||||
new org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager(registry);
|
||||
connManager.setMaxTotal(100);
|
||||
connManager.setDefaultMaxPerRoute(10);
|
||||
|
||||
RequestConfig config = createRequestConfig();
|
||||
|
||||
return org.apache.hc.client5.http.impl.classic.HttpClients.custom()
|
||||
.setConnectionManager(connManager)
|
||||
.setDefaultRequestConfig(config)
|
||||
.setConnectionManagerShared(false)
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("创建 HttpClient 失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动创建 RequestConfig
|
||||
*/
|
||||
private static RequestConfig createRequestConfig() {
|
||||
return RequestConfig.custom()
|
||||
.setConnectionRequestTimeout(org.apache.hc.core5.util.Timeout.ofSeconds(5))
|
||||
.setResponseTimeout(org.apache.hc.core5.util.Timeout.ofSeconds(10))
|
||||
.setRedirectsEnabled(false)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动创建 HttpService
|
||||
*/
|
||||
private static HttpService createHttpService(CloseableHttpClient httpClient, RequestConfig requestConfig) {
|
||||
HttpService httpService = new HttpService();
|
||||
// 使用反射设置私有字段
|
||||
try {
|
||||
java.lang.reflect.Field httpClientField = HttpService.class.getDeclaredField("httpClient");
|
||||
httpClientField.setAccessible(true);
|
||||
httpClientField.set(httpService, httpClient);
|
||||
|
||||
java.lang.reflect.Field requestConfigField = HttpService.class.getDeclaredField("requestConfig");
|
||||
requestConfigField.setAccessible(true);
|
||||
requestConfigField.set(httpService, requestConfig);
|
||||
|
||||
java.lang.reflect.Field tokenUrlField = HttpService.class.getDeclaredField("tokenUrl");
|
||||
tokenUrlField.setAccessible(true);
|
||||
tokenUrlField.set(httpService, "https://eu1.api.uat.development.abovecloud.io");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("设置 HttpService 字段失败", e);
|
||||
}
|
||||
return httpService;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
package com.mgm.mcrm.common.services;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.mgm.mcrm.booking.dtos.search.DateRange;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import com.mgm.mcrm.common.dtos.http_util.HttpRequestDefine;
|
||||
import com.mgm.mcrm.common.dtos.http_util.HttpResponseResult;
|
||||
import com.mgm.mcrm.common.constants.SysCommon;
|
||||
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;
|
||||
|
||||
@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";
|
||||
|
||||
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.mgm.mcrm.common.services;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.mgm.mcrm.common.constants.SysCommon;
|
||||
import com.mgm.mcrm.common.jms.AppControlMsgSender;
|
||||
import com.mgm.mcrm.common.dtos.msg.AppSettingMsgData;
|
||||
import com.mgm.mcrm.common.dtos.system.AppServerState;
|
||||
|
||||
@Service
|
||||
public class SysServerStateService {
|
||||
|
||||
@Autowired
|
||||
private AppControlMsgSender ctrlMsgSender;
|
||||
|
||||
public void updateCfgByRequest(AppSettingMsgData updateRequest) {
|
||||
AppServerState updServerInfo = SysCommon.updateCfgByRequest(updateRequest);
|
||||
if(ctrlMsgSender!=null) {
|
||||
SysCommon.jmsRunning = SysCommon.jmsRunning || ctrlMsgSender.sendMessage("SYNC_SERVER_STATE", updServerInfo);
|
||||
}
|
||||
}
|
||||
|
||||
public void notifyCurrentState() {
|
||||
AppServerState serverState = SysCommon.refreshAppServerState();
|
||||
if(ctrlMsgSender!=null) {
|
||||
SysCommon.jmsRunning = SysCommon.jmsRunning || ctrlMsgSender.sendMessage("SYNC_SERVER_STATE",serverState);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package com.mgm.mcrm.common.utils;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.StringReader;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.zip.Inflater;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import com.mgm.mcrm.authorization.dtos.LoginUserInfo;
|
||||
import com.mgm.mcrm.authorization.models.SysUserView;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.InputSource;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
|
||||
|
||||
public class ADFSUtil {
|
||||
|
||||
public static LoginUserInfo parseUserFromXML(String xmlResponse) {
|
||||
LoginUserInfo result=null;
|
||||
try {
|
||||
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
|
||||
InputSource inputSource = new InputSource();
|
||||
inputSource.setCharacterStream(new StringReader(xmlResponse));
|
||||
Document doc = dBuilder.parse(inputSource);
|
||||
NodeList successNodes = doc.getElementsByTagName("Assertion");
|
||||
if(successNodes!=null&&successNodes.getLength()>0) {
|
||||
result = new LoginUserInfo();
|
||||
result.setId((long) -1);
|
||||
for (int i = 0; i < successNodes.getLength(); i++) {
|
||||
Element subjectElement = (Element) successNodes.item(i);
|
||||
String nameId=getSingleNodeTextByName(subjectElement,"NameID",null,null);
|
||||
if(StringUtils.isNotBlank(nameId)) {
|
||||
result.setLoginId(nameId);
|
||||
}
|
||||
String userName=getSingleNodeTextByName(subjectElement,"Attribute","Name","claims/name");
|
||||
if(StringUtils.isNotBlank(userName)) {
|
||||
result.setDisplayName(userName);
|
||||
}
|
||||
String groupName=getSingleNodeTextByName(subjectElement,"Attribute","Name","claims/Group");
|
||||
if(StringUtils.isNotBlank(groupName)) {
|
||||
result.setGroupName(groupName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}catch(Exception err) {
|
||||
result =null;
|
||||
LogUtil.error(ADFSUtil.class, "Parse ADFS Result failed:"+err.getMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static byte[] copyArray(byte[] original, int newLength) {
|
||||
byte[] copy = new byte[newLength];
|
||||
System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static String getSingleNodeTextByName(Element parent, String tagName, String attrName, String attrValue) {
|
||||
String result =null;
|
||||
try {
|
||||
NodeList dataNodes = parent.getElementsByTagName(tagName);
|
||||
if (dataNodes!=null && dataNodes.getLength() > 0) {
|
||||
if(StringUtils.isNotBlank(attrName)) {
|
||||
for(int i=0;i<dataNodes.getLength();i++) {
|
||||
Element nodeElement = (Element) dataNodes.item(i);
|
||||
String attrTag = nodeElement.getAttribute(attrName);
|
||||
if(attrTag!=null && Strings.CI.contains(attrTag, attrValue)){
|
||||
NodeList attrNodes =nodeElement.getChildNodes();
|
||||
if(attrNodes!=null && attrNodes.getLength()>0) {
|
||||
result="";
|
||||
for(int j=0;j<attrNodes.getLength();j++) {
|
||||
String attrVal = ((Element)attrNodes.item(j)).getTextContent();
|
||||
if(attrVal!=null) {
|
||||
if(StringUtils.isNotBlank(result)) {
|
||||
result+=";";
|
||||
}
|
||||
result+=attrVal.trim();
|
||||
}
|
||||
}
|
||||
}else {
|
||||
result = nodeElement.getTextContent();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
LogUtil.info(ADFSUtil.class, "ADFS Attribute Tag:["+attrName+"]="+result);
|
||||
}else {
|
||||
Element nodeElement = (Element) dataNodes.item(0);
|
||||
result = nodeElement.getTextContent();
|
||||
LogUtil.info(ADFSUtil.class, "ADFS Name Tag:["+tagName+"]="+result);
|
||||
}
|
||||
}
|
||||
}catch(Exception err) {
|
||||
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private static byte[] decompress(byte[] compressed){
|
||||
byte[] xmlBytes = null;
|
||||
try {
|
||||
Inflater decompresser = new Inflater(true);
|
||||
decompresser.reset();
|
||||
decompresser.setInput(compressed);
|
||||
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(compressed.length);
|
||||
byte[] buf = new byte[1024];
|
||||
while (!decompresser.finished()) {
|
||||
int i = decompresser.inflate(buf);
|
||||
out.write(buf, 0, i);
|
||||
}
|
||||
xmlBytes = out.toByteArray();
|
||||
decompresser.end();
|
||||
try {
|
||||
out.close();
|
||||
}catch (Exception err) {
|
||||
}
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ADFSUtil.class, "Decompress response data failed:"+err.getMessage());
|
||||
}
|
||||
return xmlBytes;
|
||||
}
|
||||
|
||||
public static LoginUserInfo parseADFSToken(String token) {
|
||||
LoginUserInfo result = null;
|
||||
String parseContent = token;
|
||||
LogUtil.info(ADFSUtil.class, "ADFS Orig Token:["+token+"]");
|
||||
if(StringUtils.isNotBlank(parseContent)) {
|
||||
try {
|
||||
byte[] compressData = Base64.getDecoder().decode(token.getBytes("UTF-8"));
|
||||
byte[] originalData = decompress(compressData);
|
||||
parseContent = new String(originalData);
|
||||
if(StringUtils.isNotBlank(parseContent)) {
|
||||
//LogUtil.info(ADFSUtil.class, "ADFS XML Content:["+parseContent+"]");
|
||||
result = parseUserFromXML(parseContent);
|
||||
}else {
|
||||
LogUtil.error(ADFSUtil.class, "Parse ADFS Token failed");
|
||||
}
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ADFSUtil.class, "Extract ADFS Token failed:"+err.getMessage());
|
||||
}
|
||||
|
||||
}else {
|
||||
LogUtil.error(ADFSUtil.class, "ADFS Token is blank");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static LoginUserInfo parseJWTToken(String tokenData) {
|
||||
LoginUserInfo result = null;
|
||||
LogUtil.info(ADFSUtil.class, "JWT Orig Token:["+tokenData+"]");
|
||||
try {
|
||||
DecodedJWT decodeData = JWT.decode(tokenData);
|
||||
result = new LoginUserInfo();
|
||||
result.setId((long)-1);
|
||||
if(decodeData.getClaim("upn")!=null) {
|
||||
result.setLoginId(decodeData.getClaim("upn").asString());
|
||||
}
|
||||
if(decodeData.getClaim("user_group")!=null) {
|
||||
try {
|
||||
List<String> groupNames = decodeData.getClaim("user_group").asList(String.class);
|
||||
String groupNameVal = "";
|
||||
for(int i=0;i<groupNames.size();i++) {
|
||||
groupNameVal += (i>0?";":"")+groupNames.get(i);
|
||||
}
|
||||
result.setGroupName(groupNameVal);
|
||||
}catch(Exception err) {
|
||||
result.setGroupName(decodeData.getClaim("user_group").asString());
|
||||
}
|
||||
}
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ADFSUtil.class, "JWT ADFS Token:"+err.getMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.mgm.mcrm.common.utils;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.Permission;
|
||||
import java.security.PermissionCollection;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
public class AESUtil {
|
||||
|
||||
private static final String AES = "AES";
|
||||
private static final int GCM_IV_LENGTH = 12; // GCM推荐使用12字节的IV
|
||||
private static final int GCM_TAG_LENGTH = 16; // GCM认证标签长度(128位)
|
||||
|
||||
private static java.util.Base64.Encoder base64Encoder = java.util.Base64.getEncoder();
|
||||
private static java.util.Base64.Decoder base64Decoder = java.util.Base64.getDecoder();
|
||||
|
||||
static {
|
||||
java.security.Security.setProperty("crypto.policy", "unlimited");
|
||||
removeCryptographyRestrictions();
|
||||
}
|
||||
|
||||
public static void removeCryptographyRestrictions() {
|
||||
try {
|
||||
/*
|
||||
* Do the following, but with reflection to bypass access checks:
|
||||
* JceSecurity.isRestricted = false;
|
||||
* JceSecurity.defaultPolicy.perms.clear();
|
||||
* JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
|
||||
*/
|
||||
final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
|
||||
final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
|
||||
final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");
|
||||
|
||||
final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
|
||||
isRestrictedField.setAccessible(true);
|
||||
// 去除isRestricted的final限制
|
||||
final Field modifiersField = Field.class.getDeclaredField("modifiers");
|
||||
modifiersField.setAccessible(true);
|
||||
modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
|
||||
isRestrictedField.set(null, false);
|
||||
|
||||
final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
|
||||
defaultPolicyField.setAccessible(true);
|
||||
final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);
|
||||
|
||||
final Field perms = cryptoPermissions.getDeclaredField("perms");
|
||||
perms.setAccessible(true);
|
||||
((Map<?, ?>) perms.get(defaultPolicy)).clear();
|
||||
|
||||
final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
|
||||
instance.setAccessible(true);
|
||||
defaultPolicy.add((Permission) instance.get(null));
|
||||
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static SecretKey generateKey() throws Exception {
|
||||
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
|
||||
keyGen.init(256);
|
||||
return keyGen.generateKey();
|
||||
}
|
||||
public static SecretKey stringToSecretKey(String keyString) {
|
||||
byte[] keyBytes = base64Decoder.decode(keyString);
|
||||
return new SecretKeySpec(keyBytes, AES);
|
||||
}
|
||||
public static String secretKeyToString(SecretKey secretKey) {
|
||||
byte[] keyBytes = secretKey.getEncoded();
|
||||
return base64Encoder.encodeToString(keyBytes);
|
||||
}
|
||||
/**
|
||||
* AES加密
|
||||
*/
|
||||
public static String AES256Encrypt(String key, String content) {
|
||||
try {
|
||||
SecretKey secretKey = stringToSecretKey(key);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||
SecureRandom secureRandom = new SecureRandom();
|
||||
secureRandom.nextBytes(iv); // 生成随机的IV
|
||||
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey, spec);
|
||||
|
||||
byte[] ciphertext = cipher.doFinal(content.getBytes());
|
||||
byte[] encryptedData = new byte[iv.length + ciphertext.length];
|
||||
System.arraycopy(iv, 0, encryptedData, 0, iv.length);
|
||||
System.arraycopy(ciphertext, 0, encryptedData, iv.length, ciphertext.length);
|
||||
return base64Encoder.encodeToString(encryptedData);
|
||||
|
||||
} catch (Exception e) {
|
||||
//e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* AES解密
|
||||
*/
|
||||
public static String AES256Decrypt(String key, String content) {
|
||||
try {
|
||||
SecretKey secretKey = stringToSecretKey(key);
|
||||
byte[] encryptedData = base64Decoder.decode(content);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
// 从加密数据中提取IV
|
||||
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||
System.arraycopy(encryptedData, 0, iv, 0, iv.length);
|
||||
|
||||
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);
|
||||
|
||||
// 解密数据
|
||||
byte[] ciphertext = new byte[encryptedData.length - GCM_IV_LENGTH];
|
||||
System.arraycopy(encryptedData, GCM_IV_LENGTH, ciphertext, 0, ciphertext.length);
|
||||
byte[] byteDecode = cipher.doFinal(ciphertext);
|
||||
return new String(byteDecode, java.nio.charset.StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
//e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String sha256(String plainString) {
|
||||
String cipherString = null;
|
||||
try {
|
||||
// 获取实例(SHA-512同理)
|
||||
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
|
||||
// 计算摘要
|
||||
byte[] cipherBytes = messageDigest.digest(plainString.getBytes(StandardCharsets.UTF_8));
|
||||
// 输出为16进制字符串
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : cipherBytes) {
|
||||
sb.append(String.format("%02x", b));
|
||||
}
|
||||
cipherString = sb.toString();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return cipherString;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.mgm.mcrm.common.utils;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class DaoUtil {
|
||||
|
||||
private static EntityManager entityManager;
|
||||
public static final int BATCH_SIZE = 100;
|
||||
|
||||
public static Sort buildSortByFilter(String orderInfo, String defaultSortProperty){
|
||||
Sort sort=null;
|
||||
String sortColumn="";
|
||||
String sortProperties = StringUtils.isNotBlank(orderInfo)?orderInfo:defaultSortProperty;
|
||||
Direction sortDirection = Direction.ASC;
|
||||
if(StringUtils.isNotBlank(sortProperties)){
|
||||
String[] listSortProperty = sortProperties.split(";");
|
||||
for(int i=0;i<listSortProperty.length;i++) {
|
||||
if(StringUtils.isNotBlank(listSortProperty[i])) {
|
||||
String[] sortInfos = listSortProperty[i].split("-");
|
||||
sortColumn = sortInfos[0];
|
||||
sortDirection=Direction.ASC;
|
||||
if(sortInfos.length>1 && Strings.CI.equals("desc", sortInfos[1])) {
|
||||
sortDirection = Direction.DESC;
|
||||
}
|
||||
if(sort==null) {
|
||||
sort = Sort.by(sortDirection,sortColumn);
|
||||
}else {
|
||||
sort = sort.and(Sort.by(sortDirection,sortColumn));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return sort;
|
||||
}
|
||||
|
||||
|
||||
public static List<String> parseMultipleFilter(String filerValues){
|
||||
List<String> returnVals = new ArrayList<String>();
|
||||
if(StringUtils.isNotBlank(filerValues)) {
|
||||
String[] searchIds = filerValues.split(";");
|
||||
for(int i=0;i<searchIds.length;i++) {
|
||||
returnVals.add(searchIds[i]);
|
||||
}
|
||||
}
|
||||
return returnVals;
|
||||
}
|
||||
public static <T> List<T> parseMultipleFilter(String filerValues, Class<T> valueType){
|
||||
List<T> returnVals = new ArrayList<T>();
|
||||
if(StringUtils.isNotBlank(filerValues)) {
|
||||
Constructor<T> classConstructor= null;
|
||||
try {
|
||||
classConstructor = valueType.getConstructor(String.class);
|
||||
}catch(Exception err) {
|
||||
classConstructor = null;
|
||||
}
|
||||
if(classConstructor!=null) {
|
||||
String[] listSplitValues = filerValues.split(";");
|
||||
for(int i=0;i<listSplitValues.length;i++) {
|
||||
try {
|
||||
T val = classConstructor.newInstance(listSplitValues[i]);
|
||||
returnVals.add(val);
|
||||
}catch(Exception err) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return returnVals;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package com.mgm.mcrm.common.utils;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.*;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.mgm.mcrm.appsetting.services.SettingService;
|
||||
|
||||
@Slf4j
|
||||
public class DateTimeUtil {
|
||||
|
||||
@Resource
|
||||
private SettingService settingService;
|
||||
|
||||
/**
|
||||
* 根据String型时间,获取long型时间,单位毫秒
|
||||
* @param inVal 时间字符串
|
||||
* @return long型时间
|
||||
*/
|
||||
public static long fromDateStringToLong(String inVal) {
|
||||
Date date = null;
|
||||
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
|
||||
try {
|
||||
date = inputFormat.parse(inVal);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return date.getTime();
|
||||
}
|
||||
public static long getTimeSpanSSS(Date startDate,Date endDate) {
|
||||
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
|
||||
String startStr = timeFormat.format(startDate);
|
||||
String endStr = timeFormat.format(endDate);
|
||||
|
||||
long startMS = fromDateStringToLong(startStr);
|
||||
long endMS = fromDateStringToLong(endStr);
|
||||
|
||||
return endMS-startMS;
|
||||
}
|
||||
public static Date getDateFromString(String dateTimeValue,String dateFormat) {
|
||||
SimpleDateFormat dtFormat = new SimpleDateFormat(dateFormat);
|
||||
if (StringUtils.isNotBlank(dateTimeValue)) {
|
||||
try {
|
||||
return dtFormat.parse(dateTimeValue);
|
||||
} catch (Exception err) {
|
||||
log.warn(err.getMessage(), err);
|
||||
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String getDateByFormat(Date dtDateTime, String strFormat) {
|
||||
|
||||
String returnDate = null;
|
||||
|
||||
if (dtDateTime != null) {
|
||||
try {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(strFormat);
|
||||
returnDate = formatter.format(dtDateTime);
|
||||
} catch (Exception err) {
|
||||
|
||||
}
|
||||
}
|
||||
return returnDate;
|
||||
}
|
||||
|
||||
public static String getDateByFormat(LocalDateTime dateTime, String strFormat) {
|
||||
|
||||
String returnDate = null;
|
||||
|
||||
if (dateTime != null) {
|
||||
try {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(strFormat);
|
||||
returnDate = dateTime.format(formatter);
|
||||
} catch (Exception err) {
|
||||
// 可以考虑打日志
|
||||
}
|
||||
}
|
||||
|
||||
return returnDate;
|
||||
}
|
||||
|
||||
public static String getCurrentDate(String strFormat) {
|
||||
|
||||
return getDateByFormat(new Date(), strFormat);
|
||||
}
|
||||
|
||||
public static Date getCurrentDateTime(String strFormat) {
|
||||
SimpleDateFormat dtFormat = new SimpleDateFormat(strFormat);
|
||||
String dateTimeValue = getDateByFormat(new Date(), strFormat);
|
||||
|
||||
Date returnDate = null;
|
||||
try {
|
||||
returnDate = dtFormat.parse(dateTimeValue);
|
||||
} catch (Exception err) {
|
||||
|
||||
}
|
||||
|
||||
return returnDate;
|
||||
}
|
||||
public static Date addSecond(Date nowTime,Integer seconds) {
|
||||
long getTime = nowTime.getTime();
|
||||
long diffTime = seconds * 1000L;
|
||||
long newTime = getTime+diffTime;
|
||||
String strTime = getDateByFormatUseTimeStamp(newTime,"yyyy-MM-dd HH:mm:ss");
|
||||
return getDateFromString(strTime,"yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
public static Date addMin(Date nowTime,Integer mins) {
|
||||
long getTime = nowTime.getTime();
|
||||
long diffTime = mins * 60000L;
|
||||
long newTime = getTime+diffTime;
|
||||
String strTime = getDateByFormatUseTimeStamp(newTime,"yyyy-MM-dd HH:mm:ss");
|
||||
return getDateFromString(strTime,"yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
public static Date addDay(Date currdate,Integer days) {
|
||||
Calendar ca = Calendar.getInstance();
|
||||
ca.setTime(currdate);
|
||||
ca.add(Calendar.DATE, days);
|
||||
Date newTime = ca.getTime();
|
||||
return newTime;
|
||||
}
|
||||
public static Date addMonth(Date currdate,Integer months) {
|
||||
Calendar ca = Calendar.getInstance();
|
||||
ca.setTime(currdate);
|
||||
ca.add(Calendar.MONTH, months);
|
||||
Date newTime = ca.getTime();
|
||||
return newTime;
|
||||
}
|
||||
public static Date addYear(Date currdate,Integer years) {
|
||||
Calendar ca = Calendar.getInstance();
|
||||
ca.setTime(currdate);
|
||||
ca.add(Calendar.YEAR, years);
|
||||
Date newTime = ca.getTime();
|
||||
return newTime;
|
||||
}
|
||||
public static String getDateByFormatUseTimeStamp(Long timeStamp, String strFormat) {
|
||||
|
||||
String returnDate = null;
|
||||
|
||||
if (timeStamp != null) {
|
||||
try {
|
||||
SimpleDateFormat formatter;
|
||||
formatter = new SimpleDateFormat(strFormat);
|
||||
returnDate = formatter.format(timeStamp);
|
||||
} catch (Exception err) {
|
||||
|
||||
}
|
||||
}
|
||||
return returnDate;
|
||||
}
|
||||
|
||||
public static String getDiffDate(Date DateStart, Date DateEnd, String dateType) {
|
||||
String returnDate = null;
|
||||
try {
|
||||
|
||||
Instant instant1 = DateStart.toInstant();
|
||||
Instant instant2 = DateEnd.toInstant();
|
||||
|
||||
Duration duration = Duration.between(instant1, instant2);
|
||||
|
||||
//long diffTime = DateEnd.getTime() - DateStart.getTime();
|
||||
if("day".equalsIgnoreCase(dateType)) {
|
||||
//returnDate = Long.toString(diffTime / 1000 / (60 * 60 * 24));
|
||||
long days = duration.toDays();
|
||||
returnDate = Long.toString(days);
|
||||
}else if("hour".equalsIgnoreCase(dateType)) {
|
||||
//returnDate = Long.toString(diffTime / 1000 / (60 * 60));
|
||||
long hours = duration.toHours();
|
||||
returnDate = Long.toString(hours);
|
||||
}else { //minute
|
||||
long minutes = duration.toMinutes();
|
||||
returnDate = Long.toString(minutes);
|
||||
}
|
||||
} catch (Exception err) {
|
||||
|
||||
}
|
||||
return returnDate;
|
||||
}
|
||||
|
||||
public static Date getDateFromLong(Long timestamp){
|
||||
return new Date(timestamp);
|
||||
}
|
||||
|
||||
public static Long getLongFromDate(Date date){
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
public static boolean isValidDate(String dateStr) {
|
||||
try {
|
||||
dateStr=dateStr.split("T")[0];
|
||||
dateStr=dateStr.split(" ")[0];
|
||||
String[] parts = dateStr.split("-");
|
||||
|
||||
int year = Integer.parseInt(parts[0]);
|
||||
int month = Integer.parseInt(parts[1]);
|
||||
int day = Integer.parseInt(parts[2]);
|
||||
|
||||
|
||||
if (month < 1 || month > 12) {
|
||||
return false;
|
||||
}
|
||||
|
||||
YearMonth yearMonth = YearMonth.of(year, month);
|
||||
int maxDay = yearMonth.lengthOfMonth();
|
||||
|
||||
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
|
||||
if (month == 2 && isLeapYear) {
|
||||
maxDay = 29;
|
||||
} else if (month == 2) {
|
||||
maxDay = 28;
|
||||
}
|
||||
|
||||
if (day < 1 || day > maxDay) {
|
||||
return false;
|
||||
}
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
LocalDate.parse(dateStr, formatter);
|
||||
return true;
|
||||
} catch (DateTimeParseException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static Date getTodoYesterdayDay(String cutoffStartTime,String cutoffEndTime){
|
||||
String date = DateTimeUtil.getDateByFormat(new Date(), "yyyy-MM-dd");
|
||||
Date curentTime = DateTimeUtil.getCurrentDateTime("yyyy-MM-dd HH:mm");
|
||||
Date getStartTime = DateTimeUtil.getDateFromString(date+" "+cutoffStartTime, "yyyy-MM-dd HH:mm");
|
||||
Date getEndTime = DateTimeUtil.getDateFromString(date+" "+cutoffEndTime, "yyyy-MM-dd HH:mm");
|
||||
Date queryDate = DateTimeUtil.getCurrentDateTime("yyyy-MM-dd");
|
||||
if(curentTime.getTime()>=getStartTime.getTime()&&curentTime.getTime()<=getEndTime.getTime()) {
|
||||
queryDate = DateTimeUtil.addDay(queryDate, -1);
|
||||
}
|
||||
|
||||
return queryDate;
|
||||
}
|
||||
|
||||
/**
|
||||
* OPERA cashier comment 入住日期段:英文 Mar 30,禁止 Date#toString()。
|
||||
* 单晚:30 Mar;同月多晚:30-31 Mar;跨月:30 Mar - 01 Apr
|
||||
*/
|
||||
public static String formatOperaCommentStayDateRange(Date checkin, Date checkout, Integer numOfNight) {
|
||||
Locale en = Locale.ENGLISH;
|
||||
if (checkin == null) {
|
||||
return "";
|
||||
}
|
||||
boolean stayIsSingleNight = Integer.valueOf(1).equals(numOfNight);
|
||||
if (!stayIsSingleNight && numOfNight == null && checkout != null) {
|
||||
stayIsSingleNight = "1".equals(getDiffDate(checkin, checkout, "day"));
|
||||
}
|
||||
if (stayIsSingleNight) {
|
||||
return getDateByFormat(checkin, "dd MMM", en);
|
||||
}
|
||||
if (checkout == null) {
|
||||
return getDateByFormat(checkin, "dd MMM", en);
|
||||
}
|
||||
Date lastNightDate = addDay(checkout, -1);
|
||||
String firstMonthAbbr = getDateByFormat(checkin, "MMM", en);
|
||||
String lastMonthAbbr = getDateByFormat(lastNightDate, "MMM", en);
|
||||
String firstDayOfMonth = getDateByFormat(checkin, "dd", en);
|
||||
String lastDayOfMonth = getDateByFormat(lastNightDate, "dd", en);
|
||||
if (firstMonthAbbr != null && firstMonthAbbr.equals(lastMonthAbbr)) {
|
||||
return firstDayOfMonth + "-" + lastDayOfMonth + " " + firstMonthAbbr;
|
||||
}
|
||||
return firstDayOfMonth + " " + firstMonthAbbr + " - " + lastDayOfMonth + " " + lastMonthAbbr;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按指定区域格式化日期(如 OPERA comment 需固定英文月份缩写 Mar/Apr)。
|
||||
*/
|
||||
public static String getDateByFormat(Date dtDateTime, String strFormat, Locale locale) {
|
||||
String returnDate = null;
|
||||
if (dtDateTime != null && locale != null) {
|
||||
try {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(strFormat, locale);
|
||||
returnDate = formatter.format(dtDateTime);
|
||||
} catch (Exception err) {
|
||||
|
||||
}
|
||||
}
|
||||
return returnDate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.mgm.mcrm.common.utils;
|
||||
|
||||
import com.thoughtworks.xstream.XStream;
|
||||
import com.thoughtworks.xstream.mapper.MapperWrapper;
|
||||
|
||||
public class ETLXstream extends XStream {
|
||||
protected MapperWrapper wrapMapper(MapperWrapper next) {
|
||||
return new MapperWrapper(next) {
|
||||
@Override
|
||||
public boolean shouldSerializeMember(Class definedIn,String fieldName) {
|
||||
// TODO Auto-generated method stub
|
||||
//不能识别的节点
|
||||
if(definedIn==Object.class){
|
||||
return false;
|
||||
}
|
||||
if(fieldName.equals("fileName")){
|
||||
return false;
|
||||
}
|
||||
return super.shouldSerializeMember(definedIn, fieldName);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.mgm.mcrm.common.utils;
|
||||
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
import org.springframework.util.DigestUtils;
|
||||
|
||||
|
||||
public class EncryptUtil {
|
||||
|
||||
public static String sha256(String plainString) {
|
||||
String cipherString = null;
|
||||
try {
|
||||
// 获取实例(SHA-512同理)
|
||||
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
|
||||
// 计算摘要
|
||||
byte[] cipherBytes = messageDigest.digest(plainString.getBytes(StandardCharsets.UTF_8));
|
||||
// 输出为16进制字符串
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : cipherBytes) {
|
||||
sb.append(String.format("%02x", b));
|
||||
}
|
||||
cipherString = sb.toString();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return cipherString;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,931 @@
|
||||
package com.mgm.mcrm.common.utils;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
|
||||
import com.mgm.mcrm.common.dtos.BaseApiResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.apache.commons.text.StringEscapeUtils;
|
||||
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
|
||||
import org.apache.poi.ss.usermodel.BuiltinFormats;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellType;
|
||||
import org.apache.poi.ss.usermodel.DateUtil;
|
||||
import org.apache.poi.ss.usermodel.FillPatternType;
|
||||
import org.apache.poi.ss.usermodel.HorizontalAlignment;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
|
||||
import org.apache.poi.xssf.usermodel.XSSFCell;
|
||||
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
|
||||
import org.apache.poi.xssf.usermodel.XSSFColor;
|
||||
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
|
||||
import org.apache.poi.xssf.usermodel.XSSFFont;
|
||||
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
|
||||
import org.apache.poi.xssf.usermodel.XSSFRow;
|
||||
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alibaba.fastjson.parser.Feature;
|
||||
|
||||
import com.mgm.mcrm.common.constants.SysCommon;
|
||||
import com.mgm.mcrm.common.dtos.excel_model.ColumnDefine;
|
||||
import com.mgm.mcrm.common.dtos.excel_model.ColumnGroupInfo;
|
||||
import com.mgm.mcrm.common.dtos.excel_model.DataBlock;
|
||||
import com.mgm.mcrm.common.dtos.excel_model.ExportDefine;
|
||||
import com.mgm.mcrm.common.dtos.excel_model.GroupItem;
|
||||
import com.mgm.mcrm.common.dtos.excel_model.ImportDefine;
|
||||
import com.mgm.mcrm.common.dtos.excel_model.RowFieldInfo;
|
||||
import com.mgm.mcrm.common.dtos.excel_model.SheetDefine;
|
||||
import com.mgm.mcrm.common.dtos.system.ResFileResult;
|
||||
|
||||
|
||||
public class ExcelUtils {
|
||||
public static final int TEXT_ELEMENT =1;
|
||||
public static final int DATABLOCK_ELEMENT =2;
|
||||
private static int customFormatIndex = 100;
|
||||
private static final DateTimeFormatter msecondFormat = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").withZone(ZoneOffset.ofHours(8));
|
||||
private static Random rnd = new Random();
|
||||
private static Map<String,ImportDefine> importDefines = new HashMap<String,ImportDefine>();
|
||||
private static Map<String,ExportDefine> exportDefines = new HashMap<String,ExportDefine>();
|
||||
|
||||
public static void loadExcelDefines() {
|
||||
try {
|
||||
File directory = new File(SysCommon.runtime_path + "/"+SysCommon.runtimeName+"/excel_define/import/");
|
||||
String[] fileNames = directory.list();
|
||||
if (fileNames != null) {
|
||||
for (String fileName : fileNames) {
|
||||
if(Strings.CI.endsWith(fileName, ".json")) {
|
||||
String content = SysCommon.loadResFileContentByPath("/excel_define/import/"+fileName, 2);
|
||||
ImportDefine defineObject = null;
|
||||
try {
|
||||
defineObject = JSONObject.parseObject(content, ImportDefine.class,Feature.SupportNonPublicField,Feature.IgnoreNotMatch);
|
||||
if(defineObject!=null && StringUtils.isNotBlank(defineObject.getImportName())) {
|
||||
importDefines.put(defineObject.getImportName(), defineObject);
|
||||
}
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Parse import define failed with error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}catch (Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Load import define failed with error:"+err.getMessage());
|
||||
}
|
||||
try {
|
||||
File directory = new File(SysCommon.runtime_path + "/"+SysCommon.runtimeName+"/excel_define/export/");
|
||||
String[] fileNames = directory.list();
|
||||
if (fileNames != null) {
|
||||
for (String fileName : fileNames) {
|
||||
if(Strings.CI.endsWith(fileName, ".json")) {
|
||||
String content = SysCommon.loadResFileContentByPath("/excel_define/export/"+fileName, 2);
|
||||
ExportDefine defineObject = null;
|
||||
try {
|
||||
defineObject = JSONObject.parseObject(content, ExportDefine.class,Feature.SupportNonPublicField,Feature.IgnoreNotMatch);
|
||||
if(defineObject!=null && StringUtils.isNotBlank(defineObject.getExportName())) {
|
||||
exportDefines.put(defineObject.getExportName(), defineObject);
|
||||
}
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Parse export define failed with error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}catch (Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Load export define failed with error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static ImportDefine getImportDefineByName(String importName) {
|
||||
ImportDefine importDef = null;
|
||||
if(importDefines.containsKey(importName)) {
|
||||
importDef = importDefines.get(importName);
|
||||
}
|
||||
return importDef;
|
||||
}
|
||||
|
||||
public static ExportDefine getExportDefineByName(String exportName) {
|
||||
ExportDefine exportDef = null;
|
||||
if(exportDefines.containsKey(exportName)) {
|
||||
exportDef = exportDefines.get(exportName);
|
||||
}
|
||||
return exportDef;
|
||||
}
|
||||
|
||||
public static BaseApiResponse<List<Object>> importDataBlock(ImportDefine importDef, String importFileName, Map<String,List<GroupItem>> groupInfo) {
|
||||
BaseApiResponse<List<Object>> processResult = new BaseApiResponse<>();
|
||||
processResult.setSuccess(true);
|
||||
List<Object> resultData = new ArrayList<>();
|
||||
try {
|
||||
FileInputStream excelFile = new FileInputStream(importFileName);
|
||||
XSSFWorkbook wbook = new XSSFWorkbook(excelFile);
|
||||
List<SheetDefine> pageDefs = importDef.getImportPages();
|
||||
if(pageDefs!=null) {
|
||||
for(SheetDefine sheetDef:pageDefs) {
|
||||
XSSFSheet sheet=null;
|
||||
if(StringUtils.isNotBlank(sheetDef.getSheetName())) {
|
||||
sheet = wbook.getSheet(sheetDef.getSheetName());
|
||||
}else {
|
||||
sheet = wbook.getSheetAt(sheetDef.getSheetIndx());
|
||||
}
|
||||
if(sheet==null) {
|
||||
processResult.setSuccess(false);
|
||||
String errorMsg = "Data Sheet "+sheetDef.getSheetIndx()
|
||||
+(StringUtils.isNotBlank(sheetDef.getSheetName())?" ["+sheetDef.getSheetName()+"]":"")+" not found";
|
||||
processResult.setMessage(errorMsg);
|
||||
break;
|
||||
}else {
|
||||
if(sheetDef.getDataElements()!=null) {
|
||||
int lastRow=0;
|
||||
int lastCol=0;
|
||||
for(DataBlock dataBlock:sheetDef.getDataElements()) {
|
||||
List<RowFieldInfo> masterFields = new ArrayList<RowFieldInfo>();
|
||||
List<ColumnGroupInfo> groupList = new ArrayList<ColumnGroupInfo>();
|
||||
List<ColumnDefine> colDefs = dataBlock.getColumnDefs();
|
||||
Class<?> objClass = null;
|
||||
if(StringUtils.isNotBlank(dataBlock.getObjClassName())) {
|
||||
try {
|
||||
objClass = Class.forName(dataBlock.getObjClassName());
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Get import data class error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
int colIdx =0;
|
||||
for(int k=0; k<colDefs.size();k++) {
|
||||
ColumnDefine colDef = colDefs.get(k);
|
||||
if(StringUtils.isBlank(colDef.getGroupName())) {
|
||||
RowFieldInfo colInfo= getImportFieldInfoFromDefine(colDef,objClass);
|
||||
colInfo.setColIndex(colIdx);
|
||||
masterFields.add(colInfo);
|
||||
colIdx++;
|
||||
}else if(groupInfo!=null) {
|
||||
ColumnGroupInfo colGroup = new ColumnGroupInfo();
|
||||
Field attrField = null;
|
||||
Field keyAttrField=null;
|
||||
if(objClass!=null && StringUtils.isNotBlank(colDef.getAttrName())) {
|
||||
try {
|
||||
attrField = objClass.getDeclaredField(colDef.getAttrName());
|
||||
attrField.setAccessible(true);
|
||||
}catch(Exception err) {
|
||||
attrField = null;
|
||||
LogUtil.error(ExcelUtils.class, "Get import group Field Define Error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
colGroup.setGroupDataField(attrField);
|
||||
Class<?> objGroupDataClass = null;
|
||||
if(StringUtils.isNotBlank(colDef.getDataType())) {
|
||||
try {
|
||||
objGroupDataClass = Class.forName(colDef.getDataType());
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Get import group data class error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
if(objGroupDataClass!=null && StringUtils.isNotBlank(colDef.getGroupKeyAttrName())) {
|
||||
try {
|
||||
keyAttrField = objGroupDataClass.getDeclaredField(colDef.getGroupKeyAttrName());
|
||||
keyAttrField.setAccessible(true);
|
||||
}catch(Exception err) {
|
||||
keyAttrField = null;
|
||||
LogUtil.error(ExcelUtils.class, "Get Import group key Field Define Error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
//--
|
||||
List<ColumnDefine> groupColDefs = colDef.getGroupColumns();
|
||||
List<RowFieldInfo> groupColumns = new ArrayList<RowFieldInfo>();
|
||||
for(ColumnDefine gColDef:groupColDefs) {
|
||||
RowFieldInfo gField = getImportFieldInfoFromDefine(gColDef,objGroupDataClass);
|
||||
groupColumns.add(gField);
|
||||
}
|
||||
//--
|
||||
colGroup.setGroupColumns(groupColumns);
|
||||
colGroup.setGroupDataType(objGroupDataClass);
|
||||
colGroup.setKeyField(keyAttrField);
|
||||
colGroup.setColStartIndex(colIdx);
|
||||
if(groupInfo.containsKey(colDef.getGroupName())) {
|
||||
List<GroupItem> groupItems = groupInfo.get(colDef.getGroupName());
|
||||
List<GroupItem> sortGroupItems = new ArrayList<GroupItem>();
|
||||
Row headerRow = sheet.getRow(lastRow+groupItems.getFirst().getHeaderIndex());
|
||||
for(int m=0;m<groupItems.size();m++) {
|
||||
String groupKeyVal = getCellTextValueInRow(headerRow,lastCol+colIdx+m*groupColumns.size(),true).trim();
|
||||
if(StringUtils.isNotBlank(groupKeyVal)) {
|
||||
for(GroupItem gItem:groupItems) {
|
||||
if(Strings.CI.equals(groupKeyVal, gItem.getItemText())) {
|
||||
sortGroupItems.add(gItem);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
colGroup.setGroupItems(sortGroupItems);
|
||||
groupInfo.put(colDef.getGroupName(), sortGroupItems);
|
||||
colIdx+=sortGroupItems.size()*groupColumns.size();
|
||||
}
|
||||
groupList.add(colGroup);
|
||||
}
|
||||
}
|
||||
//--
|
||||
String validateCode = validateBlockTemplate(sheet, masterFields,groupList,lastRow,lastCol);
|
||||
if(StringUtils.isBlank(validateCode)) {
|
||||
int cRow=dataBlock.getOffsetRow()>=0?dataBlock.getOffsetRow():lastRow-dataBlock.getOffsetRow();
|
||||
int cCol=dataBlock.getOffsetCol()>=0?dataBlock.getOffsetCol():lastCol-dataBlock.getOffsetCol();
|
||||
List<Object> blockResult = parseImportDataBlock(sheet,objClass, masterFields,groupList,cRow,cCol);
|
||||
resultData.add(blockResult);
|
||||
}else {
|
||||
processResult.setSuccess(false);
|
||||
processResult.setCode(validateCode);
|
||||
processResult.setMessage("Invalid Import Template");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!processResult.isSuccess()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
processResult.setData(resultData);
|
||||
}
|
||||
}catch(Exception err) {
|
||||
processResult.setSuccess(false);
|
||||
processResult.setCode("-1");
|
||||
processResult.setMessage(err.getMessage());
|
||||
}
|
||||
return processResult;
|
||||
}
|
||||
|
||||
private static String validateBlockTemplate(XSSFSheet sheet,List<RowFieldInfo> masterFields,List<ColumnGroupInfo> groupList, int lastBlockRowEnd, int lastBlockColEnd) {
|
||||
String errCode = "";
|
||||
for(int i=0;i<masterFields.size();i++) {
|
||||
RowFieldInfo colDef = masterFields.get(i);
|
||||
if(StringUtils.isNotBlank(colDef.getColumnHeader()) && colDef.isCheckHeader()){
|
||||
Row headerRow = sheet.getRow(lastBlockRowEnd+colDef.getHeaderRowIdx());
|
||||
String cellVal = getCellTextValueInRow(headerRow,lastBlockColEnd+colDef.getColIndex(),true).trim();
|
||||
//LogUtil.info(ExcelUtils.class, "Check column at Col["+ (lastBlockColEnd+colDef.getColIndex())+"] with cellVal"+cellVal);
|
||||
if(!Strings.CI.equals(colDef.getColumnHeader(), cellVal)) {
|
||||
LogUtil.error(ExcelUtils.class, "Import Column Name["+colDef.getColumnHeader()+"] is not match in template");
|
||||
errCode="INVALID_TEMPLATE";
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(StringUtils.isBlank(errCode) && groupList!=null && groupList.size()>0) {
|
||||
for(int i=0;i<groupList.size();i++) {
|
||||
ColumnGroupInfo colGroup = groupList.get(i);
|
||||
List<GroupItem> gItems = colGroup.getGroupItems();
|
||||
for(int j=0;j<gItems.size();j++) {
|
||||
GroupItem gItem = gItems.get(j);
|
||||
Row headerRow = sheet.getRow(lastBlockRowEnd+gItem.getHeaderIndex());
|
||||
String groupKeyVal = getCellTextValueInRow(headerRow,lastBlockColEnd+colGroup.getColStartIndex()+j*colGroup.getGroupColumns().size(),true).trim();
|
||||
if(!Strings.CI.equals(groupKeyVal, gItem.getItemText())) {
|
||||
LogUtil.error(ExcelUtils.class, "Import Column Name["+gItem.getItemText()+"] is not match in template");
|
||||
errCode="INVALID_TEMPLATE";
|
||||
break;
|
||||
}
|
||||
//LogUtil.info(ExcelUtils.class, "Check Group column["+j+" at with cellVal"+groupKeyVal);
|
||||
}
|
||||
if(StringUtils.isNotBlank(errCode)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return errCode;
|
||||
}
|
||||
|
||||
private static List<Object> parseImportDataBlock(XSSFSheet sheet,Class<?> objClass, List<RowFieldInfo> masterFields,List<ColumnGroupInfo> groupList,int cRow, int cCol) throws InstantiationException, IllegalAccessException{
|
||||
List<Object> parseResult = new ArrayList<Object>();
|
||||
//--
|
||||
int maxDataRow = sheet.getLastRowNum();
|
||||
String[] dataRow=null;
|
||||
Object dataRowObj=null;
|
||||
boolean isEnd=false;
|
||||
while(isEnd==false) {
|
||||
boolean isEmptyRow=true;
|
||||
if(objClass==null) {
|
||||
dataRow= new String[masterFields.size()];
|
||||
}else {
|
||||
dataRowObj = objClass.newInstance();
|
||||
}
|
||||
Row curRow = sheet.getRow(cRow);
|
||||
if(curRow!=null) {
|
||||
for(int i=0; i<masterFields.size();i++) {
|
||||
RowFieldInfo fieldInfo = masterFields.get(i);
|
||||
String cellVal = getCellTextValueInRow(curRow,cCol+fieldInfo.getColIndex(),true);
|
||||
cellVal= cellVal.trim();
|
||||
if(StringUtils.isNotBlank(cellVal)) {
|
||||
isEmptyRow=false;
|
||||
}
|
||||
if(objClass==null) {
|
||||
dataRow[i]=cellVal;
|
||||
}else if(fieldInfo.getDataField() !=null) {
|
||||
try {
|
||||
fieldInfo.getDataField().set(dataRowObj,cellVal);
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Set Import Field error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
if(groupList!=null && groupList.size()>0) {
|
||||
for(ColumnGroupInfo groupInfo:groupList) {
|
||||
List<RowFieldInfo> gFields = groupInfo.getGroupColumns();
|
||||
List<GroupItem> gItems = groupInfo.getGroupItems();
|
||||
List<Object> groupData = new ArrayList<Object>();
|
||||
for(int i=0;i<gItems.size();i++) {
|
||||
Object itemRow = groupInfo.getGroupDataType().newInstance();
|
||||
try {
|
||||
groupInfo.getKeyField().set(itemRow,gItems.get(i).getItemText());
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Set Import Group Key Field error:"+err.getMessage());
|
||||
}
|
||||
for(int j=0;j<gFields.size();j++) {
|
||||
RowFieldInfo fieldInfo = gFields.get(j);
|
||||
String cellVal = getCellTextValueInRow(curRow,cCol+groupInfo.getColStartIndex()+i*gFields.size()+j,true).trim();
|
||||
try {
|
||||
fieldInfo.getDataField().set(itemRow,cellVal);
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Set Import Group Field error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
groupData.add(itemRow);
|
||||
}
|
||||
try {
|
||||
groupInfo.getGroupDataField().set(dataRowObj,groupData);
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Set Import Group Attribute Field error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if(isEmptyRow==false) {
|
||||
if(objClass==null) {
|
||||
parseResult.add(dataRow);
|
||||
}else {
|
||||
parseResult.add(dataRowObj);
|
||||
}
|
||||
}
|
||||
if(isEmptyRow==true || cRow>= maxDataRow) {
|
||||
isEnd=true;
|
||||
}
|
||||
cRow++;
|
||||
}
|
||||
//--
|
||||
return parseResult;
|
||||
}
|
||||
|
||||
//--
|
||||
public static String getCellTextValueInRow(Row row, int colIndex, boolean isAutoDetect) {
|
||||
String cellValue = "";
|
||||
if (row != null) {
|
||||
Cell cell = row.getCell(colIndex);
|
||||
if (cell != null) {
|
||||
if(isAutoDetect==false) {
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
|
||||
Date dateVal = DateUtil.getJavaDate(cell.getNumericCellValue());
|
||||
if(dateVal!=null)
|
||||
cellValue = dateFormat.format(dateVal);
|
||||
else
|
||||
cellValue="";
|
||||
}else {
|
||||
if (cell.getCellType().equals(CellType.BOOLEAN)) {
|
||||
cellValue = String.valueOf(cell.getBooleanCellValue());
|
||||
} else if (cell.getCellType().equals(CellType.NUMERIC)) {
|
||||
|
||||
double cellNumValue = cell.getNumericCellValue();
|
||||
// --如果是整數則去掉後面的位數轉成整數
|
||||
if (Math.floor(cellNumValue) == cellNumValue) {
|
||||
cellValue = String.valueOf((int) Math.floor(cellNumValue));
|
||||
} else {
|
||||
cellValue = String.valueOf(cell.getNumericCellValue());
|
||||
}
|
||||
|
||||
} else {
|
||||
cellValue = cell.getRichStringCellValue().getString();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return cellValue;
|
||||
}
|
||||
|
||||
private static RowFieldInfo getImportFieldInfoFromDefine(ColumnDefine colDef,Class<?> masterClass) {
|
||||
Field attrField = null;
|
||||
RowFieldInfo colInfo= new RowFieldInfo();
|
||||
if(masterClass!=null && StringUtils.isNotBlank(colDef.getAttrName())) {
|
||||
try {
|
||||
attrField = masterClass.getDeclaredField(colDef.getAttrName());
|
||||
attrField.setAccessible(true);
|
||||
}catch(Exception err) {
|
||||
attrField = null;
|
||||
LogUtil.error(ExcelUtils.class, "Get Field Define Error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
colInfo.setColumnHeader(colDef.getColumnHeader());
|
||||
colInfo.setHeaderRowIdx(colDef.getHeaderRowIdx());
|
||||
colInfo.setCheckHeader(colDef.isCheckHeader());
|
||||
colInfo.setDataField(attrField);
|
||||
return colInfo;
|
||||
}
|
||||
|
||||
private static RowFieldInfo getFieldInfoFromDefine(ColumnDefine colDef,Class<?> masterClass,XSSFCellStyle fieldStyle, XSSFCellStyle tStyle,XSSFDataFormat dataFormat) {
|
||||
Field attrField = null;
|
||||
RowFieldInfo colInfo= new RowFieldInfo();
|
||||
if(masterClass!=null && StringUtils.isNotBlank(colDef.getAttrName())) {
|
||||
try {
|
||||
attrField = masterClass.getDeclaredField(colDef.getAttrName());
|
||||
attrField.setAccessible(true);
|
||||
}catch(Exception err) {
|
||||
attrField = null;
|
||||
LogUtil.error(ExcelUtils.class, "Get Field Define Error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
colInfo.setCheckHeader(colDef.isCheckHeader());
|
||||
colInfo.setDataField(attrField);
|
||||
colInfo.setColumnHeader(colDef.getColumnHeader());
|
||||
colInfo.setHeaderRowIdx(colDef.getHeaderRowIdx());
|
||||
colInfo.setDateFormat(colDef.getFormatVal());
|
||||
colInfo.setDataType(colDef.getDataType());
|
||||
fieldStyle.cloneStyleFrom(tStyle);
|
||||
fieldStyle.setDataFormat(getCellTextFormatByDataType(colDef.getFormatVal(),dataFormat));
|
||||
if(StringUtils.isNotBlank(colDef.getTextAlign())) {
|
||||
String fa = colDef.getTextAlign();
|
||||
fieldStyle.setAlignment(Strings.CS.equals(fa, "center")?HorizontalAlignment.CENTER:(Strings.CS.equals(fa, "right")?HorizontalAlignment.RIGHT:HorizontalAlignment.LEFT));
|
||||
}
|
||||
colInfo.setFieldStyle(fieldStyle);
|
||||
return colInfo;
|
||||
}
|
||||
|
||||
public static File exportEXCEL(ExportDefine excelDef, Map<String,List<Object>> exportData, Map<String,List<GroupItem>> groupInfo) throws Exception {
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
|
||||
XSSFWorkbook wbook = new XSSFWorkbook();
|
||||
List<SheetDefine> pageDefs = excelDef.getExportPages();
|
||||
//--
|
||||
for(int i=0; i<pageDefs.size();i++) {
|
||||
SheetDefine pageDef = pageDefs.get(i);
|
||||
//----
|
||||
XSSFSheet wsheet = wbook.createSheet(pageDef.getSheetName());
|
||||
int cRow =0;
|
||||
int cCol = 0;
|
||||
List<DataBlock> pageElements = pageDef.getDataElements();
|
||||
if(pageElements!=null) {
|
||||
for(int j=0;j<pageElements.size();j++) {
|
||||
DataBlock dataDef = pageElements.get(j);
|
||||
XSSFColor textColor=null;
|
||||
XSSFColor headerTextColor=null;
|
||||
XSSFColor headerBkColor=null;
|
||||
if(StringUtils.isNotBlank(dataDef.getTextColor())) {
|
||||
textColor = new XSSFColor(Color.decode(dataDef.getTextColor()), new DefaultIndexedColorMap());
|
||||
}else {
|
||||
textColor = new XSSFColor(Color.black, new DefaultIndexedColorMap());
|
||||
}
|
||||
if(StringUtils.isNotBlank(dataDef.getHeaderTextColor())) {
|
||||
headerTextColor = new XSSFColor(Color.decode(dataDef.getHeaderTextColor()), new DefaultIndexedColorMap());
|
||||
}else {
|
||||
headerTextColor = new XSSFColor(Color.black, new DefaultIndexedColorMap());
|
||||
}
|
||||
if(StringUtils.isNotBlank(dataDef.getHeaderColor())) {
|
||||
headerBkColor = new XSSFColor(Color.decode(dataDef.getHeaderColor()), new DefaultIndexedColorMap());
|
||||
}else {
|
||||
headerBkColor = new XSSFColor(Color.blue, new DefaultIndexedColorMap());
|
||||
}
|
||||
//--列標題字體
|
||||
XSSFFont titleFont = wbook.createFont();
|
||||
titleFont.setFontName("Arial");
|
||||
titleFont.setBold(true);
|
||||
titleFont.setFontHeightInPoints((short)12);
|
||||
titleFont.setColor(headerTextColor);
|
||||
//--内容字體
|
||||
XSSFFont normalFont = wbook.createFont();
|
||||
normalFont.setFontName("Arial");
|
||||
normalFont.setBold(false);
|
||||
normalFont.setFontHeightInPoints((short)12);
|
||||
normalFont.setColor(textColor);
|
||||
//--主標題樣式
|
||||
XSSFCellStyle titleStyle = wbook.createCellStyle();
|
||||
titleStyle.setFont(titleFont);
|
||||
titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
titleStyle.setFillForegroundColor(headerBkColor);
|
||||
//--文本列缺省樣式
|
||||
XSSFDataFormat dataFormat = wbook.createDataFormat();
|
||||
XSSFCellStyle tStyle = wbook.createCellStyle();
|
||||
tStyle.setFont(normalFont);
|
||||
tStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));
|
||||
|
||||
//--
|
||||
if(dataDef.getOffsetRow()<0) {
|
||||
cRow = cRow+Math.abs(dataDef.getOffsetRow())-1;
|
||||
}else {
|
||||
cRow = dataDef.getOffsetRow();
|
||||
}
|
||||
if(dataDef.getOffsetCol()<0) {
|
||||
cCol = cCol+Math.abs(dataDef.getOffsetCol())-1;
|
||||
}else {
|
||||
cCol = dataDef.getOffsetCol();
|
||||
}
|
||||
//--
|
||||
String ha = dataDef.getHeaderAlign();
|
||||
titleStyle.setAlignment(Strings.CS.equals(ha, "center")?HorizontalAlignment.CENTER:(Strings.CS.equals(ha, "right")?HorizontalAlignment.RIGHT:HorizontalAlignment.LEFT));
|
||||
String ta = dataDef.getTextAlign();
|
||||
tStyle.setAlignment(Strings.CS.equals(ta, "center")?HorizontalAlignment.CENTER:(Strings.CS.equals(ta, "right")?HorizontalAlignment.RIGHT:HorizontalAlignment.LEFT));
|
||||
//--
|
||||
if(dataDef.getElementType()==ExcelUtils.TEXT_ELEMENT) {
|
||||
ColumnDefine colDef = (dataDef.getColumnDefs()!=null&& !dataDef.getColumnDefs().isEmpty())?dataDef.getColumnDefs().getFirst():null;
|
||||
if(colDef!=null) {
|
||||
if(dataDef.isShowHeader()) {
|
||||
setCellText(getCell(wsheet,cRow,cCol),titleStyle,colDef.getColumnHeader(),"String");
|
||||
cRow++;
|
||||
}
|
||||
String dataVal = "";
|
||||
List<Object> bData = exportData.get(dataDef.getBlockName());
|
||||
if(bData!=null&& !bData.isEmpty()) {
|
||||
dataVal = String.valueOf(bData.getFirst());
|
||||
}
|
||||
setCellText(getCell(wsheet,cRow,cCol),tStyle,dataVal,"String");
|
||||
if(colDef.getColumnWidth()>0) {
|
||||
wsheet.setColumnWidth(cCol, colDef.getColumnWidth()*256);
|
||||
}
|
||||
cRow++;
|
||||
cCol++;
|
||||
}
|
||||
|
||||
}else if(dataDef.getElementType()==ExcelUtils.DATABLOCK_ELEMENT) {
|
||||
int startRow = cRow;
|
||||
int startCol = cCol;
|
||||
List<ColumnDefine> colDefs = dataDef.getColumnDefs();
|
||||
Class<?> objClass = null;
|
||||
if(StringUtils.isNotBlank(dataDef.getObjClassName())) {
|
||||
try {
|
||||
objClass = Class.forName(dataDef.getObjClassName());
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Get export data class error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
List<RowFieldInfo> masterFields = new ArrayList<RowFieldInfo>();
|
||||
List<ColumnGroupInfo> groupList = new ArrayList<ColumnGroupInfo>();
|
||||
List<XSSFCellStyle> fieldStyles = new ArrayList<XSSFCellStyle>();
|
||||
int colIdx =0;
|
||||
for(int k=0; k<colDefs.size();k++) {
|
||||
ColumnDefine colDef = colDefs.get(k);
|
||||
if(StringUtils.isBlank(colDef.getGroupName())) {
|
||||
RowFieldInfo colInfo= getFieldInfoFromDefine(colDef,objClass,wbook.createCellStyle(),tStyle,dataFormat);
|
||||
colInfo.setColIndex(colIdx);
|
||||
if(dataDef.isShowHeader()) {
|
||||
for(int m=0;m<dataDef.getHeaderRowNum();m++) {
|
||||
String headerText=(m==colDef.getHeaderRowIdx()?colDef.getColumnHeader():"");
|
||||
setCellText(getCell(wsheet,startRow+m,startCol+colIdx),titleStyle,headerText,"String");
|
||||
}
|
||||
}
|
||||
if(colDef.getColumnWidth()>0) {
|
||||
wsheet.setColumnWidth(startCol+colIdx, colDef.getColumnWidth()*256);
|
||||
}
|
||||
masterFields.add(colInfo);
|
||||
colIdx++;
|
||||
}else if(groupInfo!=null) {
|
||||
ColumnGroupInfo colGroup = new ColumnGroupInfo();
|
||||
Field attrField = null;
|
||||
Field keyAttrField=null;
|
||||
if(objClass!=null && StringUtils.isNotBlank(colDef.getAttrName())) {
|
||||
try {
|
||||
attrField = objClass.getDeclaredField(colDef.getAttrName());
|
||||
attrField.setAccessible(true);
|
||||
}catch(Exception err) {
|
||||
attrField = null;
|
||||
LogUtil.error(ExcelUtils.class, "Get export group Field Define Error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
colGroup.setGroupDataField(attrField);
|
||||
Class<?> objGroupDataClass = null;
|
||||
if(StringUtils.isNotBlank(colDef.getDataType())) {
|
||||
try {
|
||||
objGroupDataClass = Class.forName(colDef.getDataType());
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Get export group data class error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
if(objGroupDataClass!=null && StringUtils.isNotBlank(colDef.getGroupKeyAttrName())) {
|
||||
try {
|
||||
keyAttrField = objGroupDataClass.getDeclaredField(colDef.getGroupKeyAttrName());
|
||||
keyAttrField.setAccessible(true);
|
||||
}catch(Exception err) {
|
||||
keyAttrField = null;
|
||||
LogUtil.error(ExcelUtils.class, "Get export group key Field Define Error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
//--
|
||||
List<ColumnDefine> groupColDefs = colDef.getGroupColumns();
|
||||
List<RowFieldInfo> groupColumns = new ArrayList<RowFieldInfo>();
|
||||
for(ColumnDefine gColDef:groupColDefs) {
|
||||
RowFieldInfo gField = getFieldInfoFromDefine(gColDef,objGroupDataClass,wbook.createCellStyle(),tStyle,dataFormat);
|
||||
groupColumns.add(gField);
|
||||
}
|
||||
//--
|
||||
colGroup.setGroupColumns(groupColumns);
|
||||
colGroup.setGroupDataType(objGroupDataClass);
|
||||
colGroup.setKeyField(keyAttrField);
|
||||
colGroup.setColStartIndex(colIdx);
|
||||
if(groupInfo.containsKey(colDef.getGroupName())) {
|
||||
List<GroupItem> groupItems = groupInfo.get(colDef.getGroupName());
|
||||
colGroup.setGroupItems(groupItems);
|
||||
if(dataDef.isShowHeader()) {
|
||||
for(int m=0;m<groupItems.size();m++) {
|
||||
GroupItem gItem=groupItems.get(m);
|
||||
if(gItem.getHeaderIndex()>=0) {
|
||||
int gRow = gItem.getHeaderIndex();
|
||||
if(groupColumns.size()>1) {
|
||||
CellRangeAddress groupHeaderMerge = new CellRangeAddress(startRow+gRow, startRow+gRow, startCol+colIdx+m*groupColumns.size(), startCol+colIdx+((m+1)*groupColumns.size()-1));
|
||||
wsheet.addMergedRegion(groupHeaderMerge);
|
||||
}
|
||||
setCellText(getCell(wsheet,startRow+gItem.getHeaderIndex(),startCol+colIdx+(m*groupColumns.size())),titleStyle,gItem.getItemText(),"String");
|
||||
}
|
||||
if(groupColDefs!=null && groupColDefs.size()>0) {
|
||||
for(int n=0;n<groupColDefs.size();n++) {
|
||||
ColumnDefine gcItem =groupColDefs.get(n);
|
||||
if(StringUtils.isNotBlank(gcItem.getColumnHeader())) {
|
||||
setCellText(getCell(wsheet,startRow+gcItem.getHeaderRowIdx(),startCol+colIdx+(m*groupColumns.size())+n),titleStyle,gcItem.getColumnHeader(),"String");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if(StringUtils.isNotBlank(colDef.getColumnHeader())) {
|
||||
int hRow = colDef.getHeaderRowIdx();
|
||||
CellRangeAddress totalHeaderMerge = new CellRangeAddress(startRow+hRow, startRow+hRow, startCol+colIdx, startCol+colIdx+(groupItems.size()*groupColumns.size())-1);
|
||||
wsheet.addMergedRegion(totalHeaderMerge);
|
||||
setCellText(getCell(wsheet,startRow+hRow,startCol+colIdx),titleStyle,colDef.getColumnHeader(),"String");
|
||||
}
|
||||
}
|
||||
colIdx+=groupColumns.size()*groupItems.size();
|
||||
}
|
||||
groupList.add(colGroup);
|
||||
}
|
||||
}
|
||||
//--
|
||||
if(dataDef.isShowHeader()) {
|
||||
startRow+=dataDef.getHeaderRowNum();
|
||||
}
|
||||
List<Object> bData = exportData.get(dataDef.getBlockName());
|
||||
int maxColIdx =0;
|
||||
if(bData!=null) {
|
||||
for(int k=0; k<bData.size();k++) {
|
||||
Object colData = bData.get(k);
|
||||
if(colData!=null) {
|
||||
for(int m=0; m<masterFields.size();m++) {
|
||||
RowFieldInfo fieldInfo = masterFields.get(m);
|
||||
if(fieldInfo!=null) {
|
||||
String dataVal = "";
|
||||
Field dataField = fieldInfo.getDataField();
|
||||
if(dataField!=null) {
|
||||
try {
|
||||
Object attrObj = dataField.get(colData);
|
||||
if(attrObj !=null && Strings.CI.equals("DATE", fieldInfo.getDataType()) && attrObj instanceof Date) {
|
||||
try {
|
||||
dateFormat = new SimpleDateFormat(fieldInfo.getDateFormat());
|
||||
dataVal = dateFormat.format(attrObj);
|
||||
}catch(Exception err) {
|
||||
dataVal = attrObj.toString();
|
||||
}
|
||||
}else {
|
||||
dataVal = (attrObj==null?"":attrObj.toString());
|
||||
}
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Get Field error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
XSSFCellStyle fieldStyle = fieldInfo.getFieldStyle();
|
||||
setCellText(getCell(wsheet,startRow,startCol+fieldInfo.getColIndex()),fieldStyle,dataVal,fieldInfo.getDataType());
|
||||
}
|
||||
}
|
||||
//--Extract group data
|
||||
for(ColumnGroupInfo dataGroup: groupList) {
|
||||
Field dataField = dataGroup.getGroupDataField();
|
||||
Class<?> dataType = dataGroup.getGroupDataType();
|
||||
List<?> groupDataList = null;
|
||||
if(dataField!=null) {
|
||||
try {
|
||||
groupDataList = (List<?>)dataField.get(colData);
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Get Group Data error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
if(groupDataList!=null) {
|
||||
for(int m=0;m<groupDataList.size();m++) {
|
||||
Object dataItem = groupDataList.get(m);
|
||||
String keyVal = "";
|
||||
try {
|
||||
Object keyAttrObj =dataGroup.getKeyField().get(dataItem);
|
||||
if(keyAttrObj!=null)
|
||||
keyVal = keyAttrObj.toString();
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Get Group Data Key error:"+err.getMessage());
|
||||
}
|
||||
for(int n=0;n<dataGroup.getGroupItems().size();n++) {
|
||||
GroupItem gItem = dataGroup.getGroupItems().get(n);
|
||||
if(Strings.CS.equals(keyVal, gItem.getItemKey())) {
|
||||
List<RowFieldInfo> gFields = dataGroup.getGroupColumns();
|
||||
for(int p=0;p<gFields.size();p++) {
|
||||
RowFieldInfo gField = gFields.get(p);
|
||||
String dataVal = "";
|
||||
if(gField.getDataField()!=null) {
|
||||
try {
|
||||
Object attrObj = gField.getDataField().get(dataItem);
|
||||
dataVal = (attrObj==null?"":attrObj.toString());
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Get Group Field error:"+err.getMessage());
|
||||
}
|
||||
}
|
||||
XSSFCellStyle fieldStyle = gField.getFieldStyle();
|
||||
int gCol = startCol+dataGroup.getColStartIndex()+n*gFields.size()+p;
|
||||
setCellText(getCell(wsheet,startRow,gCol),fieldStyle,dataVal,gField.getDataType());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
//--
|
||||
startRow++;
|
||||
}
|
||||
}
|
||||
}
|
||||
cRow = startRow;
|
||||
cCol +=maxColIdx;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//--
|
||||
String excelFileName = System.currentTimeMillis()+UUID.randomUUID().toString().substring(0, 4)+".xlsx";
|
||||
File excelFile = new File(SysCommon.runtime_path + "/"+SysCommon.runtimeName+"/tmp/" + excelFileName);
|
||||
if (!excelFile.getParentFile().exists()) {
|
||||
// 判断文件父目录是否存在
|
||||
FileUtils.forceMkdir(excelFile.getParentFile());
|
||||
}
|
||||
OutputStream os = new FileOutputStream(excelFile);
|
||||
wbook.write(os); // 写入文件
|
||||
wbook=null;
|
||||
os.close();
|
||||
return excelFile;
|
||||
}
|
||||
|
||||
private static int getCellTextFormatByDataType(String formatVal, XSSFDataFormat dataFormat) {
|
||||
if(StringUtils.isBlank(formatVal))
|
||||
formatVal = "@";
|
||||
int textFormat = BuiltinFormats.getBuiltinFormat(formatVal);
|
||||
if(textFormat<=-1) {
|
||||
textFormat = customFormatIndex;
|
||||
dataFormat.putFormat((short)textFormat, formatVal);
|
||||
customFormatIndex++;
|
||||
}
|
||||
return textFormat;
|
||||
}
|
||||
|
||||
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);
|
||||
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());
|
||||
}
|
||||
public static void errorResponse(String errorMessage,HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
//response.setContentType("text/html");
|
||||
String returnMsg = StringEscapeUtils.escapeHtml4(errorMessage);
|
||||
response.sendError(500, returnMsg);
|
||||
}
|
||||
//===========
|
||||
public static ExportDefine parseExportDefination(String jsonContent) {
|
||||
ExportDefine exportDef = null;
|
||||
try {
|
||||
exportDef = JSONObject.parseObject(jsonContent,ExportDefine.class);
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Parse Export Defination error:"+err.getMessage());
|
||||
}
|
||||
return exportDef;
|
||||
}
|
||||
|
||||
public static SheetDefine parseExportSheet(String jsonContent) {
|
||||
SheetDefine exportSheetDef = null;
|
||||
try {
|
||||
exportSheetDef = JSONObject.parseObject(jsonContent,SheetDefine.class);
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Parse Export Sheet error:"+err.getMessage());
|
||||
}
|
||||
return exportSheetDef;
|
||||
}
|
||||
|
||||
public static DataBlock parseDataElement(String jsonContent) {
|
||||
DataBlock exportDateElementDef = null;
|
||||
try {
|
||||
exportDateElementDef = JSONObject.parseObject(jsonContent,DataBlock.class);
|
||||
}catch(Exception err) {
|
||||
LogUtil.error(ExcelUtils.class, "Parse Export Data Element error:"+err.getMessage());
|
||||
}
|
||||
return exportDateElementDef;
|
||||
}
|
||||
|
||||
public static ResFileResult transTempFile(MultipartFile file) {
|
||||
ResFileResult result = new ResFileResult();
|
||||
String originalFileName = "";
|
||||
try {
|
||||
originalFileName = file.getOriginalFilename();
|
||||
String tmpFolderName =SysCommon.runtime_path+"/"+SysCommon.runtimeName+"/tmp";
|
||||
File resourceFolder = new File(tmpFolderName);
|
||||
if(!resourceFolder.exists()) {
|
||||
FileUtils.forceMkdir(resourceFolder);
|
||||
}
|
||||
Date currentTime = new Date();
|
||||
String tmpFileName = msecondFormat.format(currentTime.toInstant())+"_"+rnd.nextInt(1000)+".xlsx";
|
||||
String targetFileName = tmpFolderName+"/"+tmpFileName;
|
||||
byte[] fileData = file.getBytes();
|
||||
FileOutputStream fio = new FileOutputStream(targetFileName);
|
||||
fio.write(fileData);
|
||||
fio.close();
|
||||
result.setSuccess(true);
|
||||
result.setFileName(tmpFileName);
|
||||
result.setFilePath(targetFileName);
|
||||
}catch(Exception err) {
|
||||
result.setSuccess(false);
|
||||
LogUtil.error(ExcelUtils.class, "Read import file ["+originalFileName+"] error:"+ err.getMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public static void clearTempFile(String filePath) {
|
||||
try {
|
||||
String targetFileName = Strings.CI.startsWith(filePath, SysCommon.runtime_path)?
|
||||
filePath:(SysCommon.runtime_path+"/"+SysCommon.runtimeName+"/tmp/"+filePath);
|
||||
targetFileName = targetFileName.replace("\\", "/");
|
||||
while(targetFileName.indexOf("//")>=0) {
|
||||
targetFileName = targetFileName.replace("//", "/");
|
||||
}
|
||||
File resFile = new File(targetFileName);
|
||||
if(resFile.exists()) {
|
||||
resFile.delete();
|
||||
}
|
||||
}catch(Exception ignored) {
|
||||
|
||||
}
|
||||
}
|
||||
//===========
|
||||
private static XSSFCell getCell(XSSFSheet wsheet, int cRow, int cCol){
|
||||
XSSFCell cell = null;
|
||||
XSSFRow row = wsheet.getRow(cRow);
|
||||
if(row==null){
|
||||
row = wsheet.createRow(cRow);
|
||||
}
|
||||
cell = row.getCell(cCol);
|
||||
if(cell==null){
|
||||
cell = row.createCell(cCol);
|
||||
}
|
||||
return cell;
|
||||
}
|
||||
|
||||
private static XSSFCell setCellText(XSSFCell cell, XSSFCellStyle cellStyle, String cellValue,String dataType){
|
||||
cell.setCellStyle(cellStyle);
|
||||
if(Strings.CI.equals("Integer", dataType) || Strings.CI.equals("Double", dataType)) {
|
||||
try {
|
||||
double numVal = Double.parseDouble(cellValue);
|
||||
cell.setCellValue(numVal);
|
||||
}catch(Exception err) {
|
||||
cell.setCellValue(new XSSFRichTextString(cellValue));
|
||||
}
|
||||
}else {
|
||||
cell.setCellValue(new XSSFRichTextString(cellValue));
|
||||
}
|
||||
|
||||
return cell;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package com.mgm.mcrm.common.utils;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.security.cert.CertificateException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Strings;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.cookie.Cookie;
|
||||
import org.apache.hc.client5.http.cookie.CookieStore;
|
||||
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
|
||||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
|
||||
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
|
||||
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.hc.client5.http.ssl.TrustAllStrategy;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.apache.hc.core5.http.config.Registry;
|
||||
import org.apache.hc.core5.http.config.RegistryBuilder;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.ssl.SSLContextBuilder;
|
||||
import org.apache.hc.core5.util.Timeout;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
|
||||
|
||||
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;
|
||||
|
||||
public class HttpUtil {
|
||||
|
||||
//-----------
|
||||
public static HttpResponseResult processHttpRequest(HttpRequestDefine request) {
|
||||
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+"]");
|
||||
}
|
||||
if (!SysCommon.isAllowApiServer(requestUrl)) {
|
||||
throw new SecurityException("URL not allowed");
|
||||
}
|
||||
requestUrl = NetworkUtil.encodePathWithSpring(requestUrl);
|
||||
try {
|
||||
//--
|
||||
RequestConfig.Builder configBuilder = RequestConfig.custom();
|
||||
configBuilder.setRedirectsEnabled(false);
|
||||
if(request.getTimeout()>0) {
|
||||
int timeout = request.getTimeout();
|
||||
configBuilder.setConnectionRequestTimeout(Timeout.ofMicroseconds(timeout));
|
||||
}
|
||||
RequestConfig requestConfig = configBuilder.build();
|
||||
//--
|
||||
HttpClientBuilder clientBuilder = HttpClients.custom();
|
||||
if(Strings.CI.startsWith(requestUrl, "https://")) {
|
||||
SSLContext sslContext = null;
|
||||
try {
|
||||
sslContext = SSLContextBuilder.create().loadTrustMaterial(TrustAllStrategy.INSTANCE).build();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE ))
|
||||
.build();
|
||||
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
|
||||
|
||||
HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
|
||||
.setDefaultRequestConfig(requestConfig);
|
||||
if(request.getCredentials()!=null) {
|
||||
httpClientBuilder.setDefaultCredentialsProvider(request.getCredentials());
|
||||
}
|
||||
httpclient = httpClientBuilder.build();
|
||||
|
||||
}else {
|
||||
if(request.getCredentials()!=null) {
|
||||
clientBuilder.setDefaultCredentialsProvider(request.getCredentials());
|
||||
}
|
||||
httpclient = clientBuilder.build();
|
||||
}
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
//--
|
||||
if(Strings.CI.equals("POST", request.getRequestMethod())) {
|
||||
HttpPost httppost = new HttpPost(requestUrl);
|
||||
httppost.setConfig(requestConfig);
|
||||
if(request.isUpload()!=true) {
|
||||
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.setEntity(new StringEntity(request.getEntityContent(), Charset.forName("UTF-8")));
|
||||
responseResult.setRequestContent(request.getEntityContent());
|
||||
response = httpclient.execute(httppost,context);
|
||||
}else {
|
||||
MultipartFile processFile = request.getUploadFile();
|
||||
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.addBinaryBody(request.getFileParaName(), processFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, processFile.getName());
|
||||
HttpEntity entity = builder.build();
|
||||
httppost.setEntity(entity);
|
||||
response = httpclient.execute(httppost,context);
|
||||
}
|
||||
|
||||
}else if(Strings.CI.equals("PUT", request.getRequestMethod())){
|
||||
HttpPut httpput = new HttpPut(requestUrl);
|
||||
httpput.setConfig(requestConfig);
|
||||
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())){
|
||||
httpput.addHeader(entry.getKey(), NetworkUtil.sanitizeHeaderValue(entry.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
httpput.setEntity(new StringEntity(request.getEntityContent(), Charset.forName(request.getRequestCharSet())));
|
||||
responseResult.setRequestContent(request.getEntityContent());
|
||||
response = httpclient.execute(httpput);
|
||||
}else if(Strings.CI.equals("DELETE", request.getRequestMethod())){
|
||||
HttpDelete httpdel = new HttpDelete(requestUrl);
|
||||
httpdel.setConfig(requestConfig);
|
||||
response = httpclient.execute(httpdel,context);
|
||||
}else {
|
||||
//-- Get
|
||||
HttpGet httpget = new HttpGet(requestUrl);
|
||||
httpget.setConfig(requestConfig);
|
||||
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())){
|
||||
httpget.addHeader(entry.getKey(), NetworkUtil.sanitizeHeaderValue(entry.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
response = httpclient.execute(httpget,context);
|
||||
}
|
||||
//--
|
||||
responseResult.setRequestUrl(requestUrl);
|
||||
responseResult.setStatusCode(response.getCode());
|
||||
HttpEntity responseEntity = response.getEntity();
|
||||
if(responseEntity!=null) {
|
||||
String responseBody = EntityUtils.toString(responseEntity, Charset.forName(request.getResponseCharSet()));
|
||||
EntityUtils.consume(responseEntity);
|
||||
responseResult.setResponseContent(responseBody);
|
||||
}
|
||||
|
||||
CookieStore cookieStore = context.getCookieStore();
|
||||
if(cookieStore!=null) {
|
||||
List<Cookie> cookies = cookieStore.getCookies();
|
||||
responseResult.setCookies(cookies);
|
||||
}
|
||||
//--
|
||||
}catch(Exception err) {
|
||||
responseResult.setStatusCode(-1);
|
||||
responseResult.setMessage(err.getMessage());
|
||||
LogUtil.error(HttpUtil.class, "Request HTTP[URL:"+request.getRequestUrl()+"][Method:"+request.getRequestMethod()+"] error:"+err.getMessage());
|
||||
}finally {
|
||||
try {
|
||||
if(response!=null) {
|
||||
response.close();
|
||||
}
|
||||
}catch(Exception err) {
|
||||
|
||||
}
|
||||
try {
|
||||
if(httpclient!=null) {
|
||||
httpclient.close();
|
||||
}
|
||||
}catch(Exception err) {
|
||||
|
||||
}
|
||||
}
|
||||
return responseResult;
|
||||
}
|
||||
//-----------
|
||||
public static SSLContext getSSLContext() {
|
||||
try {
|
||||
// 这里可以填两种值 TLS和LLS , 具体差别可以自行搜索
|
||||
SSLContext sc = SSLContext.getInstance("TLS");
|
||||
// 构建新对象
|
||||
X509TrustManager manager = new X509TrustManager() {
|
||||
@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();
|
||||
}
|
||||
}
|
||||
|
||||
@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(); // 检查证书是否在有效期内
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return new java.security.cert.X509Certificate[] {};
|
||||
}
|
||||
|
||||
};
|
||||
sc.init(null, new TrustManager[]{manager}, null);
|
||||
return sc;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static String readRequestBody(HttpServletRequest request) {
|
||||
BufferedReader br = null;
|
||||
StringBuilder sb = new StringBuilder("");
|
||||
try {
|
||||
br = request.getReader();
|
||||
String str;
|
||||
while ((str = br.readLine()) != null) {
|
||||
sb.append(str);
|
||||
}
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (null != br) {
|
||||
try {
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.mgm.mcrm.common.utils;
|
||||
|
||||
import com.mgm.mcrm.common.dtos.BaseApiResponse;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.mgm.mcrm.common.constants.SysCommon;
|
||||
|
||||
public class LogUtil {
|
||||
private static String loggerName = LogUtil.class.getName();
|
||||
private static Logger logger = LoggerFactory.getLogger(loggerName);
|
||||
|
||||
public static Logger getLogger(Class callClass){
|
||||
try
|
||||
{
|
||||
logger = LoggerFactory.getLogger(callClass.getName());
|
||||
}catch(Exception err){
|
||||
loggerName = LogUtil.class.getName();
|
||||
logger = LoggerFactory.getLogger(loggerName);
|
||||
}
|
||||
return logger;
|
||||
}
|
||||
|
||||
public static void info(Class callClass,String message) {
|
||||
if(SysCommon.appDebugLog == true)
|
||||
getLogger(callClass).info(message);
|
||||
}
|
||||
|
||||
public static void warn(Class callClass,String message) {
|
||||
if(SysCommon.appDebugLog == true)
|
||||
getLogger(callClass).warn(message);
|
||||
}
|
||||
|
||||
public static void error(Class callClass,String message) {
|
||||
if(SysCommon.appDebugLog == true)
|
||||
getLogger(callClass).error(message);
|
||||
}
|
||||
|
||||
public static String getObjectAttr(Object srcObj, String[] attrNames) {
|
||||
StringBuilder attrText = new StringBuilder();
|
||||
if(srcObj!=null && attrNames!=null) {
|
||||
try {
|
||||
JSONObject jsonObject = (JSONObject)JSONObject.toJSON(srcObj);
|
||||
|
||||
for(String attr:attrNames) {
|
||||
attrText.append(attr).append("=");
|
||||
if(jsonObject.containsKey(attr)) {
|
||||
attrText.append(jsonObject.getString(attr));
|
||||
}
|
||||
attrText.append(";");
|
||||
}
|
||||
|
||||
}catch(Exception ignored) {
|
||||
|
||||
}
|
||||
}
|
||||
return attrText.toString();
|
||||
}
|
||||
|
||||
public static String getFormatLog(String operationTag, String dataTag, boolean isSuccess, String resultTag,String message) {
|
||||
String logMessage = "";
|
||||
String statusMsg = (resultTag==null?"":resultTag);
|
||||
String errorMsg = (message==null?"":message);
|
||||
logMessage = operationTag+(StringUtils.isBlank(dataTag)?"":" ["+dataTag+"]");
|
||||
if(isSuccess) {
|
||||
logMessage += (" successed" + (StringUtils.isBlank(statusMsg)?"":" with ["+statusMsg+"]"));
|
||||
}else {
|
||||
logMessage += (" failed with error ["+errorMsg+"]");
|
||||
}
|
||||
|
||||
return logMessage;
|
||||
}
|
||||
|
||||
public static String getAjaxFormatLog(BaseApiResponse result, String operation, String[] reqAttr, String[] resultAttr) {
|
||||
String logMessage = "";
|
||||
if(result!=null) {
|
||||
String reqTxt = getObjectAttr(result.getRequestData(),reqAttr);
|
||||
String resultTxt = getObjectAttr(result.getData(),resultAttr);
|
||||
logMessage = getFormatLog(operation,reqTxt,result.isSuccess(),resultTxt,result.getMessage());
|
||||
}
|
||||
return logMessage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.mgm.mcrm.common.utils;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
|
||||
@Configuration
|
||||
public class MailConfig {
|
||||
|
||||
// @Resource
|
||||
// private JavaMailSenderImpl mailSender;
|
||||
//
|
||||
// @Value("${spring.mail.username}")
|
||||
// private String username;
|
||||
//
|
||||
// /**
|
||||
// * 发送纯文本形式的email
|
||||
// *
|
||||
// * @param toEmail 收件人邮箱
|
||||
// * @param title 邮件标题
|
||||
// * @param content 邮件内容
|
||||
// */
|
||||
// public void sendTextMail(String toEmail, String title, String content) {
|
||||
// SimpleMailMessage msg = new SimpleMailMessage();
|
||||
// msg.setFrom(username);
|
||||
// msg.setTo(toEmail);
|
||||
// msg.setSubject(title);
|
||||
// msg.setText(content);
|
||||
// mailSender.send(msg);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 发送带有html的内容
|
||||
// *
|
||||
// * @param toEmail 收件人邮箱
|
||||
// * @param title 邮件标题
|
||||
// * @param htmlContent 邮件内容
|
||||
// */
|
||||
// public void sendHtmlMail(String toEmail, String title, String htmlContent) throws MessagingException {
|
||||
// MimeMessage msg = mailSender.createMimeMessage();
|
||||
// MimeMessageHelper helper = new MimeMessageHelper(msg, false, "utf-8");
|
||||
// helper.setFrom(username);
|
||||
// helper.setTo(toEmail);
|
||||
// helper.setSubject(title);
|
||||
// helper.setText(htmlContent, true);
|
||||
// mailSender.send(msg);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 添加附件的email发送
|
||||
// *
|
||||
// * @param toEmail 收件人地址
|
||||
// * @param title 邮件标题
|
||||
// * @param content 文本内容
|
||||
// * @param aboutFiles 附件信息 每个子项都是一个文件相关信息的map Map<String,String>: 1.filePath
|
||||
// * 2.fileName
|
||||
// * @throws Exception 异常
|
||||
// */
|
||||
// public void sendAttachmentMail(String toEmail, String title, String content, List<Map<String, String>> aboutFiles) throws Exception {
|
||||
// MimeMessage msg = mailSender.createMimeMessage();
|
||||
// MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
|
||||
// helper.setFrom(username);
|
||||
// helper.setTo(toEmail);
|
||||
// helper.setSubject(title);
|
||||
// helper.setText(content);
|
||||
// FileSystemResource resource = null;
|
||||
// for (Map<String, String> file : aboutFiles) {
|
||||
// resource = new FileSystemResource(file.get("filePath"));
|
||||
// if (resource.exists()) {// 是否存在资源
|
||||
// File attachmentFile = resource.getFile();
|
||||
// helper.addAttachment(file.get("fileName"), attachmentFile);
|
||||
// }
|
||||
// }
|
||||
// mailSender.send(msg);
|
||||
// }
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user