feat: complete reverse engineering, standard Maven structure, detailed code annotations and IoT-M platform architecture
This commit is contained in:
1 parent
e8dc09fb3c
commit
cd6a4c70e7
3045 files changed
+566733
-1
No files matched your search
@@ -0,0 +1,29 @@
|
||||
package com.midm.app;
|
||||
|
||||
import com.midm.model.system.SystemSetting;
|
||||
import com.mitac.cell.constant.SizeConst;
|
||||
import javax.servlet.MultipartConfigElement;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.web.servlet.MultipartConfigFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.util.unit.DataSize;
|
||||
|
||||
@Configuration
|
||||
public class AppConfig {
|
||||
@Autowired
|
||||
private MongoTemplate mongoTemplate;
|
||||
|
||||
@Bean
|
||||
public MultipartConfigElement multipartConfigElement() {
|
||||
SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is("files.maxUploadSize")), SystemSetting.class);
|
||||
long maxUploadSize = setting == null ? SizeConst.SIZE_1G * 4L : setting.getAsLong();
|
||||
MultipartConfigFactory factory = new MultipartConfigFactory();
|
||||
factory.setMaxFileSize(DataSize.ofBytes(maxUploadSize));
|
||||
factory.setMaxRequestSize(DataSize.ofBytes(maxUploadSize));
|
||||
return factory.createMultipartConfig();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.midm.app;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.concurrent.Executor;
|
||||
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.scheduling.annotation.AsyncConfigurer;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
public class AsyncConfig implements AsyncConfigurer {
|
||||
private static final int TASK_CORE_POOL_SIZE = 10;
|
||||
private static final int TASK_MAX_POOL_SIZE = 20;
|
||||
private static final int TASK_QUEUE_CAPACITY = 100;
|
||||
private AsyncUncaughtExceptionHandler asyncExceptionHandler = new AsyncUncaughtExceptionHandler() {
|
||||
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
|
||||
}
|
||||
};
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public Executor getAsyncExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(10);
|
||||
executor.setMaxPoolSize(20);
|
||||
executor.setQueueCapacity(100);
|
||||
executor.setBeanName("asyncExecutor");
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
|
||||
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
|
||||
return this.asyncExceptionHandler;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public ThreadPoolTaskScheduler getTaskScheduler() {
|
||||
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
|
||||
taskScheduler.setPoolSize(50);
|
||||
return taskScheduler;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ThreadPoolTaskExecutor getTaskExcutor() {
|
||||
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
|
||||
taskExecutor.setCorePoolSize(5);
|
||||
taskExecutor.setMaxPoolSize(50);
|
||||
taskExecutor.setQueueCapacity(150);
|
||||
return taskExecutor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.midm.app;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.midm.service.device.DeviceKeyService;
|
||||
import com.midm.service.system.SettingsService;
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.util.Pair;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
@Component
|
||||
public class BasicAuthInterceptor implements HandlerInterceptor {
|
||||
@Autowired
|
||||
DeviceKeyService deviceKeyService;
|
||||
@Autowired
|
||||
SettingsService settingsService;
|
||||
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
String serialNo = request.getHeader("serialNo");
|
||||
if (Strings.isNullOrEmpty(serialNo)) {
|
||||
return true;
|
||||
} else {
|
||||
String encryptString = request.getHeader("encryptString");
|
||||
Pair<Boolean, String> pair = this.deviceKeyService.isValidRsa(serialNo, encryptString);
|
||||
if (Boolean.TRUE == pair.getFirst()) {
|
||||
return true;
|
||||
} else {
|
||||
String errorMessage = (String)pair.getSecond();
|
||||
this.responseError(response, 403, errorMessage);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void responseError(HttpServletResponse response, int code, String message) {
|
||||
response.setStatus(code);
|
||||
response.setContentType("application/json");
|
||||
|
||||
try {
|
||||
response.getWriter().write(String.format("{ \"message\": \" %s \"}", message));
|
||||
} catch (IOException var5) {
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package com.midm.app;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.mongodb.ConnectionString;
|
||||
import com.mongodb.MongoClientSettings;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.utils.URIBuilder;
|
||||
import org.bson.Document;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
|
||||
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
|
||||
|
||||
/**
|
||||
* ======================================================================================
|
||||
* MongoDB 工业级高可用连接池与数据库配置类 (DbConfig)
|
||||
* ======================================================================================
|
||||
*
|
||||
* <p>【架构设计与高并发亮点】
|
||||
* 1. 业务场景:
|
||||
* - 管理海量设备档案、高频时序遥测数据(GPS经纬度、电池SOH、网络数据流量)及企业操作审计日志。
|
||||
* 2. 【生产级连接池参数调优】:
|
||||
* - `maxPoolSize`: 1000(支持高并发终端长连接上报写入);
|
||||
* - `connectTimeoutMS`: 5000ms(连接超时自适应);
|
||||
* - `maxIdleTimeMS`: 30000ms(空闲连接及时回收,避免占用云数据库物理句柄);
|
||||
* - `waitqueuetimeoutms`: 5000ms(防止线程池排队积压导致雪崩)。
|
||||
* 3. 【分布式高可用集群支持】:
|
||||
* - 支持单机、集群多节点逗号分隔(Replica Set 副本集模式);
|
||||
* - 支持 `mongodb+srv://` 协议(如 AWS DocumentDB / MongoDB Atlas 云原生集群);
|
||||
* - 写入策略:强制设置 `w=majority`(多数派确认,确保主从切换时数据零丢失)与 `retryWrites=true`。
|
||||
* 4. 【数据库索引自愈能力 (Index Migration & Self-Healing)】:
|
||||
* - 在 {@link #fixDb} 中,系统启动时会自动探测并主动清除低效的单字段老索引(如 `midmLog` 的单字段索引),
|
||||
* 确保复合索引(Compound Index)能够最高效命中执行计划。
|
||||
*
|
||||
* @author MiDM Core Platform Team
|
||||
*/
|
||||
@Configuration
|
||||
@EnableMongoRepositories({"com.midm.repository"})
|
||||
public class DbConfig extends AbstractMongoClientConfiguration {
|
||||
|
||||
@Value("${mongo.servers:}")
|
||||
private String dbServers;
|
||||
|
||||
@Value("${mongo.uri:}")
|
||||
private String dbUri;
|
||||
|
||||
@Value("${mongo.scheme:mongodb}")
|
||||
private String dbScheme;
|
||||
|
||||
@Value("${mongo.host:127.0.0.1}")
|
||||
private String dbHost;
|
||||
|
||||
@Value("${mongo.port:27017}")
|
||||
private Integer dbPort;
|
||||
|
||||
@Value("${mongo.dbname:db_midm}")
|
||||
private String dbName;
|
||||
|
||||
@Value("${mongo.username:}")
|
||||
private String dbUser;
|
||||
|
||||
@Value("${mongo.password:}")
|
||||
private String dbPassword;
|
||||
|
||||
@Value("${mongo.ssl:false}")
|
||||
private boolean sslEnabled;
|
||||
|
||||
@Value("${mongo.keep_alive:true}")
|
||||
private boolean keepAlive;
|
||||
|
||||
/** 最大并发连接池容量(默认 1000,保障海量终端瞬间重连时平稳接入) */
|
||||
@Value("${mongo.maxPoolSize:1000}")
|
||||
private int maxPoolSize;
|
||||
|
||||
@Value("${mongo.connectionsPerHost: 1000}")
|
||||
private int connectionsPerHost;
|
||||
|
||||
@Value("${mongo.connection_multiplier:200}")
|
||||
private int connectionMultiplier;
|
||||
|
||||
@Value("${mongo.connect_timeout:5000}")
|
||||
private int connectTimeout;
|
||||
|
||||
@Value("${mongo.wait_timeout:5000}")
|
||||
private int waitTimeout;
|
||||
|
||||
@Value("${mongo.socket_timeout:0}")
|
||||
private int socketTimeout;
|
||||
|
||||
@Value("${mongo.idle_timeout:30000}")
|
||||
private int idleTimeout;
|
||||
|
||||
@Value("${mongo.replica_set:rs0}")
|
||||
private String dbReplicaSet;
|
||||
|
||||
/**
|
||||
* 【动态连接串构建算法】根据配置文件自适应拼装生产级 MongoDB URI
|
||||
*
|
||||
* @return 包含完备连接池与安全参数的 ConnectionString
|
||||
*/
|
||||
private ConnectionString getConnectiontString() {
|
||||
// 1. 支持逗号分隔的多节点集群配置解析(如 "node1:27017,node2:27017,node3:27017")
|
||||
if (this.dbHost.contains(",")) {
|
||||
String[] hosts = this.dbHost.split(",");
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for(String host : hosts) {
|
||||
if (sb.length() > 0) {
|
||||
sb.append(",");
|
||||
}
|
||||
host = host.toLowerCase().trim();
|
||||
int indexPort = host.indexOf(":");
|
||||
if (indexPort > 0) {
|
||||
sb.append(host);
|
||||
} else {
|
||||
sb.append(host).append(":").append(this.dbPort);
|
||||
}
|
||||
}
|
||||
this.dbHost = sb.toString();
|
||||
this.dbPort = null;
|
||||
} else {
|
||||
this.dbReplicaSet = null;
|
||||
}
|
||||
|
||||
URIBuilder uriBuilder = null;
|
||||
ConnectionString connectionString = null;
|
||||
try {
|
||||
if (Strings.isNullOrEmpty(this.dbUri)) {
|
||||
uriBuilder = new URIBuilder();
|
||||
} else {
|
||||
uriBuilder = new URIBuilder(this.dbUri);
|
||||
connectionString = new ConnectionString(this.dbUri);
|
||||
}
|
||||
} catch (Exception var9) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. 注入高可靠性与强一致性参数:w=majority(多数派成功)、retryWrites=true(网络故障重试写入)
|
||||
uriBuilder.setParameter("uuidRepresentation", "javaLegacy")
|
||||
.setParameter("retryWrites", String.valueOf(true))
|
||||
.setParameter("w", "majority");
|
||||
|
||||
if (connectionString == null) {
|
||||
if (Strings.isNullOrEmpty(uriBuilder.getScheme())) {
|
||||
uriBuilder.setScheme(this.dbScheme);
|
||||
}
|
||||
if (Strings.isNullOrEmpty(uriBuilder.getHost())) {
|
||||
uriBuilder.setHost(this.dbHost);
|
||||
}
|
||||
if (uriBuilder.getPort() < 0) {
|
||||
uriBuilder.setPort(this.dbPort);
|
||||
}
|
||||
if (Strings.isNullOrEmpty(uriBuilder.getUserInfo()) && !Strings.isNullOrEmpty(this.dbUser)) {
|
||||
uriBuilder.setUserInfo(this.dbUser, this.dbPassword);
|
||||
}
|
||||
List<String> paths = uriBuilder.getPathSegments();
|
||||
if (paths != null && paths.size() != 0) {
|
||||
this.dbName = (String)paths.get(0);
|
||||
} else {
|
||||
uriBuilder.setPath(this.dbName);
|
||||
}
|
||||
} else {
|
||||
this.dbName = connectionString.getDatabase();
|
||||
}
|
||||
|
||||
// 3. 动态配置连接池水线(Pool Size、Timeout、SSL 等)
|
||||
List<NameValuePair> queryParams = uriBuilder.getQueryParams();
|
||||
Set<String> params = new HashSet();
|
||||
queryParams.forEach((param) -> params.add(param.getName()));
|
||||
|
||||
if (!params.contains("maxPoolSize")) {
|
||||
uriBuilder.setParameter("maxPoolSize", String.valueOf(this.maxPoolSize));
|
||||
}
|
||||
if (!params.contains("connectTimeoutMS")) {
|
||||
uriBuilder.setParameter("connectTimeoutMS", String.valueOf(this.connectTimeout));
|
||||
}
|
||||
if (!params.contains("maxIdleTimeMS")) {
|
||||
uriBuilder.setParameter("maxIdleTimeMS", String.valueOf(this.idleTimeout));
|
||||
}
|
||||
if (!params.contains("waitqueuetimeoutms")) {
|
||||
uriBuilder.setParameter("waitqueuetimeoutms", String.valueOf(this.waitTimeout));
|
||||
}
|
||||
|
||||
boolean isSrv = uriBuilder.getScheme().endsWith("+srv");
|
||||
if (!isSrv && !params.contains("ssl")) {
|
||||
uriBuilder.setParameter("ssl", String.valueOf(this.sslEnabled));
|
||||
}
|
||||
|
||||
if (!Strings.isNullOrEmpty(this.dbReplicaSet) && !params.contains("replicaSet")) {
|
||||
uriBuilder.setParameter("replicaSet", this.dbReplicaSet);
|
||||
}
|
||||
|
||||
try {
|
||||
URI mongoUri = uriBuilder.build();
|
||||
return new ConnectionString(mongoUri.toString());
|
||||
} catch (URISyntaxException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化创建 MongoClient 实例并触发自愈索引检查
|
||||
*/
|
||||
@Override
|
||||
public MongoClient mongoClient() {
|
||||
ConnectionString connectionString = this.getConnectiontString();
|
||||
MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build();
|
||||
MongoClient client = MongoClients.create(mongoClientSettings);
|
||||
// 执行启动期索引自愈与冲突清理
|
||||
this.fixDb(client);
|
||||
return client;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getDatabaseName() {
|
||||
return this.dbName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 开启实体类注解索引自动创建(@Indexed / @CompoundIndexes)
|
||||
*/
|
||||
@Override
|
||||
protected boolean autoIndexCreation() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 【数据库索引自愈能力】
|
||||
* <p>扫描数据库集合,主动剔除历史版本中遗留的低效单字段索引,
|
||||
* 避免其与当前版本的复合联合索引产生性能冲突。
|
||||
*/
|
||||
private void fixDb(MongoClient client) {
|
||||
MongoDatabase db = client.getDatabase(this.getDatabaseName());
|
||||
if (db != null) {
|
||||
MongoCollection<Document> siteCollection = db.getCollection("site");
|
||||
if (siteCollection != null) {
|
||||
siteCollection.listIndexes().forEach((index) -> {
|
||||
String name = index.getString("name");
|
||||
if (name.equals("idName_1")) {
|
||||
siteCollection.dropIndex(name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
MongoCollection<Document> logCollection = db.getCollection("midmLog");
|
||||
if (logCollection != null) {
|
||||
logCollection.listIndexes().forEach((index) -> {
|
||||
String name = index.getString("name");
|
||||
if (name.equals("category") || name.equals("forWhat")) {
|
||||
logCollection.dropIndex(name);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
package com.midm.app;
|
||||
|
||||
import com.google.common.reflect.TypeToken;
|
||||
import com.midm.model.device.DataUsage;
|
||||
import com.midm.model.device.Device;
|
||||
import com.midm.model.device.DeviceGroup;
|
||||
import com.midm.model.device.DeviceLicense;
|
||||
import com.midm.model.device.DeviceProfile;
|
||||
import com.midm.model.device.DeviceProfileState;
|
||||
import com.midm.model.device.DeviceReport;
|
||||
import com.midm.model.device.ProfileApps;
|
||||
import com.midm.model.device.ProfileScope;
|
||||
import com.midm.model.file.AppFile;
|
||||
import com.midm.model.log.MidmLog;
|
||||
import com.midm.model.org.Site;
|
||||
import com.midm.model.org.SiteFile;
|
||||
import com.midm.model.org.SiteLicense;
|
||||
import com.midm.model.org.User;
|
||||
import com.midm.model.system.HostLicense;
|
||||
import com.midm.model.system.LicenseModel;
|
||||
import com.midm.model.system.SystemSetting;
|
||||
import com.midm.service.system.RestoreService;
|
||||
import com.mitac.cell.db.DbObject;
|
||||
import com.mitac.cell.utils.McDateTimeUtils;
|
||||
import com.mitac.cell.utils.McJsonUtils;
|
||||
import com.mongodb.MongoNamespace;
|
||||
import com.mongodb.client.ListIndexesIterable;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoCursor;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.compress.utils.Sets;
|
||||
import org.bson.Document;
|
||||
import org.joda.time.DateTime;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.event.ContextRefreshedEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||
import org.springframework.data.mongodb.core.aggregation.Aggregation;
|
||||
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
|
||||
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndexDefinition;
|
||||
import org.springframework.data.mongodb.core.index.Index;
|
||||
import org.springframework.data.mongodb.core.query.BasicQuery;
|
||||
import org.springframework.data.mongodb.core.query.Collation;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.data.mongodb.core.query.Update;
|
||||
import org.springframework.data.mongodb.core.schema.JsonSchemaObject;
|
||||
import org.springframework.data.mongodb.core.schema.JsonSchemaObject.Type;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class DbInitialize {
|
||||
private static final long DB_SCHEME_VER_2 = 20092901L;
|
||||
private static final long DB_SCHEME_VER_3 = 22111002L;
|
||||
private static final long DB_SCHEME_VER_4 = 23072101L;
|
||||
private static final long DB_SCHEME_VER_5 = 23082501L;
|
||||
private static final long DB_SCHEME_VER_6 = 24022701L;
|
||||
private String KEY_DB_SCHEME = "db.scheme";
|
||||
@Autowired
|
||||
private MongoTemplate mongoTemplate;
|
||||
@Autowired
|
||||
private RestoreService restoreService;
|
||||
|
||||
@EventListener({ContextRefreshedEvent.class})
|
||||
public void contextRefreshedEvent() {
|
||||
this.initializeDb();
|
||||
this.updateScheme();
|
||||
}
|
||||
|
||||
private void initializeDb() {
|
||||
MongoCollection<Document> resourceMessageCollection = this.mongoTemplate.getCollection("resourceMessage");
|
||||
if (resourceMessageCollection == null || resourceMessageCollection.countDocuments() == 0L) {
|
||||
this.restoreService.restore((String)null);
|
||||
}
|
||||
|
||||
if (this.mongoTemplate.collectionExists(SystemSetting.class)) {
|
||||
SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is("db.indexed")), SystemSetting.class);
|
||||
if (setting == null) {
|
||||
Set<String> collections = this.mongoTemplate.getCollectionNames();
|
||||
collections.forEach((collection) -> this.mongoTemplate.getCollection(collection).dropIndexes());
|
||||
this.mongoTemplate.save(new SystemSetting("db.indexed", String.valueOf(true)));
|
||||
}
|
||||
}
|
||||
|
||||
if (this.mongoTemplate.collectionExists(Site.class)) {
|
||||
Query query = Query.query(Criteria.where("settings.noti.sendEmail").exists(false));
|
||||
Update update = (new Update()).set("settings.noti.sendEmail", true);
|
||||
this.mongoTemplate.updateMulti(query, update, Site.class);
|
||||
String[] forWhats = new String[]{"general", "urgent", "maintenance"};
|
||||
Document value = (new Document("enabled", true)).append("roles", new Document("SUPERVISOR", true));
|
||||
|
||||
for(String forWhat : forWhats) {
|
||||
String key = "settings.noti.support." + forWhat;
|
||||
query = Query.query(Criteria.where(key).exists(false));
|
||||
update = (new Update()).set(key, value);
|
||||
this.mongoTemplate.updateMulti(query, update, Site.class);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.mongoTemplate.collectionExists(Device.class) && this.mongoTemplate.count(new Query(), Device.class) > 0L) {
|
||||
Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.group(new String[]{"$profile.hardware_info.serial_no"}).addToSet("id").as("uuids").max("updated").as("latest").count().as("count"), Aggregation.match(Criteria.where("count").gt(1))});
|
||||
AggregationResults<Document> results = this.mongoTemplate.aggregate(aggregation, Device.class, Document.class);
|
||||
results.forEach((result) -> {
|
||||
String serialNo = result.getString("_id");
|
||||
Date updated = (Date)result.get("latest");
|
||||
this.mongoTemplate.remove(Query.query(Criteria.where("profile.hardware_info.serial_no").is(serialNo).and("updated").ne(updated)), Device.class);
|
||||
});
|
||||
}
|
||||
|
||||
if (this.mongoTemplate.collectionExists("appFile")) {
|
||||
BasicQuery basicQuery = new BasicQuery(new Document("$expr", new Document("$eq", Arrays.asList("$name", "$fileInfo.fileName"))));
|
||||
List<AppFile> apps = this.mongoTemplate.find(basicQuery, AppFile.class);
|
||||
apps.forEach((app) -> this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(app.getFileUuid())), Update.update("name", app.getLabel()), AppFile.class));
|
||||
basicQuery = new BasicQuery(new Document("appInfo.targetSdkVersion", new Document("$type", "string")));
|
||||
apps = this.mongoTemplate.find(basicQuery, AppFile.class);
|
||||
apps.forEach((app) -> {
|
||||
int version = app.getTargetSdkVersion();
|
||||
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(app.getFileUuid())), Update.update("appInfo.targetSdkVersion", version), AppFile.class);
|
||||
});
|
||||
}
|
||||
|
||||
if (this.mongoTemplate.collectionExists(DeviceReport.class)) {
|
||||
this.dropIndex(DeviceReport.class, "deviceUuid");
|
||||
}
|
||||
|
||||
this.ensureIndex(Site.class, true, "idName");
|
||||
this.ensureIndex(Site.class, false, "profile.name");
|
||||
this.ensureDeviceSerialIndex();
|
||||
this.ensureIndex(Device.class, false, "owner.uuid", "deviceGroup.uuid");
|
||||
this.ensureIndex(DeviceProfile.class, false, "deviceProfileGroup.uuid");
|
||||
this.ensureIndex(DeviceProfileState.class, false, "_id.deviceUuid");
|
||||
this.ensureIndex(DeviceProfileState.class, false, "_id.profileUuid");
|
||||
this.ensureIndex(DataUsage.class, false, "deviceUuid");
|
||||
this.ensureIndex(DataUsage.class, false, "from");
|
||||
this.ensureIndex(DataUsage.class, false, "to");
|
||||
this.ensureIndex(DeviceReport.class, false, "properties.deviceProfile.uuid", "properties.deviceProfile.updated");
|
||||
this.ensureIndex(DeviceReport.class, false, "reportedAt");
|
||||
this.ensureIndex(MidmLog.class, false, "category", "loggedAt");
|
||||
}
|
||||
|
||||
private void ensureIndex(Class entityClass, boolean unique, String... keys) {
|
||||
try {
|
||||
if (keys.length > 0) {
|
||||
Document indexDefinition = new Document();
|
||||
|
||||
for(String key : keys) {
|
||||
indexDefinition.append(key, 1);
|
||||
}
|
||||
|
||||
CompoundIndexDefinition index = new CompoundIndexDefinition(indexDefinition);
|
||||
if (unique) {
|
||||
index.unique();
|
||||
}
|
||||
|
||||
this.mongoTemplate.indexOps(entityClass).ensureIndex(index);
|
||||
}
|
||||
} catch (Exception var9) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void dropIndex(Class entityClass, String... keys) {
|
||||
if (this.mongoTemplate.collectionExists(entityClass)) {
|
||||
MongoCollection<Document> collection = this.getCollection(entityClass);
|
||||
ListIndexesIterable<Document> indexes = collection.listIndexes();
|
||||
Set<String> keySet = Sets.newHashSet(keys);
|
||||
MongoCursor var6 = indexes.iterator();
|
||||
|
||||
while(var6.hasNext()) {
|
||||
Document index = (Document)var6.next();
|
||||
Document keyMap = (Document)index.get("key", Document.class);
|
||||
if (keyMap.keySet().equals(keySet)) {
|
||||
collection.dropIndex(index.getString("name"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureDeviceSerialIndex() {
|
||||
MongoCollection<Document> collection = this.getCollection(Device.class);
|
||||
ListIndexesIterable<Document> indexes = collection.listIndexes();
|
||||
boolean isConfigured = false;
|
||||
MongoCursor indexDefinition = indexes.iterator();
|
||||
|
||||
while(indexDefinition.hasNext()) {
|
||||
Document index = (Document)indexDefinition.next();
|
||||
Document keys = (Document)index.get("key", Document.class);
|
||||
if (keys.containsKey("profile.hardware_info.serial_no") && keys.containsKey("siteUuid")) {
|
||||
if (!index.containsKey("collation")) {
|
||||
collection.dropIndex(index.getString("name"));
|
||||
} else {
|
||||
isConfigured = true;
|
||||
}
|
||||
} else if (keys.size() == 1 && keys.containsKey("siteUuid")) {
|
||||
collection.dropIndex(index.getString("name"));
|
||||
}
|
||||
}
|
||||
|
||||
if (!isConfigured) {
|
||||
Document indexDefinition = (new Document("siteUuid", 1)).append("profile.hardware_info.serial_no", 1);
|
||||
Index index = (new CompoundIndexDefinition(indexDefinition)).collation(Collation.of("en").strength(2));
|
||||
this.mongoTemplate.indexOps(Device.class).ensureIndex(index);
|
||||
}
|
||||
|
||||
collection = this.getCollection(DeviceLicense.class);
|
||||
indexes = collection.listIndexes();
|
||||
indexDefinition = indexes.iterator();
|
||||
|
||||
while(indexDefinition.hasNext()) {
|
||||
Document index = (Document)indexDefinition.next();
|
||||
Document keys = (Document)index.get("key", Document.class);
|
||||
if (keys.size() == 1 && keys.containsKey("plan")) {
|
||||
collection.dropIndex(index.getString("name"));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void updateScheme() {
|
||||
if (this.mongoTemplate.collectionExists("siteReport")) {
|
||||
MongoCollection<Document> collection = this.mongoTemplate.getCollection("siteReport");
|
||||
if (this.mongoTemplate.collectionExists(SiteFile.class)) {
|
||||
collection.drop();
|
||||
} else {
|
||||
MongoNamespace nameSpace = collection.getNamespace();
|
||||
collection.renameCollection(new MongoNamespace(nameSpace.getDatabaseName(), "siteFile"));
|
||||
}
|
||||
}
|
||||
|
||||
boolean isStandalone = this.isStandalone();
|
||||
if (this.getDbScheme() < 20092901L) {
|
||||
Query query = Query.query(Criteria.where("profile.tel").exists(true));
|
||||
Update update = new Update();
|
||||
update.rename("profile.tel", "profile.phone");
|
||||
this.mongoTemplate.updateMulti(query, update, User.class);
|
||||
this.mongoTemplate.updateMulti(query, update, Site.class);
|
||||
this.mongoTemplate.updateMulti(new Query(Criteria.where("isLite").exists(true)), (new Update()).unset("isLite"), "site");
|
||||
this.mongoTemplate.updateMulti(new Query(Criteria.where("isMust").exists(true)), (new Update()).unset("isMust"), "site");
|
||||
this.mongoTemplate.updateMulti(new Query(Criteria.where("isReseller").exists(true)), (new Update()).unset("isReseller"), "site");
|
||||
if (isStandalone) {
|
||||
this.mongoTemplate.updateMulti(new Query(), Update.update("profile.model", "midm"), Site.class);
|
||||
}
|
||||
|
||||
query = Query.query(Criteria.where("profile.owner.tel").exists(true));
|
||||
update = new Update();
|
||||
update.rename("profile.owner.tel", "profile.owner.phone");
|
||||
this.mongoTemplate.updateMulti(query, update, Device.class);
|
||||
}
|
||||
|
||||
if (this.getDbScheme() < 22111002L) {
|
||||
if (this.mongoTemplate.collectionExists("user")) {
|
||||
Query query = Query.query(Criteria.where("settings.report").exists(true));
|
||||
Update update = (new Update()).unset("settings.report");
|
||||
this.mongoTemplate.updateMulti(query, update, User.class);
|
||||
}
|
||||
|
||||
Query query = Query.query((new Criteria()).orOperator(new Criteria[]{Criteria.where("scope.group").type(new JsonSchemaObject.Type[]{Type.STRING}), Criteria.where("apps.install.uuid").type(new JsonSchemaObject.Type[]{Type.STRING}), Criteria.where("apps.install.0").type(new JsonSchemaObject.Type[]{Type.STRING})}));
|
||||
query.fields().include(new String[]{"scope.group", "apps.install"});
|
||||
List<Document> profiles = this.mongoTemplate.find(query, Document.class, "deviceProfile");
|
||||
if (profiles != null && !profiles.isEmpty()) {
|
||||
java.lang.reflect.Type installAppType = (new TypeToken() {
|
||||
}).getType();
|
||||
profiles.forEach((profile) -> {
|
||||
Update update = new Update();
|
||||
Object _id = profile.get("_id");
|
||||
Document scopeObj = (Document)profile.get("scope");
|
||||
if (scopeObj != null) {
|
||||
List<Object> groups = scopeObj.getList("group", Object.class);
|
||||
if (groups != null && !groups.isEmpty() && groups.get(0) instanceof String) {
|
||||
ProfileScope scope = (ProfileScope)McJsonUtils.toObject(scopeObj.toJson(), ProfileScope.class);
|
||||
Set<UUID> groupUuids = scope.getGroup();
|
||||
List<DeviceGroup> existingGroups = this.mongoTemplate.find(Query.query(Criteria.where("_id").in(groupUuids)), DeviceGroup.class);
|
||||
Set<UUID> existingUuids = (Set)existingGroups.stream().map((groupItem) -> groupItem.getUuid()).collect(Collectors.toSet());
|
||||
scope.setGroup(existingUuids);
|
||||
update.set("scope", scope);
|
||||
}
|
||||
}
|
||||
|
||||
Document apps = (Document)profile.get("apps");
|
||||
if (apps != null) {
|
||||
List<Object> install = apps.getList("install", Object.class);
|
||||
if (install != null && !install.isEmpty()) {
|
||||
List<ProfileApps.InstallApp> installApps = new ArrayList();
|
||||
if (install.get(0) instanceof String) {
|
||||
for(Object uuid : install) {
|
||||
UUID appUuid = UUID.fromString((String)uuid);
|
||||
AppFile appFile = (AppFile)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(appUuid)), AppFile.class);
|
||||
if (appFile != null) {
|
||||
ProfileApps.InstallApp app = new ProfileApps.InstallApp(appFile);
|
||||
installApps.add(app);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
installApps = (List)McJsonUtils.toObject(McJsonUtils.toJson(install), installAppType);
|
||||
Iterator<ProfileApps.InstallApp> it = installApps.iterator();
|
||||
|
||||
while(it.hasNext()) {
|
||||
ProfileApps.InstallApp app = (ProfileApps.InstallApp)it.next();
|
||||
if (!this.mongoTemplate.exists(Query.query(Criteria.where("_id").is(app.getUuid())), AppFile.class)) {
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (installApps.isEmpty()) {
|
||||
update.unset("apps.install");
|
||||
} else {
|
||||
update.set("apps.install", installApps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(_id)), update, DeviceProfile.class);
|
||||
});
|
||||
}
|
||||
|
||||
query = Query.query(Criteria.where("profile.startsOn").type(new JsonSchemaObject.Type[]{Type.dateType()}));
|
||||
List<DeviceProfile> deviceProfiles = this.mongoTemplate.find(query, DeviceProfile.class);
|
||||
if (!deviceProfiles.isEmpty()) {
|
||||
deviceProfiles.forEach((profile) -> {
|
||||
DbObject profileObj = profile.getProfile();
|
||||
Date startsDate = (Date)profileObj.get("startsOn");
|
||||
String starts = McDateTimeUtils.toString(new DateTime(startsDate), "yyyy-MM-dd");
|
||||
Update update = Update.update("profile.startsOn", starts);
|
||||
Object endsDate = profileObj.get("ends");
|
||||
if (endsDate != null) {
|
||||
if (endsDate instanceof Date) {
|
||||
String ends = McDateTimeUtils.toString(new DateTime(endsDate), "yyyy-MM-dd");
|
||||
update.set("profile.ends", ends);
|
||||
} else if (endsDate instanceof String) {
|
||||
String ends = ((String)endsDate).substring(0, 10);
|
||||
update.set("profile.ends", ends);
|
||||
}
|
||||
}
|
||||
|
||||
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(profile.getUuid())), update, DeviceProfile.class);
|
||||
});
|
||||
}
|
||||
|
||||
query = Query.query(Criteria.where("profile.startsOn").regex(".{11,}"));
|
||||
deviceProfiles = this.mongoTemplate.find(query, DeviceProfile.class);
|
||||
if (!deviceProfiles.isEmpty()) {
|
||||
deviceProfiles.forEach((profile) -> {
|
||||
DbObject profileObj = profile.getProfile();
|
||||
String startsDate = profileObj.getString("startsOn");
|
||||
Update update = Update.update("profile.startsOn", startsDate.substring(0, 10));
|
||||
Object endsDate = profileObj.get("ends");
|
||||
if (endsDate != null) {
|
||||
if (endsDate instanceof Date) {
|
||||
String ends = McDateTimeUtils.toString(new DateTime(endsDate), "yyyy-MM-dd");
|
||||
update.set("profile.ends", ends);
|
||||
} else if (endsDate instanceof String) {
|
||||
String ends = ((String)endsDate).substring(0, 10);
|
||||
update.set("profile.ends", ends);
|
||||
}
|
||||
}
|
||||
|
||||
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(profile.getUuid())), update, DeviceProfile.class);
|
||||
});
|
||||
}
|
||||
|
||||
String[] settingFields = new String[]{"systemProperties", "globalSettings", "systemSettings", "secureSettings"};
|
||||
query = new Query();
|
||||
List<Criteria> settingsCriteria = new ArrayList();
|
||||
|
||||
for(String field : settingFields) {
|
||||
settingsCriteria.add(Criteria.where("settings." + field).type(new JsonSchemaObject.Type[]{Type.ARRAY}));
|
||||
query.fields().include("settings." + field);
|
||||
}
|
||||
|
||||
query.addCriteria((new Criteria()).orOperator(settingsCriteria));
|
||||
profiles = this.mongoTemplate.find(query, Document.class, "deviceProfile");
|
||||
Update update = new Update();
|
||||
if (profiles != null && !profiles.isEmpty()) {
|
||||
profiles.forEach((profile) -> {
|
||||
Object _id = profile.get("_id");
|
||||
Document settings = (Document)profile.get("settings");
|
||||
if (settings != null) {
|
||||
for(String field : settingFields) {
|
||||
List<Document> categorySettings = settings.getList(field, Document.class);
|
||||
if (categorySettings != null && !categorySettings.isEmpty()) {
|
||||
try {
|
||||
Map<Object, Object> newValue = (Map)categorySettings.stream().collect(Collectors.toMap((e) -> e.get("key"), (e) -> e.get("value")));
|
||||
update.set("settings." + field, newValue);
|
||||
} catch (Exception var12) {
|
||||
update.unset("settings." + field);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(_id)), update, DeviceProfile.class);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (this.getDbScheme() < 23072101L) {
|
||||
if (isStandalone) {
|
||||
this.mongoTemplate.dropCollection(LicenseModel.class);
|
||||
this.mongoTemplate.dropCollection(DeviceLicense.class);
|
||||
this.mongoTemplate.dropCollection(SiteLicense.class);
|
||||
this.mongoTemplate.updateMulti(new Query(), (new Update()).unset("license").unset("licensed").unset("licenseExpiry"), Device.class);
|
||||
}
|
||||
|
||||
this.mongoTemplate.updateMulti(new Query(), (new Update()).unset("priority"), DeviceProfile.class);
|
||||
Query query = Query.query(Criteria.where("profile.weekOptions").exists(true));
|
||||
List<DeviceProfile> profiles = this.mongoTemplate.find(query, DeviceProfile.class);
|
||||
profiles.forEach((profile) -> {
|
||||
List<Number> options = (List)profile.getProfile("weekOptions");
|
||||
List<Integer> newOptions = (List)options.stream().map((week) -> week.intValue() + 1).collect(Collectors.toList());
|
||||
Update update = Update.update("updated", new Date(profile.getUpdated().getTime() + 1L)).set("profile.weekOptions", newOptions);
|
||||
this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(profile.getUuid())), update, DeviceProfile.class);
|
||||
});
|
||||
}
|
||||
|
||||
if (this.getDbScheme() < 23082501L) {
|
||||
this.mongoTemplate.updateMulti(Query.query(Criteria.where("state").exists(false)), Update.update("state", "done"), DeviceProfileState.class);
|
||||
this.mongoTemplate.save(new SystemSetting(this.KEY_DB_SCHEME, 23082501L));
|
||||
}
|
||||
|
||||
if (this.getDbScheme() < 24022701L) {
|
||||
Update update = new Update();
|
||||
update.unset("settings.page");
|
||||
this.mongoTemplate.updateMulti(new Query(), update, User.class);
|
||||
this.mongoTemplate.save(new SystemSetting(this.KEY_DB_SCHEME, 24022701L));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private MongoCollection getCollection(Class entityClass) {
|
||||
return this.mongoTemplate.getCollection(this.mongoTemplate.getCollectionName(entityClass));
|
||||
}
|
||||
|
||||
private long getDbScheme() {
|
||||
SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(this.KEY_DB_SCHEME)), SystemSetting.class);
|
||||
return setting != null ? setting.getAsLong() : -1L;
|
||||
}
|
||||
|
||||
private boolean isStandalone() {
|
||||
HostLicense license = (HostLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("isPrimary").is(true)), HostLicense.class);
|
||||
return license != null && license.isStandalone();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.midm.app;
|
||||
|
||||
import com.midm.model.org.User;
|
||||
import com.midm.security.UserPrincipal;
|
||||
import com.midm.service.org.SiteService;
|
||||
import com.midm.service.system.HelpMessageService;
|
||||
import com.midm.service.system.HostLicenseService;
|
||||
import com.midm.service.system.LocaleService;
|
||||
import com.midm.service.system.SettingsService;
|
||||
import com.mitac.cell.utils.McStringUtils;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.info.BuildProperties;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
@ControllerAdvice
|
||||
public final class GlobalController {
|
||||
private static final String[] excludeBindingPrefixes = new String[]{"/api/", "/img/", "/profile/", "/client/", "/icon/", "/store/", "/logo/", "/device/", "/file/", "/must/", "/userfile/", "/barcode/", "/dpc/"};
|
||||
@Autowired
|
||||
private BuildProperties buildProperties;
|
||||
@Autowired
|
||||
protected LocaleService localeService;
|
||||
@Autowired
|
||||
private SettingsService settingsService;
|
||||
@Autowired
|
||||
private HostLicenseService licenseService;
|
||||
@Autowired
|
||||
protected SiteService siteService;
|
||||
@Autowired
|
||||
private HelpMessageService helpMessageService;
|
||||
@Value("#{servletContext.contextPath}")
|
||||
private String servletContextPath;
|
||||
|
||||
@ModelAttribute("buildVersion")
|
||||
public String buildVersion() {
|
||||
return this.buildProperties.getVersion();
|
||||
}
|
||||
|
||||
@ModelAttribute("buildTime")
|
||||
public String buildTime() {
|
||||
return Date.from(this.buildProperties.getTime()).toString();
|
||||
}
|
||||
|
||||
@ModelAttribute("user")
|
||||
public Object user(HttpServletRequest request, Authentication authentication, @RequestParam(required = false) String language) {
|
||||
if (this.bindModel(request)) {
|
||||
User user = authentication == null ? this.guest(request, language) : UserPrincipal.getUser(authentication);
|
||||
if (user.getSite() == null && user.getSiteUuid() != null) {
|
||||
user.setSite(this.siteService.findByUuid(user.getSiteUuid()));
|
||||
}
|
||||
|
||||
return user;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@ModelAttribute("settings")
|
||||
public SettingsService settings() {
|
||||
return this.settingsService;
|
||||
}
|
||||
|
||||
@ModelAttribute("locales")
|
||||
public LocaleService locales() {
|
||||
return this.localeService;
|
||||
}
|
||||
|
||||
@ModelAttribute("helpService")
|
||||
public HelpMessageService helpService() {
|
||||
return this.helpMessageService;
|
||||
}
|
||||
|
||||
@ModelAttribute("isHostValid")
|
||||
public boolean isHostValid() {
|
||||
return this.licenseService.isValid();
|
||||
}
|
||||
|
||||
@ModelAttribute("deviceLimit")
|
||||
public int deviceLimit() {
|
||||
return this.licenseService.getDeviceLimit();
|
||||
}
|
||||
|
||||
@ModelAttribute("siteService")
|
||||
public SiteService siteService() {
|
||||
return this.siteService;
|
||||
}
|
||||
|
||||
@ModelAttribute("contextPath")
|
||||
public String contextPath() {
|
||||
return this.servletContextPath + "/";
|
||||
}
|
||||
|
||||
private User guest(HttpServletRequest request, String localeTag) {
|
||||
User user = new User();
|
||||
user.setName("Guest");
|
||||
if (!McStringUtils.isValid(localeTag)) {
|
||||
localeTag = request.getLocale().toLanguageTag();
|
||||
}
|
||||
|
||||
request.getSession().setAttribute("language", localeTag);
|
||||
Locale curLocale = Locale.forLanguageTag(localeTag);
|
||||
if (curLocale == null) {
|
||||
curLocale = request.getLocale();
|
||||
}
|
||||
|
||||
user.setLocale(this.localeService.findAltLocale(curLocale));
|
||||
return user;
|
||||
}
|
||||
|
||||
public boolean bindModel(HttpServletRequest request) {
|
||||
String uri = request.getRequestURI();
|
||||
|
||||
for(String prefix : excludeBindingPrefixes) {
|
||||
if (uri.startsWith(this.servletContextPath + prefix)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.midm.app;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class InterceptorConfig implements WebMvcConfigurer {
|
||||
@Autowired
|
||||
private BasicAuthInterceptor basicAuthInterceptor;
|
||||
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(this.basicAuthInterceptor).addPathPatterns(new String[]{"/api/**"});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.midm.app;
|
||||
|
||||
import com.midm.service.system.LocaleService;
|
||||
import java.text.MessageFormat;
|
||||
import java.util.Locale;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.support.AbstractMessageSource;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
|
||||
import org.thymeleaf.TemplateEngine;
|
||||
import org.thymeleaf.templateresolver.StringTemplateResolver;
|
||||
|
||||
@Configuration
|
||||
public class LocaleConfig {
|
||||
@Bean({"stringTemplateEngine"})
|
||||
public TemplateEngine stringTemplateEngine() {
|
||||
TemplateEngine templateEngine = new TemplateEngine();
|
||||
templateEngine.setTemplateResolver(new StringTemplateResolver());
|
||||
return templateEngine;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleResolver localeResolver() {
|
||||
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
|
||||
localeResolver.setDefaultLocale(Locale.US);
|
||||
return localeResolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MessageSource messageSource() {
|
||||
return new ResourceMessageSource();
|
||||
}
|
||||
|
||||
private class ResourceMessageSource extends AbstractMessageSource {
|
||||
@Autowired
|
||||
private LocaleService localeService;
|
||||
|
||||
protected MessageFormat resolveCode(String code, Locale locale) {
|
||||
String msg = this.localeService.getMessage(locale, code);
|
||||
return this.createMessageFormat(msg, locale);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.midm.app;
|
||||
|
||||
import com.mitac.cell.system.OsInfo;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
@Configuration
|
||||
public class PropertiesConfig {
|
||||
@Bean
|
||||
public static PropertySourcesPlaceholderConfigurer properties() {
|
||||
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
|
||||
List<Resource> resourceLst = new ArrayList();
|
||||
File file = new File(getConfigFolder(), "midm.properties");
|
||||
if (!file.exists()) {
|
||||
initProperties(file);
|
||||
}
|
||||
|
||||
resourceLst.add(new FileSystemResource(file));
|
||||
ppc.setLocations((Resource[])resourceLst.toArray(new Resource[0]));
|
||||
return ppc;
|
||||
}
|
||||
|
||||
private static void initProperties(File file) {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("mongo.uri", "mongodb://username:password@127.0.0.1:27017/dbname");
|
||||
|
||||
try {
|
||||
OutputStream os = new FileOutputStream(file);
|
||||
properties.store(os, "MiDM Properties");
|
||||
os.close();
|
||||
} catch (FileNotFoundException var3) {
|
||||
} catch (IOException var4) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static File getConfigFolder() {
|
||||
return (new OsInfo()).getConfigFolder("MiDM");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.midm.app;
|
||||
|
||||
import com.google.api.client.util.Value;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.SessionCookieConfig;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.info.BuildProperties;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.boot.web.servlet.ServletContextInitializer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.firewall.HttpFirewall;
|
||||
import org.springframework.security.web.firewall.StrictHttpFirewall;
|
||||
import org.springframework.security.web.header.writers.StaticHeadersWriter;
|
||||
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
|
||||
import org.springframework.web.filter.ForwardedHeaderFilter;
|
||||
|
||||
/**
|
||||
* ======================================================================================
|
||||
* 企业安全与 HTTP 防火墙配置类 (SecurityConfig)
|
||||
* ======================================================================================
|
||||
*
|
||||
* <p>【架构设计与安全防护亮点】
|
||||
* 1. 采用 Spring Security 5.7+ 现代组件化安全过滤链配置({@link SecurityFilterChain})。
|
||||
* 2. 【会话 Cookie 安全加固】:
|
||||
* - 强制开启 `HttpOnly`(防御 XSS 跨站脚本窃取 Cookie)与 `Secure`(仅限 HTTPS 加密传输)。
|
||||
* 3. 【网络防火墙与反向代理适配 (Reverse Proxy Header)】:
|
||||
* - 配置 {@link ForwardedHeaderFilter} 放在过滤器链最前端(`Integer.MIN_VALUE`),
|
||||
* 精准获取经过 Nginx / ALB 代理后终端的真实客户端 IP(X-Forwarded-For);
|
||||
* - 自定义 {@link StrictHttpFirewall}:放行 URL 编码斜杠(`%2F`)与百分号,
|
||||
* 支持 Base64 加密的动态 Token 路由安全通过。
|
||||
* 4. 【传输安全 (HSTS) 与内容安全策略 (CSP)】:
|
||||
* - 启用 HSTS (HTTP Strict Transport Security) 预加载,强制客户端全站使用 HTTPS;
|
||||
* - 密码加密方案:采用工业级单向散列加盐算法 {@link BCryptPasswordEncoder}。
|
||||
*
|
||||
* @author MiDM Core Platform Team
|
||||
*/
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
@Autowired
|
||||
private BuildProperties buildProperties;
|
||||
|
||||
@Value("${spring.thymeleaf.cache: true}")
|
||||
private boolean isDebug;
|
||||
|
||||
/**
|
||||
* 配置 Servlet 上下文 Cookie 安全属性
|
||||
*/
|
||||
@Bean
|
||||
public ServletContextInitializer servletContextInitializer() {
|
||||
return new ServletContextInitializer() {
|
||||
public void onStartup(ServletContext servletContext) throws ServletException {
|
||||
SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig();
|
||||
sessionCookieConfig.setHttpOnly(SecurityConfig.this.isDebug);
|
||||
sessionCookieConfig.setSecure(SecurityConfig.this.isDebug);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 【核心安全过滤链】配置认证、防护头与 CSP 策略
|
||||
*/
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
|
||||
// 写入统一的服务端指纹安全响应头
|
||||
StaticHeadersWriter headerWriter = new StaticHeadersWriter("Server", new String[]{"MiDM Host/MiTAC Digital", this.buildProperties.getVersion()});
|
||||
|
||||
// 针对 API 与 WebSocket 交互关闭 CSRF,禁用默认表单与 Basic 认证(由系统自定义 Token 过滤器接管)
|
||||
httpSecurity.csrf((csrf) -> csrf.disable())
|
||||
.httpBasic((httpBasic) -> httpBasic.disable())
|
||||
.formLogin((formLogin) -> formLogin.disable());
|
||||
|
||||
// 配置内容安全策略 (CSP)
|
||||
httpSecurity.headers((headers) -> headers.addHeaderWriter(headerWriter)
|
||||
.contentSecurityPolicy("default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *;"));
|
||||
|
||||
// 强制启用 HSTS 传输安全保障
|
||||
httpSecurity.headers((headers) -> headers.httpStrictTransportSecurity().preload(true).requestMatcher(AnyRequestMatcher.INSTANCE));
|
||||
|
||||
return (SecurityFilterChain)httpSecurity.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 反向代理转发头过滤器(保障真实 IP 提取)
|
||||
*/
|
||||
@Bean
|
||||
public FilterRegistrationBean forwardedHeaderFilter() {
|
||||
FilterRegistrationBean<ForwardedHeaderFilter> filterRegistrationBean = new FilterRegistrationBean();
|
||||
filterRegistrationBean.setFilter(new ForwardedHeaderFilter());
|
||||
filterRegistrationBean.setOrder(Integer.MIN_VALUE);
|
||||
return filterRegistrationBean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义 HTTP 防火墙规约
|
||||
*/
|
||||
@Bean
|
||||
public WebSecurityCustomizer webSecurityCustomizer() {
|
||||
return (web) -> web.httpFirewall(this.httpFirewall());
|
||||
}
|
||||
|
||||
/**
|
||||
* 放宽特殊字符以兼容 Base64 令牌与 RESTful 动态参数
|
||||
*/
|
||||
@Bean
|
||||
public HttpFirewall httpFirewall() {
|
||||
StrictHttpFirewall firewall = new StrictHttpFirewall();
|
||||
firewall.setAllowSemicolon(true);
|
||||
firewall.setAllowUrlEncodedPeriod(true);
|
||||
firewall.setAllowUrlEncodedPercent(true);
|
||||
firewall.setAllowUrlEncodedSlash(true);
|
||||
return firewall;
|
||||
}
|
||||
|
||||
/**
|
||||
* 全局密码散列加密器(BCrypt)
|
||||
*/
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.midm.app;
|
||||
|
||||
import com.midm.service.device.DeviceService;
|
||||
import com.midm.service.file.ReportService;
|
||||
import com.midm.service.news.NewsMessageService;
|
||||
import com.midm.service.org.SiteService;
|
||||
import com.midm.service.org.UserService;
|
||||
import com.midm.service.system.HelpMessageService;
|
||||
import com.midm.service.system.HostLicenseService;
|
||||
import com.midm.service.system.LocaleService;
|
||||
import com.midm.service.system.RestoreService;
|
||||
import com.midm.service.system.SettingsService;
|
||||
import java.util.TimeZone;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.event.ContextRefreshedEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class StartupKeeper {
|
||||
@Autowired
|
||||
private HostLicenseService hostLicenseService;
|
||||
@Autowired
|
||||
private DeviceService deviceService;
|
||||
@Autowired
|
||||
private SettingsService settingsService;
|
||||
@Autowired
|
||||
private LocaleService localeService;
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private HelpMessageService helpMessageService;
|
||||
@Autowired
|
||||
private NewsMessageService newsMessageService;
|
||||
@Autowired
|
||||
private ReportService reportService;
|
||||
@Autowired
|
||||
private SiteService siteService;
|
||||
@Autowired
|
||||
private RestoreService restoreService;
|
||||
|
||||
@EventListener({ContextRefreshedEvent.class})
|
||||
private void contextRefreshedEvent() {
|
||||
this.setDefaultTimeZone();
|
||||
this.settingsService.loadSettings();
|
||||
if (this.settingsService.syncOnStarts()) {
|
||||
this.restoreService.restore((String)null);
|
||||
}
|
||||
|
||||
this.hostLicenseService.validateLicense();
|
||||
this.localeService.loadLocaleAndResources();
|
||||
this.helpMessageService.loadMessages();
|
||||
if (this.hostLicenseService.isPrimaryServer()) {
|
||||
this.userService.updateUserNameIfNotExists();
|
||||
this.userService.clearExpiredTokens();
|
||||
this.reportService.expireReport();
|
||||
this.deviceService.initDeviceStatus();
|
||||
this.deviceService.clearOrphans();
|
||||
this.siteService.clearOrphans();
|
||||
this.newsMessageService.removeExpiredMessages();
|
||||
this.newsMessageService.scheduleToNotify();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void setDefaultTimeZone() {
|
||||
TimeZone defaultTimeZone = TimeZone.getTimeZone("UTC");
|
||||
System.setProperty("user.timezone", defaultTimeZone.getID());
|
||||
TimeZone.setDefault(defaultTimeZone);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.midm.app;
|
||||
|
||||
import com.midm.websocket.message.QueryHandler;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocket;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
|
||||
|
||||
/**
|
||||
* ======================================================================================
|
||||
* WebSocket 全双工通信配置类
|
||||
* ======================================================================================
|
||||
*
|
||||
* <p>【架构设计与业务场景】
|
||||
* 1. 负责开启系统全双工实时通信能力({@link EnableWebSocket}),作为物联网终端与云端管理控制台的接入网关。
|
||||
* 2. 路由映射:将 "/query" 端点绑定到核心消息处理器 {@link QueryHandler}。
|
||||
* 3. 跨域策略:允许跨域请求(AllowedOrigins: "*"),支持 Web 前端管理后台和不同子网终端的安全接入。
|
||||
*
|
||||
* @author MiDM Core Platform Team
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSocket
|
||||
public class WebSocketConfig implements WebSocketConfigurer {
|
||||
|
||||
/** 核心 WebSocket 消息与连接生命周期处理器 */
|
||||
@Autowired
|
||||
private QueryHandler queryHandler;
|
||||
|
||||
/**
|
||||
* 注册 WebSocket 处理器与通信端点
|
||||
*
|
||||
* @param registry WebSocket 处理器注册中心
|
||||
*/
|
||||
@Override
|
||||
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
||||
// 注册 "/query" 端点,用于处理终端注册(ENROLL)、遥测上报(REPORT)、心跳(PING/PONG)及实时控制指令下发
|
||||
registry.addHandler(this.queryHandler, new String[]{"/query"}).setAllowedOrigins(new String[]{"*"});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.midm.app.converter;
|
||||
|
||||
import com.mitac.cell.utils.McDateTimeUtils;
|
||||
import java.util.Date;
|
||||
import org.joda.time.DateTime;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class DateConverter implements Converter {
|
||||
public Date convert(String source) {
|
||||
DateTime date = null;
|
||||
|
||||
try {
|
||||
date = new DateTime(new Date(Long.parseLong(source)));
|
||||
} catch (Exception var6) {
|
||||
try {
|
||||
date = DateTime.parse(source);
|
||||
} catch (Exception var5) {
|
||||
date = McDateTimeUtils.parseDate(source, (String)null);
|
||||
if (date == null) {
|
||||
date = McDateTimeUtils.parseDate(source, "E, d MMM yyyy HH:mm:ss Z 'GMT'");
|
||||
}
|
||||
|
||||
if (date == null) {
|
||||
date = McDateTimeUtils.parseDate(source, "E, d MMM yyyy HH:mm:ss Z z");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return date == null ? null : date.toDate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.midm.app.converter;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class DirectionConverter implements Converter {
|
||||
public Sort.Direction convert(String source) {
|
||||
return Direction.valueOf(source.toUpperCase());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.midm.app.converter;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.mitac.cell.utils.McJsonUtils;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.Charset;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class JsonElementConverter implements Converter {
|
||||
public JsonElement convert(String source) {
|
||||
try {
|
||||
source = URLDecoder.decode(source, Charset.defaultCharset());
|
||||
return McJsonUtils.toJsonElement(source);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.midm.app.converter;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mitac.cell.utils.McJsonUtils;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.Charset;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class JsonObjectConverter implements Converter {
|
||||
public JsonObject convert(String source) {
|
||||
try {
|
||||
source = URLDecoder.decode(source, Charset.defaultCharset());
|
||||
return McJsonUtils.toJsonElement(source).getAsJsonObject();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.midm.app.converter;
|
||||
|
||||
import com.mitac.cell.internet.http.UserAgent;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class UserAgentConverter implements Converter {
|
||||
public UserAgent convert(String source) {
|
||||
return new UserAgent(source);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user