fix: repair decompiled sources and add exhaustive documentation

- restore generic signatures, scoped variables and missing code from original bytecode
- remove decompiler artifacts and document classes, methods, fields and packages
- restore resources, add Batik/BouncyCastle dependencies and build/runtime docs
This commit is contained in:
rick committed 2026-11-16 17:28:23 +08:00
1 parent 9d7e42eda8
commit 10aa1829f5
346 files changed
+42404 -622

No files matched your search

+7
View File
@@ -37,3 +37,10 @@ WEB-INF/
.DS_Store .DS_Store
Thumbs.db Thumbs.db
Desktop.ini Desktop.ini
# Keep static resources that happen to be zip archives
!src/main/resources/static/**/*.zip
# Local runtime data (MongoDB / smoke-test logs)
.mongo-data/
.run/
+268
View File
@@ -0,0 +1,268 @@
# MiDM 反编译正确性审计报告
审计对象:`D:\Develop\MiDM`(由 `D:\Develop\mdm_or` 反编译)
基准:`D:\Develop\mdm_or\WEB-INF\classes` 的 246 个 class + `WEB-INF/lib/CELL-1.0.0.1.jar` 的 89 个 class
日期:2026-11-16
## 结论
原项目**不能编译**:直接执行 `javac` 有 **109 个编译错误**,分布在 36 个文件。根因不是业务代码写错,而是反编译时**丢失了泛型签名、变量作用域和部分语句**。
本次审计以原始字节码为唯一基准,完成了:
1. 从字节码恢复 114 个 Java 文件的泛型/方法签名(约 540 处);
2. 修复 17 处变量重名、变量丢失、通配符捕获等反编译缺陷;
3. 发现并修复 **3 处会改变运行时行为的偏差**(`DbConfig` 丢失代码块、`CloudStorageService` 多出 null 判断、`BaseFile` 多出 null 判断);
4. 修复 4 处缺失的 `break`,补齐 3 个丢失的资源文件,替换 2 个不一致的二进制资源;
5. 补齐 `pom.xml` 中缺失的 Batik、BouncyCastle 依赖。
修复后:
- **271 个 Java 源文件编译通过,0 error**;
- 246 个原始类、3,599 个方法中,**3,583 个方法的语义操作序列与原始字节码完全一致**,其余 16 个仅为 **javac 11 → javac 18 的代码生成差异**(枚举 `<clinit>`、字符串拼接、装箱、`iinc`);
- 89 个 CELL 类、883 个方法中 878 个完全一致,其余 5 个同样是编译器版本差异;
- 类注解、方法/字段注解:**0 差异**(246 + 89 个类全部逐项比较);
- 异常表(catch 类型):**0 差异**;
- 字段、方法、常量值、继承关系:**0 差异**;
- switch 的 case 集合:**0 差异**(com.midm);
- 资源文件:修复后 **2,722 / 2,722 个文件哈希完全一致**。
---
## 一、阻断编译:泛型签名被整体剥离(109 errors / 35 files)
反编译产物把所有 `Signature` 属性丢掉了,类、方法、字段、局部变量都退化成裸类型,典型报错:
- `BaseService.java:110: cannot find symbol: class T`(方法级 `<T>` 丢失)
- `DeviceService.java:229: Object cannot be converted to Device`(`List<T>` 变成裸 `List`)
- `FileService.java:169: Object cannot be converted to UUID`
- `DateConverter.java: 不是抽象类,未覆盖 convert`(`implements Converter<String, Date>` 变成裸 `Converter`)
- `ProfileApps.java: List<CAP#1> cannot be converted to List<InstallApp>`(通配符捕获)
- `DbObject.java: Map<CAP#1,CAP#2> cannot be converted to Map<String,Object>`
**修复方式**:对每个类用 `javap -p -s` 读出原始 `Signature`,按“方法名 + 参数个数 + 参数类型”对齐,恢复:
- 类/方法类型参数,如 `public <T> T findById(Class<T>, Object)`;
- 返回值与参数泛型,如 `List<Device>`、`PageImpl<T>`、`Converter<String, Date>`;
- 字段泛型,如 `List<SiteInfo> sites`;
- 必要处补回 `Class<T>`、`Collection<?>` 等。
共修改 **114 个 Java 文件、约 560 处签名**,并补回 4 个文件缺失的 import。
---
## 二、变量作用域 / 重名 / 丢失(17 errors)
Fernflower 在 switch、try/catch、lambda 等场景把不同作用域的变量重名,或直接漏掉声明。已逐处对照 `LocalVariableTable` 和字节码修复:
| 文件 | 问题 | 修复 |
| --- | --- | --- |
| `SettingsService.java:257` | `settingsMap.put(key, (Object)null)` 与 `Map<String,String>` 不兼容 | `null` |
| `SettingsService.java:316/322` | 两个 `case` 各自声明 `Long expiry`,Java 同一 switch 作用域冲突;字节码中两段作用域互不重叠 | 两个 case 分别加 `{}` 块 |
| `FileService.java:950` | `clearSite` 中 `category` 变量被漏掉,只剩 `category` 的引用 | 恢复 `String category = file.getName();` 并 `switch(category)` |
| `ReportService.java:264` | 方法级 `groupOption` 声明被漏掉,`:584` 仍在使用 | 恢复 `String groupOption = settings.getString("groupOption","all");` |
| `DbInitialize.java:190` | 游标变量与后面的 `Document indexDefinition` 重名;原字节码实际是两段 foreach | 改为两个 `for (Document index : collection.listIndexes())` |
| `ExternalApiService.java:76` | `Pair` 局部变量与 `String[] decryptStrings` 重名 | 将 `Pair` 改名为 `failureResult` |
| `DeviceApi.java:1184` | 循环内 `DeviceLicense license` 与外层同名 | 改为 `deviceLicense` |
| `OtaFile.java:646` | `String curDisplayId` 被重复声明 | 复用外层变量 |
| `NewsMessageService.java:534` | `Set ssnSet` 重复声明 | 复用外层变量 |
| `BaseFile.java:119` | lambda 参数 `key/value` 类型丢失;且多出原始字节码没有的 `value != null` 判断 | 显式 `String key` / `String[] value`,并删除多余的 null 判断 |
| `DbObject.java` | `List<T>` 中 `T` 未定义、`Map` 构造器通配符不兼容 | 裸 `List` + `super((Map)map)` |
| `GeneralProfile.java` | `<T> T getProfile(...)` 返回 `Object`/`(Object)null` | 补 `(T)` 转换 |
| `NewsMessage.java:94` | 原始 `LinkedTreeMap` 的 `entrySet()` 迭代元素为 `Object` | 先取 `Object`,再显式转 `Map.Entry` |
| `StoreApp.java:67` | `Set<Integer>.addAll(List<?>)` 捕获失败 | 显式 `(Collection)` 转换 |
| `UserApi.java:1516` | `List<?>` 传给 `saveUsers(List<User>)` | 显式 `(List<User>)` 转换 |
| `McJsonUtils.java:221` | `<T> T clone(Object)` 泛型推断失败 | 补 `(T)` 转换 |
---
## 三、会改变运行时行为的偏差(3 处)
### 3.1 `DbConfig.getConnectiontString()`:原始字节码中的两段代码被整体丢掉
原始字节码在 `waitqueuetimeoutms` 之后还有:
1. **第二个** `connectTimeoutMS` 判断块(与前面的块重复):
```java
if (!params.contains("connectTimeoutMS")) {
uriBuilder.setParameter("connectTimeoutMS", String.valueOf(this.connectTimeout));
}
```
2. 一个 `socketTimeoutMS` 块:
```java
if (this.socketTimeout > 0 && !params.contains("socketTimeoutMS")) {
uriBuilder.setParameter("", "");
}
```
反编译源码里这两段完全不存在,意味着连接串的 `connectTimeoutMS` 只设置一次、`socketTimeoutMS` 完全不处理。现已按字节码恢复(`DbConfig.java:191`、`:199`)。
> 注意:第二段用空字符串作为参数名和值,是**原始程序本身的行为**,不是反编译写错;为保持与线上 WAR 完全一致,照原样恢复。
### 3.2 `CloudStorageService.updateMetaInfo()`:反编译多出一个 null 判断
原始字节码是直接调用:
```java
this.cloudStorage.updateMetaInfo(fileName, contentType, paths);
```
反编译源码却生成:
```java
if (this.cloudStorage != null) {
this.cloudStorage.updateMetaInfo(...);
}
```
这会把原本应抛出的 `NullPointerException` 静默吞掉,属于行为改变。已删除该判断(`CloudStorageService.java:161`)。
### 3.3 `BaseFile.setExtra()`:多出原始字节码没有的 `value != null`
原始 `lambda$setExtra$0` 的字节码开头是:
```text
aload_2
arraylength
ifle 44
```
没有 `ifnull`,即原始代码直接访问 `value.length`。项目源码却写成:
```java
if (value != null && value.length > 0 && key.startsWith("extra."))
```
这会把原本可能出现的 `NullPointerException` 静默跳过。已删除 `value != null &&`,恢复原始逻辑(`BaseFile.java:122`)。
---
## 四、缺失的 `break` / switch 贯穿(4 处)
以下 switch 在原字节码中都有 `goto`(即源码中的 `break`),反编译源码漏掉了。虽然当前后续 case 都是空分支,行为没有变化,但源码控制流已不忠实,已补回:
- `WebSocketSessionManager.java:437`:`case 109` 设置 “Site license ready” 后缺少 `break`;
- `OtaFile.java:663`:`case "mitac-package-type"` 设置类型后缺少 `break`;
- `QueryHandler.java:397`:`ENROLL` 分支末尾缺少 `break`;
- `QueryHandler.java:524`:`data_usage` 分支末尾缺少 `break`。
仍有 **2 处是原始代码的有意贯穿**,未修改:
- `FileService.clearSite()`:`default` 处理完文件后贯穿到空 case,统一执行 `++var7`;
- `DeviceProfileApi.deviceGroupRemoved()`:`case 136` 设置 `command` 后贯穿到 `default` 的设备循环并返回成功。
---
## 五、资源文件缺失 / 不一致(构建产物层面)
反编译只处理了 `.class`,资源目录有 3 个文件缺失、2 个二进制文件被替换:
| 文件 | 原 WAR | 项目原状态 | 处理 |
| --- | --- | --- | --- |
| `device_apps_service.txt` | 8 字节 | 缺失 | 从原 WAR 复制 |
| `device_service.txt` | 8 字节 | 缺失 | 从原 WAR 复制 |
| `store_ota_service.txt` | 8 字节 | 缺失 | 从原 WAR 复制 |
| `apksigner/apksigner.jar` | 440,912 字节 | 181,132 字节(不同版本) | 用原 WAR 版本覆盖 |
| `static/module/angular-filter/angular-filter.zip` | SHA-256 不同 | 内容被改动 | 用原 WAR 版本覆盖 |
修复后 `src/main/resources` 与 `WEB-INF/classes` 的非 class 资源 **2,722 个文件哈希全部一致**。
另外,`.gitignore` 里的 `*.zip` 规则会忽略 `angular-filter.zip`,已补充 `!src/main/resources/static/**/*.zip`,避免该静态资源在提交时再次丢失。
---
## 六、Maven 依赖缺失
源码直接引用了 Batik 和 BouncyCastle,但 `pom.xml` 未声明;用原 WAR 的 `WEB-INF/lib` 编译能通过,纯 Maven 构建会失败:
- `org.apache.batik.transcoder.*`(`McApkFile.java`)→ 增加 `batik-transcoder`、`batik-codec` 1.16;
- `org.bouncycastle.jce.provider.BouncyCastleProvider`、`org.bouncycastle.util.encoders.Hex` → 增加 `bcprov-jdk14` 1.64。
已写入 `pom.xml`(`:159`–`:176`)。
---
## 七、验证方法与结果
验证不是“看起来像”,而是逐字节码比较:
1. 用原始 `WEB-INF/classes` 和 `CELL-1.0.0.1.jar` 作为 ground truth;
2. 用 `javac --release 11` 重新编译反编译源码;
3. `javap -p -c` 逐方法比较语义操作(方法调用、字段访问、常量、算术、数组、异常抛出等);
4. 额外比较:注解(含值)、异常表 catch 类型、字段/方法/常量、继承关系、switch case 集合、资源哈希。
| 检查项 | 结果 |
| --- | --- |
| Java 编译 | 271 文件,**0 error** |
| com.midm 类覆盖 | 246 / 246 |
| com.midm 方法语义一致 | 3,583 / 3,599(其余 16 个为编译器版本差异) |
| CELL 类覆盖 | 89 / 89 |
| CELL 方法语义一致 | 878 / 883(其余 5 个为编译器版本差异) |
| 注解差异 | 0 |
| 异常表差异 | 0 |
| 字段 / 方法 / 常量 / 继承差异 | 0 |
| switch case 差异 | 0 |
| 资源文件差异 | 0(修复后 2,722 / 2,722) |
剩余 16 + 5 个“差异”均为 **javac 11 与 javac 18 的代码生成差异**,不是源码语义差异:
- 12 个枚举类的 `<clinit>`:javac 11 直接 `anewarray + putstatic`,javac 18 生成 `$values()` 辅助方法;
- `LicenseModel.Period.toString()`:javac 11 用 `StringBuilder`,javac 18 用 `invokedynamic makeConcatWithConstants`;
- `DeviceLicense.activate()`、`SettingsService.getInt()`:三元表达式装箱/拆箱指令不同;
- `ReportService.generateDeviceReport()`:`iadd` 与 `iinc` 的循环自增优化不同。
### 验证环境说明
- 已安装 **Apache Maven 3.9.9**(`D:\Software\apache-maven-3.9.9`),并写入用户 `MAVEN_HOME`、`M2_HOME` 与 `PATH`;
- 已安装 **MongoDB Community 7.0.14** 便携版(`D:\Software\mongodb-7.0.14`);
- 已执行 `mvn clean package -DskipTests`,**BUILD SUCCESS**,产物 `target/midm-1.1.1.12.war`(约 149 MB);
- 已实际启动 Spring Boot:`Started MainApplication`,`http://127.0.0.1:8080/` 返回登录页 200,`/dpc/qr` 返回 `image/png`。
---
## 八、仍可改进但无行为影响的部分
- 已清除全部 `var10000`/`var10001` 等 Fernflower 临时变量(约 48 处),改为直接表达式或语义化局部变量;
- 已把两处有意 switch 贯穿标注 `@SuppressWarnings("fallthrough")` 并加注释,`-Xlint` 不再报 fallthrough;
- 已修正 `MainApplication` 的 `new Class[]{...}` 与 `SiteService` 的裸 `Class[]`;
- `javac -Xlint:all` 仍有 **1,253** 条警告:498 unchecked、408 cast、326 rawtypes、14 serial、4 overrides、3 deprecation。
- 主要是局部变量仍保留裸类型(例如 `List list = ...`)、反编译器补的冗余 cast;
- 不影响运行行为,若要追求“零警告”,可以再逐文件恢复局部变量泛型。
---
## 九、环境配置与运行验证(2026-11-16 补充)
| 项目 | 结果 |
| --- | --- |
| Maven | 3.9.9,已配置代理/阿里云 mirror,`mvn -v` 正常 |
| JDK | Amazon Corretto 18.0.2(`JAVA_HOME` 已设置;编译目标 `--release 11`) |
| MongoDB | Community 7.0.14,监听 `127.0.0.1:27017` |
| 构建 | `mvn clean package -DskipTests` → BUILD SUCCESS |
| 启动 | `java -jar target/midm-1.1.1.12.war` → Started in 5.7s |
| 登录页 | `GET /` → 200 `text/html` |
| DPC 二维码 | `GET /dpc/qr` → 200 `image/png` |
| 运行日志错误 | 0 ERROR / 0 Exception |
| 清理后语义复验 | 3,583 / 3,599 方法仍完全一致(16 个编译器版本差异不变) |
启动时踩到并已修复的环境问题:`PropertiesConfig` 会强制读取
`C:\ProgramData\MiDM\midm.properties`,目录/文件不存在时直接启动失败。已创建该文件并写入
单机 Mongo 配置(`mongo.replica_set=` 为空)。
---
## 附:本次修改涉及的关键文件
- `src/main/java/com/midm/service/BaseService.java`:`<T>` 方法签名、`PageImpl<T>`
- `src/main/java/com/midm/app/DbConfig.java`:恢复两段超时参数块
- `src/main/java/com/midm/service/cloudStorage/CloudStorageService.java`:删除多余 null 判断
- `src/main/java/com/midm/service/file/FileService.java`:`category`、switch 作用域
- `src/main/java/com/midm/service/file/ReportService.java`:`groupOption`
- `src/main/java/com/midm/app/DbInitialize.java`:两个索引遍历循环
- `src/main/java/com/midm/service/ExternalApiService.java`:`failureResult`
- `src/main/java/com/midm/webservice/device/DeviceApi.java`:`deviceLicense`
- `pom.xml`:Batik / BouncyCastle 依赖
- `src/main/resources/apksigner/apksigner.jar` 等资源
+57 -8
View File
@@ -130,23 +130,72 @@ iot_m/
## 🚀 本地快速启动 ## 🚀 本地快速启动
### 1. 环境准备 ### 1. 环境准备(Windows,本机已配置)
- **JDK**:OpenJDK 11 或更高
- **构建工具**:Apache Maven 3.6+ | 组件 | 版本 | 本机路径 |
- **数据库**:MongoDB 4.x+(本地启动或使用 Docker 容器) | :--- | :--- | :--- |
| JDK | Amazon Corretto 18.0.2 | `C:\Users\rick.liu\.jdks\corretto-18.0.2` |
| Maven | Apache Maven 3.9.9 | `D:\Software\apache-maven-3.9.9` |
| MongoDB | Community 7.0.14(便携版) | `D:\Software\mongodb-7.0.14` |
已写入用户环境变量:
- `JAVA_HOME` → Corretto 18
- `MAVEN_HOME` / `M2_HOME` → Maven 3.9.9
- `PATH` 追加 `%MAVEN_HOME%\bin`
> 新开一个 PowerShell 窗口后可直接使用 `mvn`;当前会话也可用完整路径
> `D:\Software\apache-maven-3.9.9\bin\mvn.cmd`。
### 2. 启动 MongoDB ### 2. 启动 MongoDB
PowerShell(本机已验证):
```powershell
New-Item -ItemType Directory -Force D:\Develop\MiDM\.mongo-data | Out-Null
& 'D:\Software\mongodb-7.0.14\bin\mongod.exe' `
--dbpath 'D:\Develop\MiDM\.mongo-data' `
--port 27017 `
--bind_ip 127.0.0.1 `
--logpath 'D:\Develop\MiDM\.mongo-data\mongod.log' `
--logappend
```
也可以继续使用 Docker:
```bash ```bash
docker run -d --name midm-mongo -p 27017:27017 -e MONGO_INITDB_DATABASE=db_midm mongo:5.0 docker run -d --name midm-mongo -p 27017:27017 -e MONGO_INITDB_DATABASE=db_midm mongo:5.0
``` ```
### 3. 配置与启动 ### 3. 运行时配置
检查 `src/main/resources/application.properties`,确认 MongoDB 连接配置后执行:
```bash MiDM 启动时会加载 `C:\ProgramData\MiDM\midm.properties`。该文件或目录不存在时,
`PropertiesConfig` 会抛 `FileNotFoundException` 并导致启动失败。本机已创建:
```properties
mongo.uri=
mongo.host=127.0.0.1
mongo.port=27017
mongo.dbname=db_midm
mongo.replica_set=
```
> 单机 MongoDB 必须保持 `mongo.replica_set=` 为空;如果使用副本集,改为 `rs0` 并先执行
> `rs.initiate()`,否则连接串中的 `replicaSet=rs0` 会导致连接失败。
### 4. 构建与启动
```powershell
mvn clean package -DskipTests mvn clean package -DskipTests
java -jar target/midm-1.1.1.12.war java -jar target\midm-1.1.1.12.war
``` ```
系统启动后默认监听 `8080` 端口: 系统启动后默认监听 `8080` 端口:
- 登录页:`http://localhost:8080/`
- WebSocket 网关端点:`ws://localhost:8080/query` - WebSocket 网关端点:`ws://localhost:8080/query`
- 零接触 DPC 二维码端点:`http://localhost:8080/dpc/qr` - 零接触 DPC 二维码端点:`http://localhost:8080/dpc/qr`
本次已实际启动验证:`Started MainApplication`,登录页返回 200,
`/dpc/qr` 返回 `image/png`。MongoDB 日志与运行日志位于
`D:\Develop\MiDM\.mongo-data\mongod.log`、`D:\Develop\MiDM\.run\app.log`(均已 gitignore)。
+456
View File
@@ -0,0 +1,456 @@
# MiDM 源码学习指南(CODE WALKTHROUGH)
> 目标:把反编译出来的 Java 代码变成一套可以按图索骥学习的工程。
> 本文件讲**架构与调用链**;每个类/方法/字段的细节看源码里的 Javadoc
>(本次已补全 286 个类型、3,989 个方法、1,733 个字段的注释)。
---
## 0. 推荐阅读顺序
1. 先读本文件第 1~4 节,建立“端 → 云 → Mongo → 管理后台”的整体地图。
2. 读 <code>com.midm.model</code>:先看 <code>GeneralProfile</code>、<code>Device</code>、<code>DeviceProfile</code>、<code>Site</code>、<code>User</code>。
3. 读 <code>com.midm.service.BaseService</code> 与一个具体 Service(推荐 <code>DeviceService</code>)。
4. 读 <code>com.midm.websocket.message.QueryHandler</code>:这是设备协议的总入口。
5. 读 <code>com.midm.webservice.device.DeviceApi</code> / <code>DeviceProfileApi</code>:管理端 REST 入口。
6. 最后读文件/报表/云存储/安全等横向能力。
---
## 1. 系统全景
MiDM 是一套面向工业手持终端、车载平板、POS/医疗设备的 MDM/EMM 平台:
~~~text
Android 设备 (DPC/MDM Agent)
│ WebSocket /query(文本 JSON、二进制 Deflate)
│ REST /dpc/*、/file/*(下载、二维码、APK/OTA)
▼
Spring Boot 2.7 (WAR)
├─ QueryHandler ── WebSocketSessionManager ── DeviceService / ProfileService / BatteryService
├─ Controller / WebService ── UserService / SiteService / FileService / ReportService
├─ MongoTemplate / Repository ── MongoDB (db_midm)
└─ CloudStorageService ── AWS S3 / Azure Blob / GCP Storage
~~~
管理后台(Thymeleaf + 静态前端)通过 REST/JSON 与 WebSocket 同时接入;
设备端主要走 WebSocket 长连接,少量文件下载走 HTTP。
技术栈:Java 11 目标字节码、Spring Boot 2.7.15、Spring Security 5.7、
Spring Data MongoDB 3.4、Thymeleaf、POI、Flying Saucer、ZXing、OkHttp、
AWS SDK v1/v2、Azure SDK、Google Cloud Storage、Batik。
---
## 2. 目录地图
| 包 | 作用 | 先看谁 |
| --- | --- | --- |
| <code>com.midm</code> | 启动入口 | <code>MainApplication</code> |
| <code>com.midm.app</code> | Mongo/Security/WebSocket/Locale/启动初始化 | <code>DbConfig</code>、<code>SecurityConfig</code>、<code>DbInitialize</code>、<code>StartupKeeper</code> |
| <code>com.midm.app.converter</code> | 请求参数 → 对象转换 | <code>DateConverter</code>、<code>JsonObjectConverter</code> |
| <code>com.midm.constant</code> | 常量、集合名、协议码 | <code>MidmConst</code>、<code>PropertyConst</code> |
| <code>com.midm.controller</code> | 页面路由(Thymeleaf) | <code>HomeController</code>、<code>DeviceController</code> |
| <code>com.midm.controller.lib</code> | 图片/文件下载 | <code>FilesController</code>、<code>StoreController</code> |
| <code>com.midm.dpc</code> | Android Enterprise 零接触 | <code>DpcController</code>、<code>DpcModel</code> |
| <code>com.midm.model</code> | 领域模型 / Mongo 文档 | <code>GeneralProfile</code>、<code>Device</code>、<code>DeviceProfile</code> |
| <code>com.midm.repository</code> | Spring Data Repository | <code>DeviceLicenseRepository</code> |
| <code>com.midm.security</code> | 认证主体 | <code>UserPrincipal</code> |
| <code>com.midm.service</code> | 业务服务 | <code>BaseService</code>、<code>DeviceService</code>、<code>ProfileService</code> |
| <code>com.midm.webservice</code> | 管理端/设备端 REST API | <code>DeviceApi</code>、<code>DeviceProfileApi</code>、<code>UserApi</code> |
| <code>com.midm.websocket</code> | WebSocket 网关与协议处理 | <code>QueryHandler</code> |
| <code>com.mitac.cell</code> | 通用基础库 | <code>DbObject</code>、<code>McJsonUtils</code>、<code>McFile</code>、<code>McTextEncryptor</code> |
---
## 3. 启动与配置链路
### 3.1 启动入口
<code>MainApplication</code>:
- <code>@SpringBootApplication(scanBasePackages = "com.midm")</code>;
- 继承 <code>SpringBootServletInitializer</code>,既支持 <code>java -jar</code> 也支持外置 Tomcat;
- <code>@EnableScheduling</code> 打开定时任务;
- <code>restart()</code> 在非守护线程中关闭并重建 Spring 上下文,用于运行期热重启。
### 3.2 外部配置
<code>PropertiesConfig</code> 会强制读取:
~~~text
C:\ProgramData\MiDM\midm.properties
~~~
目录或文件不存在时,<code>PropertySourcesPlaceholderConfigurer</code> 会抛
<code>FileNotFoundException</code>,应用直接启动失败。本地开发建议内容:
~~~properties
mongo.uri=
mongo.host=127.0.0.1
mongo.port=27017
mongo.dbname=db_midm
mongo.replica_set=
~~~
<code>application.properties</code> 负责日志级别、Session Cookie、Tomcat access log、
Thymeleaf 缓存、静态资源缓存等 Spring Boot 配置;Mongo 连接参数集中在
<code>DbConfig</code> 的 <code>@Value</code> 字段。
### 3.3 Mongo 连接池
<code>DbConfig.getConnectiontString()</code> 根据 <code>mongo.uri</code> / <code>mongo.host</code>
动态拼装 <code>ConnectionString</code>:
- 多节点时拆分逗号分隔的 host,补齐默认端口;
- 强制 <code>w=majority</code>、<code>retryWrites=true</code>、<code>uuidRepresentation=javaLegacy</code>;
- 按配置补齐 <code>maxPoolSize</code>、<code>connectTimeoutMS</code>、<code>maxIdleTimeMS</code>、
<code>waitqueuetimeoutms</code>、<code>ssl</code>、<code>replicaSet</code>;
- <code>fixDb()</code> 在启动时做索引自愈(删除低效单字段索引,确保复合索引生效)。
> 注意:单机 MongoDB 要把 <code>mongo.replica_set</code> 置空;副本集才填 <code>rs0</code> 并执行
> <code>rs.initiate()</code>。
### 3.4 初始化与启动钩子
- <code>DbInitialize</code>:首次启动时建集合/索引、修复历史数据、补默认设置。
- <code>StartupKeeper</code>:监听 <code>ContextRefreshedEvent</code>,加载系统设置、恢复同步、
校验 License、加载语言与帮助消息、初始化设备状态、清理孤儿数据、安排通知任务。
---
## 4. 领域模型与 MongoDB
### 4.1 公共基类 <code>GeneralProfile</code>
大部分业务对象继承 <code>com.midm.model.GeneralProfile</code>:
| 字段 | 作用 |
| --- | --- |
| <code>uuid</code> | 业务主键(<code>@Id</code>),全系统统一用 UUID |
| <code>created</code> / <code>updated</code> | 创建/更新时间 |
| <code>profile</code> | <code>DbObject</code> 扩展属性包,承载厂商/硬件/软件等可变字段 |
| <code>enabled</code> | 通用启用状态 |
<code>DbObject</code> 继承 <code>org.bson.Document</code>,提供 <code>getString/getBoolean/getList/getDbObject</code>
等便捷方法,避免到处强转。
### 4.2 常用注解
| 注解 | 含义 |
| --- | --- |
| <code>@Document</code> | 映射为 MongoDB 集合 |
| <code>@Id</code> | 文档主键 |
| <code>@Indexed</code> | 建索引,常用于查询条件 |
| <code>@Field("x")</code> | 指定 Mongo 字段名 |
| <code>@Transient</code> | 不持久化,仅运行时 |
| <code>@DBRef</code> | 引用其他文档(慎用,查询成本高) |
| <code>@Expose(serialize=false)</code> | Gson 序列化时排除(如密码) |
### 4.3 核心集合(按业务)
| 领域 | 主要类 | 说明 |
| --- | --- | --- |
| 设备 | <code>Device</code>、<code>DeviceApps</code>、<code>DeviceGroup</code>、<code>DeviceNote</code> | 设备档案、已装应用、分组树、备注 |
| 策略 | <code>DeviceProfile</code>、<code>ProfileApps</code>、<code>ProfileScope</code> | 配置档案、应用/文件/OTA 项、作用域 |
| 组织 | <code>Site</code>、<code>User</code>、<code>SiteInfo</code>、<code>UserGroup</code> | 多租户站点、账号、站点成员、用户组 |
| 授权 | <code>DeviceLicense</code>、<code>SiteLicense</code>、<code>LicenseModel</code>、<code>HostLicense</code> | 设备/站点/主机 License |
| 文件 | <code>BaseFile</code>、<code>AppFile</code>、<code>OtaFile</code>、<code>StoreAppFile</code> | APK/OTA/普通文件/商店文件 |
| 遥测 | <code>Battery</code>、<code>BatteryLog</code>、<code>DataUsage</code>、<code>DeviceReport</code> | 电池健康、流量、设备报表 |
| 审计 | <code>MidmLog</code>、<code>DeviceLog</code> | 操作/设备日志 |
| 系统 | <code>SystemSetting</code>、<code>Locale</code>、<code>HelpMessage</code>、<code>NewsMessage</code> | 设置、语言、帮助、通知 |
| 商店 | <code>StoreApp</code>、<code>StoreWebApp</code>、<code>AppReleaseNote</code> | 应用商店/WebApp/发布说明 |
阅读实体时先看字段注释和注解,再看对应 Service 如何构造 <code>Criteria</code>。
---
## 5. Web 层与安全
### 5.1 两类入口
- <code>com.midm.controller</code>:返回 Thymeleaf 视图名,服务管理后台页面;
- <code>com.midm.webservice</code>:<code>@RestController</code>/JSON,服务前端 AJAX 与设备/第三方 API。
统一响应封装是 <code>MidmResponse</code>(code/message/data),异常由
<code>ExceptionController</code> 收敛。
### 5.2 认证与授权
- <code>SecurityConfig</code> 定义过滤器链、登录页、静态资源放行、CSRF/Headers;
- <code>BasicAuthInterceptor</code> 处理 Basic/Token 头;
- <code>UserPrincipal</code> 把 <code>User</code> 包装成 Spring Security 主体;
- <code>UserRole</code> 定义角色常量(SUPERVISOR、DEVICE_MANAGER、PROFILE_MANAGER 等);
- <code>UserService.authorizedUser(authentication, accessToken)</code> 是各 API 的统一鉴权入口;
- <code>user.canHandle(siteUuid, roles)</code> 做站点级权限判断。
### 5.3 典型 REST 调用链
<code>DeviceApi.findDevices()</code> → <code>UserService.authorizedUser()</code> → 站点校验 →
<code>DeviceService.findDevices()</code> → <code>BaseService.findByPage()</code> → MongoTemplate。
---
## 6. WebSocket 设备通道(重点)
### 6.1 端点与握手
<code>WebSocketConfig</code> 把 <code>/query</code> 注册到 <code>QueryHandler</code>,允许跨域。
握手完成后 <code>afterConnectionEstablished</code>:
1. <code>WebSocketSessionManager.toMidmSocketSession(session, true)</code> 从 Header/Query
解析设备序列号或用户 Token,包装成 <code>MidmWebSocketSession</code>;
2. 按配置设置文本/二进制最大缓冲;
3. 设备连接走 <code>onConnected</code>,管理端用户连接走 <code>register</code>。
### 6.2 报文模型
<code>MidmPacket</code> 是统一报文:
- <code>query</code>:请求(<code>MidmQuery</code>,含 code/request/params);
- <code>feedback</code>:响应(<code>MidmResponse</code>,含 code/message/data);
- <code>uuid</code> / <code>queryUuid</code> / <code>recieverUuid</code>:路由与幂等;
- 支持 <code>toTextMessage()</code> / <code>toBinaryMessage()</code>,二进制路径用 <code>McCompress</code> 压缩。
<code>MIDM_REQUEST</code> 定义协议码,例如:
| code | 枚举 | 含义 |
| --- | --- | --- |
| 99 | <code>PING</code> | 心跳 |
| 100 | <code>CONNECT</code> | 建连 |
| 104 | <code>ENROLL</code> | 设备注册 |
| 105 | <code>DEVICE_INFO</code> | 设备信息/遥测上报 |
| 131/132 | <code>UPDATE_PROFILE</code> / <code>UPDATE_ALL_PROFILES</code> | 策略下发/全量同步 |
| 136 | <code>REMOVE_PROFILE</code> | 移除策略 |
| 200 | <code>COMMAND</code> | 远程指令 |
| 210 | <code>QUERY</code> | 查询设备信息 |
| 400 | <code>RTC</code> | 远程协助/WebRTC 信令 |
### 6.3 消息分发
<code>QueryHandler.handleMessage</code>:
1. 刷新 pong 时间戳;
2. 若租户开启流量采集,按阈值触发 <code>updateDataUsage</code>;
3. 按帧类型分派:
- <code>PongMessage</code> → <code>onPong</code>;
- <code>TextMessage</code> → <code>handleTextMessage</code>(<code>"ping"</code> 或 JSON <code>MidmPacket</code>);
- <code>BinaryMessage</code> → <code>McDecompress</code> 解压后按 <code>feedback</code>/ping 处理。
<code>onFeedback</code> 是业务总路由:<code>ENROLL</code> 注册、<code>DEVICE_INFO</code> 更新设备、
<code>UPDATE_PROFILE</code>/命令回执、<code>RTC</code> 信令等。
### 6.4 会话管理
<code>WebSocketSessionManager</code> 维护:
- <code>deviceSessions</code>:设备 UUID → <code>MidmWebSocketSession</code>;
- <code>userSessions</code>:用户 UUID → <code>UserSocketSessions</code>;
- 心跳 ping/pong、在线状态广播、断线清理;
- <code>ReconnectMonitor</code>:滑动窗口统计重连频率,异常时 block,防止弱网重连风暴。
### 6.5 设备注册(ENROLL)链路
<code>QueryHandler.onFeedback</code> 的 <code>ENROLL</code> 分支:
1. 校验序列号;找不到站点/白名单不允许则回 451/463/461 并关闭;
2. <code>DeviceService.register()</code>:初始化设备、绑定分组、所有者、站点;
3. License 激活/试用;
4. 审计日志 <code>LogService.saveDeviceLog</code>;
5. 注册全局 Session,下发 111 + 精简设备配置;
6. License 过期则回 115 并关闭。
---
## 7. 设备生命周期与策略
### 7.1 设备
<code>DeviceService</code> 是设备中枢:
- 注册/保存/批量导入:<code>register</code>、<code>save</code>、<code>saveDevices</code>;
- 查询:<code>findBySerialNo</code>、<code>findDeviceByUuid</code>、<code>findDevices</code>(分页/过滤);
- 分组:<code>findGroupFamily</code>、<code>findChildGroups</code>、<code>findAllDevicesInGroup</code>;
- 删除/退役:<code>delete</code>、<code>retire</code>、<code>deleteBySite</code>;
- License:<code>setTrialLicense</code>、<code>activateLicense</code>、<code>renewLicense</code>;
- OTA 回调:<code>systemImageUpdated</code>、<code>regionImageUpdated</code>。
### 7.2 策略(Profile)
<code>ProfileService</code> 负责配置档案:
- CRUD:<code>save</code>、<code>find</code>、<code>delete</code>、<code>findProfiles</code>;
- 作用域:<code>updateScope</code>、<code>unscope</code>、<code>isDeviceScoped</code>、<code>isGroupScoped</code>;
- 下发:<code>notifyToSync</code> 给设备发 WebSocket 通知;
- 应用状态:<code>isProfileApplied</code>、<code>profileStatesByDevice</code>;
- 冲突解决:<code>ProfileAdvisor</code> 计算应用/设置/OTA 冲突,决定最终下发项。
### 7.3 License
- <code>DeviceLicense</code>:设备级,含 <code>licenseModel</code>、<code>expiry</code>、<code>activationCount</code>;
- <code>SiteLicense</code>:站点级采购/续费;
- <code>LicenseModel</code>:型号/周期/最大激活数;
- <code>HostLicenseService</code>:主机级 License 校验(单机/多租户模式)。
---
## 8. 文件与云存储
### 8.1 文件模型
- <code>BaseFile</code>:文件名、大小、校验和、站点、分类;
- <code>AppFile</code>:APK 包名、版本号、minSdk、签名证书;
- <code>OtaFile</code>:固件 build date、SKU、区域、系统/区域镜像标记。
### 8.2 路径规则
<code>FileService</code> 统一生成路径:<code>getFilePath</code>、<code>getDeviceFilePath</code>、
<code>getSiteFilePath</code>、<code>getMustFolderFilePath</code>。上传/下载/删除都走这里,
避免路径拼接散落各处。
### 8.3 多云策略
<code>CloudStorageService</code> 根据 <code>cloud.storage</code> 设置选择:
- <code>AwsS3</code>
- <code>AzureBlob</code>
- <code>GoogleCloudStorage</code>
统一接口:<code>upload</code>、<code>download/getUrl</code>、<code>exists</code>、<code>delete</code>、<code>list</code>、
<code>updateMetaInfo</code>、<code>refreshClient</code>。大文件用预签名 URL 让设备直连云存储,
服务端只负责签发和元数据。
### 8.4 APK 签名
<code>StoreAppService.sign()</code> 调用资源里的 <code>apksigner/apksigner.jar</code>,
用 keystore 对 APK 重签名,并记录证书 MD5/版本信息。
---
## 9. 报表、邮件与模板
### 9.1 报表
<code>ReportService</code> 基于 POI 的 <code>ExcelWriter</code> 生成三类报表:
- <code>generateDeviceReport</code>:设备清单/状态/流量/电池;
- <code>generateProfileReport</code>:策略应用情况;
- <code>generateSiteReport</code>:站点/License/设备分布。
模板在 <code>src/main/resources/report/*.xlsx</code>,生成后保存为 <code>SiteFile</code>,
可下载或邮件发送。
### 9.2 PDF
<code>com.mitac.cell.doc.HtmlToPdf</code> 用 Flying Saucer + iText 把 HTML 转 PDF。
### 9.3 邮件与模板
- <code>EmailService</code>:发送密码重置、License、报表等邮件;
- <code>TemplateService</code>:从 Mongo/资源加载模板;
- <code>McMailSender</code>:封装 JavaMail,支持抄送/密送/附件;
- <code>EmailTemplateResolver</code>:Thymeleaf 模板解析。
---
## 10. 异步、定时与并发
- <code>AsyncConfig</code>:配置 <code>ThreadPoolTaskExecutor</code>;
- <code>@Async</code>:报表生成、邮件发送、日志等不阻塞请求;
- <code>@Scheduled</code> / <code>ScheduledTaskService</code>:设备离线检查、报表过期、通知;
- <code>ReconnectMonitor</code>:滑动窗口 + 定时 unblock;
- <code>synchronized</code> / <code>ConcurrentHashMap</code>:会话表、缓存等共享状态。
读并发代码时先找“共享字段”,再看锁粒度和任务调度器。
---
## 11. 安全细节
- 设备密钥:<code>DeviceKeyService</code> 生成/保存 RSA 公私钥;
- 请求验签:<code>ExternalApiService.doRequestRsaIsValid</code> 用 RSA-OAEP 解密设备密文;
- 密码:BCrypt(<code>PasswordEncoder</code>);
- API Token:<code>UserToken</code> / <code>accessToken</code>,一次性令牌用后删除;
- 文件下载:<code>FilesController</code> 校验用户站点归属,防越权下载;
- 安全头/CSRF/Session Cookie:<code>SecurityConfig</code> + <code>application.properties</code>。
---
## 12. 构建、运行与排错
### 12.1 本机环境
- JDK 18(编译目标 11);
- Maven 3.9.9;
- MongoDB 7.0.14(单机);
- <code>C:\ProgramData\MiDM\midm.properties</code> 必须存在。
### 12.2 命令
~~~powershell
mvn clean package -DskipTests
java -jar target\midm-1.1.1.12.war
~~~
### 12.3 常见错误
| 现象 | 原因 | 处理 |
| --- | --- | --- |
| <code>FileNotFoundException: c:\ProgramData\MiDM\midm.properties</code> | 运行配置缺失 | 创建目录和文件 |
| <code>replicaSet=rs0</code> 连接失败 | 单机 Mongo 却配了副本集 | <code>mongo.replica_set=</code> 置空 |
| 端口占用 | 8080 被占用 | <code>--server.port=18081</code> |
| 登录页 404 | 访问了错误路径 | 用 <code>/</code>,不是 <code>/login</code> |
| 生成报表/邮件失败 | 模板/邮箱配置缺失 | 看 <code>SettingsService</code> 与运行日志 |
---
## 13. 建议的学习路线
| 天 | 目标 | 代码 |
| --- | --- | --- |
| Day 1 | 跑起来 + 模型 | <code>MainApplication</code> → <code>GeneralProfile</code> → <code>Device</code> → <code>Site</code> → <code>User</code> |
| Day 2 | 通用 CRUD/分页 | <code>BaseService</code> → <code>DeviceService</code> 的 find/save/delete |
| Day 3 | 设备协议 | <code>WebSocketConfig</code> → <code>QueryHandler</code> → <code>WebSocketSessionManager</code> |
| Day 4 | 策略与 License | <code>ProfileService</code> → <code>ProfileAdvisor</code> → <code>DeviceLicense</code> |
| Day 5 | 文件/报表/云存储 | <code>FileService</code> → <code>CloudStorageService</code> → <code>ReportService</code> |
| Day 6 | 安全/定时任务 | <code>SecurityConfig</code> → <code>UserPrincipal</code> → <code>ScheduledTaskService</code> |
练习建议:
1. 新增一个只读 API:<code>GET /api/device/count</code>,走 <code>DeviceService.count</code>;
2. 给 <code>Device</code> 增加一个 <code>@Indexed</code> 字段,观察 <code>DbInitialize</code> 索引;
3. 在 <code>MIDM_REQUEST</code> 增加一个协议码,在 <code>onFeedback</code> 加分支;
4. 给 <code>ProfileService</code> 增加一个“按名称模糊查询”的方法并写 Javadoc。
---
## 14. 代码索引(功能 → 类)
| 功能 | 入口 | 核心实现 |
| --- | --- | --- |
| 启动 | <code>MainApplication</code> | <code>DbConfig</code>、<code>DbInitialize</code>、<code>StartupKeeper</code> |
| 登录/鉴权 | <code>UserApi</code> | <code>UserService</code>、<code>SecurityConfig</code>、<code>UserPrincipal</code> |
| 设备列表/详情 | <code>DeviceApi</code> | <code>DeviceService</code>、<code>BaseService</code> |
| 设备注册 | <code>QueryHandler.ENROLL</code> | <code>DeviceService.register</code>、<code>WebSocketSessionManager</code> |
| 策略管理 | <code>DeviceProfileApi</code> | <code>ProfileService</code>、<code>ProfileAdvisor</code> |
| 策略下发 | <code>ProfileService.notifyToSync</code> | <code>WebSocketSessionManager</code> |
| 设备分组 | <code>DeviceApi</code> | <code>DeviceService.findGroupFamily/findChildGroups</code> |
| License | <code>LicenseApi</code>、<code>HostLicenseApi</code> | <code>LicenseService</code>、<code>HostLicenseService</code> |
| APK/OTA | <code>StoreAppsApi</code>、<code>OtasApi</code> | <code>StoreAppService</code>、<code>FileService</code>、<code>OtaFile</code> |
| 文件下载 | <code>FilesController</code>、<code>DeviceFilesApi</code> | <code>FileService</code>、<code>CloudStorageService</code> |
| 报表 | <code>ReportApi</code> | <code>ReportService</code>、<code>ExcelWriter</code> |
| 电池 | <code>BatteryApi</code> | <code>BatteryService</code> |
| 审计日志 | <code>LogsApi</code> | <code>LogService</code> |
| WebSocket | <code>/query</code> | <code>QueryHandler</code>、<code>WebSocketSessionManager</code>、<code>ReconnectMonitor</code> |
| 零接触 | <code>DpcController</code> | <code>DpcModel</code>、<code>StoreAppService</code> |
| 云存储 | <code>CloudStorageService</code> | <code>AwsS3</code>、<code>AzureBlob</code>、<code>GoogleCloudStorage</code> |
---
## 15. 读代码时最值得问的三个问题
1. **数据从哪里来?** 看 <code>@Document</code> 字段、<code>BaseService</code> 的查询条件、Mongo 索引。
2. **状态在哪里改?** 看 Service 的 save/update 与 <code>@Async</code>/定时任务。
3. **失败会怎样?** 看 <code>MidmResponse</code> 错误码、<code>throw</code>、catch 与 WebSocket <code>sendFeedback</code>。
把这三问套到每个方法上,Javadoc 里的“实现要点/主要调用”就是索引。
+19
View File
@@ -156,6 +156,25 @@
<version>9.1.22</version> <version>9.1.22</version>
</dependency> </dependency>
<!-- SVG rendering (Batik) -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-transcoder</artifactId>
<version>${batik.version}</version>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-codec</artifactId>
<version>${batik.version}</version>
</dependency>
<!-- Cryptography (BouncyCastle) -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk14</artifactId>
<version>1.64</version>
</dependency>
<!-- QR Code (ZXing) --> <!-- QR Code (ZXing) -->
<dependency> <dependency>
<groupId>com.google.zxing</groupId> <groupId>com.google.zxing</groupId>
+1 -1
View File
@@ -50,7 +50,7 @@ public class MainApplication extends SpringBootServletInitializer {
* @return 绑定当前引导类的构建器实例 * @return 绑定当前引导类的构建器实例
*/ */
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(new Class[]{MainApplication.class}); return builder.sources(MainApplication.class);
} }
/** /**
+29
View File
@@ -12,11 +12,40 @@ import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.unit.DataSize; import org.springframework.util.unit.DataSize;
/**
* 【Spring 配置类】{@code AppConfig}
*
* 类职责:
* <ul>
* <li>向 Spring 容器装配 Bean、读取外部配置并控制初始化顺序。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code mongoTemplate}(MongoTemplate):MongoDB模板</li>
* </ul>
*
* 协作对象:{@code MongoTemplate}。
*
* 学习提示:先看 @Bean 方法与 @Value 配置项,再对照 application.properties 和启动日志。
*/
@Configuration @Configuration
public class AppConfig { public class AppConfig {
/**
* MongoDB模板;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private MongoTemplate mongoTemplate; private MongoTemplate mongoTemplate;
/**
* 处理multipart配置Element。
*
* 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne、new MultipartConfigFactory。
* @return 处理结果
*/
@Bean @Bean
public MultipartConfigElement multipartConfigElement() { public MultipartConfigElement multipartConfigElement() {
SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is("files.maxUploadSize")), SystemSetting.class); SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is("files.maxUploadSize")), SystemSetting.class);
@@ -11,17 +11,56 @@ import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* 【Spring 配置类】{@code AsyncConfig}
*
* 类职责:
* <ul>
* <li>向 Spring 容器装配 Bean、读取外部配置并控制初始化顺序。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code TASK_CORE_POOL_SIZE}(int):字段 TASK_CORE_POOL_SIZE</li>
* <li>{@code TASK_MAX_POOL_SIZE}(int):字段 TASK_MAX_POOL_SIZE</li>
* <li>{@code TASK_QUEUE_CAPACITY}(int):字段 TASK_QUEUE_CAPACITY</li>
* <li>{@code asyncExceptionHandler}(AsyncUncaughtExceptionHandler):异步异常Handler</li>
* </ul>
*
* 协作对象:{@code AsyncUncaughtExceptionHandler}。
*
* 学习提示:先看 @Bean 方法与 @Value 配置项,再对照 application.properties 和启动日志。
*/
@Configuration @Configuration
@EnableAsync @EnableAsync
public class AsyncConfig implements AsyncConfigurer { public class AsyncConfig implements AsyncConfigurer {
/**
* 字段 TASK_CORE_POOL_SIZE。
*/
private static final int TASK_CORE_POOL_SIZE = 10; private static final int TASK_CORE_POOL_SIZE = 10;
/**
* 字段 TASK_MAX_POOL_SIZE。
*/
private static final int TASK_MAX_POOL_SIZE = 20; private static final int TASK_MAX_POOL_SIZE = 20;
/**
* 字段 TASK_QUEUE_CAPACITY。
*/
private static final int TASK_QUEUE_CAPACITY = 100; private static final int TASK_QUEUE_CAPACITY = 100;
/**
* 异步异常Handler。
*/
private AsyncUncaughtExceptionHandler asyncExceptionHandler = new AsyncUncaughtExceptionHandler() { private AsyncUncaughtExceptionHandler asyncExceptionHandler = new AsyncUncaughtExceptionHandler() {
public void handleUncaughtException(Throwable ex, Method method, Object... params) { public void handleUncaughtException(Throwable ex, Method method, Object... params) {
} }
}; };
/**
* 获取 {@code asyncExecutor}。
*
* 实现要点:主要调用:new ThreadPoolTaskExecutor。
* @return 字段/派生属性 {@code asyncExecutor} 的值
*/
@Bean @Bean
@Primary @Primary
public Executor getAsyncExecutor() { public Executor getAsyncExecutor() {
@@ -34,10 +73,20 @@ public class AsyncConfig implements AsyncConfigurer {
return executor; return executor;
} }
/**
* 获取 {@code asyncUncaughtExceptionHandler}。
* @return 字段/派生属性 {@code asyncUncaughtExceptionHandler} 的值
*/
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return this.asyncExceptionHandler; return this.asyncExceptionHandler;
} }
/**
* 获取 {@code taskScheduler}。
*
* 实现要点:主要调用:new ThreadPoolTaskScheduler。
* @return 字段/派生属性 {@code taskScheduler} 的值
*/
@Bean @Bean
@Primary @Primary
public ThreadPoolTaskScheduler getTaskScheduler() { public ThreadPoolTaskScheduler getTaskScheduler() {
@@ -46,6 +95,12 @@ public class AsyncConfig implements AsyncConfigurer {
return taskScheduler; return taskScheduler;
} }
/**
* 获取 {@code taskExcutor}。
*
* 实现要点:主要调用:new ThreadPoolTaskExecutor。
* @return 字段/派生属性 {@code taskExcutor} 的值
*/
@Bean @Bean
public ThreadPoolTaskExecutor getTaskExcutor() { public ThreadPoolTaskExecutor getTaskExcutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
@@ -11,13 +11,53 @@ import org.springframework.data.util.Pair;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.HandlerInterceptor;
/**
* 【Spring 组件】{@code BasicAuthInterceptor}
*
* 类职责:
* <ul>
* <li>作为 Spring 组件参与依赖注入或生命周期回调。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code deviceKeyService}(DeviceKeyService):设备密钥服务</li>
* <li>{@code settingsService}(SettingsService):设置列表服务</li>
* </ul>
*
* 协作对象:{@code DeviceKeyService、SettingsService}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
@Component @Component
public class BasicAuthInterceptor implements HandlerInterceptor { public class BasicAuthInterceptor implements HandlerInterceptor {
/**
* 设备密钥服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
DeviceKeyService deviceKeyService; DeviceKeyService deviceKeyService;
/**
* 设置列表服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
SettingsService settingsService; SettingsService settingsService;
/**
* 处理pre处理。
*
* 实现要点:包含 2 个条件分支、0 个循环。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param handler 参数 {@code handler}({@code Object})
* @return 条件成立返回 {@code true},否则返回 {@code false}
* @throws Exception 当 Exception 条件不满足或底层调用失败时抛出。
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String serialNo = request.getHeader("serialNo"); String serialNo = request.getHeader("serialNo");
if (Strings.isNullOrEmpty(serialNo)) { if (Strings.isNullOrEmpty(serialNo)) {
@@ -35,6 +75,15 @@ public class BasicAuthInterceptor implements HandlerInterceptor {
} }
} }
/**
* 处理响应错误。
*
* 实现要点:包含异常捕获与降级/回滚分支。
*
* @param response HTTP 响应({@code HttpServletResponse})
* @param code 状态码/业务码({@code int})
* @param message 消息内容({@code String})
*/
private void responseError(HttpServletResponse response, int code, String message) { private void responseError(HttpServletResponse response, int code, String message) {
response.setStatus(code); response.setStatus(code);
response.setContentType("application/json"); response.setContentType("application/json");
+97
View File
@@ -47,33 +47,83 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie
@EnableMongoRepositories({"com.midm.repository"}) @EnableMongoRepositories({"com.midm.repository"})
public class DbConfig extends AbstractMongoClientConfiguration { public class DbConfig extends AbstractMongoClientConfiguration {
/**
* 数据库Servers;从配置注入。
*
* 注解:{@code @Value("${mongo.servers:}")}。
*/
@Value("${mongo.servers:}") @Value("${mongo.servers:}")
private String dbServers; private String dbServers;
/**
* 数据库URI;从配置注入。
*
* 注解:{@code @Value("${mongo.uri:}")}。
*/
@Value("${mongo.uri:}") @Value("${mongo.uri:}")
private String dbUri; private String dbUri;
/**
* 数据库Scheme;从配置注入。
*
* 注解:{@code @Value("${mongo.scheme:mongodb}")}。
*/
@Value("${mongo.scheme:mongodb}") @Value("${mongo.scheme:mongodb}")
private String dbScheme; private String dbScheme;
/**
* 数据库Host;从配置注入。
*
* 注解:{@code @Value("${mongo.host:127.0.0.1}")}。
*/
@Value("${mongo.host:127.0.0.1}") @Value("${mongo.host:127.0.0.1}")
private String dbHost; private String dbHost;
/**
* 数据库Port;从配置注入。
*
* 注解:{@code @Value("${mongo.port:27017}")}。
*/
@Value("${mongo.port:27017}") @Value("${mongo.port:27017}")
private Integer dbPort; private Integer dbPort;
/**
* 数据库名称;从配置注入。
*
* 注解:{@code @Value("${mongo.dbname:db_midm}")}。
*/
@Value("${mongo.dbname:db_midm}") @Value("${mongo.dbname:db_midm}")
private String dbName; private String dbName;
/**
* 数据库用户;从配置注入。
*
* 注解:{@code @Value("${mongo.username:}")}。
*/
@Value("${mongo.username:}") @Value("${mongo.username:}")
private String dbUser; private String dbUser;
/**
* 数据库Password;从配置注入。
*
* 注解:{@code @Value("${mongo.password:}")}。
*/
@Value("${mongo.password:}") @Value("${mongo.password:}")
private String dbPassword; private String dbPassword;
/**
* SSLEnabled;从配置注入。
*
* 注解:{@code @Value("${mongo.ssl:false}")}。
*/
@Value("${mongo.ssl:false}") @Value("${mongo.ssl:false}")
private boolean sslEnabled; private boolean sslEnabled;
/**
* 是否keepAlive;从配置注入。
*
* 注解:{@code @Value("${mongo.keep_alive:true}")}。
*/
@Value("${mongo.keep_alive:true}") @Value("${mongo.keep_alive:true}")
private boolean keepAlive; private boolean keepAlive;
@@ -81,24 +131,59 @@ public class DbConfig extends AbstractMongoClientConfiguration {
@Value("${mongo.maxPoolSize:1000}") @Value("${mongo.maxPoolSize:1000}")
private int maxPoolSize; private int maxPoolSize;
/**
* 字段 connectionsPerHost;从配置注入。
*
* 注解:{@code @Value("${mongo.connectionsPerHost: 1000}")}。
*/
@Value("${mongo.connectionsPerHost: 1000}") @Value("${mongo.connectionsPerHost: 1000}")
private int connectionsPerHost; private int connectionsPerHost;
/**
* 字段 connectionMultiplier;从配置注入。
*
* 注解:{@code @Value("${mongo.connection_multiplier:200}")}。
*/
@Value("${mongo.connection_multiplier:200}") @Value("${mongo.connection_multiplier:200}")
private int connectionMultiplier; private int connectionMultiplier;
/**
* 字段 connectTimeout;从配置注入。
*
* 注解:{@code @Value("${mongo.connect_timeout:5000}")}。
*/
@Value("${mongo.connect_timeout:5000}") @Value("${mongo.connect_timeout:5000}")
private int connectTimeout; private int connectTimeout;
/**
* 字段 waitTimeout;从配置注入。
*
* 注解:{@code @Value("${mongo.wait_timeout:5000}")}。
*/
@Value("${mongo.wait_timeout:5000}") @Value("${mongo.wait_timeout:5000}")
private int waitTimeout; private int waitTimeout;
/**
* 字段 socketTimeout;从配置注入。
*
* 注解:{@code @Value("${mongo.socket_timeout:0}")}。
*/
@Value("${mongo.socket_timeout:0}") @Value("${mongo.socket_timeout:0}")
private int socketTimeout; private int socketTimeout;
/**
* 字段 idleTimeout;从配置注入。
*
* 注解:{@code @Value("${mongo.idle_timeout:30000}")}。
*/
@Value("${mongo.idle_timeout:30000}") @Value("${mongo.idle_timeout:30000}")
private int idleTimeout; private int idleTimeout;
/**
* 数据库Replica设置;从配置注入。
*
* 注解:{@code @Value("${mongo.replica_set:rs0}")}。
*/
@Value("${mongo.replica_set:rs0}") @Value("${mongo.replica_set:rs0}")
private String dbReplicaSet; private String dbReplicaSet;
@@ -188,11 +273,17 @@ public class DbConfig extends AbstractMongoClientConfiguration {
if (!params.contains("waitqueuetimeoutms")) { if (!params.contains("waitqueuetimeoutms")) {
uriBuilder.setParameter("waitqueuetimeoutms", String.valueOf(this.waitTimeout)); uriBuilder.setParameter("waitqueuetimeoutms", String.valueOf(this.waitTimeout));
} }
if (!params.contains("connectTimeoutMS")) {
uriBuilder.setParameter("connectTimeoutMS", String.valueOf(this.connectTimeout));
}
boolean isSrv = uriBuilder.getScheme().endsWith("+srv"); boolean isSrv = uriBuilder.getScheme().endsWith("+srv");
if (!isSrv && !params.contains("ssl")) { if (!isSrv && !params.contains("ssl")) {
uriBuilder.setParameter("ssl", String.valueOf(this.sslEnabled)); uriBuilder.setParameter("ssl", String.valueOf(this.sslEnabled));
} }
if (this.socketTimeout > 0 && !params.contains("socketTimeoutMS")) {
uriBuilder.setParameter("", "");
}
if (!Strings.isNullOrEmpty(this.dbReplicaSet) && !params.contains("replicaSet")) { if (!Strings.isNullOrEmpty(this.dbReplicaSet) && !params.contains("replicaSet")) {
uriBuilder.setParameter("replicaSet", this.dbReplicaSet); uriBuilder.setParameter("replicaSet", this.dbReplicaSet);
@@ -220,6 +311,12 @@ public class DbConfig extends AbstractMongoClientConfiguration {
return client; return client;
} }
/**
* 获取 {@code databaseName}。
*
* 框架注解:{@code @Override}。
* @return 字符串结果
*/
@Override @Override
protected String getDatabaseName() { protected String getDatabaseName() {
return this.dbName; return this.dbName;
+111 -11
View File
@@ -57,25 +57,84 @@ import org.springframework.data.mongodb.core.schema.JsonSchemaObject;
import org.springframework.data.mongodb.core.schema.JsonSchemaObject.Type; import org.springframework.data.mongodb.core.schema.JsonSchemaObject.Type;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/**
* 【Spring 组件】{@code DbInitialize}
*
* 类职责:
* <ul>
* <li>作为 Spring 组件参与依赖注入或生命周期回调。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code DB_SCHEME_VER_2}(long):字段 DB_SCHEME_VER_2</li>
* <li>{@code DB_SCHEME_VER_3}(long):字段 DB_SCHEME_VER_3</li>
* <li>{@code DB_SCHEME_VER_4}(long):字段 DB_SCHEME_VER_4</li>
* <li>{@code DB_SCHEME_VER_5}(long):字段 DB_SCHEME_VER_5</li>
* <li>{@code DB_SCHEME_VER_6}(long):字段 DB_SCHEME_VER_6</li>
* <li>{@code KEY_DB_SCHEME}(String):字段 KEY_DB_SCHEME</li>
* </ul>
*
* 协作对象:{@code MongoTemplate、RestoreService}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
@Component @Component
public class DbInitialize { public class DbInitialize {
/**
* 字段 DB_SCHEME_VER_2。
*/
private static final long DB_SCHEME_VER_2 = 20092901L; private static final long DB_SCHEME_VER_2 = 20092901L;
/**
* 字段 DB_SCHEME_VER_3。
*/
private static final long DB_SCHEME_VER_3 = 22111002L; private static final long DB_SCHEME_VER_3 = 22111002L;
/**
* 字段 DB_SCHEME_VER_4。
*/
private static final long DB_SCHEME_VER_4 = 23072101L; private static final long DB_SCHEME_VER_4 = 23072101L;
/**
* 字段 DB_SCHEME_VER_5。
*/
private static final long DB_SCHEME_VER_5 = 23082501L; private static final long DB_SCHEME_VER_5 = 23082501L;
/**
* 字段 DB_SCHEME_VER_6。
*/
private static final long DB_SCHEME_VER_6 = 24022701L; private static final long DB_SCHEME_VER_6 = 24022701L;
/**
* 字段 KEY_DB_SCHEME。
*/
private String KEY_DB_SCHEME = "db.scheme"; private String KEY_DB_SCHEME = "db.scheme";
/**
* MongoDB模板;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private MongoTemplate mongoTemplate; private MongoTemplate mongoTemplate;
/**
* restore服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private RestoreService restoreService; private RestoreService restoreService;
/**
* 处理contextRefreshed事件。
*/
@EventListener({ContextRefreshedEvent.class}) @EventListener({ContextRefreshedEvent.class})
public void contextRefreshedEvent() { public void contextRefreshedEvent() {
this.initializeDb(); this.initializeDb();
this.updateScheme(); this.updateScheme();
} }
/**
* 处理initialize数据库。
*
* 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 7 个条件分支、1 个循环;主要调用:findOne、save、new SystemSetting、new Update、updateMulti、new Document。
*/
private void initializeDb() { private void initializeDb() {
MongoCollection<Document> resourceMessageCollection = this.mongoTemplate.getCollection("resourceMessage"); MongoCollection<Document> resourceMessageCollection = this.mongoTemplate.getCollection("resourceMessage");
if (resourceMessageCollection == null || resourceMessageCollection.countDocuments() == 0L) { if (resourceMessageCollection == null || resourceMessageCollection.countDocuments() == 0L) {
@@ -147,7 +206,16 @@ public class DbInitialize {
this.ensureIndex(MidmLog.class, false, "category", "loggedAt"); this.ensureIndex(MidmLog.class, false, "category", "loggedAt");
} }
private void ensureIndex(Class entityClass, boolean unique, String... keys) { /**
* 处理ensureIndex。
*
* 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含异常捕获与降级/回滚分支;包含 2 个条件分支、1 个循环;主要调用:new Document、new CompoundIndexDefinition。
*
* @param entityClass 参数 {@code entityClass}({@code Class<?>})
* @param unique 参数 {@code unique}({@code boolean})
* @param keys 参数 {@code keys}({@code String[]})
*/
private void ensureIndex(Class<?> entityClass, boolean unique, String... keys) {
try { try {
if (keys.length > 0) { if (keys.length > 0) {
Document indexDefinition = new Document(); Document indexDefinition = new Document();
@@ -168,7 +236,15 @@ public class DbInitialize {
} }
private void dropIndex(Class entityClass, String... keys) { /**
* 处理dropIndex。
*
* 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、1 个循环;主要调用:dropIndex。
*
* @param entityClass 参数 {@code entityClass}({@code Class<?>})
* @param keys 参数 {@code keys}({@code String[]})
*/
private void dropIndex(Class<?> entityClass, String... keys) {
if (this.mongoTemplate.collectionExists(entityClass)) { if (this.mongoTemplate.collectionExists(entityClass)) {
MongoCollection<Document> collection = this.getCollection(entityClass); MongoCollection<Document> collection = this.getCollection(entityClass);
ListIndexesIterable<Document> indexes = collection.listIndexes(); ListIndexesIterable<Document> indexes = collection.listIndexes();
@@ -187,14 +263,16 @@ public class DbInitialize {
} }
} }
/**
* 处理ensure设备序列Index。
*
* 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、2 个循环;主要调用:dropIndex、new Document、new CompoundIndexDefinition。
*/
private void ensureDeviceSerialIndex() { private void ensureDeviceSerialIndex() {
MongoCollection<Document> collection = this.getCollection(Device.class); MongoCollection<Document> collection = this.getCollection(Device.class);
ListIndexesIterable<Document> indexes = collection.listIndexes();
boolean isConfigured = false; boolean isConfigured = false;
MongoCursor indexDefinition = indexes.iterator();
while(indexDefinition.hasNext()) { for(Document index : collection.listIndexes()) {
Document index = (Document)indexDefinition.next();
Document keys = (Document)index.get("key", Document.class); Document keys = (Document)index.get("key", Document.class);
if (keys.containsKey("profile.hardware_info.serial_no") && keys.containsKey("siteUuid")) { if (keys.containsKey("profile.hardware_info.serial_no") && keys.containsKey("siteUuid")) {
if (!index.containsKey("collation")) { if (!index.containsKey("collation")) {
@@ -214,11 +292,8 @@ public class DbInitialize {
} }
collection = this.getCollection(DeviceLicense.class); collection = this.getCollection(DeviceLicense.class);
indexes = collection.listIndexes();
indexDefinition = indexes.iterator();
while(indexDefinition.hasNext()) { for(Document index : collection.listIndexes()) {
Document index = (Document)indexDefinition.next();
Document keys = (Document)index.get("key", Document.class); Document keys = (Document)index.get("key", Document.class);
if (keys.size() == 1 && keys.containsKey("plan")) { if (keys.size() == 1 && keys.containsKey("plan")) {
collection.dropIndex(index.getString("name")); collection.dropIndex(index.getString("name"));
@@ -227,6 +302,11 @@ public class DbInitialize {
} }
/**
* 更新Scheme。
*
* 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含异常捕获与降级/回滚分支;包含 30 个条件分支、4 个循环;主要调用:new MongoNamespace、new Update、updateMulti、new Query、new Criteria、find。
*/
private void updateScheme() { private void updateScheme() {
if (this.mongoTemplate.collectionExists("siteReport")) { if (this.mongoTemplate.collectionExists("siteReport")) {
MongoCollection<Document> collection = this.mongoTemplate.getCollection("siteReport"); MongoCollection<Document> collection = this.mongoTemplate.getCollection("siteReport");
@@ -438,15 +518,35 @@ public class DbInitialize {
} }
private MongoCollection getCollection(Class entityClass) { /**
* 获取Collection。
*
* 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合)。
*
* @param entityClass 参数 {@code entityClass}({@code Class<?>})
* @return 字段/派生属性 {@code collection} 的值
*/
private MongoCollection<Document> getCollection(Class<?> entityClass) {
return this.mongoTemplate.getCollection(this.mongoTemplate.getCollectionName(entityClass)); return this.mongoTemplate.getCollection(this.mongoTemplate.getCollectionName(entityClass));
} }
/**
* 获取 {@code dbScheme}。
*
* 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。
* @return 数量/长度
*/
private long getDbScheme() { private long getDbScheme() {
SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(this.KEY_DB_SCHEME)), SystemSetting.class); SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(this.KEY_DB_SCHEME)), SystemSetting.class);
return setting != null ? setting.getAsLong() : -1L; return setting != null ? setting.getAsLong() : -1L;
} }
/**
* 判断 {@code standalone}。
*
* 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。
* @return 字段/派生属性 {@code standalone} 的值
*/
private boolean isStandalone() { private boolean isStandalone() {
HostLicense license = (HostLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("isPrimary").is(true)), HostLicense.class); HostLicense license = (HostLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("isPrimary").is(true)), HostLicense.class);
return license != null && license.isStandalone(); return license != null && license.isStandalone();
@@ -19,34 +19,113 @@ import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
/**
* 【Web 控制器】{@code GlobalController}
*
* 类职责:
* <ul>
* <li>接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code excludeBindingPrefixes}(String[]):字段 excludeBindingPrefixes</li>
* <li>{@code buildProperties}(BuildProperties):构建Properties</li>
* <li>{@code localeService}(LocaleService):语言区域服务</li>
* <li>{@code settingsService}(SettingsService):设置列表服务</li>
* <li>{@code licenseService}(HostLicenseService):许可证服务</li>
* <li>{@code siteService}(SiteService):站点服务</li>
* </ul>
*
* 协作对象:{@code String[]、BuildProperties、LocaleService、SettingsService、HostLicenseService、SiteService}。
*
* 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。
*/
@ControllerAdvice @ControllerAdvice
public final class GlobalController { public final class GlobalController {
/**
* 字段 excludeBindingPrefixes。
*/
private static final String[] excludeBindingPrefixes = new String[]{"/api/", "/img/", "/profile/", "/client/", "/icon/", "/store/", "/logo/", "/device/", "/file/", "/must/", "/userfile/", "/barcode/", "/dpc/"}; private static final String[] excludeBindingPrefixes = new String[]{"/api/", "/img/", "/profile/", "/client/", "/icon/", "/store/", "/logo/", "/device/", "/file/", "/must/", "/userfile/", "/barcode/", "/dpc/"};
/**
* 构建Properties;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private BuildProperties buildProperties; private BuildProperties buildProperties;
/**
* 语言区域服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
protected LocaleService localeService; protected LocaleService localeService;
/**
* 设置列表服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private SettingsService settingsService; private SettingsService settingsService;
/**
* 许可证服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private HostLicenseService licenseService; private HostLicenseService licenseService;
/**
* 站点服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
protected SiteService siteService; protected SiteService siteService;
/**
* 帮助消息服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private HelpMessageService helpMessageService; private HelpMessageService helpMessageService;
/**
* servletContext路径;从配置注入。
*
* 注解:{@code @Value("#{servletContext.contextPath}")}。
*/
@Value("#{servletContext.contextPath}") @Value("#{servletContext.contextPath}")
private String servletContextPath; private String servletContextPath;
/**
* 构建版本。
* @return 字符串结果
*/
@ModelAttribute("buildVersion") @ModelAttribute("buildVersion")
public String buildVersion() { public String buildVersion() {
return this.buildProperties.getVersion(); return this.buildProperties.getVersion();
} }
/**
* 构建时间。
* @return 字符串结果
*/
@ModelAttribute("buildTime") @ModelAttribute("buildTime")
public String buildTime() { public String buildTime() {
return Date.from(this.buildProperties.getTime()).toString(); return Date.from(this.buildProperties.getTime()).toString();
} }
/**
* 处理用户。
*
* 实现要点:包含 2 个条件分支、0 个循环。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param language 参数 {@code language}({@code String})
* @return 处理结果
*/
@ModelAttribute("user") @ModelAttribute("user")
public Object user(HttpServletRequest request, Authentication authentication, @RequestParam(required = false) String language) { public Object user(HttpServletRequest request, Authentication authentication, @RequestParam(required = false) String language) {
if (this.bindModel(request)) { if (this.bindModel(request)) {
@@ -61,41 +140,78 @@ public final class GlobalController {
} }
} }
/**
* 处理设置列表。
* @return 结果集合,可能为空
*/
@ModelAttribute("settings") @ModelAttribute("settings")
public SettingsService settings() { public SettingsService settings() {
return this.settingsService; return this.settingsService;
} }
/**
* 处理locales。
* @return 处理结果
*/
@ModelAttribute("locales") @ModelAttribute("locales")
public LocaleService locales() { public LocaleService locales() {
return this.localeService; return this.localeService;
} }
/**
* 处理帮助服务。
* @return 处理结果
*/
@ModelAttribute("helpService") @ModelAttribute("helpService")
public HelpMessageService helpService() { public HelpMessageService helpService() {
return this.helpMessageService; return this.helpMessageService;
} }
/**
* 判断 {@code hostValid}。
* @return 字段/派生属性 {@code hostValid} 的值
*/
@ModelAttribute("isHostValid") @ModelAttribute("isHostValid")
public boolean isHostValid() { public boolean isHostValid() {
return this.licenseService.isValid(); return this.licenseService.isValid();
} }
/**
* 处理设备Limit。
* @return 数量/长度
*/
@ModelAttribute("deviceLimit") @ModelAttribute("deviceLimit")
public int deviceLimit() { public int deviceLimit() {
return this.licenseService.getDeviceLimit(); return this.licenseService.getDeviceLimit();
} }
/**
* 处理站点服务。
* @return 处理结果
*/
@ModelAttribute("siteService") @ModelAttribute("siteService")
public SiteService siteService() { public SiteService siteService() {
return this.siteService; return this.siteService;
} }
/**
* 处理context路径。
* @return 字符串结果
*/
@ModelAttribute("contextPath") @ModelAttribute("contextPath")
public String contextPath() { public String contextPath() {
return this.servletContextPath + "/"; return this.servletContextPath + "/";
} }
/**
* 处理guest。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:new User。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param localeTag 参数 {@code localeTag}({@code String})
* @return 用户对象;未找到时返回 {@code null}
*/
private User guest(HttpServletRequest request, String localeTag) { private User guest(HttpServletRequest request, String localeTag) {
User user = new User(); User user = new User();
user.setName("Guest"); user.setName("Guest");
@@ -113,6 +229,14 @@ public final class GlobalController {
return user; return user;
} }
/**
* 处理bind模型。
*
* 实现要点:包含 1 个条件分支、1 个循环。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean bindModel(HttpServletRequest request) { public boolean bindModel(HttpServletRequest request) {
String uri = request.getRequestURI(); String uri = request.getRequestURI();
@@ -5,11 +5,41 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 【Spring 配置类】{@code InterceptorConfig}
*
* 类职责:
* <ul>
* <li>向 Spring 容器装配 Bean、读取外部配置并控制初始化顺序。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code basicAuthInterceptor}(BasicAuthInterceptor):basicAuth拦截器</li>
* </ul>
*
* 协作对象:{@code BasicAuthInterceptor}。
*
* 学习提示:先看 @Bean 方法与 @Value 配置项,再对照 application.properties 和启动日志。
*/
@Configuration @Configuration
public class InterceptorConfig implements WebMvcConfigurer { public class InterceptorConfig implements WebMvcConfigurer {
/**
* basicAuth拦截器;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private BasicAuthInterceptor basicAuthInterceptor; private BasicAuthInterceptor basicAuthInterceptor;
/**
* 添加Interceptors。
*
* 实现要点:包含异常捕获与降级/回滚分支。
*
* @param registry 参数 {@code registry}({@code InterceptorRegistry})
*/
public void addInterceptors(InterceptorRegistry registry) { public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.basicAuthInterceptor).addPathPatterns(new String[]{"/api/**"}); registry.addInterceptor(this.basicAuthInterceptor).addPathPatterns(new String[]{"/api/**"});
} }
@@ -13,8 +13,24 @@ import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.thymeleaf.TemplateEngine; import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.StringTemplateResolver; import org.thymeleaf.templateresolver.StringTemplateResolver;
/**
* 【Spring 配置类】{@code LocaleConfig}
*
* 类职责:
* <ul>
* <li>向 Spring 容器装配 Bean、读取外部配置并控制初始化顺序。</li>
* </ul>
*
* 学习提示:先看 @Bean 方法与 @Value 配置项,再对照 application.properties 和启动日志。
*/
@Configuration @Configuration
public class LocaleConfig { public class LocaleConfig {
/**
* 处理string模板Engine。
*
* 实现要点:主要调用:new TemplateEngine、new StringTemplateResolver。
* @return 处理结果
*/
@Bean({"stringTemplateEngine"}) @Bean({"stringTemplateEngine"})
public TemplateEngine stringTemplateEngine() { public TemplateEngine stringTemplateEngine() {
TemplateEngine templateEngine = new TemplateEngine(); TemplateEngine templateEngine = new TemplateEngine();
@@ -22,6 +38,12 @@ public class LocaleConfig {
return templateEngine; return templateEngine;
} }
/**
* 处理语言区域解析器。
*
* 实现要点:主要调用:new SessionLocaleResolver。
* @return 处理结果
*/
@Bean @Bean
public LocaleResolver localeResolver() { public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver(); SessionLocaleResolver localeResolver = new SessionLocaleResolver();
@@ -29,15 +51,51 @@ public class LocaleConfig {
return localeResolver; return localeResolver;
} }
/**
* 处理消息Source。
*
* 实现要点:主要调用:new ResourceMessageSource。
* @return 处理结果
*/
@Bean @Bean
public MessageSource messageSource() { public MessageSource messageSource() {
return new ResourceMessageSource(); return new ResourceMessageSource();
} }
/**
* 【基础设施】{@code ResourceMessageSource}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code localeService}(LocaleService):语言区域服务</li>
* </ul>
*
* 协作对象:{@code LocaleService}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
private class ResourceMessageSource extends AbstractMessageSource { private class ResourceMessageSource extends AbstractMessageSource {
/**
* 语言区域服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private LocaleService localeService; private LocaleService localeService;
/**
* 解析代码。
*
* @param code 状态码/业务码({@code String})
* @param locale 参数 {@code locale}({@code Locale})
* @return 处理结果
*/
protected MessageFormat resolveCode(String code, Locale locale) { protected MessageFormat resolveCode(String code, Locale locale) {
String msg = this.localeService.getMessage(locale, code); String msg = this.localeService.getMessage(locale, code);
return this.createMessageFormat(msg, locale); return this.createMessageFormat(msg, locale);
@@ -15,8 +15,24 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
/**
* 【Spring 配置类】{@code PropertiesConfig}
*
* 类职责:
* <ul>
* <li>向 Spring 容器装配 Bean、读取外部配置并控制初始化顺序。</li>
* </ul>
*
* 学习提示:先看 @Bean 方法与 @Value 配置项,再对照 application.properties 和启动日志。
*/
@Configuration @Configuration
public class PropertiesConfig { public class PropertiesConfig {
/**
* 处理properties。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new PropertySourcesPlaceholderConfigurer、new ArrayList、new File、exists、new FileSystemResource。
* @return 处理结果
*/
@Bean @Bean
public static PropertySourcesPlaceholderConfigurer properties() { public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
@@ -31,6 +47,13 @@ public class PropertiesConfig {
return ppc; return ppc;
} }
/**
* 初始化Properties。
*
* 实现要点:包含异常捕获与降级/回滚分支;主要调用:new Properties、new FileOutputStream、close。
*
* @param file 文件({@code File})
*/
private static void initProperties(File file) { private static void initProperties(File file) {
Properties properties = new Properties(); Properties properties = new Properties();
properties.setProperty("mongo.uri", "mongodb://username:password@127.0.0.1:27017/dbname"); properties.setProperty("mongo.uri", "mongodb://username:password@127.0.0.1:27017/dbname");
@@ -45,6 +68,12 @@ public class PropertiesConfig {
} }
/**
* 获取 {@code configFolder}。
*
* 实现要点:主要调用:new OsInfo。
* @return 字段/派生属性 {@code configFolder} 的值
*/
private static File getConfigFolder() { private static File getConfigFolder() {
return (new OsInfo()).getConfigFolder("MiDM"); return (new OsInfo()).getConfigFolder("MiDM");
} }
+11 -1
View File
@@ -44,9 +44,19 @@ import org.springframework.web.filter.ForwardedHeaderFilter;
@Configuration @Configuration
public class SecurityConfig { public class SecurityConfig {
/**
* 构建Properties;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private BuildProperties buildProperties; private BuildProperties buildProperties;
/**
* 判断是否Debug;从配置注入。
*
* 注解:{@code @Value("${spring.thymeleaf.cache: true}")}。
*/
@Value("${spring.thymeleaf.cache: true}") @Value("${spring.thymeleaf.cache: true}")
private boolean isDebug; private boolean isDebug;
@@ -91,7 +101,7 @@ public class SecurityConfig {
* 反向代理转发头过滤器(保障真实 IP 提取) * 反向代理转发头过滤器(保障真实 IP 提取)
*/ */
@Bean @Bean
public FilterRegistrationBean forwardedHeaderFilter() { public FilterRegistrationBean<ForwardedHeaderFilter> forwardedHeaderFilter() {
FilterRegistrationBean<ForwardedHeaderFilter> filterRegistrationBean = new FilterRegistrationBean(); FilterRegistrationBean<ForwardedHeaderFilter> filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new ForwardedHeaderFilter()); filterRegistrationBean.setFilter(new ForwardedHeaderFilter());
filterRegistrationBean.setOrder(Integer.MIN_VALUE); filterRegistrationBean.setOrder(Integer.MIN_VALUE);
@@ -16,29 +16,107 @@ import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/**
* 【Spring 组件】{@code StartupKeeper}
*
* 类职责:
* <ul>
* <li>作为 Spring 组件参与依赖注入或生命周期回调。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code hostLicenseService}(HostLicenseService):host许可证服务</li>
* <li>{@code deviceService}(DeviceService):设备服务</li>
* <li>{@code settingsService}(SettingsService):设置列表服务</li>
* <li>{@code localeService}(LocaleService):语言区域服务</li>
* <li>{@code userService}(UserService):用户服务</li>
* <li>{@code helpMessageService}(HelpMessageService):帮助消息服务</li>
* </ul>
*
* 协作对象:{@code HostLicenseService、DeviceService、SettingsService、LocaleService、UserService、HelpMessageService}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
@Component @Component
public class StartupKeeper { public class StartupKeeper {
/**
* host许可证服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private HostLicenseService hostLicenseService; private HostLicenseService hostLicenseService;
/**
* 设备服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private DeviceService deviceService; private DeviceService deviceService;
/**
* 设置列表服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private SettingsService settingsService; private SettingsService settingsService;
/**
* 语言区域服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private LocaleService localeService; private LocaleService localeService;
/**
* 用户服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private UserService userService; private UserService userService;
/**
* 帮助消息服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private HelpMessageService helpMessageService; private HelpMessageService helpMessageService;
/**
* 新闻消息服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private NewsMessageService newsMessageService; private NewsMessageService newsMessageService;
/**
* 报表服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private ReportService reportService; private ReportService reportService;
/**
* 站点服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private SiteService siteService; private SiteService siteService;
/**
* restore服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private RestoreService restoreService; private RestoreService restoreService;
/**
* 处理contextRefreshed事件。
*
* 实现要点:包含 2 个条件分支、0 个循环。
*/
@EventListener({ContextRefreshedEvent.class}) @EventListener({ContextRefreshedEvent.class})
private void contextRefreshedEvent() { private void contextRefreshedEvent() {
this.setDefaultTimeZone(); this.setDefaultTimeZone();
@@ -63,6 +141,9 @@ public class StartupKeeper {
} }
/**
* 设置Default时间Zone。
*/
private void setDefaultTimeZone() { private void setDefaultTimeZone() {
TimeZone defaultTimeZone = TimeZone.getTimeZone("UTC"); TimeZone defaultTimeZone = TimeZone.getTimeZone("UTC");
System.setProperty("user.timezone", defaultTimeZone.getID()); System.setProperty("user.timezone", defaultTimeZone.getID());
@@ -6,8 +6,26 @@ import org.joda.time.DateTime;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/**
* 【Spring 组件】{@code DateConverter}
*
* 类职责:
* <ul>
* <li>作为 Spring 组件参与依赖注入或生命周期回调。</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
@Component @Component
public class DateConverter implements Converter { public class DateConverter implements Converter<String, Date> {
/**
* 处理转换。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:new DateTime、new Date、parse。
*
* @param source 参数 {@code source}({@code String})
* @return 处理结果
*/
public Date convert(String source) { public Date convert(String source) {
DateTime date = null; DateTime date = null;
@@ -5,8 +5,24 @@ import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/**
* 【Spring 组件】{@code DirectionConverter}
*
* 类职责:
* <ul>
* <li>作为 Spring 组件参与依赖注入或生命周期回调。</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
@Component @Component
public class DirectionConverter implements Converter { public class DirectionConverter implements Converter<String, Sort.Direction> {
/**
* 处理转换。
*
* @param source 参数 {@code source}({@code String})
* @return 处理结果
*/
public Sort.Direction convert(String source) { public Sort.Direction convert(String source) {
return Direction.valueOf(source.toUpperCase()); return Direction.valueOf(source.toUpperCase());
} }
@@ -7,8 +7,27 @@ import java.nio.charset.Charset;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/**
* 【Spring 组件】{@code JsonElementConverter}
*
* 类职责:
* <ul>
* <li>作为 Spring 组件参与依赖注入或生命周期回调。</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
@Component @Component
public class JsonElementConverter implements Converter<String, JsonElement> { public class JsonElementConverter implements Converter<String, JsonElement> {
/**
* 处理转换。
*
* 实现要点:包含异常捕获与降级/回滚分支;主要调用:new RuntimeException。
*
* @param source 参数 {@code source}({@code String})
* @return 处理结果
* @throws RuntimeException 当 RuntimeException 条件不满足或底层调用失败时抛出。
*/
public JsonElement convert(String source) { public JsonElement convert(String source) {
try { try {
source = URLDecoder.decode(source, Charset.defaultCharset()); source = URLDecoder.decode(source, Charset.defaultCharset());
@@ -7,8 +7,27 @@ import java.nio.charset.Charset;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/**
* 【Spring 组件】{@code JsonObjectConverter}
*
* 类职责:
* <ul>
* <li>作为 Spring 组件参与依赖注入或生命周期回调。</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
@Component @Component
public class JsonObjectConverter implements Converter<String, JsonObject> { public class JsonObjectConverter implements Converter<String, JsonObject> {
/**
* 处理转换。
*
* 实现要点:包含异常捕获与降级/回滚分支;主要调用:new RuntimeException。
*
* @param source 参数 {@code source}({@code String})
* @return 处理结果
* @throws RuntimeException 当 RuntimeException 条件不满足或底层调用失败时抛出。
*/
public JsonObject convert(String source) { public JsonObject convert(String source) {
try { try {
source = URLDecoder.decode(source, Charset.defaultCharset()); source = URLDecoder.decode(source, Charset.defaultCharset());
@@ -4,8 +4,26 @@ import com.mitac.cell.internet.http.UserAgent;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/**
* 【Spring 组件】{@code UserAgentConverter}
*
* 类职责:
* <ul>
* <li>作为 Spring 组件参与依赖注入或生命周期回调。</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
@Component @Component
public class UserAgentConverter implements Converter { public class UserAgentConverter implements Converter<String, UserAgent> {
/**
* 处理转换。
*
* 实现要点:主要调用:new UserAgent。
*
* @param source 参数 {@code source}({@code String})
* @return 处理结果
*/
public UserAgent convert(String source) { public UserAgent convert(String source) {
return new UserAgent(source); return new UserAgent(source);
} }
@@ -0,0 +1,16 @@
/**
* Spring MVC 参数类型转换器:把请求中的字符串转换为日期、方向、JSON、User-Agent 等对象。
*
* <p>本包主要类型:
* <ul>
* <li>{@link DateConverter}</li>
* <li>{@link DirectionConverter}</li>
* <li>{@link JsonElementConverter}</li>
* <li>{@link JsonObjectConverter}</li>
* <li>{@link UserAgentConverter}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.app.converter;
@@ -0,0 +1,23 @@
/**
* 应用启动与基础设施配置包:Mongo、Security、WebSocket、Locale、启动初始化等。
*
* <p>本包主要类型:
* <ul>
* <li>{@link AppConfig}</li>
* <li>{@link AsyncConfig}</li>
* <li>{@link BasicAuthInterceptor}</li>
* <li>{@link DbConfig}</li>
* <li>{@link DbInitialize}</li>
* <li>{@link GlobalController}</li>
* <li>{@link InterceptorConfig}</li>
* <li>{@link LocaleConfig}</li>
* <li>{@link PropertiesConfig}</li>
* <li>{@link SecurityConfig}</li>
* <li>{@link StartupKeeper}</li>
* <li>{@link WebSocketConfig}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.app;
@@ -1,46 +1,193 @@
package com.midm.constant; package com.midm.constant;
/**
* 【常量定义】{@code GeneralConst}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code KEY_KEY}(String):字段 KEY_KEY</li>
* <li>{@code KEY_VALUE}(String):字段 KEY_VALUE</li>
* <li>{@code KEY_AUTH_KEY}(String):字段 KEY_AUTH_KEY</li>
* <li>{@code KEY_ID}(String):字段 KEY_ID</li>
* <li>{@code KEY_NAME}(String):字段 KEY_NAME</li>
* <li>{@code KEY_TITLE}(String):字段 KEY_TITLE</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class GeneralConst { public class GeneralConst {
/**
* 字段 KEY_KEY。
*/
public static final String KEY_KEY = "key"; public static final String KEY_KEY = "key";
/**
* 字段 KEY_VALUE。
*/
public static final String KEY_VALUE = "value"; public static final String KEY_VALUE = "value";
/**
* 字段 KEY_AUTH_KEY。
*/
public static final String KEY_AUTH_KEY = "auth_key"; public static final String KEY_AUTH_KEY = "auth_key";
/**
* 字段 KEY_ID。
*/
public static final String KEY_ID = "id"; public static final String KEY_ID = "id";
/**
* 字段 KEY_NAME。
*/
public static final String KEY_NAME = "name"; public static final String KEY_NAME = "name";
/**
* 字段 KEY_TITLE。
*/
public static final String KEY_TITLE = "title"; public static final String KEY_TITLE = "title";
/**
* 字段 KEY_PHONE。
*/
public static final String KEY_PHONE = "phone"; public static final String KEY_PHONE = "phone";
/**
* 字段 KEY_MOBILE。
*/
public static final String KEY_MOBILE = "mobile"; public static final String KEY_MOBILE = "mobile";
/**
* 字段 KEY_THEME。
*/
public static final String KEY_THEME = "theme"; public static final String KEY_THEME = "theme";
/**
* 字段 KEY_CONTENT。
*/
public static final String KEY_CONTENT = "content"; public static final String KEY_CONTENT = "content";
/**
* 字段 KEY_SUMMARY。
*/
public static final String KEY_SUMMARY = "summary"; public static final String KEY_SUMMARY = "summary";
/**
* 字段 KEY_USER。
*/
public static final String KEY_USER = "user"; public static final String KEY_USER = "user";
/**
* 字段 KEY_OWNER。
*/
public static final String KEY_OWNER = "owner"; public static final String KEY_OWNER = "owner";
/**
* 字段 DEFAULT。
*/
public static final String DEFAULT = "default"; public static final String DEFAULT = "default";
/**
* 字段 HTML。
*/
public static final String HTML = ".html"; public static final String HTML = ".html";
/**
* 字段 CATEGORY_APP。
*/
public static final String CATEGORY_APP = "app"; public static final String CATEGORY_APP = "app";
/**
* 字段 CATEGORY_GENERAL。
*/
public static final String CATEGORY_GENERAL = "general"; public static final String CATEGORY_GENERAL = "general";
/**
* 字段 CATEGORY_OTA。
*/
public static final String CATEGORY_OTA = "ota"; public static final String CATEGORY_OTA = "ota";
/**
* 字段 CATEGORY_WEBAPP。
*/
public static final String CATEGORY_WEBAPP = "webapp"; public static final String CATEGORY_WEBAPP = "webapp";
/**
* 字段 CATEGORY_OTHER。
*/
public static final String CATEGORY_OTHER = "other"; public static final String CATEGORY_OTHER = "other";
/**
* 字段 CATEGORY_REPORT。
*/
public static final String CATEGORY_REPORT = "report"; public static final String CATEGORY_REPORT = "report";
/**
* 字段 CATEGORY_FILE。
*/
public static final String CATEGORY_FILE = "file"; public static final String CATEGORY_FILE = "file";
/**
* 字段 CATEGORY_DEVICE。
*/
public static final String CATEGORY_DEVICE = "device"; public static final String CATEGORY_DEVICE = "device";
/**
* 字段 CATEGORY_SCREEN。
*/
public static final String CATEGORY_SCREEN = "screen"; public static final String CATEGORY_SCREEN = "screen";
/**
* 字段 CATEGORY_INSTALLED。
*/
public static final String CATEGORY_INSTALLED = "installed"; public static final String CATEGORY_INSTALLED = "installed";
/**
* 字段 CATEGORY_STORAGE。
*/
public static final String CATEGORY_STORAGE = "storage"; public static final String CATEGORY_STORAGE = "storage";
/**
* 字段 PROFILE。
*/
public static final String PROFILE = "profile"; public static final String PROFILE = "profile";
/**
* 字段 LOGO_LIGHT。
*/
public static final String LOGO_LIGHT = "light"; public static final String LOGO_LIGHT = "light";
/**
* 字段 LOGO_DARK。
*/
public static final String LOGO_DARK = "dark"; public static final String LOGO_DARK = "dark";
/**
* 字段 FAVICON。
*/
public static final String FAVICON = "favicon"; public static final String FAVICON = "favicon";
/**
* 字段 PROFILE_USERGROUP。
*/
public static final String PROFILE_USERGROUP = "usergroup"; public static final String PROFILE_USERGROUP = "usergroup";
/**
* 字段 PROFILE_ORGANIZATION。
*/
public static final String PROFILE_ORGANIZATION = "org"; public static final String PROFILE_ORGANIZATION = "org";
/**
* 字段 PROFILE_SITE。
*/
public static final String PROFILE_SITE = "site"; public static final String PROFILE_SITE = "site";
/**
* 字段 PROFILE_DEVICE_GROUP。
*/
public static final String PROFILE_DEVICE_GROUP = "deviceGroup"; public static final String PROFILE_DEVICE_GROUP = "deviceGroup";
/**
* 字段 DEFAULT_TOKEN_LIFE_CYCLE。
*/
public static final long DEFAULT_TOKEN_LIFE_CYCLE = 86400000L; public static final long DEFAULT_TOKEN_LIFE_CYCLE = 86400000L;
/**
* 字段 KEY_LANGUAGE。
*/
public static final String KEY_LANGUAGE = "language"; public static final String KEY_LANGUAGE = "language";
/**
* 字段 KEY_DESC。
*/
public static final String KEY_DESC = "desc"; public static final String KEY_DESC = "desc";
/**
* 字段 KEY_DEVICE。
*/
public static final String KEY_DEVICE = "device"; public static final String KEY_DEVICE = "device";
/**
* 字段 KEY_GROUP。
*/
public static final String KEY_GROUP = "group"; public static final String KEY_GROUP = "group";
/**
* 字段 KEY_GROUPS。
*/
public static final String KEY_GROUPS = "groups"; public static final String KEY_GROUPS = "groups";
/**
* 字段 KEY_GROUP_UUID。
*/
public static final String KEY_GROUP_UUID = "groupUuid"; public static final String KEY_GROUP_UUID = "groupUuid";
/**
* 字段 KEY_APP_FILE。
*/
public static final String KEY_APP_FILE = "appFile"; public static final String KEY_APP_FILE = "appFile";
} }
@@ -3,9 +3,38 @@ package com.midm.constant;
import java.util.Locale; import java.util.Locale;
import org.springframework.data.mongodb.core.query.Collation; import org.springframework.data.mongodb.core.query.Collation;
/**
* 【常量定义】{@code LocaleConst}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code DEFAULT_LOCALE}(Locale):字段 DEFAULT_LOCALE</li>
* <li>{@code EN_US}(String):字段 EN_US</li>
* <li>{@code COLLATION_DEFAULT}(Collation):字段 COLLATION_DEFAULT</li>
* </ul>
*
* 协作对象:{@code Locale、Collation}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class LocaleConst { public class LocaleConst {
/**
* 字段 DEFAULT_LOCALE。
*/
public static final Locale DEFAULT_LOCALE; public static final Locale DEFAULT_LOCALE;
/**
* 字段 EN_US。
*/
public static final String EN_US = "en-US"; public static final String EN_US = "en-US";
/**
* 字段 COLLATION_DEFAULT。
*/
public static final Collation COLLATION_DEFAULT; public static final Collation COLLATION_DEFAULT;
static { static {
@@ -1,8 +1,39 @@
package com.midm.constant; package com.midm.constant;
/**
* 【常量定义】{@code LocationConst}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code KEY_LAT}(String):字段 KEY_LAT</li>
* <li>{@code KEY_LATITUDE}(String):字段 KEY_LATITUDE</li>
* <li>{@code KEY_LON}(String):字段 KEY_LON</li>
* <li>{@code KEY_LONGITUDE}(String):字段 KEY_LONGITUDE</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class LocationConst { public class LocationConst {
/**
* 字段 KEY_LAT。
*/
public static String KEY_LAT = "lat"; public static String KEY_LAT = "lat";
/**
* 字段 KEY_LATITUDE。
*/
public static String KEY_LATITUDE = "latitude"; public static String KEY_LATITUDE = "latitude";
/**
* 字段 KEY_LON。
*/
public static String KEY_LON = "lon"; public static String KEY_LON = "lon";
/**
* 字段 KEY_LONGITUDE。
*/
public static String KEY_LONGITUDE = "longitude"; public static String KEY_LONGITUDE = "longitude";
} }
@@ -1,191 +1,773 @@
package com.midm.constant; package com.midm.constant;
/**
* 【常量定义】{@code MidmConst}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code MIDM}(String):字段 MIDM</li>
* <li>{@code KEY_REQUEST}(String):字段 KEY_REQUEST</li>
* <li>{@code KEY_PARAMS}(String):字段 KEY_PARAMS</li>
* <li>{@code KEY_ID}(String):字段 KEY_ID</li>
* <li>{@code KEY_UUID}(String):字段 KEY_UUID</li>
* <li>{@code KEY_EULA}(String):字段 KEY_EULA</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class MidmConst { public class MidmConst {
/**
* 字段 MIDM。
*/
public static final String MIDM = "midm"; public static final String MIDM = "midm";
/**
* 字段 KEY_REQUEST。
*/
public static final String KEY_REQUEST = "request"; public static final String KEY_REQUEST = "request";
/**
* 字段 KEY_PARAMS。
*/
public static final String KEY_PARAMS = "params"; public static final String KEY_PARAMS = "params";
/**
* 字段 KEY_ID。
*/
public static final String KEY_ID = "_id"; public static final String KEY_ID = "_id";
/**
* 字段 KEY_UUID。
*/
public static final String KEY_UUID = "uuid"; public static final String KEY_UUID = "uuid";
/**
* 字段 KEY_EULA。
*/
public static final String KEY_EULA = "eula"; public static final String KEY_EULA = "eula";
/**
* 字段 KEY_SITE。
*/
public static final String KEY_SITE = "site"; public static final String KEY_SITE = "site";
/**
* 字段 KEY_SITES。
*/
public static final String KEY_SITES = "sites"; public static final String KEY_SITES = "sites";
/**
* 字段 KEY_SITE_UUID。
*/
public static final String KEY_SITE_UUID = "siteUuid"; public static final String KEY_SITE_UUID = "siteUuid";
/**
* 字段 KEY_SITE_HAS_BATTERY_PLAN。
*/
public static final String KEY_SITE_HAS_BATTERY_PLAN = "hasBatteryPlan"; public static final String KEY_SITE_HAS_BATTERY_PLAN = "hasBatteryPlan";
/**
* 字段 KEY_GROUP_UUID。
*/
public static final String KEY_GROUP_UUID = "groupUuid"; public static final String KEY_GROUP_UUID = "groupUuid";
/**
* 字段 KEY_PARENT_UUID。
*/
public static final String KEY_PARENT_UUID = "parentUuid"; public static final String KEY_PARENT_UUID = "parentUuid";
/**
* 字段 KEY_ID_NAME。
*/
public static final String KEY_ID_NAME = "idName"; public static final String KEY_ID_NAME = "idName";
/**
* 字段 KEY_SITE_ID_NAME。
*/
public static final String KEY_SITE_ID_NAME = "siteIdName"; public static final String KEY_SITE_ID_NAME = "siteIdName";
/**
* 字段 KEY_USER_UUID。
*/
public static final String KEY_USER_UUID = "userUuid"; public static final String KEY_USER_UUID = "userUuid";
/**
* 字段 KEY_DEVICE_UUID。
*/
public static final String KEY_DEVICE_UUID = "deviceUuid"; public static final String KEY_DEVICE_UUID = "deviceUuid";
/**
* 字段 KEY_DEVICE_SERIAL。
*/
public static final String KEY_DEVICE_SERIAL = "deviceSerial"; public static final String KEY_DEVICE_SERIAL = "deviceSerial";
/**
* 字段 KEY_DEVICE_PROFILE。
*/
public static final String KEY_DEVICE_PROFILE = "deviceProfile"; public static final String KEY_DEVICE_PROFILE = "deviceProfile";
/**
* 字段 KEY_RSA。
*/
public static final String KEY_RSA = "rsa"; public static final String KEY_RSA = "rsa";
/**
* 字段 KEY_SERIALNO。
*/
public static final String KEY_SERIALNO = "serialNo"; public static final String KEY_SERIALNO = "serialNo";
/**
* 字段 KEY_TIMEZONE。
*/
public static final String KEY_TIMEZONE = "timeZone"; public static final String KEY_TIMEZONE = "timeZone";
/**
* 字段 KEY_WIFI_MAC。
*/
public static final String KEY_WIFI_MAC = "wifiMac"; public static final String KEY_WIFI_MAC = "wifiMac";
/**
* 字段 KEY_FROM。
*/
public static final String KEY_FROM = "from"; public static final String KEY_FROM = "from";
/**
* 字段 KEY_TO。
*/
public static final String KEY_TO = "to"; public static final String KEY_TO = "to";
/**
* 字段 KEY_SELF_ENROLL。
*/
public static final String KEY_SELF_ENROLL = "selfEnroll"; public static final String KEY_SELF_ENROLL = "selfEnroll";
/**
* 字段 KEY_IF_EXISTS。
*/
public static final String KEY_IF_EXISTS = "ifExists"; public static final String KEY_IF_EXISTS = "ifExists";
/**
* 字段 KEY_RTC_ENABLED。
*/
public static final String KEY_RTC_ENABLED = "rtcEnabled"; public static final String KEY_RTC_ENABLED = "rtcEnabled";
/**
* 字段 KEY_SOURCES。
*/
public static final String KEY_SOURCES = "sources"; public static final String KEY_SOURCES = "sources";
/**
* 字段 KEY_EMAIL。
*/
public static final String KEY_EMAIL = "email"; public static final String KEY_EMAIL = "email";
/**
* 字段 KEY_ENABLE。
*/
public static final String KEY_ENABLE = "enable"; public static final String KEY_ENABLE = "enable";
/**
* 字段 KEY_ENABLED。
*/
public static final String KEY_ENABLED = "enabled"; public static final String KEY_ENABLED = "enabled";
/**
* 字段 KEY_CLIENT_VERSION。
*/
public static final String KEY_CLIENT_VERSION = "clientVersion"; public static final String KEY_CLIENT_VERSION = "clientVersion";
/**
* 字段 KEY_BATTERY_SERIAL。
*/
public static final String KEY_BATTERY_SERIAL = "batterySerial"; public static final String KEY_BATTERY_SERIAL = "batterySerial";
/**
* 字段 KEY_BATTERY_CONDITION。
*/
public static final String KEY_BATTERY_CONDITION = "batteryCondition"; public static final String KEY_BATTERY_CONDITION = "batteryCondition";
/**
* 字段 KEY_COMMAND。
*/
public static final String KEY_COMMAND = "command"; public static final String KEY_COMMAND = "command";
/**
* 字段 KEY_CATEGORY。
*/
public static final String KEY_CATEGORY = "category"; public static final String KEY_CATEGORY = "category";
/**
* 字段 KEY_LOG。
*/
public static final String KEY_LOG = "log"; public static final String KEY_LOG = "log";
/**
* 字段 KEY_LOGGED_AT。
*/
public static final String KEY_LOGGED_AT = "loggedAt"; public static final String KEY_LOGGED_AT = "loggedAt";
/**
* 字段 KEY_INCLUDES。
*/
public static final String KEY_INCLUDES = "includes"; public static final String KEY_INCLUDES = "includes";
/**
* 字段 KEY_URL。
*/
public static final String KEY_URL = "url"; public static final String KEY_URL = "url";
/**
* 字段 KEY_PATH。
*/
public static final String KEY_PATH = "path"; public static final String KEY_PATH = "path";
/**
* 字段 KEY_ROOT。
*/
public static final String KEY_ROOT = "root"; public static final String KEY_ROOT = "root";
/**
* 字段 KEY_OWNER。
*/
public static final String KEY_OWNER = "owner"; public static final String KEY_OWNER = "owner";
/**
* 字段 KEY_REGION。
*/
public static final String KEY_REGION = "region"; public static final String KEY_REGION = "region";
/**
* 字段 KEY_MODEM。
*/
public static final String KEY_MODEM = "modem"; public static final String KEY_MODEM = "modem";
/**
* 字段 KEY_USER。
*/
public static final String KEY_USER = "user"; public static final String KEY_USER = "user";
/**
* 字段 KEY_DEST。
*/
public static final String KEY_DEST = "dest"; public static final String KEY_DEST = "dest";
/**
* 字段 KEY_PUSH。
*/
public static final String KEY_PUSH = "push"; public static final String KEY_PUSH = "push";
/**
* 字段 KEY_MOVE。
*/
public static final String KEY_MOVE = "move"; public static final String KEY_MOVE = "move";
/**
* 字段 KEY_DELETE。
*/
public static final String KEY_DELETE = "delete"; public static final String KEY_DELETE = "delete";
/**
* 字段 KEY_EXTRACT。
*/
public static final String KEY_EXTRACT = "extract"; public static final String KEY_EXTRACT = "extract";
/**
* 字段 KEY_KEEP_IN_HOST。
*/
public static final String KEY_KEEP_IN_HOST = "keepInHost"; public static final String KEY_KEEP_IN_HOST = "keepInHost";
/**
* 字段 KEY_IS_GLOBAL。
*/
public static final String KEY_IS_GLOBAL = "isGlobal"; public static final String KEY_IS_GLOBAL = "isGlobal";
/**
* 字段 KEY_UPDATE_VIA。
*/
public static final String KEY_UPDATE_VIA = "update_via"; public static final String KEY_UPDATE_VIA = "update_via";
/**
* 字段 KEY_SILENT_UPDATE。
*/
public static final String KEY_SILENT_UPDATE = "silent_update"; public static final String KEY_SILENT_UPDATE = "silent_update";
/**
* 字段 KEY_ALLOW_DOWNGRADE。
*/
public static final String KEY_ALLOW_DOWNGRADE = "allow_downgrade"; public static final String KEY_ALLOW_DOWNGRADE = "allow_downgrade";
/**
* 字段 KEY_SHOW_PROGRESS。
*/
public static final String KEY_SHOW_PROGRESS = "show_progress"; public static final String KEY_SHOW_PROGRESS = "show_progress";
/**
* 字段 KEY_FORCE_TO_UPDATE。
*/
public static final String KEY_FORCE_TO_UPDATE = "force_to_update"; public static final String KEY_FORCE_TO_UPDATE = "force_to_update";
/**
* 字段 KEY_REMOVE_AFTER_INSTALL。
*/
public static final String KEY_REMOVE_AFTER_INSTALL = "remove_after_install"; public static final String KEY_REMOVE_AFTER_INSTALL = "remove_after_install";
/**
* 字段 KEY_CREATED。
*/
public static final String KEY_CREATED = "created"; public static final String KEY_CREATED = "created";
/**
* 字段 KEY_UPDATED。
*/
public static final String KEY_UPDATED = "updated"; public static final String KEY_UPDATED = "updated";
/**
* 字段 KEY_APPLIED。
*/
public static final String KEY_APPLIED = "applied"; public static final String KEY_APPLIED = "applied";
/**
* 字段 KEY_REPORTED_AT。
*/
public static final String KEY_REPORTED_AT = "reportedAt"; public static final String KEY_REPORTED_AT = "reportedAt";
/**
* 字段 KEY_RESELLER。
*/
public static final String KEY_RESELLER = "reseller"; public static final String KEY_RESELLER = "reseller";
/**
* 字段 KEY_RESELLER_SITE。
*/
public static final String KEY_RESELLER_SITE = "resellerSite"; public static final String KEY_RESELLER_SITE = "resellerSite";
/**
* 字段 KEY_IS_RESELLER。
*/
public static final String KEY_IS_RESELLER = "isReseller"; public static final String KEY_IS_RESELLER = "isReseller";
/**
* 字段 KEY_DEVICE_LIMIT。
*/
public static final String KEY_DEVICE_LIMIT = "deviceLimit"; public static final String KEY_DEVICE_LIMIT = "deviceLimit";
/**
* 字段 KEY_LICENSE。
*/
public static final String KEY_LICENSE = "license"; public static final String KEY_LICENSE = "license";
/**
* 字段 KEY_RENEW。
*/
public static final String KEY_RENEW = "renew"; public static final String KEY_RENEW = "renew";
/**
* 字段 KEY_AUTO_RENEW。
*/
public static final String KEY_AUTO_RENEW = "autoRenew"; public static final String KEY_AUTO_RENEW = "autoRenew";
/**
* 字段 KEY_RENEW_TO_SAME_MODEL。
*/
public static final String KEY_RENEW_TO_SAME_MODEL = "renewToSameModel"; public static final String KEY_RENEW_TO_SAME_MODEL = "renewToSameModel";
/**
* 字段 KEY_MODEL。
*/
public static final String KEY_MODEL = "model"; public static final String KEY_MODEL = "model";
/**
* 字段 KEY_LICENSE_MODEL。
*/
public static final String KEY_LICENSE_MODEL = "licenseModel"; public static final String KEY_LICENSE_MODEL = "licenseModel";
/**
* 字段 KEY_LICENSE_FEATURE。
*/
public static final String KEY_LICENSE_FEATURE = "licenseFeature"; public static final String KEY_LICENSE_FEATURE = "licenseFeature";
/**
* 字段 KEY_FEATURES。
*/
public static final String KEY_FEATURES = "features"; public static final String KEY_FEATURES = "features";
/**
* 字段 KEY_PLAN。
*/
public static final String KEY_PLAN = "plan"; public static final String KEY_PLAN = "plan";
/**
* 字段 KEY_TARGET_PLAN。
*/
public static final String KEY_TARGET_PLAN = "targetPlan"; public static final String KEY_TARGET_PLAN = "targetPlan";
/**
* 字段 KEY_SYSTEM。
*/
public static final String KEY_SYSTEM = "system"; public static final String KEY_SYSTEM = "system";
/**
* 字段 KEY_STORE。
*/
public static final String KEY_STORE = "store"; public static final String KEY_STORE = "store";
/**
* 字段 KEY_KEYSTORE。
*/
public static final String KEY_KEYSTORE = "keyStore"; public static final String KEY_KEYSTORE = "keyStore";
/**
* 字段 KEY_REPORT。
*/
public static final String KEY_REPORT = "report"; public static final String KEY_REPORT = "report";
/**
* 字段 KEY_TEMP。
*/
public static final String KEY_TEMP = "temp"; public static final String KEY_TEMP = "temp";
/**
* 字段 KEY_DATE_TIME。
*/
public static final String KEY_DATE_TIME = "dateTime"; public static final String KEY_DATE_TIME = "dateTime";
/**
* 字段 KEY_HOUR_FORMAT。
*/
public static final String KEY_HOUR_FORMAT = "hourFormat"; public static final String KEY_HOUR_FORMAT = "hourFormat";
/**
* 字段 KEY_ACTIVITY。
*/
public static final String KEY_ACTIVITY = "activity"; public static final String KEY_ACTIVITY = "activity";
/**
* 字段 KEY_AMOUNT。
*/
public static final String KEY_AMOUNT = "amount"; public static final String KEY_AMOUNT = "amount";
/**
* 字段 KEY_TOTAL。
*/
public static final String KEY_TOTAL = "total"; public static final String KEY_TOTAL = "total";
/**
* 字段 KEY_FRESH。
*/
public static final String KEY_FRESH = "fresh"; public static final String KEY_FRESH = "fresh";
/**
* 字段 KEY_FRESH_EXPIRING。
*/
public static final String KEY_FRESH_EXPIRING = "freshExpiring"; public static final String KEY_FRESH_EXPIRING = "freshExpiring";
/**
* 字段 KEY_USED。
*/
public static final String KEY_USED = "used"; public static final String KEY_USED = "used";
/**
* 字段 KEY_USED_EXPIRING。
*/
public static final String KEY_USED_EXPIRING = "usedExpiring"; public static final String KEY_USED_EXPIRING = "usedExpiring";
/**
* 字段 KEY_ACTIVE。
*/
public static final String KEY_ACTIVE = "active"; public static final String KEY_ACTIVE = "active";
/**
* 字段 KEY_INACTIVE。
*/
public static final String KEY_INACTIVE = "inactive"; public static final String KEY_INACTIVE = "inactive";
/**
* 字段 KEY_EXPIRED。
*/
public static final String KEY_EXPIRED = "expired"; public static final String KEY_EXPIRED = "expired";
/**
* 字段 KEY_LICENSED。
*/
public static final String KEY_LICENSED = "licensed"; public static final String KEY_LICENSED = "licensed";
/**
* 字段 KEY_MEMORY。
*/
public static final String KEY_MEMORY = "memory"; public static final String KEY_MEMORY = "memory";
/**
* 字段 KEY_BATTERY。
*/
public static final String KEY_BATTERY = "battery"; public static final String KEY_BATTERY = "battery";
/**
* 字段 KEY_LOCATION。
*/
public static final String KEY_LOCATION = "location"; public static final String KEY_LOCATION = "location";
/**
* 字段 KEY_DATA_USAGE。
*/
public static final String KEY_DATA_USAGE = "dataUsage"; public static final String KEY_DATA_USAGE = "dataUsage";
/**
* 字段 REQUEST_APPS。
*/
public static final String REQUEST_APPS = "apps"; public static final String REQUEST_APPS = "apps";
/**
* 字段 REQUEST_OTAS。
*/
public static final String REQUEST_OTAS = "otas"; public static final String REQUEST_OTAS = "otas";
/**
* 字段 REQUEST_FILES。
*/
public static final String REQUEST_FILES = "files"; public static final String REQUEST_FILES = "files";
/**
* 字段 REQUEST_ENROLL。
*/
public static final String REQUEST_ENROLL = "enroll"; public static final String REQUEST_ENROLL = "enroll";
/**
* 字段 REQUEST_DATA_USAGE。
*/
public static final String REQUEST_DATA_USAGE = "data_usage"; public static final String REQUEST_DATA_USAGE = "data_usage";
/**
* 字段 KEY_REPEAT_OPTION。
*/
public static final String KEY_REPEAT_OPTION = "repeatOption"; public static final String KEY_REPEAT_OPTION = "repeatOption";
/**
* 字段 KEY_REPEAT_PERIOD。
*/
public static final String KEY_REPEAT_PERIOD = "repeatPeriod"; public static final String KEY_REPEAT_PERIOD = "repeatPeriod";
/**
* 字段 KEY_REPEAT_EVERY。
*/
public static final String KEY_REPEAT_EVERY = "repeatEvery"; public static final String KEY_REPEAT_EVERY = "repeatEvery";
/**
* 字段 VALUE_HOST。
*/
public static final String VALUE_HOST = "host"; public static final String VALUE_HOST = "host";
/**
* 字段 VALUE_DEVICE。
*/
public static final String VALUE_DEVICE = "device"; public static final String VALUE_DEVICE = "device";
/**
* 字段 VALUE_WIFI。
*/
public static final String VALUE_WIFI = "wifi"; public static final String VALUE_WIFI = "wifi";
/**
* 字段 VALUE_MOBILE。
*/
public static final String VALUE_MOBILE = "mobile"; public static final String VALUE_MOBILE = "mobile";
/**
* 字段 VALUE_BOTH。
*/
public static final String VALUE_BOTH = "both"; public static final String VALUE_BOTH = "both";
/**
* 字段 VALUE_ALL。
*/
public static final String VALUE_ALL = "all"; public static final String VALUE_ALL = "all";
/**
* 字段 VALUE_SELECTED。
*/
public static final String VALUE_SELECTED = "selected"; public static final String VALUE_SELECTED = "selected";
/**
* 字段 TYPE_WIFI。
*/
public static final String TYPE_WIFI = "WIFI"; public static final String TYPE_WIFI = "WIFI";
/**
* 字段 TYPE_MOBILE。
*/
public static final String TYPE_MOBILE = "MOBILE"; public static final String TYPE_MOBILE = "MOBILE";
/**
* 字段 VALUE_LOGO。
*/
public static final String VALUE_LOGO = "logo"; public static final String VALUE_LOGO = "logo";
/**
* 字段 VALUE_PROFILE。
*/
public static final String VALUE_PROFILE = "profile"; public static final String VALUE_PROFILE = "profile";
/**
* 字段 VALUE_BACKGROUND。
*/
public static final String VALUE_BACKGROUND = "background"; public static final String VALUE_BACKGROUND = "background";
/**
* 字段 VALUE_DEFAULT_HEART_BEAT。
*/
public static final int VALUE_DEFAULT_HEART_BEAT = 300; public static final int VALUE_DEFAULT_HEART_BEAT = 300;
/**
* 字段 KEY_WEBSOCKET_EXTENSION。
*/
public static final String KEY_WEBSOCKET_EXTENSION = "sec-websocket-extensions"; public static final String KEY_WEBSOCKET_EXTENSION = "sec-websocket-extensions";
/**
* 字段 REQUEST_UPDATE_PROFILE。
*/
public static final String REQUEST_UPDATE_PROFILE = "update_profile"; public static final String REQUEST_UPDATE_PROFILE = "update_profile";
/**
* 字段 CODE_UPDATE_PROFILE。
*/
public static final int CODE_UPDATE_PROFILE = 131; public static final int CODE_UPDATE_PROFILE = 131;
/**
* 字段 REQUEST_UPDATE_ALL_PROFILES。
*/
public static final String REQUEST_UPDATE_ALL_PROFILES = "update_profile_all"; public static final String REQUEST_UPDATE_ALL_PROFILES = "update_profile_all";
/**
* 字段 CODE_UPDATE_ALL_PROFILES。
*/
public static final int CODE_UPDATE_ALL_PROFILES = 132; public static final int CODE_UPDATE_ALL_PROFILES = 132;
/**
* 字段 REQUEST_SYNC_PROFILE。
*/
public static final String REQUEST_SYNC_PROFILE = "sync_profile"; public static final String REQUEST_SYNC_PROFILE = "sync_profile";
/**
* 字段 CODE_SYNC_PROFILE。
*/
public static final int CODE_SYNC_PROFILE = 136; public static final int CODE_SYNC_PROFILE = 136;
/**
* 字段 REQUEST_REMOVE_PROFILE。
*/
public static final String REQUEST_REMOVE_PROFILE = "remove_profile"; public static final String REQUEST_REMOVE_PROFILE = "remove_profile";
/**
* 字段 CODE_REMOVE_PROFILE。
*/
public static final int CODE_REMOVE_PROFILE = 136; public static final int CODE_REMOVE_PROFILE = 136;
/**
* 字段 KEY_THEME。
*/
public static final String KEY_THEME = "theme"; public static final String KEY_THEME = "theme";
/**
* 字段 KEY_NOTIFICATION。
*/
public static final String KEY_NOTIFICATION = "noti"; public static final String KEY_NOTIFICATION = "noti";
/**
* 字段 KEY_COUNT。
*/
public static final String KEY_COUNT = "count"; public static final String KEY_COUNT = "count";
/**
* 字段 KEY_PAGE。
*/
public static final String KEY_PAGE = "page"; public static final String KEY_PAGE = "page";
/**
* 字段 KEY_EXPIRY。
*/
public static final String KEY_EXPIRY = "expiry"; public static final String KEY_EXPIRY = "expiry";
/**
* 字段 KEY_LICENSE_EXPIRY。
*/
public static final String KEY_LICENSE_EXPIRY = "licenseExpiry"; public static final String KEY_LICENSE_EXPIRY = "licenseExpiry";
/**
* 字段 KEY_FINAL_EXPIRY。
*/
public static final String KEY_FINAL_EXPIRY = "finalExpiry"; public static final String KEY_FINAL_EXPIRY = "finalExpiry";
/**
* 字段 KEY_ACTIVATED_AT。
*/
public static final String KEY_ACTIVATED_AT = "activatedAt"; public static final String KEY_ACTIVATED_AT = "activatedAt";
/**
* 字段 KEY_ACTIVATION_COUNT。
*/
public static final String KEY_ACTIVATION_COUNT = "activationCount"; public static final String KEY_ACTIVATION_COUNT = "activationCount";
/**
* 字段 KEY_CHILD_SITE。
*/
public static final String KEY_CHILD_SITE = "childSite"; public static final String KEY_CHILD_SITE = "childSite";
/**
* 字段 KEY_URL_EXPIRY。
*/
public static final String KEY_URL_EXPIRY = "urlExpiry"; public static final String KEY_URL_EXPIRY = "urlExpiry";
/**
* 字段 KEY_ICON_EXPIRY。
*/
public static final String KEY_ICON_EXPIRY = "iconExpiry"; public static final String KEY_ICON_EXPIRY = "iconExpiry";
/**
* 字段 KEY_EXPIRED_IN_10。
*/
public static final String KEY_EXPIRED_IN_10 = "expiredIn10"; public static final String KEY_EXPIRED_IN_10 = "expiredIn10";
/**
* 字段 KEY_EXPIRED_IN_30。
*/
public static final String KEY_EXPIRED_IN_30 = "expiredIn30"; public static final String KEY_EXPIRED_IN_30 = "expiredIn30";
/**
* 字段 KEY_EXPIRED_IN_45。
*/
public static final String KEY_EXPIRED_IN_45 = "expiredIn45"; public static final String KEY_EXPIRED_IN_45 = "expiredIn45";
/**
* 字段 KEY_EXPIRED_IN_45_WITH_AUTO_RENEW。
*/
public static final String KEY_EXPIRED_IN_45_WITH_AUTO_RENEW = "expiredIn45WithAutoRenew"; public static final String KEY_EXPIRED_IN_45_WITH_AUTO_RENEW = "expiredIn45WithAutoRenew";
/**
* 字段 KEY_FOR_WHAT。
*/
public static final String KEY_FOR_WHAT = "forWhat"; public static final String KEY_FOR_WHAT = "forWhat";
/**
* 字段 KEY_REFERENCE。
*/
public static final String KEY_REFERENCE = "reference"; public static final String KEY_REFERENCE = "reference";
/**
* 字段 KEY_LOGGER。
*/
public static final String KEY_LOGGER = "logger"; public static final String KEY_LOGGER = "logger";
/**
* 字段 KEY_INSTALL。
*/
public static final String KEY_INSTALL = "install"; public static final String KEY_INSTALL = "install";
/**
* 字段 KEY_INSTALL_APPS。
*/
public static final String KEY_INSTALL_APPS = "installApps"; public static final String KEY_INSTALL_APPS = "installApps";
/**
* 字段 KEY_SHOW。
*/
public static final String KEY_SHOW = "show"; public static final String KEY_SHOW = "show";
/**
* 字段 KEY_MSETTINGS。
*/
public static final String KEY_MSETTINGS = "msettings"; public static final String KEY_MSETTINGS = "msettings";
/**
* 字段 KEY_WALLPAPER。
*/
public static final String KEY_WALLPAPER = "wallpaper"; public static final String KEY_WALLPAPER = "wallpaper";
/**
* 字段 PLAN_STANDARD_BATTERYPRO。
*/
public static final String PLAN_STANDARD_BATTERYPRO = "standardWithBatteryPro"; public static final String PLAN_STANDARD_BATTERYPRO = "standardWithBatteryPro";
/**
* 字段 PLAN_STANDARD。
*/
public static final String PLAN_STANDARD = "standard"; public static final String PLAN_STANDARD = "standard";
/**
* 字段 PLAN_LITE。
*/
public static final String PLAN_LITE = "lite"; public static final String PLAN_LITE = "lite";
/**
* 字段 KEY_ERROR。
*/
public static final String KEY_ERROR = "error"; public static final String KEY_ERROR = "error";
/**
* 字段 KEY_PAGE_FOR。
*/
public static final String KEY_PAGE_FOR = "pageFor"; public static final String KEY_PAGE_FOR = "pageFor";
/**
* 字段 KEY_HAS_USER。
*/
public static final String KEY_HAS_USER = "hasUser"; public static final String KEY_HAS_USER = "hasUser";
/**
* 字段 KEY_IP。
*/
public static final String KEY_IP = "ip"; public static final String KEY_IP = "ip";
/**
* 字段 KEY_IP_ADDR。
*/
public static final String KEY_IP_ADDR = "ip_addr"; public static final String KEY_IP_ADDR = "ip_addr";
/**
* 字段 KEY_PUBLIC_IP。
*/
public static final String KEY_PUBLIC_IP = "public_ip"; public static final String KEY_PUBLIC_IP = "public_ip";
/**
* 字段 KEY_ADD。
*/
public static final String KEY_ADD = "add"; public static final String KEY_ADD = "add";
/**
* 字段 KEY_REMOVE。
*/
public static final String KEY_REMOVE = "remove"; public static final String KEY_REMOVE = "remove";
/**
* 字段 KEY_PO。
*/
public static final String KEY_PO = "po"; public static final String KEY_PO = "po";
/**
* 字段 KEY_NOTE。
*/
public static final String KEY_NOTE = "note"; public static final String KEY_NOTE = "note";
/**
* 字段 KEY_NOTES。
*/
public static final String KEY_NOTES = "notes"; public static final String KEY_NOTES = "notes";
/**
* 字段 KEY_SETTINGS。
*/
public static final String KEY_SETTINGS = "settings"; public static final String KEY_SETTINGS = "settings";
/**
* 字段 KEY_PROFILES。
*/
public static final String KEY_PROFILES = "profiles"; public static final String KEY_PROFILES = "profiles";
/**
* 字段 KEY_STATUS。
*/
public static final String KEY_STATUS = "status"; public static final String KEY_STATUS = "status";
/**
* 字段 STATUS_ADDED。
*/
public static final String STATUS_ADDED = "added"; public static final String STATUS_ADDED = "added";
/**
* 字段 STATUS_REPLACED。
*/
public static final String STATUS_REPLACED = "replaced"; public static final String STATUS_REPLACED = "replaced";
/**
* 字段 STATUS_REMOVED。
*/
public static final String STATUS_REMOVED = "removed"; public static final String STATUS_REMOVED = "removed";
/**
* 字段 VALUE_UNKNOWN。
*/
public static final String VALUE_UNKNOWN = "unknown"; public static final String VALUE_UNKNOWN = "unknown";
/**
* 字段 VALUE_NONE。
*/
public static final String VALUE_NONE = "none"; public static final String VALUE_NONE = "none";
/**
* 字段 VALUE_NEVER。
*/
public static final String VALUE_NEVER = "never"; public static final String VALUE_NEVER = "never";
/**
* 字段 VALUE_DISABLED。
*/
public static final String VALUE_DISABLED = "disabled"; public static final String VALUE_DISABLED = "disabled";
/**
* 字段 VALUE_ONCE。
*/
public static final String VALUE_ONCE = "once"; public static final String VALUE_ONCE = "once";
/**
* 字段 VALUE_BLOCKED。
*/
public static final String VALUE_BLOCKED = "blocked"; public static final String VALUE_BLOCKED = "blocked";
/**
* 字段 VALUE_MITAC。
*/
public static final String VALUE_MITAC = "mitac"; public static final String VALUE_MITAC = "mitac";
/**
* 字段 PACKAGE_MIDM_CLIENT。
*/
public static final String PACKAGE_MIDM_CLIENT = "com.mitac.midm.client"; public static final String PACKAGE_MIDM_CLIENT = "com.mitac.midm.client";
/**
* 字段 PACKAGE_MIDM_SYSTEM。
*/
public static final String PACKAGE_MIDM_SYSTEM = "com.mitac.midm.system"; public static final String PACKAGE_MIDM_SYSTEM = "com.mitac.midm.system";
/**
* 字段 PACKAGE_MILOCK。
*/
public static final String PACKAGE_MILOCK = "com.mitac.milock"; public static final String PACKAGE_MILOCK = "com.mitac.milock";
/**
* 字段 PACKAGE_MIBATTERY。
*/
public static final String PACKAGE_MIBATTERY = "com.mitac.utils.battery"; public static final String PACKAGE_MIBATTERY = "com.mitac.utils.battery";
/**
* 字段 COLLECTION_MIDM_LOG。
*/
public static final String COLLECTION_MIDM_LOG = "midmLog"; public static final String COLLECTION_MIDM_LOG = "midmLog";
/**
* 字段 COLLECTION_DEVICE_REPORT。
*/
public static final String COLLECTION_DEVICE_REPORT = "deviceReport"; public static final String COLLECTION_DEVICE_REPORT = "deviceReport";
/**
* 字段 COLOR_RED。
*/
public static final String COLOR_RED = "red"; public static final String COLOR_RED = "red";
} }
@@ -1,93 +1,381 @@
package com.midm.constant; package com.midm.constant;
/**
* 【常量定义】{@code PropertyConst}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code CATEGORY_HADRWARE}(String):字段 CATEGORY_HADRWARE</li>
* <li>{@code CATEGORY_SOFTWARE_INFO}(String):字段 CATEGORY_SOFTWARE_INFO</li>
* <li>{@code CATEGORY_NETWORK}(String):字段 CATEGORY_NETWORK</li>
* <li>{@code CATEGORY_SHIPMENT}(String):字段 CATEGORY_SHIPMENT</li>
* <li>{@code CATEGORY_EVENT}(String):字段 CATEGORY_EVENT</li>
* <li>{@code CATEGORY_ACTIVITY}(String):字段 CATEGORY_ACTIVITY</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class PropertyConst { public class PropertyConst {
/**
* 字段 CATEGORY_HADRWARE。
*/
public static final String CATEGORY_HADRWARE = "hardware_info"; public static final String CATEGORY_HADRWARE = "hardware_info";
/**
* 字段 CATEGORY_SOFTWARE_INFO。
*/
public static final String CATEGORY_SOFTWARE_INFO = "software_info"; public static final String CATEGORY_SOFTWARE_INFO = "software_info";
/**
* 字段 CATEGORY_NETWORK。
*/
public static final String CATEGORY_NETWORK = "network"; public static final String CATEGORY_NETWORK = "network";
/**
* 字段 CATEGORY_SHIPMENT。
*/
public static final String CATEGORY_SHIPMENT = "shipment"; public static final String CATEGORY_SHIPMENT = "shipment";
/**
* 字段 CATEGORY_EVENT。
*/
public static final String CATEGORY_EVENT = "event"; public static final String CATEGORY_EVENT = "event";
/**
* 字段 CATEGORY_ACTIVITY。
*/
public static final String CATEGORY_ACTIVITY = "activity"; public static final String CATEGORY_ACTIVITY = "activity";
/**
* 字段 CATEGORY_UPDATE。
*/
public static final String CATEGORY_UPDATE = "update"; public static final String CATEGORY_UPDATE = "update";
/**
* 字段 ROLE。
*/
public static final String ROLE = "role"; public static final String ROLE = "role";
/**
* 字段 ADMIN。
*/
public static final String ADMIN = "admin"; public static final String ADMIN = "admin";
/**
* 字段 ADMINISTRATOR。
*/
public static final String ADMINISTRATOR = "Administrator"; public static final String ADMINISTRATOR = "Administrator";
/**
* 字段 NAME。
*/
public static final String NAME = "name"; public static final String NAME = "name";
/**
* 字段 NATIONAL_ID。
*/
public static final String NATIONAL_ID = "nationalId"; public static final String NATIONAL_ID = "nationalId";
/**
* 字段 GENDER。
*/
public static final String GENDER = "gender"; public static final String GENDER = "gender";
/**
* 字段 COMMENT。
*/
public static final String COMMENT = "comment"; public static final String COMMENT = "comment";
/**
* 字段 MEMO。
*/
public static final String MEMO = "memo"; public static final String MEMO = "memo";
/**
* 字段 EMAIL。
*/
public static final String EMAIL = "email"; public static final String EMAIL = "email";
/**
* 字段 LOGIN_ID。
*/
public static final String LOGIN_ID = "loginId"; public static final String LOGIN_ID = "loginId";
/**
* 字段 PASSWORD。
*/
public static final String PASSWORD = "password"; public static final String PASSWORD = "password";
/**
* 字段 PROPERTIES。
*/
public static final String PROPERTIES = "properties"; public static final String PROPERTIES = "properties";
/**
* 字段 USER_PROPERTIES。
*/
public static final String USER_PROPERTIES = "userProperties"; public static final String USER_PROPERTIES = "userProperties";
/**
* 字段 REGISTER_PROPERTIES。
*/
public static final String REGISTER_PROPERTIES = "registerProperties"; public static final String REGISTER_PROPERTIES = "registerProperties";
/**
* 字段 KEEP_SIGNIN。
*/
public static final String KEEP_SIGNIN = "keepSignIn"; public static final String KEEP_SIGNIN = "keepSignIn";
/**
* 字段 LAST_SITE。
*/
public static final String LAST_SITE = "lastSite"; public static final String LAST_SITE = "lastSite";
/**
* 字段 LAST_PAGE。
*/
public static final String LAST_PAGE = "lastPage"; public static final String LAST_PAGE = "lastPage";
/**
* 字段 DEPARTMENT。
*/
public static final String DEPARTMENT = "dept"; public static final String DEPARTMENT = "dept";
/**
* 字段 PLACE。
*/
public static final String PLACE = "place"; public static final String PLACE = "place";
/**
* 字段 REFERENCE。
*/
public static final String REFERENCE = "reference"; public static final String REFERENCE = "reference";
/**
* 字段 POST_FROM。
*/
public static final String POST_FROM = "postFrom"; public static final String POST_FROM = "postFrom";
/**
* 字段 POST_TO。
*/
public static final String POST_TO = "postTo"; public static final String POST_TO = "postTo";
/**
* 字段 DOCUMENT_NO。
*/
public static final String DOCUMENT_NO = "doc_no"; public static final String DOCUMENT_NO = "doc_no";
/**
* 字段 UPDATE。
*/
public static final String UPDATE = "update"; public static final String UPDATE = "update";
/**
* 字段 SERIAL_NO。
*/
public static final String SERIAL_NO = "serial_no"; public static final String SERIAL_NO = "serial_no";
/**
* 字段 PART_NO。
*/
public static final String PART_NO = "part_no"; public static final String PART_NO = "part_no";
/**
* 字段 PALLET_NO。
*/
public static final String PALLET_NO = "pallet_mo"; public static final String PALLET_NO = "pallet_mo";
/**
* 字段 CARTON_SN。
*/
public static final String CARTON_SN = "carton_no"; public static final String CARTON_SN = "carton_no";
/**
* 字段 ACTIVE。
*/
public static final String ACTIVE = "active"; public static final String ACTIVE = "active";
/**
* 字段 WIFI。
*/
public static final String WIFI = "wifi"; public static final String WIFI = "wifi";
/**
* 字段 WIFI_MAC。
*/
public static final String WIFI_MAC = "wifi_mac"; public static final String WIFI_MAC = "wifi_mac";
/**
* 字段 MAC_ADDRESS。
*/
public static final String MAC_ADDRESS = "mac_address"; public static final String MAC_ADDRESS = "mac_address";
/**
* 字段 SKU_ID。
*/
public static final String SKU_ID = "sku_id"; public static final String SKU_ID = "sku_id";
/**
* 字段 COMPATIBLE_SKUS。
*/
public static final String COMPATIBLE_SKUS = "compatibleSkus"; public static final String COMPATIBLE_SKUS = "compatibleSkus";
/**
* 字段 DEVICE_ID。
*/
public static final String DEVICE_ID = "deviceId"; public static final String DEVICE_ID = "deviceId";
/**
* 字段 SSID。
*/
public static final String SSID = "ssid"; public static final String SSID = "ssid";
/**
* 字段 TELEPHONY。
*/
public static final String TELEPHONY = "telephony"; public static final String TELEPHONY = "telephony";
/**
* 字段 PRODUCT_ID。
*/
public static final String PRODUCT_ID = "product_id"; public static final String PRODUCT_ID = "product_id";
/**
* 字段 PRODUCT_MODEL。
*/
public static final String PRODUCT_MODEL = "product_model"; public static final String PRODUCT_MODEL = "product_model";
/**
* 字段 BUILD_NO。
*/
public static final String BUILD_NO = "build_no"; public static final String BUILD_NO = "build_no";
/**
* 字段 DISPLAY_ID。
*/
public static final String DISPLAY_ID = "display_id"; public static final String DISPLAY_ID = "display_id";
/**
* 字段 PRODUCT_DISPLAY_ID。
*/
public static final String PRODUCT_DISPLAY_ID = "product_display_id"; public static final String PRODUCT_DISPLAY_ID = "product_display_id";
/**
* 字段 PRE_DISPLAY_ID。
*/
public static final String PRE_DISPLAY_ID = "preDisplayId"; public static final String PRE_DISPLAY_ID = "preDisplayId";
/**
* 字段 BUILD_DATE。
*/
public static final String BUILD_DATE = "build_date"; public static final String BUILD_DATE = "build_date";
/**
* 字段 REGION_VERSION。
*/
public static final String REGION_VERSION = "region_version"; public static final String REGION_VERSION = "region_version";
/**
* 字段 REGION_BUILD_DATE。
*/
public static final String REGION_BUILD_DATE = "region_build_date"; public static final String REGION_BUILD_DATE = "region_build_date";
/**
* 字段 CUSTOMER_ID。
*/
public static final String CUSTOMER_ID = "customer_id"; public static final String CUSTOMER_ID = "customer_id";
/**
* 字段 ACTIVE_NETWORK。
*/
public static final String ACTIVE_NETWORK = "active_network"; public static final String ACTIVE_NETWORK = "active_network";
/**
* 字段 SDK_VERSION。
*/
public static final String SDK_VERSION = "sdk_version"; public static final String SDK_VERSION = "sdk_version";
/**
* 字段 SCRIPT_VERSION。
*/
public static final String SCRIPT_VERSION = "script_version"; public static final String SCRIPT_VERSION = "script_version";
/**
* 字段 RELEASE_VERSION。
*/
public static final String RELEASE_VERSION = "release_version"; public static final String RELEASE_VERSION = "release_version";
/**
* 字段 OS_VERSION。
*/
public static final String OS_VERSION = "os_version"; public static final String OS_VERSION = "os_version";
/**
* 字段 GMS_AVAILABLE。
*/
public static final String GMS_AVAILABLE = "gms_available"; public static final String GMS_AVAILABLE = "gms_available";
/**
* 字段 TYPE。
*/
public static final String TYPE = "type"; public static final String TYPE = "type";
/**
* 字段 PRE_BUILD。
*/
public static final String PRE_BUILD = "preBuild"; public static final String PRE_BUILD = "preBuild";
/**
* 字段 POST_BUILD。
*/
public static final String POST_BUILD = "postBuild"; public static final String POST_BUILD = "postBuild";
/**
* 字段 STATE。
*/
public static final String STATE = "state"; public static final String STATE = "state";
/**
* 字段 IS_ONLINE。
*/
public static final String IS_ONLINE = "isOnline"; public static final String IS_ONLINE = "isOnline";
/**
* 字段 STATE_REGISTERED。
*/
public static final String STATE_REGISTERED = "registered"; public static final String STATE_REGISTERED = "registered";
/**
* 字段 STATE_ENROLLED。
*/
public static final String STATE_ENROLLED = "enrolled"; public static final String STATE_ENROLLED = "enrolled";
/**
* 字段 STATE_RETIRED。
*/
public static final String STATE_RETIRED = "retired"; public static final String STATE_RETIRED = "retired";
/**
* 字段 FILE_URL。
*/
public static final String FILE_URL = "fileUrl"; public static final String FILE_URL = "fileUrl";
/**
* 字段 ICON_URL。
*/
public static final String ICON_URL = "iconUrl"; public static final String ICON_URL = "iconUrl";
/**
* 字段 SETTINGS_HEARTBEAT_INTERVAL。
*/
public static final String SETTINGS_HEARTBEAT_INTERVAL = "websocket.heartbeat.interval"; public static final String SETTINGS_HEARTBEAT_INTERVAL = "websocket.heartbeat.interval";
/**
* 字段 MESSAGE。
*/
public static final String MESSAGE = "message"; public static final String MESSAGE = "message";
/**
* 字段 FILE_NAME。
*/
public static final String FILE_NAME = "fileName"; public static final String FILE_NAME = "fileName";
/**
* 字段 FILE_LENGTH。
*/
public static final String FILE_LENGTH = "fileLength"; public static final String FILE_LENGTH = "fileLength";
/**
* 字段 PACKAGE。
*/
public static final String PACKAGE = "package"; public static final String PACKAGE = "package";
/**
* 字段 PACKAGE_NAME。
*/
public static final String PACKAGE_NAME = "packageName"; public static final String PACKAGE_NAME = "packageName";
/**
* 字段 LABEL。
*/
public static final String LABEL = "label"; public static final String LABEL = "label";
/**
* 字段 VERSION_CODE。
*/
public static final String VERSION_CODE = "versionCode"; public static final String VERSION_CODE = "versionCode";
/**
* 字段 VERSION_NAME。
*/
public static final String VERSION_NAME = "versionName"; public static final String VERSION_NAME = "versionName";
/**
* 字段 CHECKSUM。
*/
public static final String CHECKSUM = "checksum"; public static final String CHECKSUM = "checksum";
/**
* 字段 CERT_MD5。
*/
public static final String CERT_MD5 = "certMd5"; public static final String CERT_MD5 = "certMd5";
/**
* 字段 STORAGES。
*/
public static final String STORAGES = "storages"; public static final String STORAGES = "storages";
/**
* 字段 MEMORY。
*/
public static final String MEMORY = "memory"; public static final String MEMORY = "memory";
/**
* 字段 BATTERY。
*/
public static final String BATTERY = "battery"; public static final String BATTERY = "battery";
/**
* 字段 TEMPERATURE。
*/
public static final String TEMPERATURE = "temperature"; public static final String TEMPERATURE = "temperature";
/**
* 字段 VOLTAGE。
*/
public static final String VOLTAGE = "voltage"; public static final String VOLTAGE = "voltage";
/**
* 字段 CHARGE_LEVEL。
*/
public static final String CHARGE_LEVEL = "level"; public static final String CHARGE_LEVEL = "level";
/**
* 字段 CHARGING_STATUS。
*/
public static final String CHARGING_STATUS = "charginStatus"; public static final String CHARGING_STATUS = "charginStatus";
/**
* 字段 PLUGGED。
*/
public static final String PLUGGED = "plugged"; public static final String PLUGGED = "plugged";
} }
@@ -0,0 +1,16 @@
/**
* 全局常量包:集合名、协议码、Locale、属性键等。
*
* <p>本包主要类型:
* <ul>
* <li>{@link GeneralConst}</li>
* <li>{@link LocaleConst}</li>
* <li>{@link LocationConst}</li>
* <li>{@link MidmConst}</li>
* <li>{@link PropertyConst}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.constant;
@@ -14,22 +14,88 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.LocaleResolver;
/**
* 【Java 类型】{@code BaseController}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code localeResolver}(LocaleResolver):语言区域解析器</li>
* <li>{@code localeService}(LocaleService):语言区域服务</li>
* <li>{@code userService}(UserService):用户服务</li>
* <li>{@code siteService}(SiteService):站点服务</li>
* <li>{@code user}(User):用户</li>
* <li>{@code theme}(String):字段 theme</li>
* </ul>
*
* 协作对象:{@code LocaleResolver、LocaleService、UserService、SiteService、User}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class BaseController { public class BaseController {
/**
* 语言区域解析器;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
protected LocaleResolver localeResolver; protected LocaleResolver localeResolver;
/**
* 语言区域服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
protected LocaleService localeService; protected LocaleService localeService;
/**
* 用户服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
protected UserService userService; protected UserService userService;
/**
* 站点服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
protected SiteService siteService; protected SiteService siteService;
/**
* 用户。
*/
protected User user = null; protected User user = null;
/**
* 字段 theme。
*/
protected String theme = "default"; protected String theme = "default";
/**
* 初始化对象状态(补齐 UUID/时间戳/默认字段)。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
*/
protected void init(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { protected void init(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
this.init(request, response, authentication, (String)null); this.init(request, response, authentication, (String)null);
} }
/**
* 初始化对象状态(补齐 UUID/时间戳/默认字段)。
*
* 实现要点:包含 3 个条件分支、0 个循环。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param localeTag 参数 {@code localeTag}({@code String})
*/
protected void init(HttpServletRequest request, HttpServletResponse response, Authentication authentication, String localeTag) { protected void init(HttpServletRequest request, HttpServletResponse response, Authentication authentication, String localeTag) {
this.determineUser(request, authentication); this.determineUser(request, authentication);
String userLocale = !Strings.isNullOrEmpty(localeTag) ? localeTag : (this.user != null ? this.user.getSettingAsString("language") : request.getLocale().toLanguageTag()); String userLocale = !Strings.isNullOrEmpty(localeTag) ? localeTag : (this.user != null ? this.user.getSettingAsString("language") : request.getLocale().toLanguageTag());
@@ -48,16 +114,39 @@ public class BaseController {
this.localeResolver.setLocale(request, response, altLocale); this.localeResolver.setLocale(request, response, altLocale);
} }
/**
* 获取View。
*
* @param authentication Spring Security 认证信息({@code Authentication})
* @param viewName 参数 {@code viewName}({@code String})
* @return 字符串结果
*/
protected String getView(Authentication authentication, String viewName) { protected String getView(Authentication authentication, String viewName) {
return this.getResource(authentication, viewName + ".html"); return this.getResource(authentication, viewName + ".html");
} }
/**
* 获取Resource。
*
* @param authentication Spring Security 认证信息({@code Authentication})
* @param fileName 文件名({@code String})
* @return 字符串结果
*/
protected String getResource(Authentication authentication, String fileName) { protected String getResource(Authentication authentication, String fileName) {
User user = UserPrincipal.getUser(authentication); User user = UserPrincipal.getUser(authentication);
String theme = user == null ? "default" : user.getTheme(); String theme = user == null ? "default" : user.getTheme();
return theme + fileName; return theme + fileName;
} }
/**
* 获取模板Resource。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param authentication Spring Security 认证信息({@code Authentication})
* @param fileName 文件名({@code String})
* @return 字符串结果
*/
protected String getTemplateResource(Authentication authentication, String fileName) { protected String getTemplateResource(Authentication authentication, String fileName) {
if (this.user == null) { if (this.user == null) {
this.user = UserPrincipal.getUser(authentication); this.user = UserPrincipal.getUser(authentication);
@@ -67,6 +156,14 @@ public class BaseController {
return "templates/" + theme + fileName; return "templates/" + theme + fileName;
} }
/**
* 处理determine用户。
*
* 实现要点:包含同步块;包含 1 个条件分支、0 个循环。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param authentication Spring Security 认证信息({@code Authentication})
*/
private void determineUser(HttpServletRequest request, Authentication authentication) { private void determineUser(HttpServletRequest request, Authentication authentication) {
if (authentication != null) { if (authentication != null) {
synchronized(authentication) { synchronized(authentication) {
@@ -52,11 +52,21 @@ import org.springframework.web.servlet.view.RedirectView;
public class DeviceController extends BaseController { public class DeviceController extends BaseController {
/** 设备详情页支持的功能标签页集合 */ /** 设备详情页支持的功能标签页集合 */
private static List tabs = Arrays.asList("general", "remoteControl", "apps", "files", "location", "logs"); private static List<String> tabs = Arrays.asList("general", "remoteControl", "apps", "files", "location", "logs");
/**
* 设备服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private DeviceService deviceService; private DeviceService deviceService;
/**
* 会话Manager;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private WebSocketSessionManager sessionManager; private WebSocketSessionManager sessionManager;
@@ -16,8 +16,33 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
/**
* 【Web 控制器】{@code ExceptionController}
*
* 类职责:
* <ul>
* <li>接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。</li>
* </ul>
*
* 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。
*/
@Controller @Controller
public class ExceptionController extends BaseController implements ErrorController { public class ExceptionController extends BaseController implements ErrorController {
/**
* 处理异常Handler。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 5 个条件分支、0 个循环;主要调用:new Error。
*
* 框架注解:{@code @RequestMapping(value = {"error"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param sessionId 参数 {@code sessionId}({@code String})
* @param model 参数 {@code model}({@code Model})
* @param language 参数 {@code language}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"error"}, value = {"error"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -64,6 +89,16 @@ public class ExceptionController extends BaseController implements ErrorControll
} }
} }
/**
* 处理gen204。
*
* 实现要点:包含异常捕获与降级/回滚分支。
*
* 框架注解:{@code @RequestMapping({"generate_204", "gen_204"})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
*/
@RequestMapping({"generate_204", "gen_204"}) @RequestMapping({"generate_204", "gen_204"})
public void gen204(HttpServletRequest request, HttpServletResponse response) { public void gen204(HttpServletRequest request, HttpServletResponse response) {
try { try {
@@ -74,6 +109,21 @@ public class ExceptionController extends BaseController implements ErrorControll
} }
/**
* 处理blocked。
*
* 实现要点:主要调用:new Error。
*
* 框架注解:{@code @RequestMapping(value = {"blocked"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param model 参数 {@code model}({@code Model})
* @param url 参数 {@code url}({@code String})
* @param serialNo 设备序列号({@code String})
* @param language 参数 {@code language}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"blocked"}, value = {"blocked"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -87,35 +137,96 @@ public class ExceptionController extends BaseController implements ErrorControll
return this.getView(authentication, "/error"); return this.getView(authentication, "/error");
} }
/**
* 【Java 类型】{@code Error}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code code}(int):代码</li>
* <li>{@code exception}(Exception):异常</li>
* <li>{@code message}(String):消息</li>
* </ul>
*
* 协作对象:{@code Exception}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
private class Error { private class Error {
/**
* 代码。
*/
private int code; private int code;
/**
* 异常。
*/
private Exception exception; private Exception exception;
/**
* 消息。
*/
private String message; private String message;
/**
* 构造 {@code Error} 实例。
*
* @param code 状态码/业务码({@code int})
*/
public Error(int code) { public Error(int code) {
this.setCode(code); this.setCode(code);
} }
/**
* 获取 {@code code}。
* @return 数量/长度
*/
public int getCode() { public int getCode() {
return this.code; return this.code;
} }
/**
* 设置 {@code code}。
*
* @param code 状态码/业务码({@code int})
*/
public void setCode(int code) { public void setCode(int code) {
this.code = code; this.code = code;
} }
/**
* 获取 {@code exception}。
* @return 字段/派生属性 {@code exception} 的值
*/
public Exception getException() { public Exception getException() {
return this.exception; return this.exception;
} }
/**
* 设置 {@code exception}。
*
* @param exception 参数 {@code exception}({@code Exception})
*/
public void setException(Exception exception) { public void setException(Exception exception) {
this.exception = exception; this.exception = exception;
} }
/**
* 获取 {@code message}。
* @return 字符串结果
*/
public String getMessage() { public String getMessage() {
return this.message; return this.message;
} }
/**
* 设置 {@code message}。
*
* @param message 消息内容({@code String})
*/
public void setMessage(String message) { public void setMessage(String message) {
this.message = message; this.message = message;
} }
@@ -11,8 +11,31 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
/**
* 【Web 控制器】{@code FragmentController}
*
* 类职责:
* <ul>
* <li>接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。</li>
* </ul>
*
* 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。
*/
@Controller @Controller
public class FragmentController extends BaseController { public class FragmentController extends BaseController {
/**
* 处理view。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* 框架注解:{@code @RequestMapping(value = {"/view/**"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param model 参数 {@code model}({@code Model})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/view/**"}, value = {"/view/**"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -27,6 +50,19 @@ public class FragmentController extends BaseController {
return this.getView(authentication, request.getServletPath()); return this.getView(authentication, request.getServletPath());
} }
/**
* 处理resourceView。
*
* 框架注解:{@code @RequestMapping(value = {"/view/system/resource"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param locale 参数 {@code locale}({@code Locale})
* @param model 参数 {@code model}({@code Model})
* @param category 分类(app/ota/other/report 等)({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/view/system/resource"}, value = {"/view/system/resource"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -37,6 +73,21 @@ public class FragmentController extends BaseController {
return "template/system/resource.html"; return "template/system/resource.html";
} }
/**
* 处理fragment。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* 框架注解:{@code @RequestMapping(value = {"/fragment/{fragmentName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param locale 参数 {@code locale}({@code Locale})
* @param model 参数 {@code model}({@code Model})
* @param fragmentName 参数 {@code fragmentName}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/fragment/{fragmentName}"}, value = {"/fragment/{fragmentName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -48,20 +99,48 @@ public class FragmentController extends BaseController {
model.addAttribute("hasUser", this.userService.hasUser()); model.addAttribute("hasUser", this.userService.hasUser());
} }
String var10000 = this.getView(authentication, request.getServletPath()); return this.getView(authentication, request.getServletPath()) + " :: fragment";
return var10000 + " :: fragment";
} }
/**
* 处理fragment。
*
* 框架注解:{@code @RequestMapping(value = {"/fragment/{fragmentName}/{blockName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param locale 参数 {@code locale}({@code Locale})
* @param model 参数 {@code model}({@code Model})
* @param fragmentName 参数 {@code fragmentName}({@code String})
* @param blockName 参数 {@code blockName}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/fragment/{fragmentName}/{blockName}"}, value = {"/fragment/{fragmentName}/{blockName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
) )
public String fragment(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Locale locale, Model model, @PathVariable String fragmentName, @PathVariable String blockName) { public String fragment(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Locale locale, Model model, @PathVariable String fragmentName, @PathVariable String blockName) {
super.init(request, response, authentication); super.init(request, response, authentication);
String var10000 = this.getView(authentication, "/fragment/" + fragmentName); return this.getView(authentication, "/fragment/" + fragmentName) + " :: " + blockName;
return var10000 + " :: " + blockName;
} }
/**
* 处理dialog。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* 框架注解:{@code @RequestMapping(value = {"/dialog/{dialogName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param locale 参数 {@code locale}({@code Locale})
* @param model 参数 {@code model}({@code Model})
* @param dialogName 参数 {@code dialogName}({@code String})
* @param category 分类(app/ota/other/report 等)({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/dialog/{dialogName}"}, value = {"/dialog/{dialogName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -73,7 +152,6 @@ public class FragmentController extends BaseController {
model.addAttribute("hasUser", this.userService.hasUser()); model.addAttribute("hasUser", this.userService.hasUser());
} }
String var10000 = this.getView(authentication, request.getServletPath()); return this.getView(authentication, request.getServletPath()) + " :: dialog";
return var10000 + " :: dialog";
} }
} }
@@ -23,8 +23,37 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView; import org.springframework.web.servlet.view.RedirectView;
/**
* 【Web 控制器】{@code HomeController}
*
* 类职责:
* <ul>
* <li>接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。</li>
* </ul>
*
* 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。
*/
@Controller @Controller
public class HomeController extends BaseController { public class HomeController extends BaseController {
/**
* 处理home。
*
* 实现要点:包含 13 个条件分支、0 个循环。
*
* 框架注解:{@code @RequestMapping(value = {"/", "/index.html"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param tokenUuid 参数 {@code tokenUuid}({@code UUID})
* @param siteUuid 站点 UUID({@code UUID})
* @param locale 参数 {@code locale}({@code String})
* @param model 参数 {@code model}({@code Model})
* @param hostName 参数 {@code hostName}({@code String})
* @param language 参数 {@code language}({@code String})
* @param siteId 参数 {@code siteId}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/", "/index.html"}, value = {"/", "/index.html"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -99,6 +128,18 @@ public class HomeController extends BaseController {
} }
} }
/**
* 处理home。
*
* 框架注解:{@code @RequestMapping(value = {"/remoteLogout"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param model 参数 {@code model}({@code Model})
* @param language 参数 {@code language}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/remoteLogout"}, value = {"/remoteLogout"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -109,6 +150,16 @@ public class HomeController extends BaseController {
return this.getView(authentication, "/remoteLogout"); return this.getView(authentication, "/remoteLogout");
} }
/**
* 处理homePost。
*
* 实现要点:包含异常捕获与降级/回滚分支。
*
* 框架注解:{@code @RequestMapping(value = {"/"}, method = {RequestMethod.POST})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
*/
@RequestMapping( @RequestMapping(
value = {"/"}, value = {"/"},
method = {RequestMethod.POST} method = {RequestMethod.POST}
@@ -121,6 +172,22 @@ public class HomeController extends BaseController {
} }
/**
* 注册转换为模型站点。
*
* 实现要点:包含 2 个条件分支、0 个循环。
*
* 框架注解:{@code @RequestMapping(value = {"register"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param tokenUuid 参数 {@code tokenUuid}({@code UUID})
* @param modelSite 参数 {@code modelSite}({@code String})
* @param model 参数 {@code model}({@code ModelMap})
* @param language 参数 {@code language}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"register"}, value = {"register"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -143,6 +210,18 @@ public class HomeController extends BaseController {
} }
} }
/**
* 处理redirect转换为注册。
*
* 实现要点:主要调用:new RedirectView。
*
* 框架注解:{@code @RequestMapping(value = {"{modelSite}/register"}, method = {RequestMethod.GET})}。
*
* @param model 参数 {@code model}({@code ModelMap})
* @param modelSite 参数 {@code modelSite}({@code String})
* @param language 参数 {@code language}({@code String})
* @return 处理结果
*/
@RequestMapping( @RequestMapping(
value = {"{modelSite}/register"}, value = {"{modelSite}/register"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -152,6 +231,22 @@ public class HomeController extends BaseController {
return new RedirectView("../register?modelSite=" + modelSite); return new RedirectView("../register?modelSite=" + modelSite);
} }
/**
* 处理bypassMode。
*
* 实现要点:包含 5 个条件分支、0 个循环;主要调用:new Cookie。
*
* 框架注解:{@code @RequestMapping(value = {"/bypass", "/dpc"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param tokenUuid 参数 {@code tokenUuid}({@code UUID})
* @param model 参数 {@code model}({@code ModelMap})
* @param language 参数 {@code language}({@code String})
* @param hostName 参数 {@code hostName}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/bypass", "/dpc"}, value = {"/bypass", "/dpc"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -189,6 +284,22 @@ public class HomeController extends BaseController {
} }
} }
/**
* 处理bypassMode使用模型。
*
* 实现要点:包含 5 个条件分支、0 个循环;主要调用:new Cookie。
*
* 框架注解:{@code @RequestMapping(value = {"{modelSite}/bypass", "{modelSite}/dpc"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param tokenUuid 参数 {@code tokenUuid}({@code UUID})
* @param model 参数 {@code model}({@code ModelMap})
* @param language 参数 {@code language}({@code String})
* @param hostName 参数 {@code hostName}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"{modelSite}/bypass", "{modelSite}/dpc"}, value = {"{modelSite}/bypass", "{modelSite}/dpc"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -226,6 +337,22 @@ public class HomeController extends BaseController {
} }
} }
/**
* 处理请求Trial。
*
* 实现要点:包含 5 个条件分支、0 个循环;主要调用:new Cookie。
*
* 框架注解:{@code @RequestMapping(value = {"/requestTrial"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param tokenUuid 参数 {@code tokenUuid}({@code UUID})
* @param model 参数 {@code model}({@code ModelMap})
* @param language 参数 {@code language}({@code String})
* @param hostName 参数 {@code hostName}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/requestTrial"}, value = {"/requestTrial"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -263,6 +390,14 @@ public class HomeController extends BaseController {
} }
} }
/**
* 处理forward转换为登录。
*
* 框架注解:{@code @RequestMapping(method = {RequestMethod.OPTIONS, RequestMethod.GET}, path = {"/login/{siteId}"})}。
*
* @param siteId 参数 {@code siteId}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
method = {RequestMethod.OPTIONS, RequestMethod.GET}, method = {RequestMethod.OPTIONS, RequestMethod.GET},
path = {"/login/{siteId}"} path = {"/login/{siteId}"}
@@ -16,8 +16,33 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.NotAcceptableStatusException; import org.springframework.web.server.NotAcceptableStatusException;
/**
* 【Web 控制器】{@code UserController}
*
* 类职责:
* <ul>
* <li>接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。</li>
* </ul>
*
* 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。
*/
@Controller @Controller
public class UserController extends BaseController { public class UserController extends BaseController {
/**
* 处理home。
*
* 实现要点:包含 2 个条件分支、0 个循环。
*
* 框架注解:{@code @RequestMapping(value = {"/resetPassword"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param model 参数 {@code model}({@code Model})
* @param passwordTokenUid 参数 {@code passwordTokenUid}({@code String})
* @param language 参数 {@code language}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/resetPassword"}, value = {"/resetPassword"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -43,6 +68,19 @@ public class UserController extends BaseController {
} }
} }
/**
* 获取设置列表。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new NotAcceptableStatusException。
*
* 框架注解:{@code @RequestMapping(value = {"/keepSession"}, method = {RequestMethod.GET}, produces = {"text/plain"})}、{@code @ResponseBody}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param accessToken 参数 {@code accessToken}({@code String})
* @return 字符串结果
* @throws NotAcceptableStatusException 当 NotAcceptableStatusException 条件不满足或底层调用失败时抛出。
*/
@RequestMapping( @RequestMapping(
value = {"/keepSession"}, value = {"/keepSession"},
method = {RequestMethod.GET}, method = {RequestMethod.GET},
@@ -9,8 +9,29 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
/**
* 【Web 控制器】{@code BarcodeController}
*
* 类职责:
* <ul>
* <li>接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。</li>
* </ul>
*
* 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。
*/
@Controller @Controller
public class BarcodeController { public class BarcodeController {
/**
* 处理qr代码。
*
* 框架注解:{@code @RequestMapping(value = {"/barcode/qr/{code}"}, method = {RequestMethod.GET})}。
*
* @param response HTTP 响应({@code HttpServletResponse})
* @param code 状态码/业务码({@code String})
* @param size 每页数量({@code Integer})
* @param margin 参数 {@code margin}({@code Integer})
* @param encrypt 参数 {@code encrypt}({@code Boolean})
*/
@RequestMapping( @RequestMapping(
value = {"/barcode/qr/{code}"}, value = {"/barcode/qr/{code}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -36,25 +36,103 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.HandlerMapping;
/**
* 【Web 控制器】{@code FilesController}
*
* 类职责:
* <ul>
* <li>接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code servletContext}(ServletContext):字段 servletContext</li>
* <li>{@code fileService}(FileService):文件服务</li>
* <li>{@code storeAppService}(StoreAppService):store应用服务</li>
* <li>{@code storeOtaService}(StoreOtaService):storeOTA 固件服务</li>
* <li>{@code deviceService}(DeviceService):设备服务</li>
* <li>{@code reportService}(ReportService):报表服务</li>
* </ul>
*
* 协作对象:{@code ServletContext、FileService、StoreAppService、StoreOtaService、DeviceService、ReportService}。
*
* 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。
*/
@Controller @Controller
public class FilesController { public class FilesController {
/**
* 字段 servletContext;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private ServletContext servletContext; private ServletContext servletContext;
/**
* 文件服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private FileService fileService; private FileService fileService;
/**
* store应用服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private StoreAppService storeAppService; private StoreAppService storeAppService;
/**
* storeOTA 固件服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private StoreOtaService storeOtaService; private StoreOtaService storeOtaService;
/**
* 设备服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private DeviceService deviceService; private DeviceService deviceService;
/**
* 报表服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private ReportService reportService; private ReportService reportService;
/**
* storeOther服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private StoreOtherService storeOtherService; private StoreOtherService storeOtherService;
/**
* cloud存储服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private CloudStorageService cloudStorageService; private CloudStorageService cloudStorageService;
/**
* 获取用户文件。
*
* 实现要点:主要调用:new McFile、delete。
*
* 框架注解:{@code @RequestMapping(value = {"userfile/{userUuid}/{fileUuid}/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param userUuid 用户 UUID({@code UUID})
* @param fileUuid 文件 UUID({@code UUID})
* @param fileName 文件名({@code String})
* @param position 参数 {@code position}({@code Long})
* @param crc32 参数 {@code crc32}({@code Long})
*/
@RequestMapping( @RequestMapping(
value = {"userfile/{userUuid}/{fileUuid}/{fileName}"}, value = {"userfile/{userUuid}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -66,6 +144,20 @@ public class FilesController {
file.delete(); file.delete();
} }
/**
* 处理geDevicet文件。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"file/device/{deviceUuid}/{fileUuid}/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param deviceUuid 设备 UUID({@code UUID})
* @param fileUuid 文件 UUID({@code UUID})
* @param fileName 文件名({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"file/device/{deviceUuid}/{fileUuid}/{fileName}"}, value = {"file/device/{deviceUuid}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -78,6 +170,20 @@ public class FilesController {
} }
} }
/**
* 获取文件。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"file/{fileType}/{fileUuid}/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param fileType 参数 {@code fileType}({@code String})
* @param fileUuid 文件 UUID({@code UUID})
* @param fileName 文件名({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"file/{fileType}/{fileUuid}/{fileName}"}, value = {"file/{fileType}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -103,6 +209,18 @@ public class FilesController {
} }
/**
* 获取报表模板。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile、exists。
*
* 框架注解:{@code @RequestMapping(value = {"file/report/template/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param fileName 文件名({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"file/report/template/{fileName}"}, value = {"file/report/template/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -117,6 +235,19 @@ public class FilesController {
McResource.copyFileToResponse(this.servletContext, response, file, fileName, 0, -1); McResource.copyFileToResponse(this.servletContext, response, file, fileName, 0, -1);
} }
/**
* 获取MustReserved文件。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"must/reserved/{fileUuid}/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param fileUuid 文件 UUID({@code UUID})
* @param fileName 文件名({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"must/reserved/{fileUuid}/{fileName}"}, value = {"must/reserved/{fileUuid}/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -129,6 +260,20 @@ public class FilesController {
} }
} }
/**
* 获取Must下载文件。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"must/download/{isDirectory}/{fileUuid}/{fileName}/**"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param fileUuid 文件 UUID({@code UUID})
* @param fileName 文件名({@code String})
* @param isDirectory 参数 {@code isDirectory}({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"must/download/{isDirectory}/{fileUuid}/{fileName}/**"}, value = {"must/download/{isDirectory}/{fileUuid}/{fileName}/**"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -149,6 +294,22 @@ public class FilesController {
} }
} }
/**
* 获取Store应用文件。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"store/{fileType}/{packageName}/{versionCode}/{fileUuid}/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param fileType 参数 {@code fileType}({@code String})
* @param packageName 参数 {@code packageName}({@code String})
* @param versionCode 参数 {@code versionCode}({@code long})
* @param fileUuid 文件 UUID({@code UUID})
* @param fileName 文件名({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"store/{fileType}/{packageName}/{versionCode}/{fileUuid}/{fileName}"}, value = {"store/{fileType}/{packageName}/{versionCode}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -161,6 +322,20 @@ public class FilesController {
} }
} }
/**
* 获取StoreOTA 固件文件。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"store/ota/{productId}/{fileUuid}/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param productId 参数 {@code productId}({@code String})
* @param fileUuid 文件 UUID({@code UUID})
* @param fileName 文件名({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"store/ota/{productId}/{fileUuid}/{fileName}"}, value = {"store/ota/{productId}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -173,6 +348,19 @@ public class FilesController {
} }
} }
/**
* 获取StoreOther文件。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"store/other/{fileUuid}/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param fileUuid 文件 UUID({@code UUID})
* @param fileName 文件名({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"store/other/{fileUuid}/{fileName}"}, value = {"store/other/{fileUuid}/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -185,6 +373,24 @@ public class FilesController {
} }
} }
/**
* 获取文件。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 10 个条件分支、0 个循环;主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"{siteUuid}/file/{fileType}/{fileUuid}/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param siteUuid 站点 UUID({@code String})
* @param fileType 参数 {@code fileType}({@code String})
* @param fileUuid 文件 UUID({@code String})
* @param fileName 文件名({@code String})
* @param range 参数 {@code range}({@code String})
* @param etag 参数 {@code etag}({@code String})
* @param from 起始时间({@code Integer})
*/
@RequestMapping( @RequestMapping(
value = {"{siteUuid}/file/{fileType}/{fileUuid}/{fileName}"}, value = {"{siteUuid}/file/{fileType}/{fileUuid}/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -250,6 +456,19 @@ public class FilesController {
} }
/**
* 获取应用Icon。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 6 个条件分支、0 个循环;主要调用:getUrl、new McFile、exists。
*
* 框架注解:{@code @RequestMapping(value = {"icon/app/{fileUuid}/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param fileUuid 文件 UUID({@code UUID})
* @param fileName 文件名({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"icon/app/{fileUuid}/{fileName}"}, value = {"icon/app/{fileUuid}/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -283,8 +502,7 @@ public class FilesController {
if (iconFile.exists()) { if (iconFile.exists()) {
byte[] iconData = iconFile.toBytes(); byte[] iconData = iconFile.toBytes();
if (iconData != null) { if (iconData != null) {
String var10000 = Files.getNameWithoutExtension(fileName); fileName = Files.getNameWithoutExtension(fileName) + (iconData[0] == 60 ? ".svg" : ".png");
fileName = var10000 + (iconData[0] == 60 ? ".svg" : ".png");
fileName = McUrlUtils.encode(fileName); fileName = McUrlUtils.encode(fileName);
McResource.copyFileToResponse(this.servletContext, response, iconData, fileName); McResource.copyFileToResponse(this.servletContext, response, iconData, fileName);
return; return;
@@ -296,6 +514,19 @@ public class FilesController {
} }
} }
/**
* 获取Must站点应用Icon。
*
* 实现要点:包含 3 个条件分支、0 个循环;主要调用:new McFile、exists。
*
* 框架注解:{@code @RequestMapping(value = {"icon/must/app/{profileUuid}/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param profileUuid 配置档案 UUID({@code UUID})
* @param fileName 文件名({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"icon/must/app/{profileUuid}/{fileName}"}, value = {"icon/must/app/{profileUuid}/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -318,6 +549,18 @@ public class FilesController {
} }
} }
/**
* 获取Store应用Icon。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"icon/store/app/{packageName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param packageName 参数 {@code packageName}({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"icon/store/app/{packageName}"}, value = {"icon/store/app/{packageName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -337,6 +580,18 @@ public class FilesController {
} }
} }
/**
* 获取MimeIcon。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* 框架注解:{@code @RequestMapping(value = {"icon/mime/{extension}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param extension 参数 {@code extension}({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"icon/mime/{extension}"}, value = {"icon/mime/{extension}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -350,6 +605,18 @@ public class FilesController {
forwardRequest(request, response, resourcePath); forwardRequest(request, response, resourcePath);
} }
/**
* 获取FolderIcon。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* 框架注解:{@code @RequestMapping(value = {"icon/folder/{folderType}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param folderType 参数 {@code folderType}({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"icon/folder/{folderType}"}, value = {"icon/folder/{folderType}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -363,6 +630,18 @@ public class FilesController {
forwardRequest(request, response, resourcePath); forwardRequest(request, response, resourcePath);
} }
/**
* 获取用户配置档案镜像。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new File、new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"profile/user/{userUuid}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param aHttputhentication 参数 {@code aHttputhentication}({@code Authentication})
* @param userUuid 用户 UUID({@code UUID})
*/
@RequestMapping( @RequestMapping(
value = {"profile/user/{userUuid}"}, value = {"profile/user/{userUuid}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -379,6 +658,18 @@ public class FilesController {
} }
/**
* 获取Favicon。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile、exists。
*
* 框架注解:{@code @RequestMapping(value = {"favicon"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param siteUuid 站点 UUID({@code UUID})
*/
@RequestMapping( @RequestMapping(
value = {"favicon"}, value = {"favicon"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -394,6 +685,18 @@ public class FilesController {
} }
/**
* 获取Background镜像。
*
* 实现要点:包含 3 个条件分支、0 个循环;主要调用:new McFile、exists。
*
* 框架注解:{@code @RequestMapping(value = {"background"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param siteUuid 站点 UUID({@code UUID})
*/
@RequestMapping( @RequestMapping(
value = {"background"}, value = {"background"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -421,6 +724,15 @@ public class FilesController {
} }
/**
* 获取Sitebackground镜像。
*
* 框架注解:{@code @RequestMapping(value = {"background/{siteUuid}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param siteUuid 站点 UUID({@code UUID})
*/
@RequestMapping( @RequestMapping(
value = {"background/{siteUuid}"}, value = {"background/{siteUuid}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -429,6 +741,15 @@ public class FilesController {
this.getSiteImage(request, response, siteUuid, "background"); this.getSiteImage(request, response, siteUuid, "background");
} }
/**
* 获取站点Logo镜像。
*
* 框架注解:{@code @RequestMapping(value = {"logo/{siteUuid}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param siteUuid 站点 UUID({@code UUID})
*/
@RequestMapping( @RequestMapping(
value = {"logo/{siteUuid}"}, value = {"logo/{siteUuid}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -437,6 +758,15 @@ public class FilesController {
this.getSiteImage(request, response, siteUuid, "logo"); this.getSiteImage(request, response, siteUuid, "logo");
} }
/**
* 获取站点配置档案镜像。
*
* 框架注解:{@code @RequestMapping(value = {"profile/site/{siteUuid}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param siteUuid 站点 UUID({@code UUID})
*/
@RequestMapping( @RequestMapping(
value = {"profile/site/{siteUuid}"}, value = {"profile/site/{siteUuid}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -445,6 +775,16 @@ public class FilesController {
this.getSiteImage(request, response, siteUuid, "profile"); this.getSiteImage(request, response, siteUuid, "profile");
} }
/**
* 获取站点镜像。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 5 个条件分支、0 个循环;主要调用:getUrl、new McFile、exists。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param siteUuid 站点 UUID({@code UUID})
* @param type 类型({@code String})
*/
public void getSiteImage(HttpServletRequest request, HttpServletResponse response, UUID siteUuid, String type) { public void getSiteImage(HttpServletRequest request, HttpServletResponse response, UUID siteUuid, String type) {
if (this.cloudStorageService.hasCloudStorage()) { if (this.cloudStorageService.hasCloudStorage()) {
String url = this.cloudStorageService.getUrl(siteUuid, type); String url = this.cloudStorageService.getUrl(siteUuid, type);
@@ -485,6 +825,17 @@ public class FilesController {
} }
/**
* 获取Org配置档案镜像。
*
* 实现要点:主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"profile/org/{userUuid}"}, method = {RequestMethod.GET})}。
*
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param userUuid 用户 UUID({@code UUID})
*/
@RequestMapping( @RequestMapping(
value = {"profile/org/{userUuid}"}, value = {"profile/org/{userUuid}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -495,6 +846,18 @@ public class FilesController {
McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "profile.jpg", 0, -1); McResource.copyFileToResponse(this.servletContext, response, new McFile(profilePath), "profile.jpg", 0, -1);
} }
/**
* 获取设备Screen镜像。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:exists、new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"device/screen/{deviceUuid}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param deviceUuid 设备 UUID({@code UUID})
*/
@RequestMapping( @RequestMapping(
value = {"device/screen/{deviceUuid}"}, value = {"device/screen/{deviceUuid}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -512,6 +875,19 @@ public class FilesController {
} }
} }
/**
* 获取设备文件。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"device/file/{deviceUuid}/{hostFile}/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param response HTTP 响应({@code HttpServletResponse})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param deviceUuid 设备 UUID({@code UUID})
* @param hostFile 参数 {@code hostFile}({@code String})
* @param fileName 文件名({@code String})
*/
@RequestMapping( @RequestMapping(
value = {"device/file/{deviceUuid}/{hostFile}/{fileName}"}, value = {"device/file/{deviceUuid}/{hostFile}/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -531,6 +907,18 @@ public class FilesController {
} }
/**
* 获取检查Sum。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"file/checksum/{fileUuid}"}, method = {RequestMethod.GET})}、{@code @ResponseBody}。
*
* @param authentication Spring Security 认证信息({@code Authentication})
* @param fileUuid 文件 UUID({@code UUID})
* @param size 每页数量({@code Integer})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"file/checksum/{fileUuid}"}, value = {"file/checksum/{fileUuid}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -548,6 +936,15 @@ public class FilesController {
} }
} }
/**
* 处理forward请求。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param path 参数 {@code path}({@code String})
*/
public static void forwardRequest(HttpServletRequest request, HttpServletResponse response, String path) { public static void forwardRequest(HttpServletRequest request, HttpServletResponse response, String path) {
try { try {
if (!response.isCommitted()) { if (!response.isCommitted()) {
@@ -562,6 +959,18 @@ public class FilesController {
} }
/**
* 查找文件。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、0 个循环;主要调用:getUrl。
*
* @param response HTTP 响应({@code HttpServletResponse})
* @param fileUuid 文件 UUID({@code UUID})
* @param fileType 参数 {@code fileType}({@code String})
* @param minify 参数 {@code minify}({@code boolean})
* @param siteUuid 站点 UUID({@code UUID})
* @return 文件元数据;未找到时返回 {@code null}
*/
private BaseFile findFile(HttpServletResponse response, UUID fileUuid, String fileType, boolean minify, UUID siteUuid) { private BaseFile findFile(HttpServletResponse response, UUID fileUuid, String fileType, boolean minify, UUID siteUuid) {
BaseFile file = null; BaseFile file = null;
switch (fileType) { switch (fileType) {
@@ -17,8 +17,27 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
/**
* 【Web 控制器】{@code ResourceController}
*
* 类职责:
* <ul>
* <li>接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。</li>
* </ul>
*
* 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。
*/
@Controller @Controller
public class ResourceController extends BaseController { public class ResourceController extends BaseController {
/**
* 获取Script。
*
* 框架注解:{@code @RequestMapping(value = {"/js/**", "/css/**"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param authentication Spring Security 认证信息({@code Authentication})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/js/**", "/css/**"}, value = {"/js/**", "/css/**"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -27,6 +46,19 @@ public class ResourceController extends BaseController {
return this.getResource(authentication, request.getServletPath()); return this.getResource(authentication, request.getServletPath());
} }
/**
* 获取登录Script。
*
* 框架注解:{@code @RequestMapping(value = {"js/controller/login.js"}, method = {RequestMethod.GET}, produces = {"application/javascript"})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param model 参数 {@code model}({@code Model})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param hostHeader 参数 {@code hostHeader}({@code String})
* @param hostParam 参数 {@code hostParam}({@code String})
* @param pageFor 参数 {@code pageFor}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"js/controller/login.js"}, value = {"js/controller/login.js"},
method = {RequestMethod.GET}, method = {RequestMethod.GET},
@@ -38,6 +70,18 @@ public class ResourceController extends BaseController {
return this.getResource(authentication, request.getServletPath()); return this.getResource(authentication, request.getServletPath());
} }
/**
* 获取重置PasswordScript。
*
* 框架注解:{@code @RequestMapping(value = {"/js/controller/resetPassword.js"}, method = {RequestMethod.GET}, produces = {"application/javascript"})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param model 参数 {@code model}({@code Model})
* @param authentication Spring Security 认证信息({@code Authentication})
* @param userUuid 用户 UUID({@code UUID})
* @param tokenUuid 参数 {@code tokenUuid}({@code UUID})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/js/controller/resetPassword.js"}, value = {"/js/controller/resetPassword.js"},
method = {RequestMethod.GET}, method = {RequestMethod.GET},
@@ -50,27 +94,54 @@ public class ResourceController extends BaseController {
return this.getResource(authentication, request.getServletPath()); return this.getResource(authentication, request.getServletPath());
} }
/**
* 获取镜像。
*
* 框架注解:{@code @RequestMapping(value = {"img/**"}, method = {RequestMethod.GET})}、{@code @ResponseBody}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param authentication Spring Security 认证信息({@code Authentication})
* @return 字段/派生属性 {@code image} 的值
*/
@RequestMapping( @RequestMapping(
value = {"img/**"}, value = {"img/**"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
) )
@ResponseBody @ResponseBody
public ResponseEntity getImage(HttpServletRequest request, Authentication authentication) { public ResponseEntity<?> getImage(HttpServletRequest request, Authentication authentication) {
String path = this.getTemplateResource(authentication, request.getServletPath()); String path = this.getTemplateResource(authentication, request.getServletPath());
return this.getServletResource(request, path); return this.getServletResource(request, path);
} }
/**
* 获取Images。
*
* 框架注解:{@code @RequestMapping(value = {"images/**"}, method = {RequestMethod.GET})}、{@code @ResponseBody}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param authentication Spring Security 认证信息({@code Authentication})
* @return 字段/派生属性 {@code images} 的值
*/
@RequestMapping( @RequestMapping(
value = {"images/**"}, value = {"images/**"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
) )
@ResponseBody @ResponseBody
public ResponseEntity getImages(HttpServletRequest request, Authentication authentication) { public ResponseEntity<?> getImages(HttpServletRequest request, Authentication authentication) {
String path = this.getTemplateResource(authentication, "/img" + request.getServletPath()); String path = this.getTemplateResource(authentication, "/img" + request.getServletPath());
return this.getServletResource(request, path); return this.getServletResource(request, path);
} }
private ResponseEntity getServletResource(HttpServletRequest request, String path) { /**
* 获取ServletResource。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new MediaType。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param path 参数 {@code path}({@code String})
* @return 字段/派生属性 {@code servletResource} 的值
*/
private ResponseEntity<?> getServletResource(HttpServletRequest request, String path) {
String subType = Files.getFileExtension(path); String subType = Files.getFileExtension(path);
if (Strings.isNullOrEmpty(subType)) { if (Strings.isNullOrEmpty(subType)) {
subType = "jpg"; subType = "jpg";
@@ -39,32 +39,121 @@ import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine; import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext; import org.thymeleaf.context.WebContext;
/**
* 【Web 控制器】{@code StoreController}
*
* 类职责:
* <ul>
* <li>接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code servletContext}(ServletContext):字段 servletContext</li>
* <li>{@code storeAppService}(StoreAppService):store应用服务</li>
* <li>{@code storeOtaService}(StoreOtaService):storeOTA 固件服务</li>
* <li>{@code storeWebAppService}(StoreWebAppService):storeWeb应用服务</li>
* <li>{@code stringTemplateEngine}(TemplateEngine):string模板Engine</li>
* <li>{@code keyStoreService}(KeyStoreService):密钥Store服务</li>
* </ul>
*
* 协作对象:{@code ServletContext、StoreAppService、StoreOtaService、StoreWebAppService、TemplateEngine、KeyStoreService}。
*
* 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。
*/
@Controller @Controller
@RequestMapping({"store"}) @RequestMapping({"store"})
public class StoreController { public class StoreController {
/**
* 字段 servletContext;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private ServletContext servletContext; private ServletContext servletContext;
/**
* store应用服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private StoreAppService storeAppService; private StoreAppService storeAppService;
/**
* storeOTA 固件服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private StoreOtaService storeOtaService; private StoreOtaService storeOtaService;
/**
* storeWeb应用服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private StoreWebAppService storeWebAppService; private StoreWebAppService storeWebAppService;
/**
* string模板Engine;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired @Qualifier("stringTemplateEngine")}。
*/
@Autowired @Autowired
@Qualifier("stringTemplateEngine") @Qualifier("stringTemplateEngine")
private TemplateEngine stringTemplateEngine; private TemplateEngine stringTemplateEngine;
/**
* 密钥Store服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private KeyStoreService keyStoreService; private KeyStoreService keyStoreService;
/**
* storeOther服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private StoreOtherService storeOtherService; private StoreOtherService storeOtherService;
/**
* 文件服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private FileService fileService; private FileService fileService;
/**
* cloud存储服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private CloudStorageService cloudStorageService; private CloudStorageService cloudStorageService;
/**
* host许可证服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired @Lazy}。
*/
@Autowired @Autowired
@Lazy @Lazy
private HostLicenseService hostLicenseService; private HostLicenseService hostLicenseService;
/**
* 获取最新应用。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:find。
*
* 框架注解:{@code @RequestMapping(value = {"apps/download/{packageName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param packageName 参数 {@code packageName}({@code String})
* @param range 参数 {@code range}({@code String})
* @param etag 参数 {@code etag}({@code String})
* @param certMd5 参数 {@code certMd5}({@code String})
* @param keyStoreId 参数 {@code keyStoreId}({@code String})
* @param versionCode 参数 {@code versionCode}({@code int})
*/
@RequestMapping( @RequestMapping(
value = {"apps/download/{packageName}"}, value = {"apps/download/{packageName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -82,6 +171,22 @@ public class StoreController {
this.getApp(request, response, range, etag, packageName, String.valueOf(versionCode), keyStoreId, -1); this.getApp(request, response, range, etag, packageName, String.valueOf(versionCode), keyStoreId, -1);
} }
/**
* 获取应用。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、0 个循环;主要调用:find。
*
* 框架注解:{@code @RequestMapping(value = {"apps/{packageName}/{version}/{keyStoreId}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param range 参数 {@code range}({@code String})
* @param etag 参数 {@code etag}({@code String})
* @param packageName 参数 {@code packageName}({@code String})
* @param version 参数 {@code version}({@code String})
* @param keyStoreId 参数 {@code keyStoreId}({@code String})
* @param sdkVersion 参数 {@code sdkVersion}({@code int})
*/
@RequestMapping( @RequestMapping(
value = {"apps/{packageName}/{version}/{keyStoreId}"}, value = {"apps/{packageName}/{version}/{keyStoreId}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -124,6 +229,21 @@ public class StoreController {
} }
} }
/**
* 获取应用。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。
*
* 框架注解:{@code @RequestMapping(value = {"app/{fileUuid}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param fileUuid 文件 UUID({@code UUID})
* @param range 参数 {@code range}({@code String})
* @param etag 参数 {@code etag}({@code String})
* @param position 参数 {@code position}({@code Long})
* @param checksum 参数 {@code checksum}({@code Long})
*/
@RequestMapping( @RequestMapping(
value = {"app/{fileUuid}"}, value = {"app/{fileUuid}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -142,6 +262,15 @@ public class StoreController {
} }
/**
* 获取应用。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:getUrl、new McFile。
*
* @param response HTTP 响应({@code HttpServletResponse})
* @param appFile 参数 {@code appFile}({@code StoreAppFile})
* @param range 参数 {@code range}({@code String})
*/
private void getApp(HttpServletResponse response, StoreAppFile appFile, String range) { private void getApp(HttpServletResponse response, StoreAppFile appFile, String range) {
String url = this.cloudStorageService.getUrl("store", "app", appFile.getPackageName(), appFile.getVersionCode(), appFile.getFileUuid()); String url = this.cloudStorageService.getUrl("store", "app", appFile.getPackageName(), appFile.getVersionCode(), appFile.getFileUuid());
if (Strings.isNullOrEmpty(url)) { if (Strings.isNullOrEmpty(url)) {
@@ -157,6 +286,18 @@ public class StoreController {
} }
/**
* 处理应用Release备注。
*
* 框架注解:{@code @RequestMapping(value = {"apps/{packageName}/releaseNote"}, method = {RequestMethod.GET})}、{@code @ResponseBody}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param packageName 参数 {@code packageName}({@code String})
* @param sdkVersion 参数 {@code sdkVersion}({@code int})
* @return 字符串结果
* @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。
*/
@RequestMapping( @RequestMapping(
value = {"apps/{packageName}/releaseNote"}, value = {"apps/{packageName}/releaseNote"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -166,6 +307,23 @@ public class StoreController {
return this.appReleaseNote(request, response, packageName, (String)null, (Integer)null, sdkVersion, true); return this.appReleaseNote(request, response, packageName, (String)null, (Integer)null, sdkVersion, true);
} }
/**
* 处理应用Release备注。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:new WebContext、find、process。
*
* 框架注解:{@code @RequestMapping(value = {"apps/{packageName}/{keyStore}/releaseNote", "apps/{packageName}/{keyStore}/releaseNote/{pathSdkVersion}"}, method = {RequestMethod.GET})}、{@code @ResponseBody}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param packageName 参数 {@code packageName}({@code String})
* @param keyStore 参数 {@code keyStore}({@code String})
* @param pathSdkVersion 参数 {@code pathSdkVersion}({@code Integer})
* @param sdkVersion 参数 {@code sdkVersion}({@code int})
* @param isFormal 参数 {@code isFormal}({@code Boolean})
* @return 字符串结果
* @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。
*/
@RequestMapping( @RequestMapping(
value = {"apps/{packageName}/{keyStore}/releaseNote", "apps/{packageName}/{keyStore}/releaseNote/{pathSdkVersion}"}, value = {"apps/{packageName}/{keyStore}/releaseNote", "apps/{packageName}/{keyStore}/releaseNote/{pathSdkVersion}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -196,6 +354,20 @@ public class StoreController {
return result; return result;
} }
/**
* 处理应用Release备注Show全部。
*
* 框架注解:{@code @RequestMapping(value = {"apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink", "apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink/{pathSdkVersion}"}, method = {RequestMethod.GET})}、{@code @ResponseBody}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param packageName 参数 {@code packageName}({@code String})
* @param keyStore 参数 {@code keyStore}({@code String})
* @param pathSdkVersion 参数 {@code pathSdkVersion}({@code Integer})
* @param sdkVersion 参数 {@code sdkVersion}({@code int})
* @return 字符串结果
* @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。
*/
@RequestMapping( @RequestMapping(
value = {"apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink", "apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink/{pathSdkVersion}"}, value = {"apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink", "apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink/{pathSdkVersion}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -205,6 +377,21 @@ public class StoreController {
return this.appReleaseNote(request, response, packageName, keyStore, pathSdkVersion, sdkVersion, (Boolean)null); return this.appReleaseNote(request, response, packageName, keyStore, pathSdkVersion, sdkVersion, (Boolean)null);
} }
/**
* 获取OTA 固件。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:getUrl、new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"ota/{fileUuid}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param fileUuid 文件 UUID({@code UUID})
* @param range 参数 {@code range}({@code String})
* @param etag 参数 {@code etag}({@code String})
* @param position 参数 {@code position}({@code Long})
* @param checksum 参数 {@code checksum}({@code Long})
*/
@RequestMapping( @RequestMapping(
value = {"ota/{fileUuid}"}, value = {"ota/{fileUuid}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -230,6 +417,22 @@ public class StoreController {
} }
/**
* 获取Web应用。
*
* 实现要点:包含异常捕获与降级/回滚分支;主要调用:find。
*
* 框架注解:{@code @RequestMapping(value = {"webapp/{fileUuid}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param fileUuid 文件 UUID({@code String})
* @param range 参数 {@code range}({@code String})
* @param etag 参数 {@code etag}({@code String})
* @param position 参数 {@code position}({@code Long})
* @param checksum 参数 {@code checksum}({@code Long})
* @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。
*/
@RequestMapping( @RequestMapping(
value = {"webapp/{fileUuid}"}, value = {"webapp/{fileUuid}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -246,6 +449,20 @@ public class StoreController {
this.getWebApp(response, app, range); this.getWebApp(response, app, range);
} }
/**
* 获取Web应用。
*
* 框架注解:{@code @RequestMapping(value = {"webapp/latest"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param range 参数 {@code range}({@code String})
* @param etag 参数 {@code etag}({@code String})
* @param groupId 参数 {@code groupId}({@code String})
* @param artifactId 参数 {@code artifactId}({@code String})
* @param isFormal 参数 {@code isFormal}({@code boolean})
* @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。
*/
@RequestMapping( @RequestMapping(
value = {"webapp/latest"}, value = {"webapp/latest"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -255,6 +472,15 @@ public class StoreController {
this.getWebApp(response, app, range); this.getWebApp(response, app, range);
} }
/**
* 获取Web应用。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:getUrl、new McFile、exists。
*
* @param response HTTP 响应({@code HttpServletResponse})
* @param app 参数 {@code app}({@code StoreWebApp})
* @param range 参数 {@code range}({@code String})
*/
private void getWebApp(HttpServletResponse response, StoreWebApp app, String range) { private void getWebApp(HttpServletResponse response, StoreWebApp app, String range) {
try { try {
if (app != null) { if (app != null) {
@@ -278,6 +504,23 @@ public class StoreController {
} }
/**
* 处理web应用Release备注。
*
* 实现要点:主要调用:findAll、new WebContext、process。
*
* 框架注解:{@code @RequestMapping(value = {"webapp/releaseNote"}, method = {RequestMethod.GET})}、{@code @ResponseBody}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param groupId 参数 {@code groupId}({@code String})
* @param artifactId 参数 {@code artifactId}({@code String})
* @param version 参数 {@code version}({@code String})
* @param limit 数量上限({@code int})
* @param isFormal 参数 {@code isFormal}({@code boolean})
* @return 字符串结果
* @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。
*/
@RequestMapping( @RequestMapping(
value = {"webapp/releaseNote"}, value = {"webapp/releaseNote"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -294,6 +537,21 @@ public class StoreController {
return result; return result;
} }
/**
* 获取Other文件。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:getUrl、new McFile。
*
* 框架注解:{@code @RequestMapping(value = {"other/{fileName}"}, method = {RequestMethod.GET})}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param fileName 文件名({@code String})
* @param range 参数 {@code range}({@code String})
* @param etag 参数 {@code etag}({@code String})
* @param position 参数 {@code position}({@code Long})
* @param checksum 参数 {@code checksum}({@code Long})
*/
@RequestMapping( @RequestMapping(
value = {"other/{fileName}"}, value = {"other/{fileName}"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
@@ -0,0 +1,15 @@
/**
* 文件/图片下载与静态资源控制器:处理设备截图、应用图标、报表下载等二进制响应。
*
* <p>本包主要类型:
* <ul>
* <li>{@link BarcodeController}</li>
* <li>{@link FilesController}</li>
* <li>{@link ResourceController}</li>
* <li>{@link StoreController}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.controller.lib;
@@ -0,0 +1,17 @@
/**
* 页面路由控制器:负责 Thymeleaf 页面渲染、登录跳转和静态资源入口。
*
* <p>本包主要类型:
* <ul>
* <li>{@link BaseController}</li>
* <li>{@link DeviceController}</li>
* <li>{@link ExceptionController}</li>
* <li>{@link FragmentController}</li>
* <li>{@link HomeController}</li>
* <li>{@link UserController}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.controller;
@@ -47,10 +47,25 @@ import org.springframework.web.util.UriComponentsBuilder;
*/ */
@Controller @Controller
public class DpcController { public class DpcController {
/**
* store应用服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private StoreAppService storeAppService; private StoreAppService storeAppService;
/**
* 用户服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private UserService userService; private UserService userService;
/**
* 站点服务;Spring 自动注入的依赖。
*
* 注解:{@code @Autowired}。
*/
@Autowired @Autowired
private SiteService siteService; private SiteService siteService;
@@ -84,6 +99,15 @@ public class DpcController {
return this.toDpcConfig(request, dpc); return this.toDpcConfig(request, dpc);
} }
/**
* 处理转换为Dpc配置。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 12 个条件分支、1 个循环;主要调用:new File、new URL。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param dpc 参数 {@code dpc}({@code DpcModel})
* @return 字符串结果
*/
private String toDpcConfig(HttpServletRequest request, DpcModel dpc) { private String toDpcConfig(HttpServletRequest request, DpcModel dpc) {
String adminPackage = dpc.getDeviceAdmin(); String adminPackage = dpc.getDeviceAdmin();
if (!Strings.isNullOrEmpty(adminPackage) && adminPackage.indexOf(47) < 0) { if (!Strings.isNullOrEmpty(adminPackage) && adminPackage.indexOf(47) < 0) {
@@ -145,6 +169,18 @@ public class DpcController {
return dpc.toDpcConfig(); return dpc.toDpcConfig();
} }
/**
* 获取Checksum。
*
* 实现要点:包含异常捕获与降级/回滚分支;主要调用:new URL。
*
* 框架注解:{@code @RequestMapping(value = {"/dpc/checksum"}, method = {RequestMethod.GET})}、{@code @ResponseBody}。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @param response HTTP 响应({@code HttpServletResponse})
* @param url 参数 {@code url}({@code String})
* @return 字符串结果
*/
@RequestMapping( @RequestMapping(
value = {"/dpc/checksum"}, value = {"/dpc/checksum"},
method = {RequestMethod.GET} method = {RequestMethod.GET}
+331
View File
@@ -6,94 +6,217 @@ import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
/**
* 【Android Enterprise 配置】{@code DpcModel}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code COMPONENT_MUST_SERVICE}(String):字段 COMPONENT_MUST_SERVICE</li>
* <li>{@code COMPONENT_MIDM_DPC}(String):字段 COMPONENT_MIDM_DPC</li>
* <li>{@code ssid}(String):字段 ssid</li>
* <li>{@code security}(String):字段 security</li>
* <li>{@code password}(String):密码字段(数据库中通常保存 BCrypt 哈希,不在 JSON 中序列化)</li>
* <li>{@code hidden}(Boolean):是否hidden</li>
* </ul>
*
* 协作对象:{@code MidmConfig}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class DpcModel { public class DpcModel {
/**
* 字段 COMPONENT_MUST_SERVICE。
*/
public static final String COMPONENT_MUST_SERVICE = "com.mitac.must.service/com.mitac.must.service.MustDeviceAdminReceiver"; public static final String COMPONENT_MUST_SERVICE = "com.mitac.must.service/com.mitac.must.service.MustDeviceAdminReceiver";
/**
* 字段 COMPONENT_MIDM_DPC。
*/
public static final String COMPONENT_MIDM_DPC = "com.mitac.midm.dpc/com.mitac.midm.dpc.MidmDeviceAdminReceiver"; public static final String COMPONENT_MIDM_DPC = "com.mitac.midm.dpc/com.mitac.midm.dpc.MidmDeviceAdminReceiver";
/**
* 字段 ssid。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_WIFI_SSID", alternate = {"ssid"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_WIFI_SSID", value = "android.app.extra.PROVISIONING_WIFI_SSID",
alternate = {"ssid"} alternate = {"ssid"}
) )
private String ssid; private String ssid;
/**
* 字段 security。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE", alternate = {"security"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE", value = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE",
alternate = {"security"} alternate = {"security"}
) )
private String security; private String security;
/**
* 密码字段(数据库中通常保存 BCrypt 哈希,不在 JSON 中序列化)。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_WIFI_PASSWORD", alternate = {"password"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_WIFI_PASSWORD", value = "android.app.extra.PROVISIONING_WIFI_PASSWORD",
alternate = {"password"} alternate = {"password"}
) )
private String password; private String password;
/**
* 是否hidden。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_WIFI_HIDDEN", alternate = {"hidden"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_WIFI_HIDDEN", value = "android.app.extra.PROVISIONING_WIFI_HIDDEN",
alternate = {"hidden"} alternate = {"hidden"}
) )
private Boolean hidden; private Boolean hidden;
/**
* 启用全部系统应用列表。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED", alternate = {"enableAllSystemApps"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED", value = "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED",
alternate = {"enableAllSystemApps"} alternate = {"enableAllSystemApps"}
) )
private boolean enableAllSystemApps = true; private boolean enableAllSystemApps = true;
/**
* 设备Admin。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME", alternate = {"deviceAdmin"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME", value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME",
alternate = {"deviceAdmin"} alternate = {"deviceAdmin"}
) )
private String deviceAdmin; private String deviceAdmin;
/**
* 字段 packageChecksum。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM", alternate = {"packageChecksum"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM", value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM",
alternate = {"packageChecksum"} alternate = {"packageChecksum"}
) )
private String packageChecksum; private String packageChecksum;
/**
* 下载URL。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION", alternate = {"downloadUrl"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION", value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION",
alternate = {"downloadUrl"} alternate = {"downloadUrl"}
) )
private String downloadUrl; private String downloadUrl;
/**
* 语言区域。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_LOCALE", alternate = {"locale"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_LOCALE", value = "android.app.extra.PROVISIONING_LOCALE",
alternate = {"locale"} alternate = {"locale"}
) )
private String locale; private String locale;
/**
* 时间Zone。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_TIME_ZONE", alternate = {"timeZone"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_TIME_ZONE", value = "android.app.extra.PROVISIONING_TIME_ZONE",
alternate = {"timeZone"} alternate = {"timeZone"}
) )
private String timeZone; private String timeZone;
/**
* local时间。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_LOCAL_TIME", alternate = {"localTime"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_LOCAL_TIME", value = "android.app.extra.PROVISIONING_LOCAL_TIME",
alternate = {"localTime"} alternate = {"localTime"}
) )
private String localTime; private String localTime;
/**
* midm配置。
*
* 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE", alternate = {"midm"})}。
*/
@SerializedName( @SerializedName(
value = "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE", value = "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE",
alternate = {"midm"} alternate = {"midm"}
) )
private MidmConfig midmConfig; private MidmConfig midmConfig;
/**
* 获取 {@code ssid}。
* @return 字符串结果
*/
public String getSsid() { public String getSsid() {
return this.ssid; return this.ssid;
} }
/**
* 设置 {@code ssid}。
*
* @param ssid 参数 {@code ssid}({@code String})
*/
public void setSsid(String ssid) { public void setSsid(String ssid) {
this.ssid = ssid; this.ssid = ssid;
} }
/**
* 获取 {@code security}。
* @return 字符串结果
*/
public String getSecurity() { public String getSecurity() {
return this.security; return this.security;
} }
/**
* 设置 {@code security}。
*
* @param securityType 参数 {@code securityType}({@code String})
*/
public void setSecurity(String securityType) { public void setSecurity(String securityType) {
this.security = securityType; this.security = securityType;
} }
/**
* 获取 {@code password}。
* @return 字符串结果
*/
public String getPassword() { public String getPassword() {
return this.password; return this.password;
} }
/**
* 设置 {@code password}。
*
* @param password 密码({@code String})
*/
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
/**
* 加密Password。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param passwordEncoder 参数 {@code passwordEncoder}({@code PasswordEncoder})
*/
public void encryptPassword(PasswordEncoder passwordEncoder) { public void encryptPassword(PasswordEncoder passwordEncoder) {
if (this.midmConfig != null && !Strings.isNullOrEmpty(this.midmConfig.getPassword())) { if (this.midmConfig != null && !Strings.isNullOrEmpty(this.midmConfig.getPassword())) {
this.midmConfig.setPassword(passwordEncoder.encode(this.midmConfig.getPassword())); this.midmConfig.setPassword(passwordEncoder.encode(this.midmConfig.getPassword()));
@@ -101,30 +224,63 @@ public class DpcModel {
} }
/**
* 处理hidden。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean hidden() { public boolean hidden() {
return this.hidden; return this.hidden;
} }
/**
* 设置 {@code hidden}。
*
* @param isHidden 参数 {@code isHidden}({@code boolean})
*/
public void setHidden(boolean isHidden) { public void setHidden(boolean isHidden) {
this.hidden = isHidden; this.hidden = isHidden;
} }
/**
* 判断 {@code enableAllSystemApps}。
* @return 字段/派生属性 {@code enableAllSystemApps} 的值
*/
public boolean isEnableAllSystemApps() { public boolean isEnableAllSystemApps() {
return this.enableAllSystemApps; return this.enableAllSystemApps;
} }
/**
* 设置 {@code enableAllSystemApps}。
*
* @param enableAllSystemApps 参数 {@code enableAllSystemApps}({@code boolean})
*/
public void setEnableAllSystemApps(boolean enableAllSystemApps) { public void setEnableAllSystemApps(boolean enableAllSystemApps) {
this.enableAllSystemApps = enableAllSystemApps; this.enableAllSystemApps = enableAllSystemApps;
} }
/**
* 获取 {@code deviceAdmin}。
* @return 字符串结果
*/
public String getDeviceAdmin() { public String getDeviceAdmin() {
return this.deviceAdmin; return this.deviceAdmin;
} }
/**
* 设置 {@code deviceAdmin}。
*
* @param deviceAdmin 参数 {@code deviceAdmin}({@code String})
*/
public void setDeviceAdmin(String deviceAdmin) { public void setDeviceAdmin(String deviceAdmin) {
this.deviceAdmin = deviceAdmin; this.deviceAdmin = deviceAdmin;
} }
/**
* 获取 {@code deviceAdminPackageName}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
* @return 字符串结果
*/
public String getDeviceAdminPackageName() { public String getDeviceAdminPackageName() {
if (Strings.isNullOrEmpty(this.deviceAdmin)) { if (Strings.isNullOrEmpty(this.deviceAdmin)) {
return null; return null;
@@ -134,145 +290,320 @@ public class DpcModel {
} }
} }
/**
* 获取 {@code packageChecksum}。
* @return 字符串结果
*/
public String getPackageChecksum() { public String getPackageChecksum() {
return this.packageChecksum; return this.packageChecksum;
} }
/**
* 设置 {@code packageChecksum}。
*
* @param packageChecksum 参数 {@code packageChecksum}({@code String})
*/
public void setPackageChecksum(String packageChecksum) { public void setPackageChecksum(String packageChecksum) {
this.packageChecksum = packageChecksum; this.packageChecksum = packageChecksum;
} }
/**
* 获取 {@code downloadUrl}。
* @return 字符串结果
*/
public String getDownloadUrl() { public String getDownloadUrl() {
return this.downloadUrl; return this.downloadUrl;
} }
/**
* 设置 {@code downloadUrl}。
*
* @param downloadUrl 参数 {@code downloadUrl}({@code String})
*/
public void setDownloadUrl(String downloadUrl) { public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl; this.downloadUrl = downloadUrl;
} }
/**
* 获取 {@code locale}。
* @return 字符串结果
*/
public String getLocale() { public String getLocale() {
return this.locale; return this.locale;
} }
/**
* 设置 {@code locale}。
*
* @param locale 参数 {@code locale}({@code String})
*/
public void setLocale(String locale) { public void setLocale(String locale) {
this.locale = locale; this.locale = locale;
} }
/**
* 获取 {@code midm}。
* @return 字段/派生属性 {@code midm} 的值
*/
public MidmConfig getMidm() { public MidmConfig getMidm() {
return this.midmConfig; return this.midmConfig;
} }
/**
* 设置 {@code midm}。
*
* @param midm 参数 {@code midm}({@code MidmConfig})
*/
public void setMidm(MidmConfig midm) { public void setMidm(MidmConfig midm) {
this.midmConfig = midm; this.midmConfig = midm;
} }
/**
* 处理转换为Dpc配置。
*
* 实现要点:主要调用:new GsonBuilder。
* @return 字符串结果
*/
public String toDpcConfig() { public String toDpcConfig() {
Gson gson = (new GsonBuilder()).disableHtmlEscaping().create(); Gson gson = (new GsonBuilder()).disableHtmlEscaping().create();
return gson.toJson(this); return gson.toJson(this);
} }
/**
* 【Android Enterprise 配置】{@code MidmConfig}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code hostUrl}(String):hostURL</li>
* <li>{@code clientAppUrl}(String):client应用URL</li>
* <li>{@code systemAppUrl}(String):系统应用URL</li>
* <li>{@code updateLatest}(Boolean):更新最新</li>
* <li>{@code installSilent}(Boolean):是否installSilent</li>
* <li>{@code siteId}(String):站点ID</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public static class MidmConfig { public static class MidmConfig {
/**
* hostURL。
*
* 注解:{@code @SerializedName(value = "midm.host.url", alternate = {"hostUrl"})}。
*/
@SerializedName( @SerializedName(
value = "midm.host.url", value = "midm.host.url",
alternate = {"hostUrl"} alternate = {"hostUrl"}
) )
private String hostUrl; private String hostUrl;
/**
* client应用URL。
*
* 注解:{@code @SerializedName(value = "midm.app.client.url", alternate = {"clientAppUrl"})}。
*/
@SerializedName( @SerializedName(
value = "midm.app.client.url", value = "midm.app.client.url",
alternate = {"clientAppUrl"} alternate = {"clientAppUrl"}
) )
private String clientAppUrl; private String clientAppUrl;
/**
* 系统应用URL。
*
* 注解:{@code @SerializedName(value = "midm.app.system.url", alternate = {"systemAppUrl"})}。
*/
@SerializedName( @SerializedName(
value = "midm.app.system.url", value = "midm.app.system.url",
alternate = {"systemAppUrl"} alternate = {"systemAppUrl"}
) )
private String systemAppUrl; private String systemAppUrl;
/**
* 更新最新。
*
* 注解:{@code @SerializedName(value = "midm.app.install.latest", alternate = {"updateLatest"})}。
*/
@SerializedName( @SerializedName(
value = "midm.app.install.latest", value = "midm.app.install.latest",
alternate = {"updateLatest"} alternate = {"updateLatest"}
) )
private Boolean updateLatest; private Boolean updateLatest;
/**
* 是否installSilent。
*
* 注解:{@code @SerializedName(value = "midm.app.install.slient", alternate = {"installSilent"})}。
*/
@SerializedName( @SerializedName(
value = "midm.app.install.slient", value = "midm.app.install.slient",
alternate = {"installSilent"} alternate = {"installSilent"}
) )
private Boolean installSilent; private Boolean installSilent;
/**
* 站点ID。
*
* 注解:{@code @SerializedName(value = "midm.site", alternate = {"siteId"})}。
*/
@SerializedName( @SerializedName(
value = "midm.site", value = "midm.site",
alternate = {"siteId"} alternate = {"siteId"}
) )
private String siteId; private String siteId;
/**
* 用户邮箱(登录名,建立索引)。
*
* 注解:{@code @SerializedName(value = "midm.email", alternate = {"email"})}。
*/
@SerializedName( @SerializedName(
value = "midm.email", value = "midm.email",
alternate = {"email"} alternate = {"email"}
) )
private String email; private String email;
/**
* 密码字段(数据库中通常保存 BCrypt 哈希,不在 JSON 中序列化)。
*
* 注解:{@code @SerializedName(value = "midm.password", alternate = {"password"})}。
*/
@SerializedName( @SerializedName(
value = "midm.password", value = "midm.password",
alternate = {"password"} alternate = {"password"}
) )
private String password; private String password;
/**
* 获取 {@code hostUrl}。
* @return 字符串结果
*/
public String getHostUrl() { public String getHostUrl() {
return this.hostUrl; return this.hostUrl;
} }
/**
* 设置 {@code hostUrl}。
*
* @param url 参数 {@code url}({@code String})
*/
public void setHostUrl(String url) { public void setHostUrl(String url) {
this.hostUrl = url; this.hostUrl = url;
} }
/**
* 获取 {@code clientAppUrl}。
* @return 字符串结果
*/
public String getClientAppUrl() { public String getClientAppUrl() {
return this.clientAppUrl; return this.clientAppUrl;
} }
/**
* 设置 {@code clientAppUrl}。
*
* @param clientAppUrl 参数 {@code clientAppUrl}({@code String})
*/
public void setClientAppUrl(String clientAppUrl) { public void setClientAppUrl(String clientAppUrl) {
this.clientAppUrl = clientAppUrl; this.clientAppUrl = clientAppUrl;
} }
/**
* 获取 {@code systemAppUrl}。
* @return 字符串结果
*/
public String getSystemAppUrl() { public String getSystemAppUrl() {
return this.systemAppUrl; return this.systemAppUrl;
} }
/**
* 设置 {@code systemAppUrl}。
*
* @param systemAppUrl 参数 {@code systemAppUrl}({@code String})
*/
public void setSystemAppUrl(String systemAppUrl) { public void setSystemAppUrl(String systemAppUrl) {
this.systemAppUrl = systemAppUrl; this.systemAppUrl = systemAppUrl;
} }
/**
* 获取 {@code updateLatest}。
* @return 字段/派生属性 {@code updateLatest} 的值
*/
public Boolean getUpdateLatest() { public Boolean getUpdateLatest() {
return this.updateLatest; return this.updateLatest;
} }
/**
* 设置 {@code updateLatest}。
*
* @param updateLatest 参数 {@code updateLatest}({@code Boolean})
*/
public void setUpdateLatest(Boolean updateLatest) { public void setUpdateLatest(Boolean updateLatest) {
this.updateLatest = updateLatest; this.updateLatest = updateLatest;
} }
/**
* 获取 {@code installSilent}。
* @return 字段/派生属性 {@code installSilent} 的值
*/
public Boolean getInstallSilent() { public Boolean getInstallSilent() {
return this.installSilent; return this.installSilent;
} }
/**
* 设置 {@code installSilent}。
*
* @param installSilent 参数 {@code installSilent}({@code Boolean})
*/
public void setInstallSilent(Boolean installSilent) { public void setInstallSilent(Boolean installSilent) {
this.installSilent = installSilent; this.installSilent = installSilent;
} }
/**
* 获取 {@code siteId}。
* @return 字符串结果
*/
public String getSiteId() { public String getSiteId() {
return this.siteId; return this.siteId;
} }
/**
* 设置 {@code siteId}。
*
* @param siteId 参数 {@code siteId}({@code String})
*/
public void setSiteId(String siteId) { public void setSiteId(String siteId) {
this.siteId = siteId; this.siteId = siteId;
} }
/**
* 获取 {@code email}。
* @return 字符串结果
*/
public String getEmail() { public String getEmail() {
return this.email; return this.email;
} }
/**
* 设置 {@code email}。
*
* @param email 邮箱({@code String})
*/
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
/**
* 获取 {@code password}。
* @return 字符串结果
*/
public String getPassword() { public String getPassword() {
return this.password; return this.password;
} }
/**
* 设置 {@code password}。
*
* @param password 密码({@code String})
*/
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
+34
View File
@@ -9,7 +9,25 @@ import java.security.NoSuchAlgorithmException;
import java.util.Base64; import java.util.Base64;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
/**
* 【Android Enterprise 配置】{@code DpcUtils}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class DpcUtils { public class DpcUtils {
/**
* 获取Checksum。
*
* 实现要点:包含异常捕获与降级/回滚分支。
*
* @param url 参数 {@code url}({@code URL})
* @return 字符串结果
*/
public static String getChecksum(URL url) { public static String getChecksum(URL url) {
try { try {
return getChecksum(IOUtils.toByteArray(url.openStream())); return getChecksum(IOUtils.toByteArray(url.openStream()));
@@ -18,10 +36,26 @@ public class DpcUtils {
} }
} }
/**
* 获取Checksum。
*
* 实现要点:主要调用:exists、new McFile。
*
* @param file 文件({@code File})
* @return 字符串结果
*/
public static String getChecksum(File file) { public static String getChecksum(File file) {
return !file.exists() ? null : getChecksum((new McFile(file)).toBytes()); return !file.exists() ? null : getChecksum((new McFile(file)).toBytes());
} }
/**
* 获取Checksum。
*
* 实现要点:包含异常捕获与降级/回滚分支。
*
* @param bytes 参数 {@code bytes}({@code byte[]})
* @return 字符串结果
*/
public static String getChecksum(byte[] bytes) { public static String getChecksum(byte[] bytes) {
try { try {
MessageDigest shaDigest = MessageDigest.getInstance("SHA-256"); MessageDigest shaDigest = MessageDigest.getInstance("SHA-256");
@@ -0,0 +1,14 @@
/**
* Android Enterprise 零接触(Zero-Touch)配置:生成 DPC 二维码与 provisioning JSON。
*
* <p>本包主要类型:
* <ul>
* <li>{@link DpcController}</li>
* <li>{@link DpcModel}</li>
* <li>{@link DpcUtils}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.dpc;
@@ -10,34 +10,102 @@ import org.joda.time.DateTime;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.index.Indexed;
/**
* 【Java 类型】{@code GeneralProfile}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code profile}(DbObject):配置档案</li>
* <li>{@code settings}(DbObject):设置列表</li>
* <li>{@code created}(Date):创建时间</li>
* <li>{@code updated}(Date):最后更新时间</li>
* <li>{@code enabled}(Boolean):是否启用</li>
* </ul>
*
* 协作对象:{@code DbObject}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class GeneralProfile { public class GeneralProfile {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
protected UUID uuid; protected UUID uuid;
/**
* 配置档案。
*/
protected DbObject profile; protected DbObject profile;
/**
* 设置列表。
*/
protected DbObject settings; protected DbObject settings;
/**
* 创建时间。
*/
protected Date created; protected Date created;
/**
* 最后更新时间;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
protected Date updated; protected Date updated;
/**
* 是否启用。
*/
protected Boolean enabled; protected Boolean enabled;
/**
* 初始化对象状态(补齐 UUID/时间戳/默认字段)。
*
* 实现要点:主要调用:new Date。
*/
public void init() { public void init() {
this.generateId(); this.generateId();
this.created = new Date(); this.created = new Date();
this.updated = this.created; this.updated = this.created;
} }
/**
* 生成ID。
*/
public void generateId() { public void generateId() {
this.uuid = UUID.randomUUID(); this.uuid = UUID.randomUUID();
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code profile}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getProfile() { public DbObject getProfile() {
if (this.profile == null) { if (this.profile == null) {
this.profile = new DbObject(); this.profile = new DbObject();
@@ -46,10 +114,21 @@ public class GeneralProfile {
return this.profile; return this.profile;
} }
/**
* 设置 {@code profile}。
*
* @param profile 设备配置档案({@code DbObject})
*/
public void setProfile(DbObject profile) { public void setProfile(DbObject profile) {
this.profile = profile; this.profile = profile;
} }
/**
* 获取 {@code settings}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getSettings() { public DbObject getSettings() {
if (this.settings == null) { if (this.settings == null) {
this.settings = new DbObject(); this.settings = new DbObject();
@@ -58,34 +137,72 @@ public class GeneralProfile {
return this.settings; return this.settings;
} }
/**
* 设置 {@code settings}。
*
* @param settings 参数 {@code settings}({@code DbObject})
*/
public void setSettings(DbObject settings) { public void setSettings(DbObject settings) {
this.settings = settings; this.settings = settings;
} }
/**
* 获取 {@code created}。
* @return 字段/派生属性 {@code created} 的值
*/
public Date getCreated() { public Date getCreated() {
return this.created; return this.created;
} }
/**
* 设置 {@code created}。
*
* @param created 参数 {@code created}({@code Date})
*/
public void setCreated(Date created) { public void setCreated(Date created) {
this.created = created; this.created = created;
} }
/**
* 获取 {@code updated}。
* @return 字段/派生属性 {@code updated} 的值
*/
public Date getUpdated() { public Date getUpdated() {
return this.updated; return this.updated;
} }
/**
* 设置 {@code updated}。
*
* @param updated 参数 {@code updated}({@code Date})
*/
public void setUpdated(Date updated) { public void setUpdated(Date updated) {
this.updated = updated; this.updated = updated;
} }
/**
* 设置Updated。
*
* 实现要点:主要调用:new Date。
*/
public void setUpdated() { public void setUpdated() {
this.setUpdated(new Date()); this.setUpdated(new Date());
} }
/**
* 获取 {@code enabled}。
* @return 字段/派生属性 {@code enabled} 的值
*/
public boolean getEnabled() { public boolean getEnabled() {
return this.enabled != null && this.enabled; return this.enabled != null && this.enabled;
} }
/**
* 判断 {@code ended}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
* @return 字段/派生属性 {@code ended} 的值
*/
public boolean isEnded() { public boolean isEnded() {
if ("ends".equals(this.getProfile("endsOption"))) { if ("ends".equals(this.getProfile("endsOption"))) {
DateTime dateTime = McDateTimeUtils.parseDate((String)this.getProfile("ends"), "yyyy-MM-dd").plusDays(1); DateTime dateTime = McDateTimeUtils.parseDate((String)this.getProfile("ends"), "yyyy-MM-dd").plusDays(1);
@@ -95,18 +212,38 @@ public class GeneralProfile {
} }
} }
/**
* 设置 {@code enabled}。
*
* @param enabled 参数 {@code enabled}({@code Boolean})
*/
public void setEnabled(Boolean enabled) { public void setEnabled(Boolean enabled) {
this.enabled = enabled; this.enabled = enabled;
} }
public Object getProfile(String key) { /**
return this.getProfile(key, (Object)null); * 获取配置档案。
*
* @param key 键/配置项({@code String})
* @return 字段/派生属性 {@code profile} 的值
*/
public <T> T getProfile(String key) {
return this.getProfile(key, (T)null);
} }
public Object getProfile(String key, Object defaultValue) { /**
* 获取配置档案。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。
*
* @param key 键/配置项({@code String})
* @param defaultValue 参数 {@code defaultValue}({@code T})
* @return 字段/派生属性 {@code profile} 的值
*/
public <T> T getProfile(String key, T defaultValue) {
if (this.getProfile().containsKey(key)) { if (this.getProfile().containsKey(key)) {
try { try {
return this.getProfile().get(key); return (T)this.getProfile().get(key);
} catch (Exception var4) { } catch (Exception var4) {
} }
} }
@@ -114,35 +251,96 @@ public class GeneralProfile {
return defaultValue; return defaultValue;
} }
/**
* 获取配置档案AsBoolean。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param key 键/配置项({@code String})
* @param subCategory 参数 {@code subCategory}({@code String})
* @param item 参数 {@code item}({@code String})
* @param def 参数 {@code def}({@code boolean})
* @return 字段/派生属性 {@code profileAsBoolean} 的值
*/
public boolean getProfileAsBoolean(String category, String key, String subCategory, String item, boolean def) { public boolean getProfileAsBoolean(String category, String key, String subCategory, String item, boolean def) {
Boolean value = McBooleanUtils.isTrue(this.getProfile(category, key, subCategory, item)); Boolean value = McBooleanUtils.isTrue(this.getProfile(category, key, subCategory, item));
return value == null ? def : value; return value == null ? def : value;
} }
/**
* 获取配置档案。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param key 键/配置项({@code String})
* @param subCategory 参数 {@code subCategory}({@code String})
* @param item 参数 {@code item}({@code String})
* @return 字段/派生属性 {@code profile} 的值
*/
public Object getProfile(String category, String key, String subCategory, String item) { public Object getProfile(String category, String key, String subCategory, String item) {
return this.getProfileCategory(category, key, subCategory).get(item); return this.getProfileCategory(category, key, subCategory).get(item);
} }
/**
* 获取配置档案Category。
*
* @param categoryNames 参数 {@code categoryNames}({@code String[]})
* @return MongoDB 文档扩展对象
*/
public DbObject getProfileCategory(String... categoryNames) { public DbObject getProfileCategory(String... categoryNames) {
return this.getProfile().getDbObject(categoryNames); return this.getProfile().getDbObject(categoryNames);
} }
/**
* 获取Category配置档案。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param key 键/配置项({@code String})
* @return 字段/派生属性 {@code categoryProfile} 的值
*/
public Object getCategoryProfile(String category, String key) { public Object getCategoryProfile(String category, String key) {
return this.getProfileCategory(category) == null ? null : this.getProfileCategory(category).get(key); return this.getProfileCategory(category) == null ? null : this.getProfileCategory(category).get(key);
} }
/**
* 设置配置档案。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setProfile(String key, Object value) { public void setProfile(String key, Object value) {
this.getProfile().put(key, value); this.getProfile().put(key, value);
} }
/**
* 设置配置档案。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setProfile(String category, String key, Object value) { public void setProfile(String category, String key, Object value) {
this.getProfileCategory(category).put(key, value); this.getProfileCategory(category).put(key, value);
} }
/**
* 设置配置档案。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param subCategory 参数 {@code subCategory}({@code String})
* @param item 参数 {@code item}({@code String})
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setProfile(String category, String subCategory, String item, String key, Object value) { public void setProfile(String category, String subCategory, String item, String key, Object value) {
this.getProfileCategory(category, subCategory, item).put(key, value); this.getProfileCategory(category, subCategory, item).put(key, value);
} }
/**
* 移除配置档案。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:remove。
*
* @param key 键/配置项({@code String})
*/
public void removeProfile(String key) { public void removeProfile(String key) {
if (this.profile != null) { if (this.profile != null) {
this.profile.remove(key); this.profile.remove(key);
@@ -150,47 +348,121 @@ public class GeneralProfile {
} }
/**
* 获取设置。
*
* @param key 键/配置项({@code String})
* @return 字段/派生属性 {@code setting} 的值
*/
public Object getSetting(String key) { public Object getSetting(String key) {
return this.getSettings().get(key); return this.getSettings().get(key);
} }
/**
* 获取设置AsString。
*
* @param key 键/配置项({@code String})
* @return 字符串结果
*/
public String getSettingAsString(String key) { public String getSettingAsString(String key) {
return this.getSettings().getString(key, (String)null); return this.getSettings().getString(key, (String)null);
} }
/**
* 获取设置AsInt。
*
* @param key 键/配置项({@code String})
* @param def 参数 {@code def}({@code int})
* @return 数量/长度
*/
public int getSettingAsInt(String key, int def) { public int getSettingAsInt(String key, int def) {
return this.getSettings().getInteger(key, def); return this.getSettings().getInteger(key, def);
} }
/**
* 获取设置AsFloat。
*
* @param key 键/配置项({@code String})
* @param def 参数 {@code def}({@code float})
* @return 字段/派生属性 {@code settingAsFloat} 的值
*/
public float getSettingAsFloat(String key, float def) { public float getSettingAsFloat(String key, float def) {
return this.getSettings().getFloat(key, def); return this.getSettings().getFloat(key, def);
} }
/**
* 获取设置AsBoolean。
*
* @param key 键/配置项({@code String})
* @return 字段/派生属性 {@code settingAsBoolean} 的值
*/
public boolean getSettingAsBoolean(String key) { public boolean getSettingAsBoolean(String key) {
return this.getSettingAsBoolean(key, false); return this.getSettingAsBoolean(key, false);
} }
/**
* 获取设置AsBoolean。
*
* @param key 键/配置项({@code String})
* @param def 参数 {@code def}({@code boolean})
* @return 字段/派生属性 {@code settingAsBoolean} 的值
*/
public boolean getSettingAsBoolean(String key, boolean def) { public boolean getSettingAsBoolean(String key, boolean def) {
return this.getSettings().containsKey(key) ? McBooleanUtils.isTrue(this.getSetting(key)) : def; return this.getSettings().containsKey(key) ? McBooleanUtils.isTrue(this.getSetting(key)) : def;
} }
/**
* 获取设置AsBoolean。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param key 键/配置项({@code String})
* @param def 参数 {@code def}({@code boolean})
* @return 字段/派生属性 {@code settingAsBoolean} 的值
*/
public boolean getSettingAsBoolean(String category, String key, boolean def) { public boolean getSettingAsBoolean(String category, String key, boolean def) {
Boolean value = McBooleanUtils.isTrue(this.getSetting(category, key)); Boolean value = McBooleanUtils.isTrue(this.getSetting(category, key));
return value == null ? def : value; return value == null ? def : value;
} }
/**
* 获取设置AsUUID。
*
* @param key 键/配置项({@code String})
* @return UUID
*/
public UUID getSettingAsUuid(String key) { public UUID getSettingAsUuid(String key) {
return this.getSettings().getUuid(key); return this.getSettings().getUuid(key);
} }
/**
* 获取设置列表Category。
*
* @param categoryNames 参数 {@code categoryNames}({@code String[]})
* @return MongoDB 文档扩展对象
*/
public DbObject getSettingsCategory(String... categoryNames) { public DbObject getSettingsCategory(String... categoryNames) {
return this.getSettings().getDbObject(categoryNames); return this.getSettings().getDbObject(categoryNames);
} }
/**
* 获取设置。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param key 键/配置项({@code String})
* @return 字段/派生属性 {@code setting} 的值
*/
public Object getSetting(String category, String key) { public Object getSetting(String category, String key) {
return this.getSettingsCategory(category).get(key); return this.getSettingsCategory(category).get(key);
} }
/**
* 设置设置。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param key 键/配置项({@code String})
* @param value 值({@code UUID})
*/
public void setSetting(String key, UUID value) { public void setSetting(String key, UUID value) {
if (value != null) { if (value != null) {
this.getSettings().put(key, value.toString()); this.getSettings().put(key, value.toString());
@@ -200,10 +472,25 @@ public class GeneralProfile {
} }
/**
* 设置设置。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setSetting(String key, Object value) { public void setSetting(String key, Object value) {
this.getSettings().put(key, value); this.getSettings().put(key, value);
} }
/**
* 设置设置。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:remove。
*
* @param categoryName 参数 {@code categoryName}({@code String})
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setSetting(String categoryName, String key, Object value) { public void setSetting(String categoryName, String key, Object value) {
Document dbObject = this.getSettingsCategory(categoryName); Document dbObject = this.getSettingsCategory(categoryName);
if (value != null) { if (value != null) {
@@ -214,27 +501,53 @@ public class GeneralProfile {
} }
/**
* 移除选项。
*
* @param key 键/配置项({@code String})
*/
public void removeOption(String key) { public void removeOption(String key) {
this.getSettings().remove(key); this.getSettings().remove(key);
} }
/**
* 获取 {@code name}。
* @return 字符串结果
*/
public String getName() { public String getName() {
Object value = this.getProfile("name"); Object value = this.getProfile("name");
return value == null ? null : (String)value; return value == null ? null : (String)value;
} }
/**
* 设置 {@code name}。
*
* @param name 参数 {@code name}({@code String})
*/
public void setName(String name) { public void setName(String name) {
this.setProfile("name", name); this.setProfile("name", name);
} }
/**
* 获取 {@code description}。
* @return 字符串结果
*/
public String getDescription() { public String getDescription() {
return (String)this.getProfile("desc"); return (String)this.getProfile("desc");
} }
/**
* 设置 {@code description}。
*
* @param desc 参数 {@code desc}({@code String})
*/
public void setDescription(String desc) { public void setDescription(String desc) {
this.setProfile("desc", desc); this.setProfile("desc", desc);
} }
/**
* 处理minify。
*/
public void minify() { public void minify() {
this.created = null; this.created = null;
} }
@@ -1,25 +1,72 @@
package com.midm.model; package com.midm.model;
/**
* 【Java 类型】{@code GroupByResult}
*
* 类职责:
* <ul>
* <li>提供该包内的可复用能力。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code groups}(String[]):分组列表</li>
* <li>{@code count}(int):统计</li>
* </ul>
*
* 协作对象:{@code String[]}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class GroupByResult { public class GroupByResult {
/**
* 分组列表。
*/
private String[] groups; private String[] groups;
/**
* 统计。
*/
private int count; private int count;
/**
* 获取 {@code count}。
* @return 数量/长度
*/
public int getCount() { public int getCount() {
return this.count; return this.count;
} }
/**
* 设置 {@code count}。
*
* @param count 参数 {@code count}({@code int})
*/
public void setCount(int count) { public void setCount(int count) {
this.count = count; this.count = count;
} }
/**
* 获取 {@code group}。
* @return 字符串结果
*/
public String getGroup() { public String getGroup() {
return this.groups.length > 0 ? this.groups[0] : null; return this.groups.length > 0 ? this.groups[0] : null;
} }
/**
* 获取 {@code groups}。
* @return 字段/派生属性 {@code groups} 的值
*/
public String[] getGroups() { public String[] getGroups() {
return this.groups; return this.groups;
} }
/**
* 设置 {@code groups}。
*
* @param groups 参数 {@code groups}({@code String[]})
*/
public void setGroups(String[] groups) { public void setGroups(String[] groups) {
this.groups = groups; this.groups = groups;
} }
@@ -2,6 +2,22 @@ package com.midm.model;
import com.google.common.base.CharMatcher; import com.google.common.base.CharMatcher;
/**
* 【枚举常量】{@code IF_EXISTS_OPTION}
*
* 类职责:
* <ul>
* <li>用有限枚举值表达状态/类型,避免魔法字符串。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code option}(int):选项</li>
* </ul>
*
* 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。
*/
public enum IF_EXISTS_OPTION { public enum IF_EXISTS_OPTION {
ignore(0), ignore(0),
skip(0), skip(0),
@@ -11,12 +27,28 @@ public enum IF_EXISTS_OPTION {
modify(2), modify(2),
remove(3); remove(3);
/**
* 选项。
*/
public int option; public int option;
/**
* 构造 {@code IF_EXISTS_OPTION} 实例。
*
* @param option 参数 {@code option}({@code int})
*/
private IF_EXISTS_OPTION(int option) { private IF_EXISTS_OPTION(int option) {
this.option = option; this.option = option;
} }
/**
* 处理获取。
*
* 实现要点:包含异常捕获与降级/回滚分支。
*
* @param key 键/配置项({@code String})
* @return 处理结果
*/
public static IF_EXISTS_OPTION get(String key) { public static IF_EXISTS_OPTION get(String key) {
try { try {
return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase()); return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase());
@@ -25,6 +57,12 @@ public enum IF_EXISTS_OPTION {
} }
} }
/**
* 获取选项。
*
* @param option 参数 {@code option}({@code String})
* @return 数量/长度
*/
public static int getOption(String option) { public static int getOption(String option) {
return get(option).option; return get(option).option;
} }
@@ -12,61 +12,147 @@ import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes; import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code Battery}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code siteUuid}(UUID):用户所属站点 UUID</li>
* <li>{@code states}(DbObject):字段 states</li>
* <li>{@code deviceGroupPath}(String):设备分组路径</li>
* </ul>
*
* 协作对象:{@code DbObject}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
@CompoundIndexes({@CompoundIndex( @CompoundIndexes({@CompoundIndex(
def = "{'profile.hardware_info.batterySerial':1}", def = "{'profile.hardware_info.batterySerial':1}",
unique = true unique = true
)}) )})
public class Battery extends GeneralProfile { public class Battery extends GeneralProfile {
/**
* 用户所属站点 UUID。
*/
private UUID siteUuid; private UUID siteUuid;
/**
* 字段 states。
*/
private DbObject states; private DbObject states;
/**
* 设备分组路径;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private String deviceGroupPath; private String deviceGroupPath;
/**
* 构造 {@code Battery} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public Battery() { public Battery() {
this.init(); this.init();
} }
/**
* 设置 {@code siteUuid}。
*
* @param siteUuid 站点 UUID({@code UUID})
*/
public void setSiteUuid(UUID siteUuid) { public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid; this.siteUuid = siteUuid;
} }
/**
* 获取 {@code siteUuid}。
* @return UUID
*/
public UUID getSiteUuid() { public UUID getSiteUuid() {
return this.siteUuid; return this.siteUuid;
} }
/**
* 获取 {@code batterySerial}。
* @return 字符串结果
*/
public String getBatterySerial() { public String getBatterySerial() {
return (String)this.getCategoryProfile("hardware_info", "batterySerial"); return (String)this.getCategoryProfile("hardware_info", "batterySerial");
} }
/**
* 获取 {@code deviceSerial}。
* @return 字符串结果
*/
public String getDeviceSerial() { public String getDeviceSerial() {
return (String)this.getCategoryProfile("hardware_info", "deviceSerial"); return (String)this.getCategoryProfile("hardware_info", "deviceSerial");
} }
/**
* 设置 {@code deviceSerial}。
*
* @param deviceSerial 参数 {@code deviceSerial}({@code String})
*/
public void setDeviceSerial(String deviceSerial) { public void setDeviceSerial(String deviceSerial) {
this.setProfile("hardware_info", "deviceSerial", deviceSerial.trim()); this.setProfile("hardware_info", "deviceSerial", deviceSerial.trim());
} }
/**
* 获取 {@code model}。
* @return 字符串结果
*/
public String getModel() { public String getModel() {
return (String)this.getCategoryProfile("hardware_info", "model"); return (String)this.getCategoryProfile("hardware_info", "model");
} }
/**
* 获取 {@code deviceId}。
* @return 字符串结果
*/
public String getDeviceId() { public String getDeviceId() {
return (String)this.getCategoryProfile("hardware_info", "device_id"); return (String)this.getCategoryProfile("hardware_info", "device_id");
} }
/**
* 设置 {@code registerState}。
*
* @param state 参数 {@code state}({@code String})
*/
public void setRegisterState(String state) { public void setRegisterState(String state) {
this.getStates().put("state", state); this.getStates().put("state", state);
} }
/**
* 获取 {@code registerState}。
* @return 字符串结果
*/
public String getRegisterState() { public String getRegisterState() {
return this.getStates().getString("state"); return this.getStates().getString("state");
} }
/**
* 获取 {@code batteryCondition}。
* @return 数量/长度
*/
public Integer getBatteryCondition() { public Integer getBatteryCondition() {
return this.getStates().getInteger("batteryCondition", -1); return this.getStates().getInteger("batteryCondition", -1);
} }
/**
* 获取 {@code states}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getStates() { public DbObject getStates() {
if (this.states == null) { if (this.states == null) {
this.states = new DbObject(); this.states = new DbObject();
@@ -75,20 +161,42 @@ public class Battery extends GeneralProfile {
return this.states; return this.states;
} }
/**
* 获取 {@code deviceGroupPath}。
* @return 字符串结果
*/
public String getDeviceGroupPath() { public String getDeviceGroupPath() {
return this.deviceGroupPath; return this.deviceGroupPath;
} }
/**
* 设置 {@code deviceGroupPath}。
*
* @param deviceGroupPath 参数 {@code deviceGroupPath}({@code String})
*/
public void setDeviceGroupPath(String deviceGroupPath) { public void setDeviceGroupPath(String deviceGroupPath) {
this.deviceGroupPath = deviceGroupPath; this.deviceGroupPath = deviceGroupPath;
} }
/**
* 获取 {@code lastTemp}。
*
* 实现要点:主要调用:new TypeToken。
* @return 字段/派生属性 {@code lastTemp} 的值
*/
public ValueWithTime getLastTemp() { public ValueWithTime getLastTemp() {
List<ValueWithTime> dbTempList = (List)McJsonUtils.toObject(McJsonUtils.toJson(this.getStates().get("temperature")), (new TypeToken() { List<ValueWithTime> dbTempList = (List)McJsonUtils.toObject(McJsonUtils.toJson(this.getStates().get("temperature")), (new TypeToken() {
}).getType()); }).getType());
return dbTempList.isEmpty() ? null : (ValueWithTime)dbTempList.get(0); return dbTempList.isEmpty() ? null : (ValueWithTime)dbTempList.get(0);
} }
/**
* 设置 {@code lastTemp}。
*
* 实现要点:主要调用:new DbObject、new ArrayList。
*
* @param t 参数 {@code t}({@code ValueWithTime})
*/
public void setLastTemp(ValueWithTime t) { public void setLastTemp(ValueWithTime t) {
DbObject obj = new DbObject(); DbObject obj = new DbObject();
obj.append("reportedAt", t.getReportedAt()).append("value", t.getValue()); obj.append("reportedAt", t.getReportedAt()).append("value", t.getValue());
@@ -97,22 +205,58 @@ public class Battery extends GeneralProfile {
this.getStates().put("temperature", list); this.getStates().put("temperature", list);
} }
/**
* 【枚举常量】{@code BATTERY_CONDITION}
*
* 类职责:
* <ul>
* <li>用有限枚举值表达状态/类型,避免魔法字符串。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code value}(int):值</li>
* </ul>
*
* 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。
*/
public static enum BATTERY_CONDITION { public static enum BATTERY_CONDITION {
UNKNOWN(-1), UNKNOWN(-1),
GOOD(0), GOOD(0),
AVERAGE(1), AVERAGE(1),
SERVICE_SOON(2); SERVICE_SOON(2);
/**
* 值。
*/
private int value; private int value;
/**
* 构造 {@code BATTERY_CONDITION} 实例。
*
* @param value 值({@code int})
*/
private BATTERY_CONDITION(int value) { private BATTERY_CONDITION(int value) {
this.value = value; this.value = value;
} }
/**
* 获取 {@code value}。
* @return 数量/长度
*/
public int getValue() { public int getValue() {
return this.value; return this.value;
} }
/**
* 处理用于值。
*
* 实现要点:包含 1 个条件分支、1 个循环。
*
* @param value 值({@code int})
* @return 处理结果
*/
public static BATTERY_CONDITION forValue(int value) { public static BATTERY_CONDITION forValue(int value) {
for(BATTERY_CONDITION e : values()) { for(BATTERY_CONDITION e : values()) {
if (e.value == value) { if (e.value == value) {
@@ -8,35 +8,108 @@ import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code BatteryLog}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code batterySerial}(String):电池序列</li>
* <li>{@code category}(String):字段 category</li>
* <li>{@code log}(String):日志</li>
* <li>{@code reportedAt}(Date):时间字段</li>
* <li>{@code states}(DbObject):字段 states</li>
* </ul>
*
* 协作对象:{@code DbObject}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
@CompoundIndex( @CompoundIndex(
def = "{batterySerial: 1, reportedAt: 1}" def = "{batterySerial: 1, reportedAt: 1}"
) )
public class BatteryLog { public class BatteryLog {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid = UUID.randomUUID(); private UUID uuid = UUID.randomUUID();
/**
* 电池序列;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private String batterySerial; private String batterySerial;
/**
* 字段 category;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private String category; private String category;
/**
* 日志。
*/
private String log; private String log;
/**
* 时间字段;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private Date reportedAt; private Date reportedAt;
/**
* 字段 states。
*/
private DbObject states; private DbObject states;
/**
* 时间字段。
*/
private Date recordedAt = new Date(); private Date recordedAt = new Date();
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 获取 {@code batterySerial}。
* @return 字符串结果
*/
public String getBatterySerial() { public String getBatterySerial() {
return this.batterySerial; return this.batterySerial;
} }
/**
* 设置 {@code category}。
*
* @param category 分类(app/ota/other/report 等)({@code String})
*/
public void setCategory(String category) { public void setCategory(String category) {
this.category = category; this.category = category;
} }
/**
* 获取 {@code states}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getStates() { public DbObject getStates() {
if (this.states == null) { if (this.states == null) {
this.states = new DbObject(); this.states = new DbObject();
@@ -45,6 +118,10 @@ public class BatteryLog {
return this.states; return this.states;
} }
/**
* 获取 {@code reportedAt}。
* @return 字段/派生属性 {@code reportedAt} 的值
*/
public Date getReportedAt() { public Date getReportedAt() {
return this.reportedAt; return this.reportedAt;
} }
@@ -2,27 +2,74 @@ package com.midm.model.battery;
import java.util.Date; import java.util.Date;
/**
* 【领域模型】{@code ValueWithTime}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code reportedAt}(Date):时间字段</li>
* <li>{@code value}(double):值</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class ValueWithTime { public class ValueWithTime {
/**
* 时间字段。
*/
private Date reportedAt; private Date reportedAt;
/**
* 值。
*/
private double value; private double value;
/**
* 构造 {@code ValueWithTime} 实例。
*
* @param reportedAt 参数 {@code reportedAt}({@code Date})
* @param value 值({@code double})
*/
public ValueWithTime(Date reportedAt, double value) { public ValueWithTime(Date reportedAt, double value) {
this.reportedAt = reportedAt; this.reportedAt = reportedAt;
this.value = value; this.value = value;
} }
/**
* 获取 {@code reportedAt}。
* @return 字段/派生属性 {@code reportedAt} 的值
*/
public Date getReportedAt() { public Date getReportedAt() {
return this.reportedAt; return this.reportedAt;
} }
/**
* 设置 {@code reportedAt}。
*
* @param reportedAt 参数 {@code reportedAt}({@code Date})
*/
public void setReportedAt(Date reportedAt) { public void setReportedAt(Date reportedAt) {
this.reportedAt = reportedAt; this.reportedAt = reportedAt;
} }
/**
* 获取 {@code value}。
* @return 字段/派生属性 {@code value} 的值
*/
public double getValue() { public double getValue() {
return this.value; return this.value;
} }
/**
* 设置 {@code value}。
*
* @param value 值({@code double})
*/
public void setValue(double value) { public void setValue(double value) {
this.value = value; this.value = value;
} }
@@ -0,0 +1,14 @@
/**
* 电池健康度(BMS)模型:电压、温度、循环次数、SOH 状态等遥测数据。
*
* <p>本包主要类型:
* <ul>
* <li>{@link Battery}</li>
* <li>{@link BatteryLog}</li>
* <li>{@link ValueWithTime}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.model.battery;
@@ -2,89 +2,222 @@ package com.midm.model.device;
import com.google.common.base.Strings; import com.google.common.base.Strings;
/**
* 【领域模型】{@code AppInfo}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code packageName}(String):package名称</li>
* <li>{@code label}(String):字段 label</li>
* <li>{@code versionName}(String):版本名称</li>
* <li>{@code versionCode}(Integer):版本代码</li>
* <li>{@code minSdkVersion}(Integer):minSDK版本</li>
* <li>{@code appSize}(Long):应用数量</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class AppInfo { public class AppInfo {
/**
* package名称。
*/
private String packageName; private String packageName;
/**
* 字段 label。
*/
private String label; private String label;
/**
* 版本名称。
*/
private String versionName; private String versionName;
/**
* 版本代码。
*/
private Integer versionCode; private Integer versionCode;
/**
* minSDK版本。
*/
private Integer minSdkVersion; private Integer minSdkVersion;
/**
* 应用数量。
*/
private Long appSize; private Long appSize;
/**
* 数据数量。
*/
private Long dataSize; private Long dataSize;
/**
* 第一Installed。
*/
private Long firstInstalled; private Long firstInstalled;
/**
* 最后Updated。
*/
private Long lastUpdated; private Long lastUpdated;
/**
* 获取 {@code packageName}。
* @return 字符串结果
*/
public String getPackageName() { public String getPackageName() {
return this.packageName; return this.packageName;
} }
/**
* 设置 {@code packageName}。
*
* @param packageName 参数 {@code packageName}({@code String})
*/
public void setPackageName(String packageName) { public void setPackageName(String packageName) {
this.packageName = packageName; this.packageName = packageName;
} }
/**
* 获取 {@code label}。
* @return 字符串结果
*/
public String getLabel() { public String getLabel() {
return Strings.isNullOrEmpty(this.label) ? this.packageName : this.label; return Strings.isNullOrEmpty(this.label) ? this.packageName : this.label;
} }
/**
* 设置 {@code label}。
*
* @param label 参数 {@code label}({@code String})
*/
public void setLabel(String label) { public void setLabel(String label) {
this.label = label; this.label = label;
} }
/**
* 获取 {@code versionName}。
* @return 字符串结果
*/
public String getVersionName() { public String getVersionName() {
return this.versionName; return this.versionName;
} }
/**
* 设置 {@code versionName}。
*
* @param versionName 参数 {@code versionName}({@code String})
*/
public void setVersionName(String versionName) { public void setVersionName(String versionName) {
this.versionName = versionName; this.versionName = versionName;
} }
/**
* 获取 {@code versionCode}。
* @return 数量/长度
*/
public int getVersionCode() { public int getVersionCode() {
return this.versionCode; return this.versionCode;
} }
/**
* 设置 {@code versionCode}。
*
* @param versionCode 参数 {@code versionCode}({@code int})
*/
public void setVersionCode(int versionCode) { public void setVersionCode(int versionCode) {
this.versionCode = versionCode; this.versionCode = versionCode;
} }
/**
* 处理minSDK版本。
* @return 数量/长度
*/
public int minSdkVersion() { public int minSdkVersion() {
return this.minSdkVersion; return this.minSdkVersion;
} }
/**
* 设置 {@code minSdkVersion}。
*
* @param version 参数 {@code version}({@code int})
*/
public void setMinSdkVersion(int version) { public void setMinSdkVersion(int version) {
this.minSdkVersion = version; this.minSdkVersion = version;
} }
/**
* 获取 {@code appSize}。
* @return 数量/长度
*/
public long getAppSize() { public long getAppSize() {
return this.appSize; return this.appSize;
} }
/**
* 设置 {@code appSize}。
*
* @param appSize 参数 {@code appSize}({@code long})
*/
public void setAppSize(long appSize) { public void setAppSize(long appSize) {
this.appSize = appSize; this.appSize = appSize;
} }
/**
* 获取 {@code dataSize}。
* @return 数量/长度
*/
public long getDataSize() { public long getDataSize() {
return this.dataSize; return this.dataSize;
} }
/**
* 设置 {@code dataSize}。
*
* @param dataSize 参数 {@code dataSize}({@code long})
*/
public void setDataSize(long dataSize) { public void setDataSize(long dataSize) {
this.dataSize = dataSize; this.dataSize = dataSize;
} }
/**
* 获取 {@code firstInstalled}。
* @return 数量/长度
*/
public long getFirstInstalled() { public long getFirstInstalled() {
return this.firstInstalled; return this.firstInstalled;
} }
/**
* 设置 {@code firstInstalled}。
*
* @param firstInstalled 参数 {@code firstInstalled}({@code long})
*/
public void setFirstInstalled(long firstInstalled) { public void setFirstInstalled(long firstInstalled) {
this.firstInstalled = firstInstalled; this.firstInstalled = firstInstalled;
} }
/**
* 获取 {@code lastUpdated}。
* @return 数量/长度
*/
public long getLastUpdated() { public long getLastUpdated() {
return this.lastUpdated; return this.lastUpdated;
} }
/**
* 设置 {@code lastUpdated}。
*
* @param lastUpdated 参数 {@code lastUpdated}({@code long})
*/
public void setLastUpdated(long lastUpdated) { public void setLastUpdated(long lastUpdated) {
this.lastUpdated = lastUpdated; this.lastUpdated = lastUpdated;
} }
/**
* 返回对象的可读字符串表示。
* @return 字符串结果
*/
public String toString() { public String toString() {
return String.format("%s %s(%s)", this.label, this.versionName, this.packageName); return String.format("%s %s(%s)", this.label, this.versionName, this.packageName);
} }
@@ -2,6 +2,21 @@ package com.midm.model.device;
import com.google.common.base.CharMatcher; import com.google.common.base.CharMatcher;
/**
* 【枚举常量】{@code DEVICE_PROPERTY}
*
* 类职责:
* <ul>
* <li>用有限枚举值表达状态/类型,避免魔法字符串。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* </ul>
*
* 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。
*/
public enum DEVICE_PROPERTY { public enum DEVICE_PROPERTY {
serialno, serialno,
serial_no, serial_no,
@@ -41,6 +56,14 @@ public enum DEVICE_PROPERTY {
rsa, rsa,
unknown; unknown;
/**
* 处理获取。
*
* 实现要点:包含异常捕获与降级/回滚分支。
*
* @param key 键/配置项({@code String})
* @return 处理结果
*/
public static DEVICE_PROPERTY get(String key) { public static DEVICE_PROPERTY get(String key) {
try { try {
return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase()); return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase());
@@ -8,30 +8,98 @@ import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code DataUsage}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code deviceUuid}(UUID):设备UUID</li>
* <li>{@code siteUuid}(UUID):用户所属站点 UUID</li>
* <li>{@code from}(Date):从</li>
* <li>{@code to}(Date):转换为</li>
* <li>{@code usage}(DbObject):用量</li>
* </ul>
*
* 协作对象:{@code DbObject}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
@CompoundIndex( @CompoundIndex(
def = "{deviceUuid: 1, siteUuid: 1}" def = "{deviceUuid: 1, siteUuid: 1}"
) )
public class DataUsage { public class DataUsage {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid; private UUID uuid;
/**
* 设备UUID。
*/
private UUID deviceUuid; private UUID deviceUuid;
/**
* 用户所属站点 UUID。
*/
private UUID siteUuid; private UUID siteUuid;
/**
* 从;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private Date from; private Date from;
/**
* 转换为;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private Date to; private Date to;
/**
* 用量。
*/
private DbObject usage; private DbObject usage;
/**
* 时间字段;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed(expireAfterSeconds = 15552000)}。
*/
@Indexed( @Indexed(
expireAfterSeconds = 15552000 expireAfterSeconds = 15552000
) )
private Date recordedAt; private Date recordedAt;
/**
* 构造 {@code DataUsage} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*
* 实现要点:主要调用:new Date。
*/
public DataUsage() { public DataUsage() {
this.uuid = UUID.randomUUID(); this.uuid = UUID.randomUUID();
this.recordedAt = new Date(); this.recordedAt = new Date();
} }
/**
* 构造 {@code DataUsage} 实例。
*
* 实现要点:包含 5 个条件分支、0 个循环;主要调用:new Date、remove。
*
* @param device 设备({@code Device})
* @param report 参数 {@code report}({@code DbObject})
*/
public DataUsage(Device device, DbObject report) { public DataUsage(Device device, DbObject report) {
this(); this();
this.setSiteUuid(device.getSiteUuid()); this.setSiteUuid(device.getSiteUuid());
@@ -67,70 +135,152 @@ public class DataUsage {
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code deviceUuid}。
* @return UUID
*/
public UUID getDeviceUuid() { public UUID getDeviceUuid() {
return this.deviceUuid; return this.deviceUuid;
} }
/**
* 设置 {@code deviceUuid}。
*
* @param deviceUuid 设备 UUID({@code UUID})
*/
public void setDeviceUuid(UUID deviceUuid) { public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid; this.deviceUuid = deviceUuid;
} }
/**
* 获取 {@code siteUuid}。
* @return UUID
*/
public UUID getSiteUuid() { public UUID getSiteUuid() {
return this.siteUuid; return this.siteUuid;
} }
/**
* 设置 {@code siteUuid}。
*
* @param siteUuid 站点 UUID({@code UUID})
*/
public void setSiteUuid(UUID siteUuid) { public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid; this.siteUuid = siteUuid;
} }
/**
* 获取 {@code from}。
* @return 字段/派生属性 {@code from} 的值
*/
public Date getFrom() { public Date getFrom() {
return this.from; return this.from;
} }
/**
* 设置 {@code from}。
*
* @param from 起始时间({@code Date})
*/
public void setFrom(Date from) { public void setFrom(Date from) {
this.from = from; this.from = from;
} }
/**
* 获取 {@code to}。
* @return 字段/派生属性 {@code to} 的值
*/
public Date getTo() { public Date getTo() {
return this.to; return this.to;
} }
/**
* 设置 {@code to}。
*
* @param to 结束时间({@code Date})
*/
public void setTo(Date to) { public void setTo(Date to) {
this.to = to; this.to = to;
} }
/**
* 获取 {@code usage}。
* @return MongoDB 文档扩展对象
*/
public DbObject getUsage() { public DbObject getUsage() {
return this.usage; return this.usage;
} }
/**
* 获取用量。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param key 键/配置项({@code String})
* @return 数量/长度
*/
public long getUsage(String category, String key) { public long getUsage(String category, String key) {
return this.getUsage().getDbObject(new String[]{category}).getLong(key, 0L); return this.getUsage().getDbObject(new String[]{category}).getLong(key, 0L);
} }
/**
* 设置 {@code usage}。
*
* @param usage 参数 {@code usage}({@code DbObject})
*/
public void setUsage(DbObject usage) { public void setUsage(DbObject usage) {
this.usage = usage; this.usage = usage;
} }
/**
* 获取 {@code recordedAt}。
* @return 字段/派生属性 {@code recordedAt} 的值
*/
public Date getRecordedAt() { public Date getRecordedAt() {
return this.recordedAt; return this.recordedAt;
} }
/**
* 设置 {@code recordedAt}。
*
* @param recordedAt 参数 {@code recordedAt}({@code Date})
*/
public void setRecordedAt(Date recordedAt) { public void setRecordedAt(Date recordedAt) {
this.recordedAt = recordedAt; this.recordedAt = recordedAt;
} }
/**
* 判断是否LaterThan。
*
* @param usage 参数 {@code usage}({@code DataUsage})
* @return 字段/派生属性 {@code laterThan} 的值
*/
public boolean isLaterThan(DataUsage usage) { public boolean isLaterThan(DataUsage usage) {
return usage.getTo().getTime() < this.getFrom().getTime(); return usage.getTo().getTime() < this.getFrom().getTime();
} }
/**
* 判断是否Overlapped。
*
* @param usage 参数 {@code usage}({@code DataUsage})
* @return 字段/派生属性 {@code overlapped} 的值
*/
public boolean isOverlapped(DataUsage usage) { public boolean isOverlapped(DataUsage usage) {
return usage.getFrom().getTime() >= this.getTo().getTime() && usage.getTo().getTime() <= this.getTo().getTime(); return usage.getFrom().getTime() >= this.getTo().getTime() && usage.getTo().getTime() <= this.getTo().getTime();
} }
+342 -5
View File
@@ -80,7 +80,7 @@ public class Device extends GeneralProfile {
/** 临时字段:设备当前生效的策略清单缓存 */ /** 临时字段:设备当前生效的策略清单缓存 */
@Transient @Transient
private List deviceProfiles; private List<Document> deviceProfiles;
/** 许可激活时间点索引 */ /** 许可激活时间点索引 */
@Indexed @Indexed
@@ -107,40 +107,82 @@ public class Device extends GeneralProfile {
private Date lastDisconnected; private Date lastDisconnected;
/** 终端已安装的应用程序包信息清单快照 */ /** 终端已安装的应用程序包信息清单快照 */
private List installedApps; private List<AppInfo> installedApps;
/**
* 获取 {@code rsa}。
* @return 字符串结果
*/
public String getRsa() { public String getRsa() {
return this.rsa; return this.rsa;
} }
/**
* 设置 {@code rsa}。
*
* @param rsa 参数 {@code rsa}({@code String})
*/
public void setRsa(String rsa) { public void setRsa(String rsa) {
this.rsa = rsa; this.rsa = rsa;
} }
/**
* 获取 {@code siteUuid}。
* @return UUID
*/
public UUID getSiteUuid() { public UUID getSiteUuid() {
return this.siteUuid; return this.siteUuid;
} }
/**
* 设置 {@code siteUuid}。
*
* @param siteUuid 站点 UUID({@code UUID})
*/
public void setSiteUuid(UUID siteUuid) { public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid; this.siteUuid = siteUuid;
} }
/**
* 获取 {@code groupUuid}。
* @return UUID
*/
public UUID getGroupUuid() { public UUID getGroupUuid() {
return this.groupUuid; return this.groupUuid;
} }
/**
* 获取 {@code groupPath}。
* @return 字符串结果
*/
public String getGroupPath() { public String getGroupPath() {
return this.groupPath; return this.groupPath;
} }
/**
* 设置 {@code groupPath}。
*
* @param groupPath 参数 {@code groupPath}({@code String})
*/
public void setGroupPath(String groupPath) { public void setGroupPath(String groupPath) {
this.groupPath = groupPath; this.groupPath = groupPath;
} }
/**
* 获取 {@code owner}。
* @return 用户对象;未找到时返回 {@code null}
*/
public User getOwner() { public User getOwner() {
return this.owner; return this.owner;
} }
/**
* 设置 {@code owner}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param owner 参数 {@code owner}({@code User})
*/
public void setOwner(User owner) { public void setOwner(User owner) {
this.owner = owner; this.owner = owner;
if (owner != null) { if (owner != null) {
@@ -149,18 +191,40 @@ public class Device extends GeneralProfile {
} }
/**
* 获取 {@code ownerUuid}。
* @return UUID
*/
public UUID getOwnerUuid() { public UUID getOwnerUuid() {
return this.ownerUuid; return this.ownerUuid;
} }
/**
* 设置 {@code ownerUuid}。
*
* @param ownerUuid 所有者用户 UUID({@code UUID})
*/
public void setOwnerUuid(UUID ownerUuid) { public void setOwnerUuid(UUID ownerUuid) {
this.ownerUuid = ownerUuid; this.ownerUuid = ownerUuid;
} }
/**
* 判断 {@code owner}。
* @return 字段/派生属性 {@code owner} 的值
*/
public boolean hasOwner() { public boolean hasOwner() {
return this.getOwner() != null; return this.getOwner() != null;
} }
/**
* 获取所有者信息。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param key 键/配置项({@code String})
* @param defaultValue 参数 {@code defaultValue}({@code String})
* @return 字符串结果
*/
public String getOwnerInfo(String key, String defaultValue) { public String getOwnerInfo(String key, String defaultValue) {
if (this.owner == null) { if (this.owner == null) {
DbObject owner = this.getProfileCategory(new String[]{"owner"}); DbObject owner = this.getProfileCategory(new String[]{"owner"});
@@ -170,18 +234,37 @@ public class Device extends GeneralProfile {
} }
} }
/**
* 判断 {@code associated}。
* @return 字段/派生属性 {@code associated} 的值
*/
public boolean isAssociated() { public boolean isAssociated() {
return this.getDeviceGroup() != null; return this.getDeviceGroup() != null;
} }
/**
* 判断 {@code register}。
* @return 字段/派生属性 {@code register} 的值
*/
public boolean canRegister() { public boolean canRegister() {
return !Strings.isNullOrEmpty(this.getSerialNo()); return !Strings.isNullOrEmpty(this.getSerialNo());
} }
/**
* 获取 {@code deviceGroup}。
* @return 设备分组;未找到时返回 {@code null}
*/
public DeviceGroup getDeviceGroup() { public DeviceGroup getDeviceGroup() {
return this.deviceGroup; return this.deviceGroup;
} }
/**
* 设置 {@code deviceGroup}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param deviceGroup 设备分组对象({@code DeviceGroup})
*/
public void setDeviceGroup(DeviceGroup deviceGroup) { public void setDeviceGroup(DeviceGroup deviceGroup) {
if (deviceGroup != null && deviceGroup.getSiteUuid().equals(this.getSiteUuid())) { if (deviceGroup != null && deviceGroup.getSiteUuid().equals(this.getSiteUuid())) {
this.deviceGroup = deviceGroup; this.deviceGroup = deviceGroup;
@@ -192,6 +275,12 @@ public class Device extends GeneralProfile {
} }
/**
* 获取 {@code states}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getStates() { public DbObject getStates() {
if (this.states == null) { if (this.states == null) {
this.states = new DbObject(); this.states = new DbObject();
@@ -200,132 +289,276 @@ public class Device extends GeneralProfile {
return this.states; return this.states;
} }
/**
* 设置 {@code states}。
*
* @param states 参数 {@code states}({@code DbObject})
*/
public void setStates(DbObject states) { public void setStates(DbObject states) {
this.states = states; this.states = states;
} }
/**
* 获取 {@code state}。
* @return 字符串结果
*/
public String getState() { public String getState() {
return this.getStates().getString("state", "unknown"); return this.getStates().getString("state", "unknown");
} }
/**
* 设置 {@code state}。
*
* @param state 参数 {@code state}({@code String})
*/
public void setState(String state) { public void setState(String state) {
this.setState("state", state); this.setState("state", state);
} }
/**
* 判断 {@code online}。
* @return 字段/派生属性 {@code online} 的值
*/
public boolean isOnline() { public boolean isOnline() {
return this.getStates().getBoolean("isOnline", false); return this.getStates().getBoolean("isOnline", false);
} }
/**
* 设置 {@code online}。
*
* @param online 参数 {@code online}({@code boolean})
*/
public void setOnline(boolean online) { public void setOnline(boolean online) {
this.setState("isOnline", online); this.setState("isOnline", online);
} }
/**
* 判断 {@code blocked}。
* @return 字段/派生属性 {@code blocked} 的值
*/
public boolean isBlocked() { public boolean isBlocked() {
return this.getStates().containsKey("blocked"); return this.getStates().containsKey("blocked");
} }
/**
* 设置状态。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setState(String key, Object value) { public void setState(String key, Object value) {
this.getStates().append(key, value); this.getStates().append(key, value);
} }
/**
* 设置 {@code clientVersion}。
*
* @param version 参数 {@code version}({@code int})
*/
public void setClientVersion(int version) { public void setClientVersion(int version) {
this.getStates().put("clientVersion", version); this.getStates().put("clientVersion", version);
} }
/**
* 获取 {@code clientVersion}。
* @return 数量/长度
*/
public int getClientVersion() { public int getClientVersion() {
return this.getStates().getInteger("clientVersion", -1); return this.getStates().getInteger("clientVersion", -1);
} }
/**
* 获取 {@code batteryCondition}。
* @return 字段/派生属性 {@code batteryCondition} 的值
*/
public Battery.BATTERY_CONDITION getBatteryCondition() { public Battery.BATTERY_CONDITION getBatteryCondition() {
return Battery.BATTERY_CONDITION.forValue(this.getStates().getInteger("batteryCondition", -1)); return Battery.BATTERY_CONDITION.forValue(this.getStates().getInteger("batteryCondition", -1));
} }
/**
* 判断 {@code oldClient}。
* @return 字段/派生属性 {@code oldClient} 的值
*/
public boolean hasOldClient() { public boolean hasOldClient() {
return this.getClientVersion() < 0; return this.getClientVersion() < 0;
} }
/**
* 获取 {@code enrolled}。
* @return 字段/派生属性 {@code enrolled} 的值
*/
public Date getEnrolled() { public Date getEnrolled() {
return this.enrolled; return this.enrolled;
} }
/**
* 判断 {@code enrolled}。
* @return 字段/派生属性 {@code enrolled} 的值
*/
public boolean isEnrolled() { public boolean isEnrolled() {
return this.enrolled != null; return this.enrolled != null;
} }
/**
* 设置 {@code enrolled}。
*
* @param enrolled 参数 {@code enrolled}({@code Date})
*/
public void setEnrolled(Date enrolled) { public void setEnrolled(Date enrolled) {
this.enrolled = enrolled; this.enrolled = enrolled;
this.setState("enrolled"); this.setState("enrolled");
this.setLicenseExpiry(); this.setLicenseExpiry();
} }
/**
* 判断 {@code retired}。
* @return 字段/派生属性 {@code retired} 的值
*/
public boolean isRetired() { public boolean isRetired() {
return this.getState().equals("retired"); return this.getState().equals("retired");
} }
/**
* 获取 {@code lastCheckedIn}。
* @return 字段/派生属性 {@code lastCheckedIn} 的值
*/
public Date getLastCheckedIn() { public Date getLastCheckedIn() {
return this.lastCheckedIn; return this.lastCheckedIn;
} }
/**
* 设置最后Checked在。
*
* 实现要点:主要调用:new Date。
*/
public void setLastCheckedIn() { public void setLastCheckedIn() {
this.setLastCheckedIn(new Date()); this.setLastCheckedIn(new Date());
} }
/**
* 设置 {@code lastCheckedIn}。
*
* @param lastCheckedIn 参数 {@code lastCheckedIn}({@code Date})
*/
public void setLastCheckedIn(Date lastCheckedIn) { public void setLastCheckedIn(Date lastCheckedIn) {
this.lastCheckedIn = lastCheckedIn; this.lastCheckedIn = lastCheckedIn;
} }
/**
* 获取 {@code lastDisconnected}。
* @return 字段/派生属性 {@code lastDisconnected} 的值
*/
public Date getLastDisconnected() { public Date getLastDisconnected() {
return this.lastDisconnected; return this.lastDisconnected;
} }
/**
* 设置最后Disconnected。
*
* 实现要点:主要调用:new Date。
*/
public void setLastDisconnected() { public void setLastDisconnected() {
this.lastDisconnected = new Date(); this.lastDisconnected = new Date();
} }
/**
* 设置 {@code lastDisconnected}。
*
* @param disconnected 参数 {@code disconnected}({@code Date})
*/
public void setLastDisconnected(Date disconnected) { public void setLastDisconnected(Date disconnected) {
this.lastDisconnected = disconnected; this.lastDisconnected = disconnected;
} }
public List getInstalledApps() { /**
* 获取 {@code installedApps}。
* @return 应用信息列表,可能为空
*/
public List<AppInfo> getInstalledApps() {
return this.installedApps; return this.installedApps;
} }
public void setInstalledApps(List installedApps) { /**
* 设置 {@code installedApps}。
*
* @param installedApps 参数 {@code installedApps}({@code List<AppInfo>})
*/
public void setInstalledApps(List<AppInfo> installedApps) {
this.installedApps = installedApps; this.installedApps = installedApps;
} }
public void setDeviceProfiles(List deviceProfiles) { /**
* 设置 {@code deviceProfiles}。
*
* @param deviceProfiles 参数 {@code deviceProfiles}({@code List<Document>})
*/
public void setDeviceProfiles(List<Document> deviceProfiles) {
this.deviceProfiles = deviceProfiles; this.deviceProfiles = deviceProfiles;
} }
/**
* 获取 {@code serialNo}。
* @return 字符串结果
*/
public String getSerialNo() { public String getSerialNo() {
return (String)this.getCategoryProfile("hardware_info", "serial_no"); return (String)this.getCategoryProfile("hardware_info", "serial_no");
} }
/**
* 设置 {@code serialNo}。
*
* @param serialNo 设备序列号({@code String})
*/
public void setSerialNo(String serialNo) { public void setSerialNo(String serialNo) {
this.setProfile("hardware_info", "serial_no", serialNo.trim()); this.setProfile("hardware_info", "serial_no", serialNo.trim());
} }
/**
* 获取 {@code modelId}。
* @return 字符串结果
*/
public String getModelId() { public String getModelId() {
return (String)this.getCategoryProfile("hardware_info", "product_id"); return (String)this.getCategoryProfile("hardware_info", "product_id");
} }
/**
* 获取 {@code buildNo}。
* @return 字符串结果
*/
public String getBuildNo() { public String getBuildNo() {
return this.getProfileCategory(new String[]{"software_info"}).getString("build_no"); return this.getProfileCategory(new String[]{"software_info"}).getString("build_no");
} }
/**
* 获取 {@code displayId}。
* @return 字符串结果
*/
public String getDisplayId() { public String getDisplayId() {
return this.getProfileCategory(new String[]{"software_info"}).getString("display_id"); return this.getProfileCategory(new String[]{"software_info"}).getString("display_id");
} }
/**
* 获取 {@code productDisplayId}。
* @return 字符串结果
*/
public String getProductDisplayId() { public String getProductDisplayId() {
return this.getProfileCategory(new String[]{"software_info"}).getString("product_display_id"); return this.getProfileCategory(new String[]{"software_info"}).getString("product_display_id");
} }
/**
* 获取 {@code buildDate}。
* @return 数量/长度
*/
public long getBuildDate() { public long getBuildDate() {
return this.getProfileCategory(new String[]{"software_info"}).getLong("build_date", -1L); return this.getProfileCategory(new String[]{"software_info"}).getLong("build_date", -1L);
} }
/**
* 获取 {@code sdkVersion}。
*
* 实现要点:包含 8 个条件分支、0 个循环。
* @return 数量/长度
*/
public int getSdkVersion() { public int getSdkVersion() {
if (this.isEnrolled()) { if (this.isEnrolled()) {
int version = this.getProfileCategory(new String[]{"software_info"}).getInteger("sdk_version", -1); int version = this.getProfileCategory(new String[]{"software_info"}).getInteger("sdk_version", -1);
@@ -352,26 +585,52 @@ public class Device extends GeneralProfile {
} }
} }
/**
* 获取 {@code customerId}。
* @return 字符串结果
*/
public String getCustomerId() { public String getCustomerId() {
return (String)this.getCategoryProfile("software_info", "customer_id"); return (String)this.getCategoryProfile("software_info", "customer_id");
} }
/**
* 获取 {@code regionImgVersion}。
* @return 字符串结果
*/
public String getRegionImgVersion() { public String getRegionImgVersion() {
return this.getProfile().getDbObject(new String[]{"software_info"}).getString("region_version"); return this.getProfile().getDbObject(new String[]{"software_info"}).getString("region_version");
} }
/**
* 获取 {@code scriptVersion}。
* @return 字符串结果
*/
public String getScriptVersion() { public String getScriptVersion() {
return (String)this.getCategoryProfile("software_info", "script_version"); return (String)this.getCategoryProfile("software_info", "script_version");
} }
/**
* 获取 {@code regionBuildDate}。
* @return 数量/长度
*/
public long getRegionBuildDate() { public long getRegionBuildDate() {
return this.getProfile().getDbObject(new String[]{"software_info"}).getLong("region_build_date"); return this.getProfile().getDbObject(new String[]{"software_info"}).getLong("region_build_date");
} }
/**
* 判断 {@code gmsAvailable}。
* @return 字段/派生属性 {@code gmsAvailable} 的值
*/
public boolean isGmsAvailable() { public boolean isGmsAvailable() {
return this.getProfile().getDbObject(new String[]{"software_info"}).getBoolean("gms_available"); return this.getProfile().getDbObject(new String[]{"software_info"}).getBoolean("gms_available");
} }
/**
* 获取 {@code skuId}。
*
* 实现要点:包含 7 个条件分支、0 个循环。
* @return 字符串结果
*/
public String getSkuId() { public String getSkuId() {
String skuId = (String)this.getCategoryProfile("hardware_info", "sku_id"); String skuId = (String)this.getCategoryProfile("hardware_info", "sku_id");
if (skuId == null) { if (skuId == null) {
@@ -404,27 +663,54 @@ public class Device extends GeneralProfile {
return skuId; return skuId;
} }
/**
* 获取 {@code deviceId}。
* @return 字符串结果
*/
public String getDeviceId() { public String getDeviceId() {
return (String)this.getCategoryProfile("hardware_info", "device_id"); return (String)this.getCategoryProfile("hardware_info", "device_id");
} }
/**
* 获取 {@code buildFingerPrint}。
* @return 字符串结果
*/
public String getBuildFingerPrint() { public String getBuildFingerPrint() {
return (String)this.getCategoryProfile("software_info", "build_fingerprint"); return (String)this.getCategoryProfile("software_info", "build_fingerprint");
} }
/**
* 判断 {@code mobileConnected}。
* @return 字段/派生属性 {@code mobileConnected} 的值
*/
public boolean isMobileConnected() { public boolean isMobileConnected() {
String type = this.getProfileCategory(new String[]{"network", "active"}).getString("type"); String type = this.getProfileCategory(new String[]{"network", "active"}).getString("type");
return "MOBILE".equalsIgnoreCase(type); return "MOBILE".equalsIgnoreCase(type);
} }
/**
* 获取 {@code wifiMacAddr}。
* @return 字符串结果
*/
public String getWifiMacAddr() { public String getWifiMacAddr() {
return this.getProfileCategory(new String[]{"network", "wifi"}).getString("mac_address"); return this.getProfileCategory(new String[]{"network", "wifi"}).getString("mac_address");
} }
/**
* 获取 {@code license}。
* @return 字段/派生属性 {@code license} 的值
*/
public DeviceLicense getLicense() { public DeviceLicense getLicense() {
return this.license; return this.license;
} }
/**
* 设置 {@code license}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Date。
*
* @param license 参数 {@code license}({@code DeviceLicense})
*/
public void setLicense(DeviceLicense license) { public void setLicense(DeviceLicense license) {
this.license = license; this.license = license;
if (license != null) { if (license != null) {
@@ -434,14 +720,28 @@ public class Device extends GeneralProfile {
} }
/**
* 获取 {@code licensed}。
* @return 字段/派生属性 {@code licensed} 的值
*/
public Date getLicensed() { public Date getLicensed() {
return this.licensed; return this.licensed;
} }
/**
* 设置 {@code licensed}。
*
* @param licensed 参数 {@code licensed}({@code Date})
*/
public void setLicensed(Date licensed) { public void setLicensed(Date licensed) {
this.licensed = licensed; this.licensed = licensed;
} }
/**
* 设置许可证Expiry。
*
* 实现要点:包含 2 个条件分支、0 个循环。
*/
private void setLicenseExpiry() { private void setLicenseExpiry() {
if (this.hasLicense()) { if (this.hasLicense()) {
if (!this.license.isActivated() && this.isEnrolled()) { if (!this.license.isActivated() && this.isEnrolled()) {
@@ -452,6 +752,12 @@ public class Device extends GeneralProfile {
} }
} }
/**
* 获取 {@code licenseExpiry}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
* @return 字段/派生属性 {@code licenseExpiry} 的值
*/
public Date getLicenseExpiry() { public Date getLicenseExpiry() {
if (this.licenseExpiry == null && this.hasLicense()) { if (this.licenseExpiry == null && this.hasLicense()) {
this.licenseExpiry = this.license.getExpiry(); this.licenseExpiry = this.license.getExpiry();
@@ -460,35 +766,66 @@ public class Device extends GeneralProfile {
return this.licenseExpiry; return this.licenseExpiry;
} }
/**
* 判断 {@code licenseExpired}。
* @return 字段/派生属性 {@code licenseExpired} 的值
*/
public boolean isLicenseExpired() { public boolean isLicenseExpired() {
return this.license != null && !this.license.isPerpetual() && this.license.isExpired(); return this.license != null && !this.license.isPerpetual() && this.license.isExpired();
} }
/**
* 设置 {@code licenseExpiry}。
*
* @param expiry 参数 {@code expiry}({@code Date})
*/
public void setLicenseExpiry(Date expiry) { public void setLicenseExpiry(Date expiry) {
this.licenseExpiry = expiry; this.licenseExpiry = expiry;
} }
/**
* 判断 {@code license}。
* @return 字段/派生属性 {@code license} 的值
*/
public boolean hasLicense() { public boolean hasLicense() {
return this.license != null; return this.license != null;
} }
/**
* 判断 {@code trial}。
* @return 字段/派生属性 {@code trial} 的值
*/
public boolean isTrial() { public boolean isTrial() {
return !this.hasLicense() || this.license.isTrial(); return !this.hasLicense() || this.license.isTrial();
} }
/**
* 移除许可证。
*/
public void removeLicense() { public void removeLicense() {
this.setLicense((DeviceLicense)null); this.setLicense((DeviceLicense)null);
} }
/**
* 获取 {@code plan}。
* @return 字符串结果
*/
public String getPlan() { public String getPlan() {
return this.license.getPlan(); return this.license.getPlan();
} }
/**
* 处理重置。
*/
public void reset() { public void reset() {
this.setEnrolled((Date)null); this.setEnrolled((Date)null);
this.getStates().clear(); this.getStates().clear();
} }
/**
* 处理clone。
* @return 匹配的设备对象;未找到时返回 {@code null}
*/
public Device clone() { public Device clone() {
return (Device)McJsonUtils.clone(this); return (Device)McJsonUtils.clone(this);
} }
@@ -10,64 +10,167 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code DeviceApps}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code deviceUuid}(UUID):设备UUID</li>
* <li>{@code serialNo}(String):序列号</li>
* <li>{@code category}(String):字段 category</li>
* <li>{@code apps}(List<AppInfo>):应用列表</li>
* <li>{@code reported}(Date):时间字段</li>
* </ul>
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class DeviceApps { public class DeviceApps {
/**
* 设备UUID;MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID deviceUuid; private UUID deviceUuid;
/**
* 序列号;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private String serialNo; private String serialNo;
/**
* 字段 category。
*/
private String category = "installed"; private String category = "installed";
private List apps; /**
* 应用列表。
*/
private List<AppInfo> apps;
/**
* 时间字段。
*/
private Date reported = new Date(); private Date reported = new Date();
/**
* 获取 {@code deviceUuid}。
* @return UUID
*/
public UUID getDeviceUuid() { public UUID getDeviceUuid() {
return this.deviceUuid; return this.deviceUuid;
} }
/**
* 设置 {@code deviceUuid}。
*
* @param deviceUuid 设备 UUID({@code UUID})
*/
public void setDeviceUuid(UUID deviceUuid) { public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid; this.deviceUuid = deviceUuid;
} }
/**
* 获取 {@code serialNo}。
* @return 字符串结果
*/
public String getSerialNo() { public String getSerialNo() {
return this.serialNo; return this.serialNo;
} }
/**
* 设置 {@code serialNo}。
*
* @param serialNo 设备序列号({@code String})
*/
public void setSerialNo(String serialNo) { public void setSerialNo(String serialNo) {
this.serialNo = serialNo; this.serialNo = serialNo;
} }
/**
* 获取 {@code category}。
* @return 字符串结果
*/
public String getCategory() { public String getCategory() {
return this.category; return this.category;
} }
/**
* 设置 {@code category}。
*
* @param category 分类(app/ota/other/report 等)({@code String})
*/
public void setCategory(String category) { public void setCategory(String category) {
this.category = category; this.category = category;
} }
public List getApps() { /**
* 获取 {@code apps}。
* @return 应用信息列表,可能为空
*/
public List<AppInfo> getApps() {
return this.apps; return this.apps;
} }
public void setApps(List apps) { /**
* 设置 {@code apps}。
*
* @param apps 参数 {@code apps}({@code List<AppInfo>})
*/
public void setApps(List<AppInfo> apps) {
this.apps = apps; this.apps = apps;
} }
/**
* 获取 {@code clientService}。
* @return 字段/派生属性 {@code clientService} 的值
*/
public AppInfo getClientService() { public AppInfo getClientService() {
return this.getApp("com.mitac.midm.client"); return this.getApp("com.mitac.midm.client");
} }
/**
* 设置 {@code clientService}。
*
* @param appInfo 参数 {@code appInfo}({@code AppInfo})
*/
public void setClientService(AppInfo appInfo) { public void setClientService(AppInfo appInfo) {
this.setApp(appInfo); this.setApp(appInfo);
} }
/**
* 获取 {@code systemService}。
* @return 字段/派生属性 {@code systemService} 的值
*/
public AppInfo getSystemService() { public AppInfo getSystemService() {
return this.getApp("com.mitac.midm.system"); return this.getApp("com.mitac.midm.system");
} }
/**
* 设置 {@code systemService}。
*
* @param appInfo 参数 {@code appInfo}({@code AppInfo})
*/
public void setSystemService(AppInfo appInfo) { public void setSystemService(AppInfo appInfo) {
this.setApp(appInfo); this.setApp(appInfo);
} }
/**
* 获取应用。
*
* 实现要点:包含 2 个条件分支、1 个循环。
*
* @param packageName 参数 {@code packageName}({@code String})
* @return 字段/派生属性 {@code app} 的值
*/
public AppInfo getApp(String packageName) { public AppInfo getApp(String packageName) {
if (this.apps != null) { if (this.apps != null) {
for(AppInfo app : this.apps) { for(AppInfo app : this.apps) {
@@ -81,6 +184,13 @@ public class DeviceApps {
return null; return null;
} }
/**
* 设置 {@code app}。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:new ArrayList。
*
* @param newApp 参数 {@code newApp}({@code AppInfo})
*/
public void setApp(AppInfo newApp) { public void setApp(AppInfo newApp) {
if (newApp != null && !Strings.isNullOrEmpty(newApp.getPackageName())) { if (newApp != null && !Strings.isNullOrEmpty(newApp.getPackageName())) {
if (this.apps == null) { if (this.apps == null) {
@@ -91,6 +201,11 @@ public class DeviceApps {
} }
} }
/**
* 修复Abnormal。
*
* 实现要点:包含 2 个条件分支、1 个循环;主要调用:remove。
*/
public void fixAbnormal() { public void fixAbnormal() {
Iterator<AppInfo> it = this.apps.iterator(); Iterator<AppInfo> it = this.apps.iterator();
@@ -107,14 +222,34 @@ public class DeviceApps {
} }
/**
* 获取 {@code reported}。
* @return 字段/派生属性 {@code reported} 的值
*/
public Date getReported() { public Date getReported() {
return this.reported; return this.reported;
} }
/**
* 设置 {@code reported}。
*
* @param reported 参数 {@code reported}({@code Date})
*/
public void setReported(Date reported) { public void setReported(Date reported) {
this.reported = reported; this.reported = reported;
} }
/**
* 判断是否应用Installed。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param deviceSdk 参数 {@code deviceSdk}({@code int})
* @param packageName 参数 {@code packageName}({@code String})
* @param versionCode 参数 {@code versionCode}({@code long})
* @param minSdk 参数 {@code minSdk}({@code int})
* @return 字段/派生属性 {@code appInstalled} 的值
*/
public boolean isAppInstalled(int deviceSdk, String packageName, long versionCode, int minSdk) { public boolean isAppInstalled(int deviceSdk, String packageName, long versionCode, int minSdk) {
if (minSdk != -1 && deviceSdk < minSdk) { if (minSdk != -1 && deviceSdk < minSdk) {
return true; return true;
@@ -124,6 +259,14 @@ public class DeviceApps {
} }
} }
/**
* 比较当前对象与另一个对象是否相等。
*
* 实现要点:包含 4 个条件分支、1 个循环。
*
* @param obj 参数 {@code obj}({@code Object})
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean equals(Object obj) { public boolean equals(Object obj) {
List<AppInfo> newApps = null; List<AppInfo> newApps = null;
if (obj instanceof DeviceApps) { if (obj instanceof DeviceApps) {
@@ -6,23 +6,78 @@ import java.util.UUID;
import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code DeviceGroup}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code siteUuid}(UUID):用户所属站点 UUID</li>
* <li>{@code parentUuid}(UUID):父级UUID</li>
* <li>{@code order}(Integer):字段 order</li>
* <li>{@code deviceNumbers}(Integer):设备Numbers</li>
* <li>{@code children}(List<DeviceGroup>):子级</li>
* </ul>
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class DeviceGroup extends GeneralProfile implements Comparable { public class DeviceGroup extends GeneralProfile implements Comparable<Object> {
/**
* 用户所属站点 UUID。
*/
private UUID siteUuid; private UUID siteUuid;
/**
* 父级UUID。
*/
private UUID parentUuid; private UUID parentUuid;
/**
* 字段 order。
*/
private Integer order; private Integer order;
/**
* 设备Numbers;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private Integer deviceNumbers; private Integer deviceNumbers;
private List children; /**
* 子级。
*/
private List<DeviceGroup> children;
/**
* 构造 {@code DeviceGroup} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public DeviceGroup() { public DeviceGroup() {
this.deviceNumbers = 0; this.deviceNumbers = 0;
} }
/**
* 构造 {@code DeviceGroup} 实例。
*
* @param uuid 对象 UUID({@code UUID})
*/
public DeviceGroup(UUID uuid) { public DeviceGroup(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 构造 {@code DeviceGroup} 实例。
*
* @param siteUuid 站点 UUID({@code UUID})
* @param parentUuid 参数 {@code parentUuid}({@code UUID})
* @param name 参数 {@code name}({@code String})
*/
public DeviceGroup(UUID siteUuid, UUID parentUuid, String name) { public DeviceGroup(UUID siteUuid, UUID parentUuid, String name) {
this.init(); this.init();
this.siteUuid = siteUuid; this.siteUuid = siteUuid;
@@ -30,50 +85,109 @@ public class DeviceGroup extends GeneralProfile implements Comparable {
this.setName(name); this.setName(name);
} }
/**
* 获取 {@code siteUuid}。
* @return UUID
*/
public UUID getSiteUuid() { public UUID getSiteUuid() {
return this.siteUuid; return this.siteUuid;
} }
/**
* 设置 {@code siteUuid}。
*
* @param siteUuid 站点 UUID({@code UUID})
*/
public void setSiteUuid(UUID siteUuid) { public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid; this.siteUuid = siteUuid;
} }
/**
* 获取 {@code parentUuid}。
* @return UUID
*/
public UUID getParentUuid() { public UUID getParentUuid() {
return this.parentUuid; return this.parentUuid;
} }
/**
* 设置 {@code parentUuid}。
*
* @param parentUuid 参数 {@code parentUuid}({@code UUID})
*/
public void setParentUuid(UUID parentUuid) { public void setParentUuid(UUID parentUuid) {
this.parentUuid = parentUuid; this.parentUuid = parentUuid;
} }
/**
* 获取 {@code order}。
* @return 数量/长度
*/
public Integer getOrder() { public Integer getOrder() {
return this.order; return this.order;
} }
/**
* 设置 {@code order}。
*
* @param order 参数 {@code order}({@code Integer})
*/
public void setOrder(Integer order) { public void setOrder(Integer order) {
this.order = order; this.order = order;
} }
/**
* 获取 {@code deviceNumbers}。
* @return 数量/长度
*/
public Integer getDeviceNumbers() { public Integer getDeviceNumbers() {
return this.deviceNumbers; return this.deviceNumbers;
} }
/**
* 设置 {@code deviceNumbers}。
*
* @param numbers 参数 {@code numbers}({@code Integer})
*/
public void setDeviceNumbers(Integer numbers) { public void setDeviceNumbers(Integer numbers) {
this.deviceNumbers = numbers == null ? 0 : numbers; this.deviceNumbers = numbers == null ? 0 : numbers;
} }
public List getChildren() { /**
* 获取 {@code children}。
* @return 设备分组列表,可能为空
*/
public List<DeviceGroup> getChildren() {
return this.children; return this.children;
} }
public void setChildren(List children) { /**
* 设置 {@code children}。
*
* @param children 参数 {@code children}({@code List<DeviceGroup>})
*/
public void setChildren(List<DeviceGroup> children) {
this.children = children; this.children = children;
} }
/**
* 比较当前对象与另一个对象是否相等。
*
* @param uuid 对象 UUID({@code UUID})
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean equals(UUID uuid) { public boolean equals(UUID uuid) {
return this.uuid != null && this.uuid.equals(uuid); return this.uuid != null && this.uuid.equals(uuid);
} }
/**
* 按业务字段比较两个对象的顺序。
*
* 实现要点:包含 3 个条件分支、0 个循环。
*
* @param target 参数 {@code target}({@code Object})
* @return 数量/长度
*/
public int compareTo(Object target) { public int compareTo(Object target) {
UUID targetUuid = null; UUID targetUuid = null;
if (target instanceof UUID) { if (target instanceof UUID) {
@@ -6,19 +6,68 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code DeviceKey}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code deviceSerial}(String):设备序列</li>
* <li>{@code rsa}(String):RSA</li>
* <li>{@code created}(Date):创建时间</li>
* </ul>
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class DeviceKey { public class DeviceKey {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid; private UUID uuid;
/**
* 设备序列;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private String deviceSerial; private String deviceSerial;
/**
* RSA。
*/
private String rsa; private String rsa;
/**
* 创建时间。
*/
private Date created; private Date created;
/**
* 构造 {@code DeviceKey} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public DeviceKey() { public DeviceKey() {
this((String)null, (String)null); this((String)null, (String)null);
} }
/**
* 构造 {@code DeviceKey} 实例。
*
* 实现要点:主要调用:new Date。
*
* @param deviceSerial 参数 {@code deviceSerial}({@code String})
* @param rsa 参数 {@code rsa}({@code String})
*/
public DeviceKey(String deviceSerial, String rsa) { public DeviceKey(String deviceSerial, String rsa) {
this.uuid = UUID.randomUUID(); this.uuid = UUID.randomUUID();
this.created = new Date(); this.created = new Date();
@@ -26,22 +75,44 @@ public class DeviceKey {
this.rsa = rsa; this.rsa = rsa;
} }
/**
* 获取 {@code deviceSerial}。
* @return 字符串结果
*/
public String getDeviceSerial() { public String getDeviceSerial() {
return this.deviceSerial; return this.deviceSerial;
} }
/**
* 设置 {@code deviceSerial}。
*
* @param deviceSerial 参数 {@code deviceSerial}({@code String})
*/
public void setDeviceSerial(String deviceSerial) { public void setDeviceSerial(String deviceSerial) {
this.deviceSerial = deviceSerial; this.deviceSerial = deviceSerial;
} }
/**
* 获取 {@code rsa}。
* @return 字符串结果
*/
public String getRsa() { public String getRsa() {
return this.rsa; return this.rsa;
} }
/**
* 设置 {@code rsa}。
*
* @param rsa 参数 {@code rsa}({@code String})
*/
public void setRsa(String rsa) { public void setRsa(String rsa) {
this.rsa = rsa; this.rsa = rsa;
} }
/**
* 获取 {@code created}。
* @return 字段/派生属性 {@code created} 的值
*/
public Date getCreated() { public Date getCreated() {
return this.created; return this.created;
} }
@@ -17,6 +17,31 @@ import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code DeviceLicense}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code deviceUuid}(UUID):设备UUID</li>
* <li>{@code deviceSerial}(String):设备序列</li>
* <li>{@code siteLicense}(SiteLicense):站点许可证</li>
* <li>{@code childSiteLicense}(SiteLicense):子站点许可证</li>
* <li>{@code site}(Site):站点</li>
* </ul>
*
* 协作对象:{@code SiteLicense、Site、LicenseModel}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
@CompoundIndexes({@CompoundIndex( @CompoundIndexes({@CompoundIndex(
def = "{'site.$id': 1}" def = "{'site.$id': 1}"
@@ -36,33 +61,107 @@ import org.springframework.data.mongodb.core.mapping.Document;
def = "{'childSite.$id': 1, 'site.$id': 1, 'expiry': 1}" def = "{'childSite.$id': 1, 'site.$id': 1, 'expiry': 1}"
)}) )})
public class DeviceLicense { public class DeviceLicense {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid; private UUID uuid;
/**
* 设备UUID;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private UUID deviceUuid; private UUID deviceUuid;
/**
* 设备序列;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private String deviceSerial; private String deviceSerial;
/**
* 站点许可证;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private SiteLicense siteLicense; private SiteLicense siteLicense;
/**
* 子站点许可证;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private SiteLicense childSiteLicense; private SiteLicense childSiteLicense;
/**
* 站点;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private Site site; private Site site;
/**
* 子站点;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private Site childSite; private Site childSite;
/**
* 许可证模型;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private LicenseModel licenseModel; private LicenseModel licenseModel;
/**
* 计划。
*/
private String plan; private String plan;
/**
* 是否autoRenew。
*/
private boolean autoRenew; private boolean autoRenew;
/**
* renew转换为Same模型。
*/
private boolean renewToSameModel; private boolean renewToSameModel;
/**
* activation统计。
*/
private int activationCount; private int activationCount;
/**
* 时间字段;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private Date activatedAt; private Date activatedAt;
/**
* 时间字段;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private Date expiry; private Date expiry;
private List reactivated; /**
* 日期集合。
*/
private List<Date> reactivated;
/**
* 创建时间。
*/
private Date created; private Date created;
/**
* 构造 {@code DeviceLicense} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*
* 实现要点:主要调用:new Date。
*/
public DeviceLicense() { public DeviceLicense() {
this.plan = "standard"; this.plan = "standard";
this.autoRenew = false; this.autoRenew = false;
@@ -71,44 +170,92 @@ public class DeviceLicense {
this.created = new Date(); this.created = new Date();
} }
/**
* 构造 {@code DeviceLicense} 实例。
*
* @param license 参数 {@code license}({@code SiteLicense})
*/
public DeviceLicense(SiteLicense license) { public DeviceLicense(SiteLicense license) {
this((Device)null, (SiteLicense)license); this((Device)null, (SiteLicense)license);
} }
/**
* 构造 {@code DeviceLicense} 实例。
*
* @param license 参数 {@code license}({@code SiteLicense})
* @param plan 参数 {@code plan}({@code String})
*/
public DeviceLicense(SiteLicense license, String plan) { public DeviceLicense(SiteLicense license, String plan) {
this((Device)null, (SiteLicense)license); this((Device)null, (SiteLicense)license);
this.setPlan(plan); this.setPlan(plan);
} }
/**
* 构造 {@code DeviceLicense} 实例。
*
* @param device 设备({@code Device})
*/
public DeviceLicense(Device device) { public DeviceLicense(Device device) {
this(); this();
this.setDevice(device); this.setDevice(device);
} }
/**
* 构造 {@code DeviceLicense} 实例。
*
* @param device 设备({@code Device})
* @param license 参数 {@code license}({@code SiteLicense})
*/
public DeviceLicense(Device device, SiteLicense license) { public DeviceLicense(Device device, SiteLicense license) {
this(); this();
this.setSiteLicense(license); this.setSiteLicense(license);
this.setDevice(device); this.setDevice(device);
} }
/**
* 构造 {@code DeviceLicense} 实例。
*
* @param device 设备({@code Device})
* @param licenseModel 参数 {@code licenseModel}({@code LicenseModel})
*/
public DeviceLicense(Device device, LicenseModel licenseModel) { public DeviceLicense(Device device, LicenseModel licenseModel) {
this(); this();
this.setLicenseModel(licenseModel); this.setLicenseModel(licenseModel);
this.setDevice(device); this.setDevice(device);
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code siteLicense}。
* @return 字段/派生属性 {@code siteLicense} 的值
*/
public SiteLicense getSiteLicense() { public SiteLicense getSiteLicense() {
return this.siteLicense; return this.siteLicense;
} }
/**
* 设置 {@code siteLicense}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param license 参数 {@code license}({@code SiteLicense})
*/
public void setSiteLicense(SiteLicense license) { public void setSiteLicense(SiteLicense license) {
this.siteLicense = license; this.siteLicense = license;
if (license != null) { if (license != null) {
@@ -120,22 +267,46 @@ public class DeviceLicense {
} }
/**
* 获取 {@code childSiteLicense}。
* @return 字段/派生属性 {@code childSiteLicense} 的值
*/
public SiteLicense getChildSiteLicense() { public SiteLicense getChildSiteLicense() {
return this.childSiteLicense; return this.childSiteLicense;
} }
/**
* 设置 {@code childSiteLicense}。
*
* @param license 参数 {@code license}({@code SiteLicense})
*/
public void setChildSiteLicense(SiteLicense license) { public void setChildSiteLicense(SiteLicense license) {
this.childSiteLicense = license; this.childSiteLicense = license;
} }
/**
* 判断 {@code lite}。
* @return 字段/派生属性 {@code lite} 的值
*/
public boolean isLite() { public boolean isLite() {
return this.site.isLite() || this.plan.equals("lite"); return this.site.isLite() || this.plan.equals("lite");
} }
/**
* 获取 {@code site}。
* @return 站点对象;未找到时返回 {@code null}
*/
public Site getSite() { public Site getSite() {
return this.site; return this.site;
} }
/**
* 设置 {@code site}。
*
* 实现要点:包含 2 个条件分支、0 个循环。
*
* @param site 站点/企业({@code Site})
*/
public void setSite(Site site) { public void setSite(Site site) {
if (site == null) { if (site == null) {
this.site = this.childSite = null; this.site = this.childSite = null;
@@ -148,26 +319,56 @@ public class DeviceLicense {
} }
/**
* 获取 {@code childSite}。
* @return 站点对象;未找到时返回 {@code null}
*/
public Site getChildSite() { public Site getChildSite() {
return this.childSite; return this.childSite;
} }
/**
* 设置 {@code childSite}。
*
* @param child 参数 {@code child}({@code Site})
*/
public void setChildSite(Site child) { public void setChildSite(Site child) {
this.childSite = child; this.childSite = child;
} }
/**
* 判断 {@code licenseModel}。
* @return 字段/派生属性 {@code licenseModel} 的值
*/
public boolean hasLicenseModel() { public boolean hasLicenseModel() {
return this.getLicenseModel() != null; return this.getLicenseModel() != null;
} }
/**
* 获取 {@code licenseModel}。
* @return 字段/派生属性 {@code licenseModel} 的值
*/
public LicenseModel getLicenseModel() { public LicenseModel getLicenseModel() {
return this.licenseModel; return this.licenseModel;
} }
/**
* 设置 {@code licenseModel}。
*
* @param licenseModel 参数 {@code licenseModel}({@code LicenseModel})
*/
public void setLicenseModel(LicenseModel licenseModel) { public void setLicenseModel(LicenseModel licenseModel) {
this.setLicenseModel(licenseModel, true); this.setLicenseModel(licenseModel, true);
} }
/**
* 设置许可证模型。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Date。
*
* @param licenseModel 参数 {@code licenseModel}({@code LicenseModel})
* @param setExpiry 参数 {@code setExpiry}({@code boolean})
*/
public void setLicenseModel(LicenseModel licenseModel, boolean setExpiry) { public void setLicenseModel(LicenseModel licenseModel, boolean setExpiry) {
this.licenseModel = licenseModel; this.licenseModel = licenseModel;
if (licenseModel != null && setExpiry) { if (licenseModel != null && setExpiry) {
@@ -176,14 +377,31 @@ public class DeviceLicense {
} }
/**
* 获取 {@code deviceUuid}。
* @return UUID
*/
public UUID getDeviceUuid() { public UUID getDeviceUuid() {
return this.deviceUuid; return this.deviceUuid;
} }
/**
* 设置 {@code deviceUuid}。
*
* @param deviceUuid 设备 UUID({@code UUID})
*/
public void setDeviceUuid(UUID deviceUuid) { public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid; this.deviceUuid = deviceUuid;
} }
/**
* 设置 {@code device}。
*
* 实现要点:包含 8 个条件分支、0 个循环;主要调用:new Date。
*
* @param device 设备({@code Device})
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean setDevice(Device device) { public boolean setDevice(Device device) {
if (this.isExceedActivationCount() && this.beforeExpiry()) { if (this.isExceedActivationCount() && this.beforeExpiry()) {
return false; return false;
@@ -222,42 +440,89 @@ public class DeviceLicense {
} }
} }
/**
* 获取 {@code deviceSerial}。
* @return 字符串结果
*/
public String getDeviceSerial() { public String getDeviceSerial() {
return this.deviceSerial; return this.deviceSerial;
} }
/**
* 设置 {@code deviceSerial}。
*
* @param serialNo 设备序列号({@code String})
*/
public void setDeviceSerial(String serialNo) { public void setDeviceSerial(String serialNo) {
this.deviceSerial = serialNo; this.deviceSerial = serialNo;
} }
/**
* 获取 {@code plan}。
* @return 字符串结果
*/
public String getPlan() { public String getPlan() {
return this.plan; return this.plan;
} }
/**
* 设置 {@code plan}。
*
* @param plan 参数 {@code plan}({@code String})
*/
public void setPlan(String plan) { public void setPlan(String plan) {
this.plan = plan; this.plan = plan;
} }
/**
* 判断 {@code autoRenew}。
* @return 字段/派生属性 {@code autoRenew} 的值
*/
public boolean isAutoRenew() { public boolean isAutoRenew() {
return this.autoRenew; return this.autoRenew;
} }
/**
* 设置 {@code autoRenew}。
*
* @param autoRenew 参数 {@code autoRenew}({@code boolean})
*/
public void setAutoRenew(boolean autoRenew) { public void setAutoRenew(boolean autoRenew) {
this.autoRenew = autoRenew; this.autoRenew = autoRenew;
} }
/**
* 判断 {@code renewToSameModel}。
* @return 字段/派生属性 {@code renewToSameModel} 的值
*/
public boolean isRenewToSameModel() { public boolean isRenewToSameModel() {
return this.renewToSameModel; return this.renewToSameModel;
} }
/**
* 设置 {@code renewToSameModel}。
*
* @param renewToSameModel 参数 {@code renewToSameModel}({@code boolean})
*/
public void setRenewToSameModel(boolean renewToSameModel) { public void setRenewToSameModel(boolean renewToSameModel) {
this.renewToSameModel = renewToSameModel; this.renewToSameModel = renewToSameModel;
} }
/**
* 获取 {@code activationCount}。
* @return 数量/长度
*/
public int getActivationCount() { public int getActivationCount() {
return this.activationCount; return this.activationCount;
} }
/**
* 设置 {@code activationCount}。
*
* 实现要点:包含 2 个条件分支、0 个循环。
*
* @param count 参数 {@code count}({@code int})
*/
public void setActivationCount(int count) { public void setActivationCount(int count) {
if (count < 0) { if (count < 0) {
count = 0; count = 0;
@@ -270,6 +535,11 @@ public class DeviceLicense {
} }
/**
* 重置Activation统计。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*/
public void resetActivationCount() { public void resetActivationCount() {
if (this.isTrial()) { if (this.isTrial()) {
this.setActivationCount(0); this.setActivationCount(0);
@@ -280,22 +550,46 @@ public class DeviceLicense {
} }
/**
* 处理exceedActivation统计。
*
* @param maxActivationCount 参数 {@code maxActivationCount}({@code int})
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean exceedActivationCount(int maxActivationCount) { public boolean exceedActivationCount(int maxActivationCount) {
return this.activationCount > maxActivationCount; return this.activationCount > maxActivationCount;
} }
/**
* 判断 {@code active}。
* @return 字段/派生属性 {@code active} 的值
*/
public boolean isActive() { public boolean isActive() {
return this.activatedAt == null; return this.activatedAt == null;
} }
/**
* 判断 {@code activated}。
* @return 字段/派生属性 {@code activated} 的值
*/
public boolean isActivated() { public boolean isActivated() {
return this.activatedAt != null; return this.activatedAt != null;
} }
/**
* 判断 {@code expired}。
* @return 字段/派生属性 {@code expired} 的值
*/
public boolean isExpired() { public boolean isExpired() {
return !this.beforeExpiry(); return !this.beforeExpiry();
} }
/**
* 判断 {@code extend}。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:new DateTime。
* @return 字段/派生属性 {@code extend} 的值
*/
public boolean canExtend() { public boolean canExtend() {
if (!this.isPerpetual()) { if (!this.isPerpetual()) {
return false; return false;
@@ -311,14 +605,32 @@ public class DeviceLicense {
} }
} }
/**
* 获取 {@code activatedAt}。
* @return 字段/派生属性 {@code activatedAt} 的值
*/
public Date getActivatedAt() { public Date getActivatedAt() {
return this.activatedAt; return this.activatedAt;
} }
/**
* 处理激活。
*
* 实现要点:主要调用:new Date。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public Boolean activate() { public Boolean activate() {
return this.isActivated() ? true : this.setActivatedAt(new Date()); return this.isActivated() ? true : this.setActivatedAt(new Date());
} }
/**
* 设置 {@code activatedAt}。
*
* 实现要点:包含 4 个条件分支、0 个循环。
*
* @param activatedAt 参数 {@code activatedAt}({@code Date})
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public Boolean setActivatedAt(Date activatedAt) { public Boolean setActivatedAt(Date activatedAt) {
if (!this.isActivated()) { if (!this.isActivated()) {
this.activatedAt = activatedAt; this.activatedAt = activatedAt;
@@ -339,71 +651,155 @@ public class DeviceLicense {
} }
} }
/**
* 处理重置。
*/
public void reset() { public void reset() {
this.setDevice((Device)null); this.setDevice((Device)null);
} }
/**
* 获取 {@code expiry}。
* @return 字段/派生属性 {@code expiry} 的值
*/
public Date getExpiry() { public Date getExpiry() {
return this.expiry; return this.expiry;
} }
/**
* 处理beforeExpiry。
*
* 实现要点:主要调用:new Date。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean beforeExpiry() { public boolean beforeExpiry() {
return this.expiry != null && this.expiry.after(new Date()); return this.expiry != null && this.expiry.after(new Date());
} }
/**
* 设置 {@code expiry}。
*
* @param expiryDate 参数 {@code expiryDate}({@code Date})
*/
public void setExpiry(Date expiryDate) { public void setExpiry(Date expiryDate) {
this.expiry = expiryDate; this.expiry = expiryDate;
} }
/**
* 处理extendExpiryDays。
*
* 实现要点:主要调用:new DateTime。
*
* @param days 参数 {@code days}({@code int})
*/
public void extendExpiryDays(int days) { public void extendExpiryDays(int days) {
this.setExpiry((new DateTime()).plusDays(days).toDate()); this.setExpiry((new DateTime()).plusDays(days).toDate());
} }
/**
* 处理过期。
*
* 实现要点:主要调用:new Date。
*/
public void expire() { public void expire() {
this.setExpiry(new Date()); this.setExpiry(new Date());
} }
/**
* 获取 {@code created}。
* @return 字段/派生属性 {@code created} 的值
*/
public Date getCreated() { public Date getCreated() {
return this.created; return this.created;
} }
/**
* 设置 {@code created}。
*
* @param created 参数 {@code created}({@code Date})
*/
public void setCreated(Date created) { public void setCreated(Date created) {
this.created = created; this.created = created;
} }
/**
* 判断 {@code perpetual}。
* @return 字段/派生属性 {@code perpetual} 的值
*/
public boolean isPerpetual() { public boolean isPerpetual() {
return this.licenseModel != null && this.licenseModel.isPerpetual(); return this.licenseModel != null && this.licenseModel.isPerpetual();
} }
/**
* 判断 {@code trial}。
* @return 字段/派生属性 {@code trial} 的值
*/
public boolean isTrial() { public boolean isTrial() {
return this.siteLicense == null || this.licenseModel == null || this.licenseModel.isTrial(); return this.siteLicense == null || this.licenseModel == null || this.licenseModel.isTrial();
} }
/**
* 判断 {@code exceedActivationCount}。
* @return 字段/派生属性 {@code exceedActivationCount} 的值
*/
public boolean isExceedActivationCount() { public boolean isExceedActivationCount() {
int maxCount = this.licenseModel == null ? 2 : this.licenseModel.getMaxActivation(); int maxCount = this.licenseModel == null ? 2 : this.licenseModel.getMaxActivation();
return maxCount > 0 && maxCount <= this.activationCount; return maxCount > 0 && maxCount <= this.activationCount;
} }
/**
* 判断 {@code valid}。
*
* 实现要点:主要调用:new Date。
* @return 字段/派生属性 {@code valid} 的值
*/
public boolean isValid() { public boolean isValid() {
return this.isPerpetual() ? true : (new Date()).before(this.expiry); return this.isPerpetual() ? true : (new Date()).before(this.expiry);
} }
/**
* 判断是否Same许可证模型。
*
* @param licenseModelUuid 许可证型号 UUID({@code UUID})
* @return 字段/派生属性 {@code sameLicenseModel} 的值
*/
public boolean isSameLicenseModel(UUID licenseModelUuid) { public boolean isSameLicenseModel(UUID licenseModelUuid) {
return this.licenseModel != null && this.licenseModel.getUuid().equals(licenseModelUuid); return this.licenseModel != null && this.licenseModel.getUuid().equals(licenseModelUuid);
} }
/**
* 获取 {@code remainingDays}。
*
* 实现要点:主要调用:new Date、new DateTime。
* @return 数量/长度
*/
public int getRemainingDays() { public int getRemainingDays() {
return this.expiry.before(new Date()) ? 0 : McDateTimeUtils.daysBetween(new DateTime(this.expiry), DateTime.now()); return this.expiry.before(new Date()) ? 0 : McDateTimeUtils.daysBetween(new DateTime(this.expiry), DateTime.now());
} }
public List getReactivated() { /**
* 获取 {@code reactivated}。
* @return 日期列表,可能为空
*/
public List<Date> getReactivated() {
return this.reactivated; return this.reactivated;
} }
public void setReactivated(List reactivated) { /**
* 设置 {@code reactivated}。
*
* @param reactivated 参数 {@code reactivated}({@code List<Date>})
*/
public void setReactivated(List<Date> reactivated) {
this.reactivated = reactivated; this.reactivated = reactivated;
} }
/**
* 处理reactivate。
*
* 实现要点:包含 3 个条件分支、0 个循环;主要调用:new ArrayList、new DateTime。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean reactivate() { public boolean reactivate() {
if (this.isPerpetual()) { if (this.isPerpetual()) {
if (this.reactivated == null) { if (this.reactivated == null) {
@@ -421,6 +817,10 @@ public class DeviceLicense {
return false; return false;
} }
/**
* 获取 {@code po}。
* @return 字符串结果
*/
public String getPo() { public String getPo() {
return this.childSiteLicense != null ? this.childSiteLicense.getPo() : (this.siteLicense != null ? this.siteLicense.getPo() : null); return this.childSiteLicense != null ? this.childSiteLicense.getPo() : (this.siteLicense != null ? this.siteLicense.getPo() : null);
} }
@@ -7,66 +7,172 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code DeviceNote}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code deviceUuid}(UUID):设备UUID</li>
* <li>{@code writerUuid}(UUID):writerUUID</li>
* <li>{@code writer}(User):字段 writer</li>
* <li>{@code note}(String):备注</li>
* <li>{@code registeredAt}(Date):时间字段</li>
* </ul>
*
* 协作对象:{@code User}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class DeviceNote { public class DeviceNote {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid; private UUID uuid;
/**
* 设备UUID。
*/
private UUID deviceUuid; private UUID deviceUuid;
/**
* writerUUID。
*/
private UUID writerUuid; private UUID writerUuid;
/**
* 字段 writer;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private User writer; private User writer;
/**
* 备注。
*/
private String note; private String note;
/**
* 时间字段。
*/
private Date registeredAt; private Date registeredAt;
/**
* 初始化对象状态(补齐 UUID/时间戳/默认字段)。
*
* 实现要点:主要调用:new Date。
*/
public void init() { public void init() {
this.setUuid(UUID.randomUUID()); this.setUuid(UUID.randomUUID());
this.setRegisteredAt(new Date()); this.setRegisteredAt(new Date());
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code deviceUuid}。
* @return UUID
*/
public UUID getDeviceUuid() { public UUID getDeviceUuid() {
return this.deviceUuid; return this.deviceUuid;
} }
/**
* 设置 {@code deviceUuid}。
*
* @param deviceUuid 设备 UUID({@code UUID})
*/
public void setDeviceUuid(UUID deviceUuid) { public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid; this.deviceUuid = deviceUuid;
} }
/**
* 获取 {@code writerUuid}。
* @return UUID
*/
public UUID getWriterUuid() { public UUID getWriterUuid() {
return this.writerUuid; return this.writerUuid;
} }
/**
* 设置 {@code writerUuid}。
*
* @param writerUuid 参数 {@code writerUuid}({@code UUID})
*/
public void setWriterUuid(UUID writerUuid) { public void setWriterUuid(UUID writerUuid) {
this.writerUuid = writerUuid; this.writerUuid = writerUuid;
} }
/**
* 获取 {@code writer}。
* @return 用户对象;未找到时返回 {@code null}
*/
public User getWriter() { public User getWriter() {
return this.writer; return this.writer;
} }
/**
* 设置 {@code writer}。
*
* @param writer 参数 {@code writer}({@code User})
*/
public void setWriter(User writer) { public void setWriter(User writer) {
this.writer = writer; this.writer = writer;
} }
/**
* 获取 {@code note}。
* @return 字符串结果
*/
public String getNote() { public String getNote() {
return this.note; return this.note;
} }
/**
* 设置 {@code note}。
*
* @param note 参数 {@code note}({@code String})
*/
public void setNote(String note) { public void setNote(String note) {
this.note = note; this.note = note;
} }
/**
* 获取 {@code registeredAt}。
* @return 字段/派生属性 {@code registeredAt} 的值
*/
public Date getRegisteredAt() { public Date getRegisteredAt() {
return this.registeredAt; return this.registeredAt;
} }
/**
* 设置 {@code registeredAt}。
*
* @param registeredAt 参数 {@code registeredAt}({@code Date})
*/
public void setRegisteredAt(Date registeredAt) { public void setRegisteredAt(Date registeredAt) {
this.registeredAt = registeredAt; this.registeredAt = registeredAt;
} }
@@ -16,61 +16,178 @@ import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code DeviceProfile}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code siteUuid}(UUID):用户所属站点 UUID</li>
* <li>{@code deviceProfileGroup}(DeviceProfileGroup):设备配置档案分组</li>
* <li>{@code writerUuid}(UUID):writerUUID</li>
* <li>{@code isGlobal}(boolean):判断是否Global</li>
* <li>{@code status}(DbObject):状态</li>
* <li>{@code apps}(ProfileApps):应用列表</li>
* </ul>
*
* 协作对象:{@code DeviceProfileGroup、DbObject、ProfileApps、ProfileScope、User}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
@CompoundIndex( @CompoundIndex(
def = "{'deviceProfileGroup.uuid': 1}" def = "{'deviceProfileGroup.uuid': 1}"
) )
public class DeviceProfile extends GeneralProfile { public class DeviceProfile extends GeneralProfile {
/**
* 用户所属站点 UUID;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private UUID siteUuid; private UUID siteUuid;
/**
* 设备配置档案分组;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private DeviceProfileGroup deviceProfileGroup; private DeviceProfileGroup deviceProfileGroup;
/**
* writerUUID。
*/
private UUID writerUuid; private UUID writerUuid;
/**
* 判断是否Global。
*/
private boolean isGlobal; private boolean isGlobal;
/**
* 状态。
*/
private DbObject status; private DbObject status;
/**
* 应用列表。
*/
private ProfileApps apps; private ProfileApps apps;
private List otas; /**
* UUID集合。
*/
private List<UUID> otas;
/**
* 文件列表。
*/
private DbObject files; private DbObject files;
/**
* 范围。
*/
private ProfileScope scope; private ProfileScope scope;
private List sequence; /**
* UUID集合。
*/
private List<UUID> sequence;
/**
* 字段 progress;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private DbObject progress; private DbObject progress;
/**
* 字段 reference;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private DbObject reference; private DbObject reference;
/**
* 分组UUID;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private UUID groupUuid; private UUID groupUuid;
/**
* 字段 writer;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private User writer; private User writer;
/**
* need旧格式化;Gson 序列化控制;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Expose(serialize = false) @Transient}。
*/
@Expose( @Expose(
serialize = false serialize = false
) )
@Transient @Transient
private boolean needOldFormat = false; private boolean needOldFormat = false;
/**
* 获取 {@code siteUuid}。
* @return UUID
*/
public UUID getSiteUuid() { public UUID getSiteUuid() {
return this.siteUuid; return this.siteUuid;
} }
/**
* 判断 {@code global}。
* @return 字段/派生属性 {@code global} 的值
*/
public boolean isGlobal() { public boolean isGlobal() {
return this.isGlobal; return this.isGlobal;
} }
/**
* 设置 {@code isGlobal}。
*
* @param isGlobal 参数 {@code isGlobal}({@code boolean})
*/
public void setIsGlobal(boolean isGlobal) { public void setIsGlobal(boolean isGlobal) {
this.isGlobal = isGlobal; this.isGlobal = isGlobal;
} }
/**
* 获取 {@code groupUuid}。
* @return UUID
*/
public UUID getGroupUuid() { public UUID getGroupUuid() {
return this.groupUuid; return this.groupUuid;
} }
/**
* 设置 {@code groupUuid}。
*
* @param groupUuid 分组 UUID({@code UUID})
*/
public void setGroupUuid(UUID groupUuid) { public void setGroupUuid(UUID groupUuid) {
this.groupUuid = groupUuid; this.groupUuid = groupUuid;
} }
/**
* 获取 {@code deviceProfileGroup}。
* @return 字段/派生属性 {@code deviceProfileGroup} 的值
*/
public DeviceProfileGroup getDeviceProfileGroup() { public DeviceProfileGroup getDeviceProfileGroup() {
return this.deviceProfileGroup; return this.deviceProfileGroup;
} }
/**
* 设置 {@code deviceProfileGroup}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param deviceProfileGroup 参数 {@code deviceProfileGroup}({@code DeviceProfileGroup})
*/
public void setDeviceProfileGroup(DeviceProfileGroup deviceProfileGroup) { public void setDeviceProfileGroup(DeviceProfileGroup deviceProfileGroup) {
this.deviceProfileGroup = deviceProfileGroup; this.deviceProfileGroup = deviceProfileGroup;
if (deviceProfileGroup == null) { if (deviceProfileGroup == null) {
@@ -79,7 +196,13 @@ public class DeviceProfile extends GeneralProfile {
} }
public Set getFileUUids() { /**
* 获取 {@code fileUUids}。
*
* 实现要点:包含 3 个条件分支、0 个循环;主要调用:new HashSet。
* @return UUID列表,可能为空
*/
public Set<UUID> getFileUUids() {
Set<UUID> pushUuids = new HashSet(); Set<UUID> pushUuids = new HashSet();
if (this.files != null && !this.files.isEmpty() && this.files.containsKey("push")) { if (this.files != null && !this.files.isEmpty() && this.files.containsKey("push")) {
List<DbObject> pushes = this.files.getList("push", DbObject.class); List<DbObject> pushes = this.files.getList("push", DbObject.class);
@@ -99,74 +222,153 @@ public class DeviceProfile extends GeneralProfile {
return pushUuids; return pushUuids;
} }
/**
* 应用Order。
* @return 字符串结果
*/
public String applyOrder() { public String applyOrder() {
return this.getProfile().getString("applyOrder", "none"); return this.getProfile().getString("applyOrder", "none");
} }
public List getSequence() { /**
* 获取 {@code sequence}。
* @return UUID列表,可能为空
*/
public List<UUID> getSequence() {
return this.sequence; return this.sequence;
} }
/**
* 判断 {@code sequence}。
* @return 字段/派生属性 {@code sequence} 的值
*/
public boolean hasSequence() { public boolean hasSequence() {
return this.sequence != null && !this.sequence.isEmpty(); return this.sequence != null && !this.sequence.isEmpty();
} }
public void setSequence(List sequence) { /**
* 设置 {@code sequence}。
*
* @param sequence 参数 {@code sequence}({@code List<UUID>})
*/
public void setSequence(List<UUID> sequence) {
this.sequence = sequence; this.sequence = sequence;
} }
/**
* 设置 {@code siteUuid}。
*
* @param siteUuid 站点 UUID({@code UUID})
*/
public void setSiteUuid(UUID siteUuid) { public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid; this.siteUuid = siteUuid;
} }
/**
* 获取 {@code writerUuid}。
* @return UUID
*/
public UUID getWriterUuid() { public UUID getWriterUuid() {
return this.writerUuid; return this.writerUuid;
} }
/**
* 设置 {@code writerUuid}。
*
* @param writerUuid 参数 {@code writerUuid}({@code UUID})
*/
public void setWriterUuid(UUID writerUuid) { public void setWriterUuid(UUID writerUuid) {
this.writerUuid = writerUuid; this.writerUuid = writerUuid;
} }
/**
* 获取 {@code status}。
* @return MongoDB 文档扩展对象
*/
public DbObject getStatus() { public DbObject getStatus() {
return this.status; return this.status;
} }
/**
* 设置 {@code status}。
*
* @param status 状态({@code DbObject})
*/
public void setStatus(DbObject status) { public void setStatus(DbObject status) {
this.status = status; this.status = status;
} }
/**
* 获取 {@code scope}。
* @return 字段/派生属性 {@code scope} 的值
*/
public ProfileScope getScope() { public ProfileScope getScope() {
return this.scope; return this.scope;
} }
/**
* 判断 {@code scope}。
* @return 字段/派生属性 {@code scope} 的值
*/
public boolean hasScope() { public boolean hasScope() {
return this.scope != null && this.scope.hasScoped(); return this.scope != null && this.scope.hasScoped();
} }
/**
* 判断 {@code scopeDeviceGroups}。
* @return 字段/派生属性 {@code scopeDeviceGroups} 的值
*/
public boolean hasScopeDeviceGroups() { public boolean hasScopeDeviceGroups() {
return this.scope != null && this.scope.getGroup() != null && !this.scope.getGroup().isEmpty(); return this.scope != null && this.scope.getGroup() != null && !this.scope.getGroup().isEmpty();
} }
public Set getScopedDeviceGroups() { /**
* 获取 {@code scopedDeviceGroups}。
* @return UUID列表,可能为空
*/
public Set<UUID> getScopedDeviceGroups() {
return this.scope == null ? null : this.scope.getGroup(); return this.scope == null ? null : this.scope.getGroup();
} }
public Set getScopedDevice() { /**
* 获取 {@code scopedDevice}。
* @return String列表,可能为空
*/
public Set<String> getScopedDevice() {
return this.scope == null ? null : this.scope.getDevice(); return this.scope == null ? null : this.scope.getDevice();
} }
/**
* 设置 {@code scope}。
*
* @param scope 参数 {@code scope}({@code ProfileScope})
*/
public void setScope(ProfileScope scope) { public void setScope(ProfileScope scope) {
this.scope = scope; this.scope = scope;
} }
/**
* 获取 {@code writer}。
* @return 用户对象;未找到时返回 {@code null}
*/
public User getWriter() { public User getWriter() {
return this.writer; return this.writer;
} }
/**
* 设置 {@code writer}。
*
* @param writer 参数 {@code writer}({@code User})
*/
public void setWriter(User writer) { public void setWriter(User writer) {
this.writer = writer; this.writer = writer;
} }
/**
* 初始化应用列表。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*/
public void initApps() { public void initApps() {
if (this.apps != null) { if (this.apps != null) {
this.apps.initInstallApp(); this.apps.initInstallApp();
@@ -175,11 +377,21 @@ public class DeviceProfile extends GeneralProfile {
} }
/**
* 获取 {@code apps}。
* @return 字段/派生属性 {@code apps} 的值
*/
public ProfileApps getApps() { public ProfileApps getApps() {
return this.apps; return this.apps;
} }
public List getInstallApps() { /**
* 获取 {@code installApps}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
* @return 配置档案Apps.Install应用列表,可能为空
*/
public List<ProfileApps.InstallApp> getInstallApps() {
if (this.apps == null) { if (this.apps == null) {
this.initApps(); this.initApps();
} }
@@ -187,7 +399,13 @@ public class DeviceProfile extends GeneralProfile {
return this.apps == null ? null : this.apps.getInstallApp(); return this.apps == null ? null : this.apps.getInstallApp();
} }
public List getInstallUuids() { /**
* 获取 {@code installUuids}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
* @return UUID列表,可能为空
*/
public List<UUID> getInstallUuids() {
if (this.apps == null) { if (this.apps == null) {
this.initApps(); this.initApps();
} }
@@ -195,6 +413,14 @@ public class DeviceProfile extends GeneralProfile {
return this.apps != null ? this.apps.getInstallUuids() : null; return this.apps != null ? this.apps.getInstallUuids() : null;
} }
/**
* 获取Install应用。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param packageName 参数 {@code packageName}({@code String})
* @return 字段/派生属性 {@code installApp} 的值
*/
public ProfileApps.InstallApp getInstallApp(String packageName) { public ProfileApps.InstallApp getInstallApp(String packageName) {
if (this.apps == null) { if (this.apps == null) {
this.initApps(); this.initApps();
@@ -203,18 +429,37 @@ public class DeviceProfile extends GeneralProfile {
return this.apps != null ? this.apps.getInstallApp(packageName) : null; return this.apps != null ? this.apps.getInstallApp(packageName) : null;
} }
/**
* 设置 {@code apps}。
*
* @param apps 参数 {@code apps}({@code ProfileApps})
*/
public void setApps(ProfileApps apps) { public void setApps(ProfileApps apps) {
this.apps = apps; this.apps = apps;
} }
/**
* 处理need旧格式化。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean needOldFormat() { public boolean needOldFormat() {
return this.needOldFormat; return this.needOldFormat;
} }
/**
* 设置 {@code needOldFormat}。
*
* @param need 参数 {@code need}({@code boolean})
*/
public void setNeedOldFormat(boolean need) { public void setNeedOldFormat(boolean need) {
this.needOldFormat = need; this.needOldFormat = need;
} }
/**
* 设置转换为旧格式化。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*/
public void setToOldFormat() { public void setToOldFormat() {
if (this.apps != null) { if (this.apps != null) {
this.apps.setToOldFormat(); this.apps.setToOldFormat();
@@ -222,50 +467,106 @@ public class DeviceProfile extends GeneralProfile {
} }
public List getWhiteListPackages() { /**
* 获取 {@code whiteListPackages}。
* @return String列表,可能为空
*/
public List<String> getWhiteListPackages() {
return this.apps != null ? this.apps.getPackageList(this.apps.getWhiteList()) : null; return this.apps != null ? this.apps.getPackageList(this.apps.getWhiteList()) : null;
} }
public List getBlackListPackages() { /**
* 获取 {@code blackListPackages}。
* @return String列表,可能为空
*/
public List<String> getBlackListPackages() {
return this.apps != null ? this.apps.getPackageList(this.apps.getWhiteList()) : null; return this.apps != null ? this.apps.getPackageList(this.apps.getWhiteList()) : null;
} }
public List getOtas() { /**
* 获取 {@code otas}。
* @return UUID列表,可能为空
*/
public List<UUID> getOtas() {
return this.otas; return this.otas;
} }
public void setOtas(List otas) { /**
* 设置 {@code otas}。
*
* @param otas 参数 {@code otas}({@code List<UUID>})
*/
public void setOtas(List<UUID> otas) {
this.otas = otas; this.otas = otas;
} }
/**
* 检查构建日期。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean checkBuildDate() { public boolean checkBuildDate() {
return this.getSettingAsBoolean("otas", "checkBuildDate", false); return this.getSettingAsBoolean("otas", "checkBuildDate", false);
} }
/**
* 获取 {@code files}。
* @return MongoDB 文档扩展对象
*/
public DbObject getFiles() { public DbObject getFiles() {
return this.files; return this.files;
} }
/**
* 设置 {@code files}。
*
* @param files 参数 {@code files}({@code DbObject})
*/
public void setFiles(DbObject files) { public void setFiles(DbObject files) {
this.files = files; this.files = files;
} }
/**
* 获取 {@code progress}。
* @return MongoDB 文档扩展对象
*/
public DbObject getProgress() { public DbObject getProgress() {
return this.progress; return this.progress;
} }
/**
* 设置 {@code progress}。
*
* @param progress 参数 {@code progress}({@code DbObject})
*/
public void setProgress(DbObject progress) { public void setProgress(DbObject progress) {
this.progress = progress; this.progress = progress;
} }
/**
* 获取 {@code reference}。
* @return MongoDB 文档扩展对象
*/
public DbObject getReference() { public DbObject getReference() {
return this.reference; return this.reference;
} }
/**
* 设置 {@code reference}。
*
* @param reference 参数 {@code reference}({@code DbObject})
*/
public void setReference(DbObject reference) { public void setReference(DbObject reference) {
this.reference = reference; this.reference = reference;
} }
/**
* 设置Reference。
*
* 实现要点:包含 3 个条件分支、0 个循环;主要调用:remove、new DbObject。
*
* @param key 键/配置项({@code String})
* @param data 参数 {@code data}({@code Object})
*/
public void setReference(String key, Object data) { public void setReference(String key, Object data) {
if (data == null) { if (data == null) {
if (this.reference != null) { if (this.reference != null) {
@@ -279,6 +580,11 @@ public class DeviceProfile extends GeneralProfile {
} }
/**
* 处理unset日期时间设置列表。
*
* 实现要点:包含 3 个条件分支、0 个循环;主要调用:remove。
*/
public void unsetDateTimeSettings() { public void unsetDateTimeSettings() {
DbObject settings = this.getSettingsCategory(new String[]{"system", "dateTime"}); DbObject settings = this.getSettingsCategory(new String[]{"system", "dateTime"});
if (settings != null) { if (settings != null) {
@@ -295,6 +601,11 @@ public class DeviceProfile extends GeneralProfile {
} }
/**
* 转换Custom设置列表用于设备。
*
* 实现要点:包含 6 个条件分支、1 个循环;主要调用:new DbObject、remove。
*/
public void convertCustomSettingsForDevice() { public void convertCustomSettingsForDevice() {
String[] categories = new String[]{"systemProperties", "globalSettings", "systemSettings", "secureSettings"}; String[] categories = new String[]{"systemProperties", "globalSettings", "systemSettings", "secureSettings"};
@@ -327,14 +638,25 @@ public class DeviceProfile extends GeneralProfile {
} }
/**
* 移除If号范围。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean removeIfNoScope() { public boolean removeIfNoScope() {
return this.getProfile().getBoolean("removeIfNoScope", false); return this.getProfile().getBoolean("removeIfNoScope", false);
} }
/**
* 处理unscopeIfApplied。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean unscopeIfApplied() { public boolean unscopeIfApplied() {
return this.getProfile().getBoolean("unscopeIfApplied", false); return this.getProfile().getBoolean("unscopeIfApplied", false);
} }
/**
* 处理minify。
*/
public void minify() { public void minify() {
super.minify(); super.minify();
this.deviceProfileGroup = null; this.deviceProfileGroup = null;
@@ -343,6 +665,10 @@ public class DeviceProfile extends GeneralProfile {
this.writer = null; this.writer = null;
} }
/**
* 处理clone。
* @return 设备配置档案;未找到时返回 {@code null}
*/
public DeviceProfile clone() { public DeviceProfile clone() {
return (DeviceProfile)McJsonUtils.clone(this); return (DeviceProfile)McJsonUtils.clone(this);
} }
@@ -6,52 +6,136 @@ import java.util.UUID;
import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code DeviceProfileGroup}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code siteUuid}(UUID):用户所属站点 UUID</li>
* <li>{@code parentUuid}(UUID):父级UUID</li>
* <li>{@code order}(Integer):字段 order</li>
* <li>{@code deviceProfileNumbers}(Long):设备配置档案Numbers</li>
* <li>{@code children}(List<DeviceProfileGroup>):子级</li>
* </ul>
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class DeviceProfileGroup extends GeneralProfile { public class DeviceProfileGroup extends GeneralProfile {
/**
* 用户所属站点 UUID。
*/
private UUID siteUuid; private UUID siteUuid;
/**
* 父级UUID。
*/
private UUID parentUuid; private UUID parentUuid;
/**
* 字段 order。
*/
private Integer order; private Integer order;
/**
* 设备配置档案Numbers;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private Long deviceProfileNumbers; private Long deviceProfileNumbers;
private List children; /**
* 子级。
*/
private List<DeviceProfileGroup> children;
/**
* 获取 {@code siteUuid}。
* @return UUID
*/
public UUID getSiteUuid() { public UUID getSiteUuid() {
return this.siteUuid; return this.siteUuid;
} }
/**
* 设置 {@code siteUuid}。
*
* @param siteUuid 站点 UUID({@code UUID})
*/
public void setSiteUuid(UUID siteUuid) { public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid; this.siteUuid = siteUuid;
} }
/**
* 获取 {@code parentUuid}。
* @return UUID
*/
public UUID getParentUuid() { public UUID getParentUuid() {
return this.parentUuid; return this.parentUuid;
} }
/**
* 设置 {@code parentUuid}。
*
* @param parentUuid 参数 {@code parentUuid}({@code UUID})
*/
public void setParentUuid(UUID parentUuid) { public void setParentUuid(UUID parentUuid) {
this.parentUuid = parentUuid; this.parentUuid = parentUuid;
} }
/**
* 获取 {@code order}。
* @return 数量/长度
*/
public Integer getOrder() { public Integer getOrder() {
return this.order; return this.order;
} }
/**
* 设置 {@code order}。
*
* @param order 参数 {@code order}({@code Integer})
*/
public void setOrder(Integer order) { public void setOrder(Integer order) {
this.order = order; this.order = order;
} }
/**
* 获取 {@code deviceProfileNumbers}。
* @return 数量/长度
*/
public Long getDeviceProfileNumbers() { public Long getDeviceProfileNumbers() {
return this.deviceProfileNumbers; return this.deviceProfileNumbers;
} }
/**
* 设置 {@code deviceProfileNumbers}。
*
* @param numbers 参数 {@code numbers}({@code Long})
*/
public void setDeviceProfileNumbers(Long numbers) { public void setDeviceProfileNumbers(Long numbers) {
this.deviceProfileNumbers = numbers; this.deviceProfileNumbers = numbers;
} }
public List getChildren() { /**
* 获取 {@code children}。
* @return 设备配置档案分组列表,可能为空
*/
public List<DeviceProfileGroup> getChildren() {
return this.children; return this.children;
} }
public void setChildren(List children) { /**
* 设置 {@code children}。
*
* @param children 参数 {@code children}({@code List<DeviceProfileGroup>})
*/
public void setChildren(List<DeviceProfileGroup> children) {
this.children = children; this.children = children;
} }
} }
@@ -11,6 +11,31 @@ import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code DeviceProfileState}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code STATE_IN_PROGRESS}(String):字段 STATE_IN_PROGRESS</li>
* <li>{@code STATE_DONE}(String):字段 STATE_DONE</li>
* <li>{@code STATE_UNKNWON}(String):字段 STATE_UNKNWON</li>
* <li>{@code scoped}(Scoped):字段 scoped</li>
* <li>{@code updated}(long):最后更新时间</li>
* <li>{@code state}(String):状态</li>
* </ul>
*
* 协作对象:{@code Scoped、DeviceReport}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
@CompoundIndexes({@CompoundIndex( @CompoundIndexes({@CompoundIndex(
def = "{'_id.deviceUuid': 1}" def = "{'_id.deviceUuid': 1}"
@@ -18,103 +43,238 @@ import org.springframework.data.mongodb.core.mapping.Document;
def = "{'_id.profileUuid': 1}" def = "{'_id.profileUuid': 1}"
)}) )})
public class DeviceProfileState { public class DeviceProfileState {
/**
* 字段 STATE_IN_PROGRESS。
*/
public static final String STATE_IN_PROGRESS = "in_progress"; public static final String STATE_IN_PROGRESS = "in_progress";
/**
* 字段 STATE_DONE。
*/
public static final String STATE_DONE = "done"; public static final String STATE_DONE = "done";
/**
* 字段 STATE_UNKNWON。
*/
public static final String STATE_UNKNWON = "unknown"; public static final String STATE_UNKNWON = "unknown";
/**
* 字段 scoped;MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private Scoped scoped; private Scoped scoped;
/**
* 最后更新时间。
*/
private long updated = -1L; private long updated = -1L;
/**
* 状态;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private String state = "unknown"; private String state = "unknown";
/**
* 应用第一状态。
*/
private String applyFirstState = "unknown"; private String applyFirstState = "unknown";
/**
* 字段 applied;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private long applied; private long applied;
/**
* 报表;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private DeviceReport report; private DeviceReport report;
/**
* 构造 {@code DeviceProfileState} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public DeviceProfileState() { public DeviceProfileState() {
} }
/**
* 构造 {@code DeviceProfileState} 实例。
*
* 实现要点:主要调用:new Scoped、new Date。
*
* @param device 设备({@code Device})
* @param profile 设备配置档案({@code DeviceProfile})
*/
public DeviceProfileState(Device device, DeviceProfile profile) { public DeviceProfileState(Device device, DeviceProfile profile) {
this.scoped = new Scoped(profile.getUuid(), device.getUuid()); this.scoped = new Scoped(profile.getUuid(), device.getUuid());
this.updated = profile.getUpdated().getTime(); this.updated = profile.getUpdated().getTime();
this.applied = (new Date()).getTime(); this.applied = (new Date()).getTime();
} }
/**
* 构造 {@code DeviceProfileState} 实例。
*
* @param report 参数 {@code report}({@code DeviceReport})
*/
public DeviceProfileState(DeviceReport report) { public DeviceProfileState(DeviceReport report) {
this.setReport(report); this.setReport(report);
} }
/**
* 获取 {@code scoped}。
* @return 字段/派生属性 {@code scoped} 的值
*/
public Scoped getScoped() { public Scoped getScoped() {
return this.scoped; return this.scoped;
} }
/**
* 设置 {@code scoped}。
*
* @param scoped 参数 {@code scoped}({@code Scoped})
*/
public void setScoped(Scoped scoped) { public void setScoped(Scoped scoped) {
this.scoped = scoped; this.scoped = scoped;
} }
/**
* 获取 {@code profileUuid}。
* @return UUID
*/
public UUID getProfileUuid() { public UUID getProfileUuid() {
return this.getScoped().getProfileUuid(); return this.getScoped().getProfileUuid();
} }
/**
* 获取 {@code deviceUuid}。
* @return UUID
*/
public UUID getDeviceUuid() { public UUID getDeviceUuid() {
return this.getScoped().getDeviceUuid(); return this.getScoped().getDeviceUuid();
} }
/**
* 获取 {@code updated}。
* @return 数量/长度
*/
public long getUpdated() { public long getUpdated() {
return this.updated; return this.updated;
} }
/**
* 设置 {@code updated}。
*
* @param updated 参数 {@code updated}({@code long})
*/
public void setUpdated(long updated) { public void setUpdated(long updated) {
this.updated = updated; this.updated = updated;
} }
/**
* 获取 {@code state}。
* @return 字符串结果
*/
public String getState() { public String getState() {
return this.state; return this.state;
} }
/**
* 判断 {@code done}。
* @return 字段/派生属性 {@code done} 的值
*/
public boolean isDone() { public boolean isDone() {
return this.state == null || this.state.equals("done"); return this.state == null || this.state.equals("done");
} }
/**
* 设置 {@code state}。
*
* @param state 参数 {@code state}({@code String})
*/
public void setState(String state) { public void setState(String state) {
this.state = state; this.state = state;
} }
/**
* 获取 {@code applyFirstState}。
* @return 字符串结果
*/
public String getApplyFirstState() { public String getApplyFirstState() {
return this.applyFirstState; return this.applyFirstState;
} }
/**
* 判断 {@code applyFirstDone}。
* @return 字段/派生属性 {@code applyFirstDone} 的值
*/
public boolean isApplyFirstDone() { public boolean isApplyFirstDone() {
return this.applyFirstState != null && this.applyFirstState.equals("done"); return this.applyFirstState != null && this.applyFirstState.equals("done");
} }
/**
* 设置 {@code applyFirstState}。
*
* @param applyFirstState 参数 {@code applyFirstState}({@code String})
*/
public void setApplyFirstState(String applyFirstState) { public void setApplyFirstState(String applyFirstState) {
this.applyFirstState = applyFirstState; this.applyFirstState = applyFirstState;
} }
/**
* 获取 {@code applied}。
* @return 数量/长度
*/
public long getApplied() { public long getApplied() {
return this.applied; return this.applied;
} }
/**
* 设置 {@code applied}。
*
* @param applied 参数 {@code applied}({@code long})
*/
public void setApplied(long applied) { public void setApplied(long applied) {
this.applied = applied; this.applied = applied;
this.setState("done"); this.setState("done");
} }
/**
* 设置Applied。
*
* @param applied 参数 {@code applied}({@code long})
* @param state 参数 {@code state}({@code String})
*/
public void setApplied(long applied, String state) { public void setApplied(long applied, String state) {
this.state = state; this.state = state;
this.applied = applied; this.applied = applied;
} }
/**
* 设置Applied。
*
* 实现要点:主要调用:new Date。
*/
public void setApplied() { public void setApplied() {
this.applied = (new Date()).getTime(); this.applied = (new Date()).getTime();
} }
/**
* 获取 {@code report}。
* @return 字段/派生属性 {@code report} 的值
*/
public DeviceReport getReport() { public DeviceReport getReport() {
return this.report; return this.report;
} }
/**
* 设置 {@code report}。
*
* 实现要点:主要调用:new Scoped。
*
* @param report 参数 {@code report}({@code DeviceReport})
*/
public void setReport(DeviceReport report) { public void setReport(DeviceReport report) {
this.report = report; this.report = report;
DbObject profile = report.getProperties().getDbObject(new String[]{"deviceProfile"}); DbObject profile = report.getProperties().getDbObject(new String[]{"deviceProfile"});
@@ -124,30 +284,81 @@ public class DeviceProfileState {
this.setState("done"); this.setState("done");
} }
/**
* 【领域模型】{@code Scoped}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code profileUuid}(UUID):配置档案UUID</li>
* <li>{@code deviceUuid}(UUID):设备UUID</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public static class Scoped implements Serializable { public static class Scoped implements Serializable {
/**
* 配置档案UUID。
*/
private UUID profileUuid; private UUID profileUuid;
/**
* 设备UUID。
*/
private UUID deviceUuid; private UUID deviceUuid;
/**
* 构造 {@code Scoped} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public Scoped() { public Scoped() {
} }
/**
* 构造 {@code Scoped} 实例。
*
* @param profileUuid 配置档案 UUID({@code UUID})
* @param deviceUuid 设备 UUID({@code UUID})
*/
public Scoped(UUID profileUuid, UUID deviceUuid) { public Scoped(UUID profileUuid, UUID deviceUuid) {
this.profileUuid = profileUuid; this.profileUuid = profileUuid;
this.deviceUuid = deviceUuid; this.deviceUuid = deviceUuid;
} }
/**
* 获取 {@code profileUuid}。
* @return UUID
*/
public UUID getProfileUuid() { public UUID getProfileUuid() {
return this.profileUuid; return this.profileUuid;
} }
/**
* 设置 {@code profileUuid}。
*
* @param profileUuid 配置档案 UUID({@code UUID})
*/
public void setProfileUuid(UUID profileUuid) { public void setProfileUuid(UUID profileUuid) {
this.profileUuid = profileUuid; this.profileUuid = profileUuid;
} }
/**
* 获取 {@code deviceUuid}。
* @return UUID
*/
public UUID getDeviceUuid() { public UUID getDeviceUuid() {
return this.deviceUuid; return this.deviceUuid;
} }
/**
* 设置 {@code deviceUuid}。
*
* @param deviceUuid 设备 UUID({@code UUID})
*/
public void setDeviceUuid(UUID deviceUuid) { public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid; this.deviceUuid = deviceUuid;
} }
@@ -53,43 +53,89 @@ public class DeviceReport {
/** 云端服务端持久化写入数据库的系统时间戳 */ /** 云端服务端持久化写入数据库的系统时间戳 */
private Date recordedAt; private Date recordedAt;
/**
* 构造 {@code DeviceReport} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public DeviceReport() { public DeviceReport() {
this.setRecordedAt(); this.setRecordedAt();
} }
/**
* 初始化对象状态(补齐 UUID/时间戳/默认字段)。
*
* 实现要点:主要调用:new Date。
*/
public void init() { public void init() {
this.setUuid(UUID.randomUUID()); this.setUuid(UUID.randomUUID());
this.setReportedAt(new Date()); this.setReportedAt(new Date());
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code deviceUuid}。
* @return UUID
*/
public UUID getDeviceUuid() { public UUID getDeviceUuid() {
return this.deviceUuid; return this.deviceUuid;
} }
/**
* 设置 {@code deviceUuid}。
*
* @param deviceUuid 设备 UUID({@code UUID})
*/
public void setDeviceUuid(UUID deviceUuid) { public void setDeviceUuid(UUID deviceUuid) {
this.deviceUuid = deviceUuid; this.deviceUuid = deviceUuid;
} }
/**
* 获取 {@code serialNo}。
* @return 字符串结果
*/
public String getSerialNo() { public String getSerialNo() {
return this.serialNo; return this.serialNo;
} }
/**
* 设置 {@code serialNo}。
*
* @param serialNo 设备序列号({@code String})
*/
public void setSerialNo(String serialNo) { public void setSerialNo(String serialNo) {
this.serialNo = serialNo; this.serialNo = serialNo;
} }
/**
* 判断 {@code properties}。
* @return 字段/派生属性 {@code properties} 的值
*/
public boolean hasProperties() { public boolean hasProperties() {
return this.properties != null && !this.properties.isEmpty(); return this.properties != null && !this.properties.isEmpty();
} }
/**
* 获取 {@code properties}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getProperties() { public DbObject getProperties() {
if (this.properties == null) { if (this.properties == null) {
this.properties = new DbObject(); this.properties = new DbObject();
@@ -98,38 +144,82 @@ public class DeviceReport {
return this.properties; return this.properties;
} }
/**
* 设置 {@code properties}。
*
* @param properties 参数 {@code properties}({@code DbObject})
*/
public void setProperties(DbObject properties) { public void setProperties(DbObject properties) {
this.properties = properties; this.properties = properties;
} }
/**
* 获取 {@code reportedAt}。
* @return 字段/派生属性 {@code reportedAt} 的值
*/
public Date getReportedAt() { public Date getReportedAt() {
return this.reportedAt; return this.reportedAt;
} }
/**
* 设置 {@code reportedAt}。
*
* @param reportedAt 参数 {@code reportedAt}({@code Date})
*/
public void setReportedAt(Date reportedAt) { public void setReportedAt(Date reportedAt) {
this.reportedAt = reportedAt; this.reportedAt = reportedAt;
} }
/**
* 获取 {@code recordedAt}。
* @return 字段/派生属性 {@code recordedAt} 的值
*/
public Date getRecordedAt() { public Date getRecordedAt() {
return this.recordedAt; return this.recordedAt;
} }
/**
* 设置 {@code recordedAt}。
*
* @param recordedAt 参数 {@code recordedAt}({@code Date})
*/
public void setRecordedAt(Date recordedAt) { public void setRecordedAt(Date recordedAt) {
this.recordedAt = recordedAt; this.recordedAt = recordedAt;
} }
/**
* 设置RecordedAt。
*
* 实现要点:主要调用:new Date。
*/
public void setRecordedAt() { public void setRecordedAt() {
this.recordedAt = new Date(); this.recordedAt = new Date();
} }
/**
* 设置Property。
*
* @param key 键/配置项({@code String})
* @param val 参数 {@code val}({@code Object})
*/
public void setProperty(String key, Object val) { public void setProperty(String key, Object val) {
this.getProperties().append(key, val); this.getProperties().append(key, val);
} }
/**
* 获取Property。
*
* @param key 键/配置项({@code String})
* @return 字段/派生属性 {@code property} 的值
*/
public Object getProperty(String key) { public Object getProperty(String key) {
return this.getProperties().get(key); return this.getProperties().get(key);
} }
/**
* 返回对象的可读字符串表示。
* @return 字符串结果
*/
public String toString() { public String toString() {
return McJsonUtils.toJson(this); return McJsonUtils.toJson(this);
} }
@@ -15,45 +15,126 @@ import java.util.stream.Collectors;
import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Field; import org.springframework.data.mongodb.core.mapping.Field;
/**
* 【领域模型】{@code ProfileApps}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code install}(List<?>):?集合</li>
* <li>{@code installApp}(List<InstallApp>):install应用</li>
* <li>{@code uninstall}(List<DbObject>):数据库Object集合</li>
* <li>{@code appWidget}(List<DbObject>):应用Widget</li>
* <li>{@code widget}(List<DbObject>):数据库Object集合</li>
* <li>{@code grantAll}(List<DbObject>):grant全部</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class ProfileApps { public class ProfileApps {
private List install; /**
* ?集合。
*/
private List<?> install;
/**
* install应用;不持久化到 MongoDB,仅运行时使用;Gson 序列化控制。
*
* 注解:{@code @Transient @Expose(serialize = false)}。
*/
@Transient @Transient
@Expose( @Expose(
serialize = false serialize = false
) )
private List installApp; private List<InstallApp> installApp;
private List uninstall; /**
* 数据库Object集合。
*/
private List<DbObject> uninstall;
/**
* 应用Widget;通过 @Field 映射到 MongoDB 字段。
*
* 注解:{@code @SerializedName("add_appwidget") @Field("add_appwidget")}。
*/
@SerializedName("add_appwidget") @SerializedName("add_appwidget")
@Field("add_appwidget") @Field("add_appwidget")
private List appWidget; private List<DbObject> appWidget;
private List widget; /**
* 数据库Object集合。
*/
private List<DbObject> widget;
/**
* grant全部;通过 @Field 映射到 MongoDB 字段。
*
* 注解:{@code @SerializedName("grant_all") @Field("grant_all")}。
*/
@SerializedName("grant_all") @SerializedName("grant_all")
@Field("grant_all") @Field("grant_all")
private List grantAll; private List<DbObject> grantAll;
private List disabled; /**
* 数据库Object集合。
*/
private List<DbObject> disabled;
/**
* Wi-FiOnly;通过 @Field 映射到 MongoDB 字段。
*
* 注解:{@code @SerializedName("wifi_only") @Field("wifi_only")}。
*/
@SerializedName("wifi_only") @SerializedName("wifi_only")
@Field("wifi_only") @Field("wifi_only")
private List wifiOnly; private List<DbObject> wifiOnly;
/**
* white列出;通过 @Field 映射到 MongoDB 字段。
*
* 注解:{@code @SerializedName("white_list") @Field("white_list")}。
*/
@SerializedName("white_list") @SerializedName("white_list")
@Field("white_list") @Field("white_list")
private List whiteList; private List<DbObject> whiteList;
/**
* black列出;通过 @Field 映射到 MongoDB 字段。
*
* 注解:{@code @SerializedName("black_list") @Field("black_list")}。
*/
@SerializedName("black_list") @SerializedName("black_list")
@Field("black_list") @Field("black_list")
private List blackList; private List<DbObject> blackList;
public List getInstall() { /**
* 获取 {@code install}。
* @return ?列表,可能为空
*/
public List<?> getInstall() {
return this.install; return this.install;
} }
public void setInstall(List install) { /**
* 设置 {@code install}。
*
* @param install 参数 {@code install}({@code List<?>})
*/
public void setInstall(List<?> install) {
this.install = install; this.install = install;
} }
/**
* 设置转换为旧格式化。
*/
public void setToOldFormat() { public void setToOldFormat() {
this.install = this.getInstallUuids(); this.install = this.getInstallUuids();
} }
public List getInstallApp() { /**
* 获取 {@code installApp}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
* @return Install应用列表,可能为空
*/
public List<InstallApp> getInstallApp() {
if (this.installApp == null && this.install != null) { if (this.installApp == null && this.install != null) {
this.initInstallApp(); this.initInstallApp();
} }
@@ -61,10 +142,15 @@ public class ProfileApps {
return this.installApp; return this.installApp;
} }
/**
* 初始化Install应用。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:new TypeToken。
*/
public void initInstallApp() { public void initInstallApp() {
if (this.install != null && !this.install.isEmpty()) { if (this.install != null && !this.install.isEmpty()) {
if (this.install.get(0) instanceof InstallApp) { if (this.install.get(0) instanceof InstallApp) {
this.installApp = this.install; this.installApp = (List<InstallApp>)this.install;
} else { } else {
this.installApp = (List)McJsonUtils.toObject(McJsonUtils.toJsonElement(this.install), (new TypeToken() { this.installApp = (List)McJsonUtils.toObject(McJsonUtils.toJsonElement(this.install), (new TypeToken() {
}).getType()); }).getType());
@@ -74,15 +160,32 @@ public class ProfileApps {
} }
public void setInstallApp(List installApp) { /**
* 设置 {@code installApp}。
*
* @param installApp 参数 {@code installApp}({@code List<InstallApp>})
*/
public void setInstallApp(List<InstallApp> installApp) {
this.installApp = installApp; this.installApp = installApp;
} }
/**
* 判断 {@code installApps}。
* @return 字段/派生属性 {@code installApps} 的值
*/
public boolean hasInstallApps() { public boolean hasInstallApps() {
this.getInstallApp(); this.getInstallApp();
return this.installApp != null && !this.installApp.isEmpty(); return this.installApp != null && !this.installApp.isEmpty();
} }
/**
* 获取Install应用。
*
* 实现要点:包含 2 个条件分支、1 个循环。
*
* @param packageName 参数 {@code packageName}({@code String})
* @return 字段/派生属性 {@code installApp} 的值
*/
public InstallApp getInstallApp(String packageName) { public InstallApp getInstallApp(String packageName) {
if (!this.hasInstallApps()) { if (!this.hasInstallApps()) {
return null; return null;
@@ -97,6 +200,14 @@ public class ProfileApps {
} }
} }
/**
* 移除Install应用。
*
* 实现要点:包含 2 个条件分支、1 个循环;主要调用:remove。
*
* @param appUuid 参数 {@code appUuid}({@code UUID})
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean removeInstallApp(UUID appUuid) { public boolean removeInstallApp(UUID appUuid) {
if (this.hasInstallApps()) { if (this.hasInstallApps()) {
Iterator<InstallApp> it = this.installApp.iterator(); Iterator<InstallApp> it = this.installApp.iterator();
@@ -112,83 +223,177 @@ public class ProfileApps {
return false; return false;
} }
public List getInstallUuids() { /**
* 获取 {@code installUuids}。
* @return UUID列表,可能为空
*/
public List<UUID> getInstallUuids() {
return this.installApp != null ? (List)this.installApp.stream().map((app) -> app.getUuid()).collect(Collectors.toList()) : null; return this.installApp != null ? (List)this.installApp.stream().map((app) -> app.getUuid()).collect(Collectors.toList()) : null;
} }
public List getUninstall() { /**
* 获取 {@code uninstall}。
* @return 数据库Object列表,可能为空
*/
public List<DbObject> getUninstall() {
return this.toDbList(this.uninstall); return this.toDbList(this.uninstall);
} }
public void setUninstall(List uninstall) { /**
* 设置 {@code uninstall}。
*
* @param uninstall 参数 {@code uninstall}({@code List<DbObject>})
*/
public void setUninstall(List<DbObject> uninstall) {
this.uninstall = uninstall; this.uninstall = uninstall;
} }
public List getAppWidget() { /**
* 获取 {@code appWidget}。
* @return 数据库Object列表,可能为空
*/
public List<DbObject> getAppWidget() {
return this.appWidget; return this.appWidget;
} }
public void setAppWidget(List addAppWidget) { /**
* 设置 {@code appWidget}。
*
* @param addAppWidget 参数 {@code addAppWidget}({@code List<DbObject>})
*/
public void setAppWidget(List<DbObject> addAppWidget) {
this.appWidget = addAppWidget; this.appWidget = addAppWidget;
} }
public List getWidget() { /**
* 获取 {@code widget}。
* @return 数据库Object列表,可能为空
*/
public List<DbObject> getWidget() {
return this.widget; return this.widget;
} }
public void setWidget(List widget) { /**
* 设置 {@code widget}。
*
* @param widget 参数 {@code widget}({@code List<DbObject>})
*/
public void setWidget(List<DbObject> widget) {
this.widget = widget; this.widget = widget;
} }
public List getGrantAll() { /**
* 获取 {@code grantAll}。
* @return 数据库Object列表,可能为空
*/
public List<DbObject> getGrantAll() {
return this.toDbList(this.grantAll); return this.toDbList(this.grantAll);
} }
public void setGrantAll(List grantAll) { /**
* 设置 {@code grantAll}。
*
* @param grantAll 参数 {@code grantAll}({@code List<DbObject>})
*/
public void setGrantAll(List<DbObject> grantAll) {
this.grantAll = grantAll; this.grantAll = grantAll;
} }
public List getDisabled() { /**
* 获取 {@code disabled}。
* @return 数据库Object列表,可能为空
*/
public List<DbObject> getDisabled() {
return this.toDbList(this.disabled); return this.toDbList(this.disabled);
} }
public void setDisabled(List disabled) { /**
* 设置 {@code disabled}。
*
* @param disabled 参数 {@code disabled}({@code List<DbObject>})
*/
public void setDisabled(List<DbObject> disabled) {
this.disabled = disabled; this.disabled = disabled;
} }
public List getWifiOnly() { /**
* 获取 {@code wifiOnly}。
* @return 数据库Object列表,可能为空
*/
public List<DbObject> getWifiOnly() {
return this.toDbList(this.wifiOnly); return this.toDbList(this.wifiOnly);
} }
public void setWifiOnly(List wifiOnly) { /**
* 设置 {@code wifiOnly}。
*
* @param wifiOnly 参数 {@code wifiOnly}({@code List<DbObject>})
*/
public void setWifiOnly(List<DbObject> wifiOnly) {
this.wifiOnly = wifiOnly; this.wifiOnly = wifiOnly;
} }
public List getWhiteList() { /**
* 获取 {@code whiteList}。
* @return 数据库Object列表,可能为空
*/
public List<DbObject> getWhiteList() {
return this.toDbList(this.whiteList); return this.toDbList(this.whiteList);
} }
public void setWhiteList(List whiteList) { /**
* 设置 {@code whiteList}。
*
* @param whiteList 参数 {@code whiteList}({@code List<DbObject>})
*/
public void setWhiteList(List<DbObject> whiteList) {
this.whiteList = whiteList; this.whiteList = whiteList;
} }
public List getBlackList() { /**
* 获取 {@code blackList}。
* @return 数据库Object列表,可能为空
*/
public List<DbObject> getBlackList() {
return this.toDbList(this.blackList); return this.toDbList(this.blackList);
} }
public void setBlackList(List blackList) { /**
* 设置 {@code blackList}。
*
* @param blackList 参数 {@code blackList}({@code List<DbObject>})
*/
public void setBlackList(List<DbObject> blackList) {
this.blackList = blackList; this.blackList = blackList;
} }
public List getPackageList(List apps) { /**
* 获取Package列出。
*
* @param apps 参数 {@code apps}({@code List<DbObject>})
* @return String列表,可能为空
*/
public List<String> getPackageList(List<DbObject> apps) {
return apps != null ? (List)apps.stream().map((app) -> app.getString("package")).collect(Collectors.toList()) : null; return apps != null ? (List)apps.stream().map((app) -> app.getString("package")).collect(Collectors.toList()) : null;
} }
/**
* 判断 {@code empty}。
* @return 字段/派生属性 {@code empty} 的值
*/
public boolean isEmpty() { public boolean isEmpty() {
return (this.install == null || this.install.isEmpty()) && (this.uninstall == null || this.uninstall.isEmpty()) && (this.appWidget == null || this.appWidget.isEmpty()) && (this.widget == null || this.widget.isEmpty()) && (this.grantAll == null || this.grantAll.isEmpty()) && (this.disabled == null || this.disabled.isEmpty()) && (this.wifiOnly == null || this.wifiOnly.isEmpty()) && (this.whiteList == null || this.whiteList.isEmpty()) && (this.blackList == null || this.blackList.isEmpty()); return (this.install == null || this.install.isEmpty()) && (this.uninstall == null || this.uninstall.isEmpty()) && (this.appWidget == null || this.appWidget.isEmpty()) && (this.widget == null || this.widget.isEmpty()) && (this.grantAll == null || this.grantAll.isEmpty()) && (this.disabled == null || this.disabled.isEmpty()) && (this.wifiOnly == null || this.wifiOnly.isEmpty()) && (this.whiteList == null || this.whiteList.isEmpty()) && (this.blackList == null || this.blackList.isEmpty());
} }
private List toDbList(List list) { /**
* 处理转换为数据库列出。
*
* 实现要点:包含 3 个条件分支、0 个循环;主要调用:new ArrayList、new DbObject。
*
* @param list 参数 {@code list}({@code List<?>})
* @return 数据库Object列表,可能为空
*/
private List<DbObject> toDbList(List<?> list) {
if (list != null && !list.isEmpty()) { if (list != null && !list.isEmpty()) {
List<DbObject> dbList = new ArrayList(); List<DbObject> dbList = new ArrayList();
list.forEach((item) -> { list.forEach((item) -> {
@@ -205,78 +410,196 @@ public class ProfileApps {
} }
} }
/**
* 【领域模型】{@code InstallApp}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code packageName}(String):package名称</li>
* <li>{@code silentInstall}(Boolean):是否silentInstall</li>
* <li>{@code grantAll}(Boolean):grant全部</li>
* <li>{@code startsOnUpdate}(Boolean):starts处理更新</li>
* <li>{@code rebootsOnUpdate}(Boolean):reboots处理更新</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public static class InstallApp { public static class InstallApp {
/**
* 对象唯一标识(MongoDB 主键)。
*/
private UUID uuid; private UUID uuid;
/**
* package名称。
*/
private String packageName; private String packageName;
/**
* 是否silentInstall;通过 @Field 映射到 MongoDB 字段。
*
* 注解:{@code @SerializedName("silent_install") @Field("silent_install")}。
*/
@SerializedName("silent_install") @SerializedName("silent_install")
@Field("silent_install") @Field("silent_install")
private Boolean silentInstall = true; private Boolean silentInstall = true;
/**
* grant全部;通过 @Field 映射到 MongoDB 字段。
*
* 注解:{@code @SerializedName("grant_all") @Field("grant_all")}。
*/
@SerializedName("grant_all") @SerializedName("grant_all")
@Field("grant_all") @Field("grant_all")
private Boolean grantAll = false; private Boolean grantAll = false;
/**
* starts处理更新;通过 @Field 映射到 MongoDB 字段。
*
* 注解:{@code @SerializedName("starts_on_update") @Field("starts_on_update")}。
*/
@SerializedName("starts_on_update") @SerializedName("starts_on_update")
@Field("starts_on_update") @Field("starts_on_update")
private Boolean startsOnUpdate = false; private Boolean startsOnUpdate = false;
/**
* reboots处理更新;通过 @Field 映射到 MongoDB 字段。
*
* 注解:{@code @SerializedName("reboots_on_update") @Field("reboots_on_update")}。
*/
@SerializedName("reboots_on_update") @SerializedName("reboots_on_update")
@Field("reboots_on_update") @Field("reboots_on_update")
private Boolean rebootsOnUpdate = false; private Boolean rebootsOnUpdate = false;
/**
* 构造 {@code InstallApp} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public InstallApp() { public InstallApp() {
} }
/**
* 构造 {@code InstallApp} 实例。
*
* @param appFile 参数 {@code appFile}({@code AppFile})
*/
public InstallApp(AppFile appFile) { public InstallApp(AppFile appFile) {
this.uuid = appFile.getFileUuid(); this.uuid = appFile.getFileUuid();
this.packageName = appFile.getPackageName(); this.packageName = appFile.getPackageName();
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code packageName}。
* @return 字符串结果
*/
public String getPackageName() { public String getPackageName() {
return this.packageName; return this.packageName;
} }
/**
* 设置 {@code packageName}。
*
* @param packageName 参数 {@code packageName}({@code String})
*/
public void setPackageName(String packageName) { public void setPackageName(String packageName) {
this.packageName = packageName; this.packageName = packageName;
} }
/**
* 获取 {@code silentInstall}。
* @return 字段/派生属性 {@code silentInstall} 的值
*/
public Boolean getSilentInstall() { public Boolean getSilentInstall() {
return this.silentInstall; return this.silentInstall;
} }
/**
* 设置 {@code silentInstall}。
*
* @param silentInstall 参数 {@code silentInstall}({@code Boolean})
*/
public void setSilentInstall(Boolean silentInstall) { public void setSilentInstall(Boolean silentInstall) {
this.silentInstall = silentInstall; this.silentInstall = silentInstall;
} }
/**
* 获取 {@code grantAll}。
* @return 字段/派生属性 {@code grantAll} 的值
*/
public Boolean getGrantAll() { public Boolean getGrantAll() {
return this.grantAll; return this.grantAll;
} }
/**
* 设置 {@code grantAll}。
*
* @param grantAll 参数 {@code grantAll}({@code Boolean})
*/
public void setGrantAll(Boolean grantAll) { public void setGrantAll(Boolean grantAll) {
this.grantAll = grantAll; this.grantAll = grantAll;
} }
/**
* 获取 {@code startsOnUpdate}。
* @return 字段/派生属性 {@code startsOnUpdate} 的值
*/
public Boolean getStartsOnUpdate() { public Boolean getStartsOnUpdate() {
return this.startsOnUpdate; return this.startsOnUpdate;
} }
/**
* 设置 {@code startsOnUpdate}。
*
* @param startsOnUpdate 参数 {@code startsOnUpdate}({@code Boolean})
*/
public void setStartsOnUpdate(Boolean startsOnUpdate) { public void setStartsOnUpdate(Boolean startsOnUpdate) {
this.startsOnUpdate = startsOnUpdate; this.startsOnUpdate = startsOnUpdate;
} }
/**
* 获取 {@code rebootsOnUpdate}。
* @return 字段/派生属性 {@code rebootsOnUpdate} 的值
*/
public Boolean getRebootsOnUpdate() { public Boolean getRebootsOnUpdate() {
return this.rebootsOnUpdate; return this.rebootsOnUpdate;
} }
/**
* 设置 {@code rebootsOnUpdate}。
*
* @param rebootsOnUpdate 参数 {@code rebootsOnUpdate}({@code Boolean})
*/
public void setRebootsOnUpdate(Boolean rebootsOnUpdate) { public void setRebootsOnUpdate(Boolean rebootsOnUpdate) {
this.rebootsOnUpdate = rebootsOnUpdate; this.rebootsOnUpdate = rebootsOnUpdate;
} }
/**
* 比较当前对象与另一个对象是否相等。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param obj 参数 {@code obj}({@code Object})
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof InstallApp)) { if (!(obj instanceof InstallApp)) {
return false; return false;
@@ -4,19 +4,62 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
/**
* 【领域模型】{@code ProfileScope}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code group}(Set<UUID>):分组</li>
* <li>{@code device}(Set<String>):设备</li>
* <li>{@code userGroup}(Set<String>):用户分组</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class ProfileScope { public class ProfileScope {
Set group; /**
Set device; * 分组。
Set userGroup; */
Set<UUID> group;
/**
* 设备。
*/
Set<String> device;
/**
* 用户分组。
*/
Set<String> userGroup;
public Set getGroup() { /**
* 获取 {@code group}。
* @return UUID列表,可能为空
*/
public Set<UUID> getGroup() {
return this.group; return this.group;
} }
public void setGroup(Set group) { /**
* 设置 {@code group}。
*
* @param group 分组对象({@code Set<UUID>})
*/
public void setGroup(Set<UUID> group) {
this.group = group; this.group = group;
} }
/**
* 添加分组。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new HashSet。
*
* @param groupUuid 分组 UUID({@code UUID})
*/
public void addGroup(UUID groupUuid) { public void addGroup(UUID groupUuid) {
if (this.group == null) { if (this.group == null) {
this.group = new HashSet(); this.group = new HashSet();
@@ -25,6 +68,13 @@ public class ProfileScope {
} }
/**
* 移除分组。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:remove。
*
* @param groupUuid 分组 UUID({@code UUID})
*/
public void removeGroup(UUID groupUuid) { public void removeGroup(UUID groupUuid) {
if (this.group != null) { if (this.group != null) {
this.group.remove(groupUuid); this.group.remove(groupUuid);
@@ -32,14 +82,30 @@ public class ProfileScope {
} }
public Set getDevice() { /**
* 获取 {@code device}。
* @return String列表,可能为空
*/
public Set<String> getDevice() {
return this.device; return this.device;
} }
public void setDevice(Set device) { /**
* 设置 {@code device}。
*
* @param device 设备({@code Set<String>})
*/
public void setDevice(Set<String> device) {
this.device = device; this.device = device;
} }
/**
* 添加设备。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new HashSet。
*
* @param serialNo 设备序列号({@code String})
*/
public void addDevice(String serialNo) { public void addDevice(String serialNo) {
if (this.device == null) { if (this.device == null) {
this.device = new HashSet(); this.device = new HashSet();
@@ -48,6 +114,13 @@ public class ProfileScope {
} }
/**
* 移除设备。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:remove。
*
* @param serialNo 设备序列号({@code String})
*/
public void removeDevice(String serialNo) { public void removeDevice(String serialNo) {
if (this.device != null) { if (this.device != null) {
this.device.remove(serialNo); this.device.remove(serialNo);
@@ -55,14 +128,27 @@ public class ProfileScope {
} }
public Set getUserGroup() { /**
* 获取 {@code userGroup}。
* @return String列表,可能为空
*/
public Set<String> getUserGroup() {
return this.userGroup; return this.userGroup;
} }
public void setUserGroup(Set userGroup) { /**
* 设置 {@code userGroup}。
*
* @param userGroup 参数 {@code userGroup}({@code Set<String>})
*/
public void setUserGroup(Set<String> userGroup) {
this.userGroup = userGroup; this.userGroup = userGroup;
} }
/**
* 判断 {@code scoped}。
* @return 字段/派生属性 {@code scoped} 的值
*/
public boolean hasScoped() { public boolean hasScoped() {
return this.group != null && !this.group.isEmpty() || this.device != null && !this.device.isEmpty() || this.userGroup != null && !this.userGroup.isEmpty(); return this.group != null && !this.group.isEmpty() || this.device != null && !this.device.isEmpty() || this.userGroup != null && !this.userGroup.isEmpty();
} }
@@ -8,25 +8,92 @@ import java.util.TimerTask;
import java.util.UUID; import java.util.UUID;
import org.joda.time.LocalDateTime; import org.joda.time.LocalDateTime;
/**
* 【领域模型】{@code ReconnectMonitor}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code BLOCKING_HOURS}(int):字段 BLOCKING_HOURS</li>
* <li>{@code RECONNECT_FOR}(int):字段 RECONNECT_FOR</li>
* <li>{@code device}(Device):设备</li>
* <li>{@code startedAt}(Date):时间字段</li>
* <li>{@code prevMins}(long):字段 prevMins</li>
* <li>{@code count}(int):统计</li>
* </ul>
*
* 协作对象:{@code Device、Timer、OnAbusedListener}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class ReconnectMonitor { public class ReconnectMonitor {
/**
* 字段 BLOCKING_HOURS。
*/
private static final int BLOCKING_HOURS = 12; private static final int BLOCKING_HOURS = 12;
/**
* 字段 RECONNECT_FOR。
*/
private static final int RECONNECT_FOR = 10; private static final int RECONNECT_FOR = 10;
/**
* 设备。
*/
private Device device; private Device device;
/**
* 时间字段。
*/
private Date startedAt; private Date startedAt;
/**
* 字段 prevMins。
*/
private long prevMins; private long prevMins;
/**
* 统计。
*/
private int count; private int count;
/**
* 总数。
*/
private int total; private int total;
/**
* 时间字段。
*/
private Date blockedAt; private Date blockedAt;
/**
* 时间字段。
*/
private Date unblockAt; private Date unblockAt;
/**
* unblock定时器。
*/
private Timer unblockTimer; private Timer unblockTimer;
/**
* 监听器。
*/
private OnAbusedListener listener; private OnAbusedListener listener;
/**
* 构造 {@code ReconnectMonitor} 实例。
*
* @param device 设备({@code Device})
* @param listener 参数 {@code listener}({@code OnAbusedListener})
*/
public ReconnectMonitor(Device device, OnAbusedListener listener) { public ReconnectMonitor(Device device, OnAbusedListener listener) {
this.device = device; this.device = device;
this.listener = listener; this.listener = listener;
this.init(); this.init();
} }
/**
* 初始化对象状态(补齐 UUID/时间戳/默认字段)。
*
* 实现要点:主要调用:new Date。
*/
private void init() { private void init() {
this.startedAt = new Date(); this.startedAt = new Date();
this.blockedAt = null; this.blockedAt = null;
@@ -35,34 +102,67 @@ public class ReconnectMonitor {
this.total = this.count = 1; this.total = this.count = 1;
} }
/**
* 获取 {@code device}。
* @return 匹配的设备对象;未找到时返回 {@code null}
*/
public Device getDevice() { public Device getDevice() {
return this.device; return this.device;
} }
/**
* 获取 {@code deviceUuid}。
* @return UUID
*/
public UUID getDeviceUuid() { public UUID getDeviceUuid() {
return this.device.getUuid(); return this.device.getUuid();
} }
/**
* 获取 {@code startedAt}。
* @return 字段/派生属性 {@code startedAt} 的值
*/
public Date getStartedAt() { public Date getStartedAt() {
return this.startedAt; return this.startedAt;
} }
/**
* 获取 {@code blockedAt}。
* @return 字段/派生属性 {@code blockedAt} 的值
*/
public Date getBlockedAt() { public Date getBlockedAt() {
return this.blockedAt; return this.blockedAt;
} }
/**
* 获取 {@code unblockAt}。
* @return 字段/派生属性 {@code unblockAt} 的值
*/
public Date getUnblockAt() { public Date getUnblockAt() {
return this.unblockAt; return this.unblockAt;
} }
/**
* 获取 {@code count}。
* @return 数量/长度
*/
public int getCount() { public int getCount() {
return this.count; return this.count;
} }
/**
* 获取 {@code total}。
* @return 数量/长度
*/
public int getTotal() { public int getTotal() {
return this.total; return this.total;
} }
/**
* 处理connected。
*
* 实现要点:包含 3 个条件分支、0 个循环;主要调用:new Date。
*/
public void connected() { public void connected() {
long curMins = this.getCurMins(); long curMins = this.getCurMins();
long gap = curMins - this.prevMins; long gap = curMins - this.prevMins;
@@ -82,16 +182,32 @@ public class ReconnectMonitor {
} }
/**
* 判断 {@code blocked}。
* @return 字段/派生属性 {@code blocked} 的值
*/
public boolean isBlocked() { public boolean isBlocked() {
return this.blockedAt != null; return this.blockedAt != null;
} }
/**
* 处理block。
*
* 实现要点:主要调用:new Date、new LocalDateTime。
*/
public void block() { public void block() {
this.blockedAt = new Date(); this.blockedAt = new Date();
this.unblockAt = (new LocalDateTime(this.blockedAt)).plusHours(12).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).toDate(); this.unblockAt = (new LocalDateTime(this.blockedAt)).plusHours(12).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).toDate();
this.startUnblockTimer(); this.startUnblockTimer();
} }
/**
* 处理block。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:new Date。
*
* @param device 设备({@code Device})
*/
public void block(Device device) { public void block(Device device) {
if (device.isBlocked()) { if (device.isBlocked()) {
DbObject blockedState = device.getStates().getDbObject(new String[]{"blocked"}); DbObject blockedState = device.getStates().getDbObject(new String[]{"blocked"});
@@ -108,10 +224,14 @@ public class ReconnectMonitor {
} }
/**
* 启动Unblock定时器。
*
* 实现要点:主要调用:new Timer、new Date、schedule、new TimerTask。
*/
private void startUnblockTimer() { private void startUnblockTimer() {
this.stopUnblockTimer(); this.stopUnblockTimer();
String var10003 = this.device.getUuid().toString(); this.unblockTimer = new Timer(this.device.getUuid().toString() + (new Date()).getTime());
this.unblockTimer = new Timer(var10003 + (new Date()).getTime());
this.unblockTimer.schedule(new TimerTask() { this.unblockTimer.schedule(new TimerTask() {
public void run() { public void run() {
ReconnectMonitor.this.unblock((User)null); ReconnectMonitor.this.unblock((User)null);
@@ -119,6 +239,11 @@ public class ReconnectMonitor {
}, this.unblockAt); }, this.unblockAt);
} }
/**
* 停止Unblock定时器。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:cancel。
*/
private void stopUnblockTimer() { private void stopUnblockTimer() {
if (this.unblockTimer != null) { if (this.unblockTimer != null) {
try { try {
@@ -131,6 +256,13 @@ public class ReconnectMonitor {
} }
/**
* 处理unblock。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param user 当前用户({@code User})
*/
public void unblock(User user) { public void unblock(User user) {
this.stopUnblockTimer(); this.stopUnblockTimer();
this.startedAt = null; this.startedAt = null;
@@ -144,6 +276,11 @@ public class ReconnectMonitor {
} }
/**
* 处理处理Abused。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*/
private void onAbused() { private void onAbused() {
this.block(); this.block();
if (this.listener != null) { if (this.listener != null) {
@@ -152,13 +289,40 @@ public class ReconnectMonitor {
} }
/**
* 获取 {@code curMins}。
*
* 实现要点:主要调用:new Date。
* @return 数量/长度
*/
private long getCurMins() { private long getCurMins() {
return (new Date()).getTime() / 60000L; return (new Date()).getTime() / 60000L;
} }
/**
* 【接口契约】{@code OnAbusedListener}
*
* 类职责:
* <ul>
* <li>定义调用方与实现方之间的契约,屏蔽具体实现。</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public interface OnAbusedListener { public interface OnAbusedListener {
/**
* 处理处理Abused。
*
* @param monitor 参数 {@code monitor}({@code ReconnectMonitor})
*/
void onAbused(ReconnectMonitor monitor); void onAbused(ReconnectMonitor monitor);
/**
* 处理处理Unblocked。
*
* @param monitor 参数 {@code monitor}({@code ReconnectMonitor})
* @param user 当前用户({@code User})
*/
void onUnblocked(ReconnectMonitor monitor, User user); void onUnblocked(ReconnectMonitor monitor, User user);
} }
} }
@@ -0,0 +1,27 @@
/**
* 设备领域模型:设备档案、分组、策略、应用、License、遥测状态。
*
* <p>本包主要类型:
* <ul>
* <li>{@link AppInfo}</li>
* <li>{@link DEVICE_PROPERTY}</li>
* <li>{@link DataUsage}</li>
* <li>{@link Device}</li>
* <li>{@link DeviceApps}</li>
* <li>{@link DeviceGroup}</li>
* <li>{@link DeviceKey}</li>
* <li>{@link DeviceLicense}</li>
* <li>{@link DeviceNote}</li>
* <li>{@link DeviceProfile}</li>
* <li>{@link DeviceProfileGroup}</li>
* <li>{@link DeviceProfileState}</li>
* <li>{@link DeviceReport}</li>
* <li>{@link ProfileApps}</li>
* <li>{@link ProfileScope}</li>
* <li>{@link ReconnectMonitor}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.model.device;
+224 -2
View File
@@ -12,24 +12,76 @@ import net.dongliu.apk.parser.bean.ApkMeta;
import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code AppFile}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code appInfo}(DbObject):应用信息</li>
* <li>{@code updateOptions}(DbObject):更新选项列表</li>
* <li>{@code generateIcon}(boolean):生成Icon</li>
* </ul>
*
* 协作对象:{@code DbObject}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class AppFile extends BaseFile { public class AppFile extends BaseFile {
/**
* 应用信息。
*/
private DbObject appInfo; private DbObject appInfo;
/**
* 更新选项列表。
*/
private DbObject updateOptions; private DbObject updateOptions;
/**
* 生成Icon;不持久化到 MongoDB,仅运行时使用;Gson 序列化控制。
*
* 注解:{@code @Transient @Expose(serialize = false)}。
*/
@Transient @Transient
@Expose( @Expose(
serialize = false serialize = false
) )
private boolean generateIcon; private boolean generateIcon;
/**
* 构造 {@code AppFile} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public AppFile() { public AppFile() {
this.generateIcon = true; this.generateIcon = true;
} }
/**
* 构造 {@code AppFile} 实例。
*
* @param user 当前用户({@code User})
* @param fileUuid 文件 UUID({@code UUID})
* @param file 文件({@code McFile})
*/
public AppFile(User user, UUID fileUuid, McFile file) { public AppFile(User user, UUID fileUuid, McFile file) {
this(user, fileUuid, file, true); this(user, fileUuid, file, true);
} }
/**
* 构造 {@code AppFile} 实例。
*
* @param user 当前用户({@code User})
* @param fileUuid 文件 UUID({@code UUID})
* @param file 文件({@code McFile})
* @param generateIcon 参数 {@code generateIcon}({@code boolean})
*/
public AppFile(User user, UUID fileUuid, McFile file, boolean generateIcon) { public AppFile(User user, UUID fileUuid, McFile file, boolean generateIcon) {
super(user, fileUuid, file); super(user, fileUuid, file);
this.generateIcon = true; this.generateIcon = true;
@@ -37,14 +89,28 @@ public class AppFile extends BaseFile {
this.setAppInfo(file); this.setAppInfo(file);
} }
/**
* 判断 {@code apk}。
* @return 字段/派生属性 {@code apk} 的值
*/
public boolean isApk() { public boolean isApk() {
return !Strings.isNullOrEmpty(this.getPackageName()); return !Strings.isNullOrEmpty(this.getPackageName());
} }
/**
* 判断 {@code systemPermission}。
* @return 字段/派生属性 {@code systemPermission} 的值
*/
public boolean hasSystemPermission() { public boolean hasSystemPermission() {
return "android.uid.system".equals(this.getSharedUserId()); return "android.uid.system".equals(this.getSharedUserId());
} }
/**
* 获取 {@code appInfo}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getAppInfo() { public DbObject getAppInfo() {
if (this.appInfo == null) { if (this.appInfo == null) {
this.appInfo = new DbObject(); this.appInfo = new DbObject();
@@ -53,14 +119,31 @@ public class AppFile extends BaseFile {
return this.appInfo; return this.appInfo;
} }
/**
* 设置 {@code appInfo}。
*
* @param appInfo 参数 {@code appInfo}({@code DbObject})
*/
public void setAppInfo(DbObject appInfo) { public void setAppInfo(DbObject appInfo) {
this.appInfo = appInfo; this.appInfo = appInfo;
} }
/**
* 设置应用信息。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setAppInfo(String key, Object value) { public void setAppInfo(String key, Object value) {
this.getAppInfo().append(key, value); this.getAppInfo().append(key, value);
} }
/**
* 获取 {@code updateOptions}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getUpdateOptions() { public DbObject getUpdateOptions() {
if (this.updateOptions == null) { if (this.updateOptions == null) {
this.updateOptions = new DbObject(); this.updateOptions = new DbObject();
@@ -69,30 +152,65 @@ public class AppFile extends BaseFile {
return this.updateOptions; return this.updateOptions;
} }
/**
* 设置 {@code updateOptions}。
*
* @param updateOptions 参数 {@code updateOptions}({@code DbObject})
*/
public void setUpdateOptions(DbObject updateOptions) { public void setUpdateOptions(DbObject updateOptions) {
this.updateOptions = updateOptions; this.updateOptions = updateOptions;
} }
/**
* 设置更新选项列表。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setUpdateOptions(String key, Object value) { public void setUpdateOptions(String key, Object value) {
this.getUpdateOptions().append(key, value); this.getUpdateOptions().append(key, value);
} }
/**
* 判断 {@code mitacApp}。
* @return 字段/派生属性 {@code mitacApp} 的值
*/
public boolean isMitacApp() { public boolean isMitacApp() {
return this.getPackageName().toLowerCase().contains("mitac"); return this.getPackageName().toLowerCase().contains("mitac");
} }
/**
* 获取 {@code packageName}。
* @return 字符串结果
*/
public String getPackageName() { public String getPackageName() {
return this.getAppInfo().getString("packageName"); return this.getAppInfo().getString("packageName");
} }
/**
* 设置 {@code packageName}。
*
* @param packageName 参数 {@code packageName}({@code String})
*/
public void setPackageName(String packageName) { public void setPackageName(String packageName) {
this.setAppInfo("packageName", packageName); this.setAppInfo("packageName", packageName);
} }
/**
* 获取 {@code sharedUserId}。
* @return 字符串结果
*/
public String getSharedUserId() { public String getSharedUserId() {
return this.getAppInfo().getString("sharedUid"); return this.getAppInfo().getString("sharedUid");
} }
/**
* 设置 {@code sharedUserId}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param sharedUid 参数 {@code sharedUid}({@code String})
*/
public void setSharedUserId(String sharedUid) { public void setSharedUserId(String sharedUid) {
if (!Strings.isNullOrEmpty(sharedUid)) { if (!Strings.isNullOrEmpty(sharedUid)) {
this.setAppInfo("sharedUid", sharedUid); this.setAppInfo("sharedUid", sharedUid);
@@ -100,42 +218,89 @@ public class AppFile extends BaseFile {
} }
/**
* 获取 {@code label}。
* @return 字符串结果
*/
public String getLabel() { public String getLabel() {
return this.getAppInfo().getString("label"); return this.getAppInfo().getString("label");
} }
/**
* 设置 {@code label}。
*
* @param label 参数 {@code label}({@code String})
*/
public void setLabel(String label) { public void setLabel(String label) {
this.setAppInfo("label", label); this.setAppInfo("label", label);
} }
/**
* 获取 {@code iconName}。
* @return 字符串结果
*/
public String getIconName() { public String getIconName() {
return this.getAppInfo().getString("iconName"); return this.getAppInfo().getString("iconName");
} }
/**
* 设置 {@code iconName}。
*
* @param iconName 参数 {@code iconName}({@code String})
*/
public void setIconName(String iconName) { public void setIconName(String iconName) {
this.setAppInfo("iconName", iconName); this.setAppInfo("iconName", iconName);
} }
/**
* 获取 {@code versionCode}。
* @return 数量/长度
*/
public long getVersionCode() { public long getVersionCode() {
return this.getAppInfo().getLong("versionCode"); return this.getAppInfo().getLong("versionCode");
} }
/**
* 设置 {@code versionCode}。
*
* @param versionCode 参数 {@code versionCode}({@code long})
*/
public void setVersionCode(long versionCode) { public void setVersionCode(long versionCode) {
this.setAppInfo("versionCode", versionCode); this.setAppInfo("versionCode", versionCode);
} }
/**
* 获取 {@code versionName}。
* @return 字符串结果
*/
public String getVersionName() { public String getVersionName() {
return this.getAppInfo().getString("versionName"); return this.getAppInfo().getString("versionName");
} }
/**
* 设置 {@code versionName}。
*
* @param versionName 参数 {@code versionName}({@code String})
*/
public void setVersionName(String versionName) { public void setVersionName(String versionName) {
this.setAppInfo("versionName", versionName); this.setAppInfo("versionName", versionName);
} }
/**
* 获取 {@code minSdkVersion}。
* @return 数量/长度
*/
public int getMinSdkVersion() { public int getMinSdkVersion() {
return this.getAppInfo().getInteger("minSdkVersion", -1); return this.getAppInfo().getInteger("minSdkVersion", -1);
} }
/**
* 设置 {@code minSdkVersion}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param minSdkVersion 参数 {@code minSdkVersion}({@code String})
*/
public void setMinSdkVersion(String minSdkVersion) { public void setMinSdkVersion(String minSdkVersion) {
if (!Strings.isNullOrEmpty(minSdkVersion)) { if (!Strings.isNullOrEmpty(minSdkVersion)) {
this.setMinSdkVersion(Integer.parseInt(minSdkVersion)); this.setMinSdkVersion(Integer.parseInt(minSdkVersion));
@@ -143,14 +308,30 @@ public class AppFile extends BaseFile {
} }
/**
* 设置 {@code minSdkVersion}。
*
* @param minSdkVersion 参数 {@code minSdkVersion}({@code int})
*/
public void setMinSdkVersion(int minSdkVersion) { public void setMinSdkVersion(int minSdkVersion) {
this.setAppInfo("minSdkVersion", minSdkVersion); this.setAppInfo("minSdkVersion", minSdkVersion);
} }
/**
* 获取 {@code maxSdkVersion}。
* @return 数量/长度
*/
public int getMaxSdkVersion() { public int getMaxSdkVersion() {
return this.getAppInfo().getInteger("maxSdkVersion", -1); return this.getAppInfo().getInteger("maxSdkVersion", -1);
} }
/**
* 设置 {@code maxSdkVersion}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param maxSdkVersion 参数 {@code maxSdkVersion}({@code String})
*/
public void setMaxSdkVersion(String maxSdkVersion) { public void setMaxSdkVersion(String maxSdkVersion) {
if (!Strings.isNullOrEmpty(maxSdkVersion)) { if (!Strings.isNullOrEmpty(maxSdkVersion)) {
this.setAppInfo("maxSdkVersion", Integer.parseInt(maxSdkVersion)); this.setAppInfo("maxSdkVersion", Integer.parseInt(maxSdkVersion));
@@ -158,10 +339,21 @@ public class AppFile extends BaseFile {
} }
/**
* 获取 {@code targetSdkVersion}。
* @return 数量/长度
*/
public int getTargetSdkVersion() { public int getTargetSdkVersion() {
return this.getAppInfo().getInteger("targetSdkVersion", -1); return this.getAppInfo().getInteger("targetSdkVersion", -1);
} }
/**
* 设置 {@code targetSdkVersion}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param targetSdkVersion 参数 {@code targetSdkVersion}({@code String})
*/
public void setTargetSdkVersion(String targetSdkVersion) { public void setTargetSdkVersion(String targetSdkVersion) {
if (Strings.isNullOrEmpty(targetSdkVersion)) { if (Strings.isNullOrEmpty(targetSdkVersion)) {
this.getAppInfo().remove("targetSdkVersion"); this.getAppInfo().remove("targetSdkVersion");
@@ -171,18 +363,38 @@ public class AppFile extends BaseFile {
} }
public List getUserPermission() { /**
* 获取 {@code userPermission}。
* @return String列表,可能为空
*/
public List<String> getUserPermission() {
return this.getAppInfo().getList("userPermission", String.class); return this.getAppInfo().getList("userPermission", String.class);
} }
public void setUserPermission(List userPermission) { /**
* 设置 {@code userPermission}。
*
* @param userPermission 参数 {@code userPermission}({@code List<String>})
*/
public void setUserPermission(List<String> userPermission) {
this.setAppInfo("userPermission", userPermission); this.setAppInfo("userPermission", userPermission);
} }
/**
* 获取 {@code certMd5}。
* @return 字符串结果
*/
public String getCertMd5() { public String getCertMd5() {
return this.getAppInfo().getString("certMd5"); return this.getAppInfo().getString("certMd5");
} }
/**
* 设置 {@code certMd5}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param certMd5 参数 {@code certMd5}({@code String})
*/
public void setCertMd5(String certMd5) { public void setCertMd5(String certMd5) {
if (!Strings.isNullOrEmpty(certMd5)) { if (!Strings.isNullOrEmpty(certMd5)) {
this.setAppInfo("certMd5", certMd5); this.setAppInfo("certMd5", certMd5);
@@ -190,6 +402,13 @@ public class AppFile extends BaseFile {
} }
/**
* 设置 {@code appInfo}。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:new McApkFile、close。
*
* @param file 文件({@code McFile})
*/
public void setAppInfo(McFile file) { public void setAppInfo(McFile file) {
try { try {
McApkFile apkFile = new McApkFile(file); McApkFile apkFile = new McApkFile(file);
@@ -220,6 +439,9 @@ public class AppFile extends BaseFile {
} }
/**
* 处理minify。
*/
public void minify() { public void minify() {
super.minify(); super.minify();
this.setUserPermission((List)null); this.setUserPermission((List)null);
+286 -2
View File
@@ -14,23 +14,90 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code BaseFile}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code fileUuid}(UUID):文件UUID</li>
* <li>{@code userUuid}(UUID):用户UUID</li>
* <li>{@code siteUuid}(UUID):用户所属站点 UUID</li>
* <li>{@code fileInfo}(DbObject):文件信息</li>
* <li>{@code extra}(DbObject):字段 extra</li>
* <li>{@code name}(String):名称</li>
* </ul>
*
* 协作对象:{@code DbObject}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class BaseFile { public class BaseFile {
/**
* 文件UUID;MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
protected UUID fileUuid; protected UUID fileUuid;
/**
* 用户UUID。
*/
protected UUID userUuid; protected UUID userUuid;
/**
* 用户所属站点 UUID;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
protected UUID siteUuid; protected UUID siteUuid;
/**
* 文件信息。
*/
protected DbObject fileInfo; protected DbObject fileInfo;
/**
* 字段 extra。
*/
protected DbObject extra; protected DbObject extra;
/**
* 名称。
*/
protected String name; protected String name;
/**
* 是否启用。
*/
protected boolean enabled = true; protected boolean enabled = true;
/**
* 最后Updated。
*/
protected Date lastUpdated; protected Date lastUpdated;
/**
* 时间字段。
*/
protected Date registeredAt; protected Date registeredAt;
/**
* 构造 {@code BaseFile} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public BaseFile() { public BaseFile() {
} }
/**
* 构造 {@code BaseFile} 实例。
*
* @param user 当前用户({@code User})
* @param fileUuid 文件 UUID({@code UUID})
* @param file 文件({@code McFile})
*/
public BaseFile(User user, UUID fileUuid, McFile file) { public BaseFile(User user, UUID fileUuid, McFile file) {
this.setUserUuid(user); this.setUserUuid(user);
this.setFileUuid(fileUuid); this.setFileUuid(fileUuid);
@@ -38,30 +105,64 @@ public class BaseFile {
this.initRegisteredAt(); this.initRegisteredAt();
} }
/**
* 获取 {@code siteUuid}。
* @return UUID
*/
public UUID getSiteUuid() { public UUID getSiteUuid() {
return this.siteUuid; return this.siteUuid;
} }
/**
* 设置 {@code siteUuid}。
*
* @param siteUuid 站点 UUID({@code UUID})
*/
public void setSiteUuid(UUID siteUuid) { public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid; this.siteUuid = siteUuid;
} }
/**
* 获取 {@code fileUuid}。
* @return UUID
*/
public UUID getFileUuid() { public UUID getFileUuid() {
return this.fileUuid; return this.fileUuid;
} }
/**
* 设置 {@code fileUuid}。
*
* @param uid 参数 {@code uid}({@code UUID})
*/
public void setFileUuid(UUID uid) { public void setFileUuid(UUID uid) {
this.fileUuid = uid; this.fileUuid = uid;
} }
/**
* 获取 {@code userUuid}。
* @return UUID
*/
public UUID getUserUuid() { public UUID getUserUuid() {
return this.userUuid; return this.userUuid;
} }
/**
* 设置 {@code userUuid}。
*
* @param uid 参数 {@code uid}({@code UUID})
*/
public void setUserUuid(UUID uid) { public void setUserUuid(UUID uid) {
this.userUuid = uid; this.userUuid = uid;
} }
/**
* 设置 {@code userUuid}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param user 当前用户({@code User})
*/
public void setUserUuid(User user) { public void setUserUuid(User user) {
if (user != null) { if (user != null) {
this.userUuid = user.getUuid(); this.userUuid = user.getUuid();
@@ -69,6 +170,12 @@ public class BaseFile {
} }
/**
* 获取 {@code fileInfo}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getFileInfo() { public DbObject getFileInfo() {
if (this.fileInfo == null) { if (this.fileInfo == null) {
this.fileInfo = new DbObject(); this.fileInfo = new DbObject();
@@ -77,6 +184,14 @@ public class BaseFile {
return this.fileInfo; return this.fileInfo;
} }
/**
* 获取文件信息AsString。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
*
* @param key 键/配置项({@code String})
* @return 字符串结果
*/
public String getFileInfoAsString(String key) { public String getFileInfoAsString(String key) {
if (this.fileInfo == null) { if (this.fileInfo == null) {
this.fileInfo = new DbObject(); this.fileInfo = new DbObject();
@@ -85,14 +200,29 @@ public class BaseFile {
return this.fileInfo.getString(key); return this.fileInfo.getString(key);
} }
/**
* 移除文件信息。
*/
public void removeFileInfo() { public void removeFileInfo() {
this.fileInfo = null; this.fileInfo = null;
} }
/**
* 设置 {@code fileInfo}。
*
* @param fileInfo 参数 {@code fileInfo}({@code DbObject})
*/
public void setFileInfo(DbObject fileInfo) { public void setFileInfo(DbObject fileInfo) {
this.fileInfo = fileInfo; this.fileInfo = fileInfo;
} }
/**
* 设置 {@code fileInfo}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:exists。
*
* @param file 文件({@code McFile})
*/
public void setFileInfo(McFile file) { public void setFileInfo(McFile file) {
if (file.exists()) { if (file.exists()) {
this.setLength(file.length()); this.setLength(file.length());
@@ -102,15 +232,31 @@ public class BaseFile {
} }
/**
* 获取 {@code extra}。
* @return MongoDB 文档扩展对象
*/
public DbObject getExtra() { public DbObject getExtra() {
return this.extra; return this.extra;
} }
/**
* 设置 {@code extra}。
*
* @param extra 参数 {@code extra}({@code DbObject})
*/
public void setExtra(DbObject extra) { public void setExtra(DbObject extra) {
this.extra = extra; this.extra = extra;
} }
public void setExtra(Map parameters) { /**
* 设置 {@code extra}。
*
* 实现要点:包含 3 个条件分支、0 个循环;主要调用:new DbObject。
*
* @param parameters 参数 {@code parameters}({@code Map<String, String[]>})
*/
public void setExtra(Map<String, String[]> parameters) {
if (parameters != null) { if (parameters != null) {
if (this.extra == null) { if (this.extra == null) {
this.extra = new DbObject(); this.extra = new DbObject();
@@ -119,7 +265,7 @@ public class BaseFile {
parameters.forEach((k, v) -> { parameters.forEach((k, v) -> {
String key = (String) k; String key = (String) k;
String[] value = (String[]) v; String[] value = (String[]) v;
if (value != null && value.length > 0 && key.startsWith("extra.")) { if (value.length > 0 && key.startsWith("extra.")) {
this.extra.put(key.substring(6), value.length == 1 ? value[0] : Arrays.asList(value)); this.extra.put(key.substring(6), value.length == 1 ? value[0] : Arrays.asList(value));
} }
@@ -128,30 +274,63 @@ public class BaseFile {
} }
/**
* 获取 {@code enabled}。
* @return 字段/派生属性 {@code enabled} 的值
*/
public boolean getEnabled() { public boolean getEnabled() {
return this.enabled; return this.enabled;
} }
/**
* 设置 {@code enabled}。
*
* @param enabled 参数 {@code enabled}({@code boolean})
*/
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
this.enabled = enabled; this.enabled = enabled;
} }
/**
* 获取 {@code name}。
* @return 字符串结果
*/
public String getName() { public String getName() {
return this.name; return this.name;
} }
/**
* 设置 {@code name}。
*
* @param name 参数 {@code name}({@code String})
*/
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/**
* 获取 {@code fileName}。
* @return 字符串结果
*/
public String getFileName() { public String getFileName() {
return this.getFileInfo().getString("fileName"); return this.getFileInfo().getString("fileName");
} }
/**
* 设置 {@code fileName}。
*
* @param fileName 文件名({@code String})
*/
public void setFileName(String fileName) { public void setFileName(String fileName) {
this.setFileInfo("fileName", fileName); this.setFileInfo("fileName", fileName);
} }
/**
* 获取 {@code contentType}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Tika。
* @return 字符串结果
*/
public String getContentType() { public String getContentType() {
String contentType = this.getFileInfo().getString("contentType"); String contentType = this.getFileInfo().getString("contentType");
if (Strings.isNullOrEmpty(contentType)) { if (Strings.isNullOrEmpty(contentType)) {
@@ -162,30 +341,64 @@ public class BaseFile {
return contentType; return contentType;
} }
/**
* 设置 {@code type}。
*
* @param contentType Content-Type({@code String})
*/
public void setType(String contentType) { public void setType(String contentType) {
this.setFileInfo("contentType", contentType); this.setFileInfo("contentType", contentType);
} }
/**
* 获取 {@code length}。
* @return 数量/长度
*/
public long getLength() { public long getLength() {
return this.getFileInfo().getLong("length"); return this.getFileInfo().getLong("length");
} }
/**
* 设置 {@code length}。
*
* @param length 参数 {@code length}({@code long})
*/
public void setLength(long length) { public void setLength(long length) {
this.setFileInfo("length", length); this.setFileInfo("length", length);
} }
/**
* 获取 {@code checksum}。
* @return 数量/长度
*/
public long getChecksum() { public long getChecksum() {
return this.getFileInfo().getLong("checksum"); return this.getFileInfo().getLong("checksum");
} }
/**
* 设置 {@code checksum}。
*
* @param checksum 参数 {@code checksum}({@code long})
*/
public void setChecksum(long checksum) { public void setChecksum(long checksum) {
this.setFileInfo("checksum", checksum); this.setFileInfo("checksum", checksum);
} }
/**
* 获取 {@code lastModified}。
* @return 数量/长度
*/
public long getLastModified() { public long getLastModified() {
return this.getFileInfo().getLong("lastModified"); return this.getFileInfo().getLong("lastModified");
} }
/**
* 设置 {@code lastModified}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Date。
*
* @param lastModified 参数 {@code lastModified}({@code long})
*/
public void setLastModified(long lastModified) { public void setLastModified(long lastModified) {
if (lastModified <= 0L) { if (lastModified <= 0L) {
lastModified = (new Date()).getTime(); lastModified = (new Date()).getTime();
@@ -194,25 +407,51 @@ public class BaseFile {
this.setFileInfo("lastModified", lastModified); this.setFileInfo("lastModified", lastModified);
} }
/**
* 设置文件信息。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setFileInfo(String key, Object value) { public void setFileInfo(String key, Object value) {
this.getFileInfo().append(key, value); this.getFileInfo().append(key, value);
} }
/**
* 设置 {@code fileUrl}。
*
* @param url 参数 {@code url}({@code String})
*/
public void setFileUrl(String url) { public void setFileUrl(String url) {
this.setFileInfo("fileUrl", url); this.setFileInfo("fileUrl", url);
} }
/**
* 获取 {@code urlExpiry}。
* @return 数量/长度
*/
public long getUrlExpiry() { public long getUrlExpiry() {
Date expiry = this.getFileInfo().getDate("urlExpiry"); Date expiry = this.getFileInfo().getDate("urlExpiry");
return expiry == null ? -1L : expiry.getTime(); return expiry == null ? -1L : expiry.getTime();
} }
/**
* 设置 {@code cloudUrl}。
*
* @param url 参数 {@code url}({@code String})
*/
public void setCloudUrl(String url) { public void setCloudUrl(String url) {
this.setFileInfo("fileUrl", url); this.setFileInfo("fileUrl", url);
Date expiry = LocalDateTime.now().plusDays(6).toDate(); Date expiry = LocalDateTime.now().plusDays(6).toDate();
this.setFileInfo("urlExpiry", expiry); this.setFileInfo("urlExpiry", expiry);
} }
/**
* 判断 {@code fileUrl}。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:new Date。
* @return 字段/派生属性 {@code fileUrl} 的值
*/
public boolean hasFileUrl() { public boolean hasFileUrl() {
boolean hasUrl = this.getFileInfo().containsKey("fileUrl"); boolean hasUrl = this.getFileInfo().containsKey("fileUrl");
if (hasUrl && this.getFileInfo().containsKey("urlExpiry")) { if (hasUrl && this.getFileInfo().containsKey("urlExpiry")) {
@@ -226,10 +465,20 @@ public class BaseFile {
return hasUrl; return hasUrl;
} }
/**
* 获取 {@code fileUrl}。
* @return 字符串结果
*/
public String getFileUrl() { public String getFileUrl() {
return this.getFileInfoAsString("fileUrl"); return this.getFileInfoAsString("fileUrl");
} }
/**
* 判断 {@code iconUrl}。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:new Date。
* @return 字段/派生属性 {@code iconUrl} 的值
*/
public boolean hasIconUrl() { public boolean hasIconUrl() {
boolean hasUrl = this.getFileInfo().containsKey("iconUrl"); boolean hasUrl = this.getFileInfo().containsKey("iconUrl");
if (hasUrl && this.getFileInfo().containsKey("iconExpiry")) { if (hasUrl && this.getFileInfo().containsKey("iconExpiry")) {
@@ -243,37 +492,72 @@ public class BaseFile {
return hasUrl; return hasUrl;
} }
/**
* 设置 {@code iconUrl}。
*
* @param url 参数 {@code url}({@code String})
*/
public void setIconUrl(String url) { public void setIconUrl(String url) {
this.setFileInfo("iconUrl", url); this.setFileInfo("iconUrl", url);
Date expiry = LocalDateTime.now().plusDays(6).toDate(); Date expiry = LocalDateTime.now().plusDays(6).toDate();
this.setFileInfo("iconExpiry", expiry); this.setFileInfo("iconExpiry", expiry);
} }
/**
* 获取 {@code iconUrl}。
* @return 字符串结果
*/
public String getIconUrl() { public String getIconUrl() {
return this.getFileInfoAsString("iconUrl"); return this.getFileInfoAsString("iconUrl");
} }
/**
* 获取 {@code lastUpdated}。
* @return 字段/派生属性 {@code lastUpdated} 的值
*/
public Date getLastUpdated() { public Date getLastUpdated() {
return this.lastUpdated; return this.lastUpdated;
} }
/**
* 设置 {@code lastUpdated}。
*
* @param lastUpdated 参数 {@code lastUpdated}({@code Date})
*/
public void setLastUpdated(Date lastUpdated) { public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated; this.lastUpdated = lastUpdated;
} }
/**
* 获取 {@code registeredAt}。
* @return 字段/派生属性 {@code registeredAt} 的值
*/
public Date getRegisteredAt() { public Date getRegisteredAt() {
return this.registeredAt; return this.registeredAt;
} }
/**
* 设置 {@code registeredAt}。
*
* @param registeredAt 参数 {@code registeredAt}({@code Date})
*/
public void setRegisteredAt(Date registeredAt) { public void setRegisteredAt(Date registeredAt) {
this.registeredAt = registeredAt; this.registeredAt = registeredAt;
} }
/**
* 初始化RegisteredAt。
*
* 实现要点:主要调用:new Date。
*/
public void initRegisteredAt() { public void initRegisteredAt() {
this.setRegisteredAt(new Date()); this.setRegisteredAt(new Date());
this.setLastUpdated(this.getRegisteredAt()); this.setLastUpdated(this.getRegisteredAt());
} }
/**
* 处理minify。
*/
public void minify() { public void minify() {
this.userUuid = null; this.userUuid = null;
this.registeredAt = null; this.registeredAt = null;
@@ -1,80 +1,212 @@
package com.midm.model.file; package com.midm.model.file;
/**
* 【领域模型】{@code DeployOption}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code PROPERTY_DEFAULT}(String):字段 PROPERTY_DEFAULT</li>
* <li>{@code PROPERTY_FORCE_TO_DOWNLOAD}(String):字段 PROPERTY_FORCE_TO_DOWNLOAD</li>
* <li>{@code PROPERTY_FORCE_TO_INSTALL}(String):字段 PROPERTY_FORCE_TO_INSTALL</li>
* <li>{@code PROPERTY_SAVE_AS}(String):字段 PROPERTY_SAVE_AS</li>
* <li>{@code PROPERTY_KEEP_BACKUP}(String):字段 PROPERTY_KEEP_BACKUP</li>
* <li>{@code isDefault}(boolean):判断是否Default</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class DeployOption { public class DeployOption {
/**
* 字段 PROPERTY_DEFAULT。
*/
public static final String PROPERTY_DEFAULT = "default"; public static final String PROPERTY_DEFAULT = "default";
/**
* 字段 PROPERTY_FORCE_TO_DOWNLOAD。
*/
public static final String PROPERTY_FORCE_TO_DOWNLOAD = "force_to_download"; public static final String PROPERTY_FORCE_TO_DOWNLOAD = "force_to_download";
/**
* 字段 PROPERTY_FORCE_TO_INSTALL。
*/
public static final String PROPERTY_FORCE_TO_INSTALL = "force_to_install"; public static final String PROPERTY_FORCE_TO_INSTALL = "force_to_install";
/**
* 字段 PROPERTY_SAVE_AS。
*/
public static final String PROPERTY_SAVE_AS = "save_as"; public static final String PROPERTY_SAVE_AS = "save_as";
/**
* 字段 PROPERTY_KEEP_BACKUP。
*/
public static final String PROPERTY_KEEP_BACKUP = "keep_backgup"; public static final String PROPERTY_KEEP_BACKUP = "keep_backgup";
/**
* 判断是否Default。
*/
private boolean isDefault; private boolean isDefault;
/**
* uninstall第一。
*/
private boolean uninstallFirst; private boolean uninstallFirst;
/**
* keep数据。
*/
private boolean keepData; private boolean keepData;
/**
* force转换为下载。
*/
private boolean forceToDownload; private boolean forceToDownload;
/**
* forece转换为Install。
*/
private boolean foreceToInstall; private boolean foreceToInstall;
/**
* 保存转换为。
*/
private String saveTo; private String saveTo;
/**
* 是否keepBackup。
*/
private boolean keepBackup; private boolean keepBackup;
/**
* 判断是否用户Mode。
*/
private boolean isUserMode; private boolean isUserMode;
/**
* 获取 {@code isDefault}。
* @return 字段/派生属性 {@code isDefault} 的值
*/
public boolean getIsDefault() { public boolean getIsDefault() {
return this.isDefault; return this.isDefault;
} }
/**
* 设置 {@code isDefault}。
*
* @param isDefault 参数 {@code isDefault}({@code boolean})
*/
public void setIsDefault(boolean isDefault) { public void setIsDefault(boolean isDefault) {
this.isDefault = isDefault; this.isDefault = isDefault;
} }
/**
* 获取 {@code uninstallFirst}。
* @return 字段/派生属性 {@code uninstallFirst} 的值
*/
public boolean getUninstallFirst() { public boolean getUninstallFirst() {
return this.uninstallFirst; return this.uninstallFirst;
} }
/**
* 设置 {@code uninstallFirst}。
*
* @param uninstallFirst 参数 {@code uninstallFirst}({@code boolean})
*/
public void setUninstallFirst(boolean uninstallFirst) { public void setUninstallFirst(boolean uninstallFirst) {
this.uninstallFirst = uninstallFirst; this.uninstallFirst = uninstallFirst;
} }
/**
* 获取 {@code keepData}。
* @return 字段/派生属性 {@code keepData} 的值
*/
public boolean getKeepData() { public boolean getKeepData() {
return this.keepData; return this.keepData;
} }
/**
* 设置 {@code keepData}。
*
* @param keepData 参数 {@code keepData}({@code boolean})
*/
public void setKeepData(boolean keepData) { public void setKeepData(boolean keepData) {
this.keepData = keepData; this.keepData = keepData;
} }
/**
* 获取 {@code forceToDownload}。
* @return 字段/派生属性 {@code forceToDownload} 的值
*/
public boolean getForceToDownload() { public boolean getForceToDownload() {
return this.forceToDownload; return this.forceToDownload;
} }
/**
* 设置 {@code forceToDownload}。
*
* @param forceToDownload 参数 {@code forceToDownload}({@code boolean})
*/
public void setForceToDownload(boolean forceToDownload) { public void setForceToDownload(boolean forceToDownload) {
this.forceToDownload = forceToDownload; this.forceToDownload = forceToDownload;
} }
/**
* 获取 {@code foreceToInstall}。
* @return 字段/派生属性 {@code foreceToInstall} 的值
*/
public boolean getForeceToInstall() { public boolean getForeceToInstall() {
return this.foreceToInstall; return this.foreceToInstall;
} }
/**
* 设置 {@code foreceToInstall}。
*
* @param foreceToInstall 参数 {@code foreceToInstall}({@code boolean})
*/
public void setForeceToInstall(boolean foreceToInstall) { public void setForeceToInstall(boolean foreceToInstall) {
this.foreceToInstall = foreceToInstall; this.foreceToInstall = foreceToInstall;
} }
/**
* 获取 {@code saveTo}。
* @return 字符串结果
*/
public String getSaveTo() { public String getSaveTo() {
return this.saveTo; return this.saveTo;
} }
/**
* 设置 {@code saveTo}。
*
* @param saveTo 参数 {@code saveTo}({@code String})
*/
public void setSaveTo(String saveTo) { public void setSaveTo(String saveTo) {
this.saveTo = saveTo; this.saveTo = saveTo;
} }
/**
* 获取 {@code keepBackup}。
* @return 字段/派生属性 {@code keepBackup} 的值
*/
public boolean getKeepBackup() { public boolean getKeepBackup() {
return this.keepBackup; return this.keepBackup;
} }
/**
* 设置 {@code keepBackup}。
*
* @param keepBackup 参数 {@code keepBackup}({@code boolean})
*/
public void setKeepBackup(boolean keepBackup) { public void setKeepBackup(boolean keepBackup) {
this.keepBackup = keepBackup; this.keepBackup = keepBackup;
} }
/**
* 获取 {@code isUserMode}。
* @return 字段/派生属性 {@code isUserMode} 的值
*/
public boolean getIsUserMode() { public boolean getIsUserMode() {
return this.isUserMode; return this.isUserMode;
} }
/**
* 设置 {@code isUserMode}。
*
* @param isUserMode 参数 {@code isUserMode}({@code boolean})
*/
public void setIsUserMode(boolean isUserMode) { public void setIsUserMode(boolean isUserMode) {
this.isUserMode = isUserMode; this.isUserMode = isUserMode;
} }
@@ -1,5 +1,20 @@
package com.midm.model.file; package com.midm.model.file;
/**
* 【枚举常量】{@code FILE_TYPE}
*
* 类职责:
* <ul>
* <li>用有限枚举值表达状态/类型,避免魔法字符串。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* </ul>
*
* 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。
*/
public enum FILE_TYPE { public enum FILE_TYPE {
OTA, OTA,
REGION, REGION,
+437 -1
View File
@@ -45,6 +45,9 @@ import org.springframework.data.mongodb.core.mapping.Document;
public class OtaFile extends BaseFile implements Comparable<OtaFile> { public class OtaFile extends BaseFile implements Comparable<OtaFile> {
/** Android Recovery 固件升级脚本入口 */ /** Android Recovery 固件升级脚本入口 */
private static final String ENTRY_META_INF = "META-INF/com/"; private static final String ENTRY_META_INF = "META-INF/com/";
/**
* 字段 ENTRY_UPDATE_SCRIPT。
*/
private static final String ENTRY_UPDATE_SCRIPT = "META-INF/com/google/android/updater-script"; private static final String ENTRY_UPDATE_SCRIPT = "META-INF/com/google/android/updater-script";
/** Android 操作系统属性字典路径(包含型号、Build版本、指纹等关键参数) */ /** Android 操作系统属性字典路径(包含型号、Build版本、指纹等关键参数) */
@@ -55,19 +58,39 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
/** OTA 元数据配置文件(版本区间、差分基线版本等) */ /** OTA 元数据配置文件(版本区间、差分基线版本等) */
private static final String ENTRY_METADATA = "META-INF/com/android/metadata"; private static final String ENTRY_METADATA = "META-INF/com/android/metadata";
/**
* 字段 ENTRY_UPDATE_INFO。
*/
private static final String ENTRY_UPDATE_INFO = "META-INF/com/android/update_info"; private static final String ENTRY_UPDATE_INFO = "META-INF/com/android/update_info";
/** 解析固件包后提取的硬件规格与构建元数据字典 */ /** 解析固件包后提取的硬件规格与构建元数据字典 */
private DbObject otaInfo; private DbObject otaInfo;
/**
* 构造 {@code OtaFile} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public OtaFile() { public OtaFile() {
} }
/**
* 构造 {@code OtaFile} 实例。
*
* @param user 当前用户({@code User})
* @param fileUuid 文件 UUID({@code UUID})
* @param file 文件({@code McFile})
*/
public OtaFile(User user, UUID fileUuid, McFile file) { public OtaFile(User user, UUID fileUuid, McFile file) {
super(user, fileUuid, file); super(user, fileUuid, file);
this.setOtaInfo(file); this.setOtaInfo(file);
} }
/**
* 判断 {@code otaImage}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
* @return 字段/派生属性 {@code otaImage} 的值
*/
public boolean isOtaImage() { public boolean isOtaImage() {
if (Strings.isNullOrEmpty(this.getProductId()) && Strings.isNullOrEmpty(this.getDeviceId())) { if (Strings.isNullOrEmpty(this.getProductId()) && Strings.isNullOrEmpty(this.getDeviceId())) {
return false; return false;
@@ -76,6 +99,12 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
} }
} }
/**
* 获取 {@code otaInfo}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getOtaInfo() { public DbObject getOtaInfo() {
if (this.otaInfo == null) { if (this.otaInfo == null) {
this.otaInfo = new DbObject(); this.otaInfo = new DbObject();
@@ -84,14 +113,32 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
return this.otaInfo; return this.otaInfo;
} }
/**
* 设置 {@code otaInfo}。
*
* @param otaInfo 参数 {@code otaInfo}({@code DbObject})
*/
public void setOtaInfo(DbObject otaInfo) { public void setOtaInfo(DbObject otaInfo) {
this.otaInfo = otaInfo; this.otaInfo = otaInfo;
} }
/**
* 设置OTA 固件信息。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setOtaInfo(String key, Object value) { public void setOtaInfo(String key, Object value) {
this.getOtaInfo().append(key, value); this.getOtaInfo().append(key, value);
} }
/**
* 设置 {@code otaInfo}。
*
* 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ZipFile。
*
* @param file 文件({@code McFile})
*/
public void setOtaInfo(McFile file) { public void setOtaInfo(McFile file) {
try { try {
this.retrieveBuildInfo(new ZipFile(file)); this.retrieveBuildInfo(new ZipFile(file));
@@ -100,30 +147,61 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
} }
/**
* 获取 {@code type}。
* @return 字符串结果
*/
public String getType() { public String getType() {
return this.getOtaInfo().getString("type", "system"); return this.getOtaInfo().getString("type", "system");
} }
/**
* 判断 {@code systemImage}。
* @return 字段/派生属性 {@code systemImage} 的值
*/
public boolean isSystemImage() { public boolean isSystemImage() {
return this.getType().equals("system"); return this.getType().equals("system");
} }
/**
* 判断 {@code regionImage}。
* @return 字段/派生属性 {@code regionImage} 的值
*/
public boolean isRegionImage() { public boolean isRegionImage() {
return this.getType().equals("region"); return this.getType().equals("region");
} }
/**
* 判断 {@code modemImage}。
* @return 字段/派生属性 {@code modemImage} 的值
*/
public boolean isModemImage() { public boolean isModemImage() {
return this.getType().equals("modem"); return this.getType().equals("modem");
} }
/**
* 判断 {@code abUpdate}。
* @return 字段/派生属性 {@code abUpdate} 的值
*/
public boolean isAbUpdate() { public boolean isAbUpdate() {
return this.getOtaInfo().getBoolean("abUpdate", false); return this.getOtaInfo().getBoolean("abUpdate", false);
} }
/**
* 判断 {@code partial}。
* @return 字段/派生属性 {@code partial} 的值
*/
public boolean isPartial() { public boolean isPartial() {
return this.getOtaInfo().containsKey("preBuild"); return this.getOtaInfo().containsKey("preBuild");
} }
/**
* 设置 {@code type}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param type 类型({@code String})
*/
public void setType(String type) { public void setType(String type) {
if (type.toLowerCase().equals("base")) { if (type.toLowerCase().equals("base")) {
type = "system"; type = "system";
@@ -132,67 +210,142 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
this.getOtaInfo().put("type", type); this.getOtaInfo().put("type", type);
} }
/**
* 设置 {@code abUpdate}。
*
* @param abUpdate 参数 {@code abUpdate}({@code boolean})
*/
public void setAbUpdate(boolean abUpdate) { public void setAbUpdate(boolean abUpdate) {
this.getOtaInfo().put("abUpdate", abUpdate); this.getOtaInfo().put("abUpdate", abUpdate);
} }
/**
* 获取 {@code buildDate}。
* @return 数量/长度
*/
public long getBuildDate() { public long getBuildDate() {
return this.getOtaInfo().getLong("buildDate", -1L); return this.getOtaInfo().getLong("buildDate", -1L);
} }
/**
* 设置 {@code buildDate}。
*
* @param date 参数 {@code date}({@code long})
*/
public void setBuildDate(long date) { public void setBuildDate(long date) {
this.setOtaInfo("buildDate", date); this.setOtaInfo("buildDate", date);
} }
/**
* 获取 {@code sdkLevel}。
* @return 数量/长度
*/
public int getSdkLevel() { public int getSdkLevel() {
return this.getOtaInfo().getInteger("sdk", -1); return this.getOtaInfo().getInteger("sdk", -1);
} }
/**
* 设置 {@code sdkLevel}。
*
* @param level 参数 {@code level}({@code int})
*/
public void setSdkLevel(int level) { public void setSdkLevel(int level) {
this.setOtaInfo("sdk", level); this.setOtaInfo("sdk", level);
} }
/**
* 获取 {@code postBuildDate}。
* @return 数量/长度
*/
public long getPostBuildDate() { public long getPostBuildDate() {
return this.getOtaInfo().getLong("postBuildDate", -1L); return this.getOtaInfo().getLong("postBuildDate", -1L);
} }
/**
* 设置 {@code postBuildDate}。
*
* @param date 参数 {@code date}({@code long})
*/
public void setPostBuildDate(long date) { public void setPostBuildDate(long date) {
this.setOtaInfo("postBuildDate", date); this.setOtaInfo("postBuildDate", date);
} }
/**
* 获取 {@code productId}。
* @return 字符串结果
*/
public String getProductId() { public String getProductId() {
return this.getOtaInfo().getString("productId"); return this.getOtaInfo().getString("productId");
} }
/**
* 设置 {@code productId}。
*
* @param productId 参数 {@code productId}({@code String})
*/
public void setProductId(String productId) { public void setProductId(String productId) {
this.setOtaInfo("productId", productId); this.setOtaInfo("productId", productId);
} }
/**
* 获取 {@code targetProduct}。
* @return 字符串结果
*/
public String getTargetProduct() { public String getTargetProduct() {
return this.getOtaInfo().getString("targetProduct"); return this.getOtaInfo().getString("targetProduct");
} }
/**
* 设置 {@code targetProduct}。
*
* @param productId 参数 {@code productId}({@code String})
*/
public void setTargetProduct(String productId) { public void setTargetProduct(String productId) {
this.setOtaInfo("targetProduct", productId); this.setOtaInfo("targetProduct", productId);
} }
/**
* 获取 {@code skuId}。
* @return 字符串结果
*/
public String getSkuId() { public String getSkuId() {
return this.getOtaInfo().getString("skuId"); return this.getOtaInfo().getString("skuId");
} }
/**
* 设置 {@code skuId}。
*
* @param skuId 参数 {@code skuId}({@code String})
*/
public void setSkuId(String skuId) { public void setSkuId(String skuId) {
this.setOtaInfo("skuId", skuId); this.setOtaInfo("skuId", skuId);
} }
/**
* 判断 {@code compatibleSkuIds}。
* @return 字段/派生属性 {@code compatibleSkuIds} 的值
*/
public boolean hasCompatibleSkuIds() { public boolean hasCompatibleSkuIds() {
List<String> ids = this.getOtaInfo().getList("compatibleSkuIds", String.class); List<String> ids = this.getOtaInfo().getList("compatibleSkuIds", String.class);
return ids != null && ids.size() > 0; return ids != null && ids.size() > 0;
} }
public List getCompatibleSkuIds() { /**
* 获取 {@code compatibleSkuIds}。
* @return String列表,可能为空
*/
public List<String> getCompatibleSkuIds() {
return this.getOtaInfo().getList("compatibleSkuIds", String.class); return this.getOtaInfo().getList("compatibleSkuIds", String.class);
} }
/**
* 判断是否CompatibleSkuID。
*
* 实现要点:包含 2 个条件分支、0 个循环。
*
* @param skuId 参数 {@code skuId}({@code String})
* @return 字段/派生属性 {@code compatibleSkuId} 的值
*/
public boolean isCompatibleSkuId(String skuId) { public boolean isCompatibleSkuId(String skuId) {
if (Strings.isNullOrEmpty(skuId)) { if (Strings.isNullOrEmpty(skuId)) {
return false; return false;
@@ -207,6 +360,13 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
} }
} }
/**
* 设置 {@code compatibleSkuIds}。
*
* 实现要点:包含 2 个条件分支、0 个循环。
*
* @param skuIds 参数 {@code skuIds}({@code String})
*/
public void setCompatibleSkuIds(String skuIds) { public void setCompatibleSkuIds(String skuIds) {
if (!Strings.isNullOrEmpty(skuIds)) { if (!Strings.isNullOrEmpty(skuIds)) {
String[] ids = skuIds.split("\\s*,\\s*"); String[] ids = skuIds.split("\\s*,\\s*");
@@ -217,34 +377,74 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
} }
/**
* 获取 {@code deviceId}。
* @return 字符串结果
*/
public String getDeviceId() { public String getDeviceId() {
return this.getOtaInfo().getString("deviceId"); return this.getOtaInfo().getString("deviceId");
} }
/**
* 设置 {@code deviceId}。
*
* @param deviceId 参数 {@code deviceId}({@code String})
*/
public void setDeviceId(String deviceId) { public void setDeviceId(String deviceId) {
this.setOtaInfo("deviceId", deviceId); this.setOtaInfo("deviceId", deviceId);
} }
/**
* 获取 {@code displayId}。
* @return 字符串结果
*/
public String getDisplayId() { public String getDisplayId() {
return this.getOtaInfo().getString("displayId"); return this.getOtaInfo().getString("displayId");
} }
/**
* 设置 {@code displayId}。
*
* @param displayId 参数 {@code displayId}({@code String})
*/
public void setDisplayId(String displayId) { public void setDisplayId(String displayId) {
this.setOtaInfo("displayId", displayId); this.setOtaInfo("displayId", displayId);
} }
/**
* 设置 {@code productDisplayId}。
*
* @param displayId 参数 {@code displayId}({@code String})
*/
public void setProductDisplayId(String displayId) { public void setProductDisplayId(String displayId) {
this.setOtaInfo("productDisplayId", displayId); this.setOtaInfo("productDisplayId", displayId);
} }
/**
* 获取 {@code preDisplayId}。
* @return 字符串结果
*/
public String getPreDisplayId() { public String getPreDisplayId() {
return this.getOtaInfo().getString("preDisplayId"); return this.getOtaInfo().getString("preDisplayId");
} }
/**
* 设置 {@code preDisplayId}。
*
* @param displayId 参数 {@code displayId}({@code String})
*/
public void setPreDisplayId(String displayId) { public void setPreDisplayId(String displayId) {
this.setOtaInfo("preDisplayId", displayId); this.setOtaInfo("preDisplayId", displayId);
} }
/**
* 解析SkuID。
*
* 实现要点:包含 3 个条件分支、0 个循环。
*
* @param displayId 参数 {@code displayId}({@code String})
* @return 字符串结果
*/
public static String parseSkuId(String displayId) { public static String parseSkuId(String displayId) {
if (displayId != null) { if (displayId != null) {
int startIndex = displayId.indexOf(46); int startIndex = displayId.indexOf(46);
@@ -262,142 +462,302 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
return null; return null;
} }
/**
* 获取 {@code brand}。
* @return 字符串结果
*/
public String getBrand() { public String getBrand() {
return this.getOtaInfo().getString("brand"); return this.getOtaInfo().getString("brand");
} }
/**
* 设置 {@code brand}。
*
* @param brand 参数 {@code brand}({@code String})
*/
public void setBrand(String brand) { public void setBrand(String brand) {
this.setOtaInfo("brand", brand); this.setOtaInfo("brand", brand);
} }
/**
* 获取 {@code customer}。
* @return 字符串结果
*/
public String getCustomer() { public String getCustomer() {
return this.getOtaInfo().getString("customer"); return this.getOtaInfo().getString("customer");
} }
/**
* 设置 {@code customer}。
*
* @param customer 参数 {@code customer}({@code String})
*/
public void setCustomer(String customer) { public void setCustomer(String customer) {
this.setOtaInfo("customer", customer); this.setOtaInfo("customer", customer);
} }
/**
* 获取 {@code customerId}。
* @return 字符串结果
*/
public String getCustomerId() { public String getCustomerId() {
return this.getOtaInfo().getString("customerId"); return this.getOtaInfo().getString("customerId");
} }
/**
* 设置 {@code customerId}。
*
* @param customerId 参数 {@code customerId}({@code String})
*/
public void setCustomerId(String customerId) { public void setCustomerId(String customerId) {
this.setOtaInfo("customerId", customerId); this.setOtaInfo("customerId", customerId);
} }
/**
* 获取 {@code partNo}。
* @return 字符串结果
*/
public String getPartNo() { public String getPartNo() {
return this.getOtaInfo().getString("partNo"); return this.getOtaInfo().getString("partNo");
} }
/**
* 设置 {@code partNo}。
*
* @param partNo 参数 {@code partNo}({@code String})
*/
public void setPartNo(String partNo) { public void setPartNo(String partNo) {
this.setOtaInfo("partNo", partNo); this.setOtaInfo("partNo", partNo);
} }
/**
* 获取 {@code osVersion}。
* @return 字符串结果
*/
public String getOsVersion() { public String getOsVersion() {
return this.getOtaInfo().getString("osVersion"); return this.getOtaInfo().getString("osVersion");
} }
/**
* 设置 {@code osVersion}。
*
* @param version 参数 {@code version}({@code String})
*/
public void setOsVersion(String version) { public void setOsVersion(String version) {
this.setOtaInfo("osVersion", version); this.setOtaInfo("osVersion", version);
} }
/**
* 获取 {@code scriptVersion}。
* @return 字符串结果
*/
public String getScriptVersion() { public String getScriptVersion() {
return this.getOtaInfo().getString("scriptVersion"); return this.getOtaInfo().getString("scriptVersion");
} }
/**
* 设置 {@code scriptVersion}。
*
* @param partNo 参数 {@code partNo}({@code String})
*/
public void setScriptVersion(String partNo) { public void setScriptVersion(String partNo) {
this.setOtaInfo("scriptVersion", partNo); this.setOtaInfo("scriptVersion", partNo);
} }
/**
* 获取 {@code releaseVersion}。
* @return 字符串结果
*/
public String getReleaseVersion() { public String getReleaseVersion() {
return this.getOtaInfo().getString("releaseVersion"); return this.getOtaInfo().getString("releaseVersion");
} }
/**
* 设置 {@code releaseVersion}。
*
* @param partNo 参数 {@code partNo}({@code String})
*/
public void setReleaseVersion(String partNo) { public void setReleaseVersion(String partNo) {
this.setOtaInfo("releaseVersion", partNo); this.setOtaInfo("releaseVersion", partNo);
} }
/**
* 获取 {@code marketName1}。
* @return 字符串结果
*/
public String getMarketName1() { public String getMarketName1() {
return this.getOtaInfo().getString("marketName1"); return this.getOtaInfo().getString("marketName1");
} }
/**
* 设置 {@code marketName1}。
*
* @param name 参数 {@code name}({@code String})
*/
public void setMarketName1(String name) { public void setMarketName1(String name) {
this.setOtaInfo("marketName1", name); this.setOtaInfo("marketName1", name);
} }
/**
* 获取 {@code marketName2}。
* @return 字符串结果
*/
public String getMarketName2() { public String getMarketName2() {
return this.getOtaInfo().getString("marketName2"); return this.getOtaInfo().getString("marketName2");
} }
/**
* 设置 {@code marketName2}。
*
* @param name 参数 {@code name}({@code String})
*/
public void setMarketName2(String name) { public void setMarketName2(String name) {
this.setOtaInfo("marketName2", name); this.setOtaInfo("marketName2", name);
} }
/**
* 获取 {@code securityPatchLevel}。
* @return 字符串结果
*/
public String getSecurityPatchLevel() { public String getSecurityPatchLevel() {
return this.getOtaInfo().getString("securityPatch"); return this.getOtaInfo().getString("securityPatch");
} }
/**
* 设置 {@code securityPatchLevel}。
*
* @param level 参数 {@code level}({@code String})
*/
public void setSecurityPatchLevel(String level) { public void setSecurityPatchLevel(String level) {
this.setOtaInfo("securityPatch", level); this.setOtaInfo("securityPatch", level);
} }
/**
* 获取 {@code buildType}。
* @return 字符串结果
*/
public String getBuildType() { public String getBuildType() {
return this.getOtaInfo().getString("buildType"); return this.getOtaInfo().getString("buildType");
} }
/**
* 设置 {@code buildType}。
*
* @param buildType 参数 {@code buildType}({@code String})
*/
public void setBuildType(String buildType) { public void setBuildType(String buildType) {
this.setOtaInfo("buildType", buildType); this.setOtaInfo("buildType", buildType);
} }
/**
* 获取 {@code buildTags}。
* @return 字符串结果
*/
public String getBuildTags() { public String getBuildTags() {
return this.getOtaInfo().getString("buildTags"); return this.getOtaInfo().getString("buildTags");
} }
/**
* 设置 {@code buildTags}。
*
* @param buildTags 参数 {@code buildTags}({@code String})
*/
public void setBuildTags(String buildTags) { public void setBuildTags(String buildTags) {
this.setOtaInfo("buildTags", buildTags); this.setOtaInfo("buildTags", buildTags);
} }
/**
* 获取 {@code preBuild}。
* @return 字符串结果
*/
public String getPreBuild() { public String getPreBuild() {
return this.getOtaInfo().getString("preBuild"); return this.getOtaInfo().getString("preBuild");
} }
/**
* 设置 {@code preBuild}。
*
* @param value 值({@code String})
*/
public void setPreBuild(String value) { public void setPreBuild(String value) {
this.setOtaInfo("preBuild", value); this.setOtaInfo("preBuild", value);
} }
/**
* 获取 {@code otaCertHash}。
* @return 字符串结果
*/
public String getOtaCertHash() { public String getOtaCertHash() {
return this.getOtaInfo().getString("otaCert"); return this.getOtaInfo().getString("otaCert");
} }
/**
* 设置 {@code otaCertHash}。
*
* @param hash 参数 {@code hash}({@code String})
*/
public void setOtaCertHash(String hash) { public void setOtaCertHash(String hash) {
this.setOtaInfo("otaCert", hash); this.setOtaInfo("otaCert", hash);
} }
/**
* 获取 {@code modemSku}。
* @return 字符串结果
*/
public String getModemSku() { public String getModemSku() {
return this.getOtaInfo().getString("modemSku"); return this.getOtaInfo().getString("modemSku");
} }
/**
* 设置 {@code modemSku}。
*
* @param hash 参数 {@code hash}({@code String})
*/
public void setModemSku(String hash) { public void setModemSku(String hash) {
this.setOtaInfo("modemSku", hash); this.setOtaInfo("modemSku", hash);
} }
/**
* 获取 {@code modemFirmwareVersion}。
* @return 字符串结果
*/
public String getModemFirmwareVersion() { public String getModemFirmwareVersion() {
return this.getOtaInfo().getString("modemFirmwareVersion"); return this.getOtaInfo().getString("modemFirmwareVersion");
} }
/**
* 设置 {@code modemFirmwareVersion}。
*
* @param hash 参数 {@code hash}({@code String})
*/
public void setModemFirmwareVersion(String hash) { public void setModemFirmwareVersion(String hash) {
this.setOtaInfo("modemFirmwareVersion", hash); this.setOtaInfo("modemFirmwareVersion", hash);
} }
/**
* 获取 {@code modemFirmwareLongVersion}。
* @return 字符串结果
*/
public String getModemFirmwareLongVersion() { public String getModemFirmwareLongVersion() {
return this.getOtaInfo().getString("modemFirmwareLongVersion"); return this.getOtaInfo().getString("modemFirmwareLongVersion");
} }
/**
* 设置 {@code modemFirmwareLongVersion}。
*
* @param hash 参数 {@code hash}({@code String})
*/
public void setModemFirmwareLongVersion(String hash) { public void setModemFirmwareLongVersion(String hash) {
this.setOtaInfo("modemFirmwareLongVersion", hash); this.setOtaInfo("modemFirmwareLongVersion", hash);
} }
/**
* 处理retrieve构建信息。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 13 个条件分支、2 个循环;主要调用:new ZipInputStream、close。
*
* @param zipFile 参数 {@code zipFile}({@code ZipFile})
*/
private void retrieveBuildInfo(ZipFile zipFile) { private void retrieveBuildInfo(ZipFile zipFile) {
try { try {
Enumeration<? extends ZipEntry> entries = zipFile.entries(); Enumeration<? extends ZipEntry> entries = zipFile.entries();
@@ -475,6 +835,13 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
} }
/**
* 处理dispatchUpdaterScript。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 8 个条件分支、0 个循环。
*
* @param is 参数 {@code is}({@code InputStream})
*/
private void dispatchUpdaterScript(InputStream is) { private void dispatchUpdaterScript(InputStream is) {
try { try {
String script = IOUtils.toString(is, "UTF-8"); String script = IOUtils.toString(is, "UTF-8");
@@ -520,6 +887,13 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
} }
/**
* 处理dispatchProp。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 0 个条件分支、1 个循环;主要调用:new Properties。
*
* @param input 参数 {@code input}({@code InputStream})
*/
private void dispatchProp(InputStream input) { private void dispatchProp(InputStream input) {
try { try {
Properties properties = new Properties(); Properties properties = new Properties();
@@ -534,6 +908,13 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
} }
/**
* 处理dispatchJSON。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、1 个循环。
*
* @param input 参数 {@code input}({@code InputStream})
*/
private void dispatchJson(InputStream input) { private void dispatchJson(InputStream input) {
if (input != null) { if (input != null) {
JsonElement json = McJsonUtils.toJsonElement(input); JsonElement json = McJsonUtils.toJsonElement(input);
@@ -552,11 +933,26 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
} }
} }
/**
* 处理dispatchOTA 固件证书。
*
* 实现要点:主要调用:new McOtaCert。
*
* @param otaCertIs 参数 {@code otaCertIs}({@code InputStream})
*/
private void dispatchOtaCert(InputStream otaCertIs) { private void dispatchOtaCert(InputStream otaCertIs) {
McOtaCert otaCert = new McOtaCert(otaCertIs); McOtaCert otaCert = new McOtaCert(otaCertIs);
this.setOtaCertHash(otaCert.getBase64Hash()); this.setOtaCertHash(otaCert.getBase64Hash());
} }
/**
* 设置OTA 固件Property。
*
* 实现要点:包含 25 个条件分支、0 个循环。
*
* @param key 键/配置项({@code String})
* @param value 值({@code String})
*/
private void setOtaProperty(String key, String value) { private void setOtaProperty(String key, String value) {
switch (key) { switch (key) {
case "ota-type": case "ota-type":
@@ -660,6 +1056,7 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
break; break;
case "mitac-package-type": case "mitac-package-type":
this.setType(value); this.setType(value);
break;
case "post-build-incremental": case "post-build-incremental":
default: default:
break; break;
@@ -711,10 +1108,21 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
} }
/**
* 获取 {@code postBuild}。
* @return 字符串结果
*/
public String getPostBuild() { public String getPostBuild() {
return this.getOtaInfo().getString("postBuild"); return this.getOtaInfo().getString("postBuild");
} }
/**
* 处理dispatchPost构建。
*
* 实现要点:包含 4 个条件分支、0 个循环。
*
* @param text 参数 {@code text}({@code String})
*/
private void dispatchPostBuild(String text) { private void dispatchPostBuild(String text) {
this.setOtaInfo("postBuild", text); this.setOtaInfo("postBuild", text);
String[] tags = text.split(":"); String[] tags = text.split(":");
@@ -736,6 +1144,17 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
} }
/**
* 处理subString。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param sb 参数 {@code sb}({@code String})
* @param key 键/配置项({@code String})
* @param prefix 参数 {@code prefix}({@code String})
* @param suffix 参数 {@code suffix}({@code String})
* @return 字符串结果
*/
private String subString(String sb, String key, String prefix, String suffix) { private String subString(String sb, String key, String prefix, String suffix) {
int keyIndex = sb.indexOf(key); int keyIndex = sb.indexOf(key);
if (keyIndex < 0) { if (keyIndex < 0) {
@@ -747,6 +1166,15 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
} }
} }
/**
* 处理最后SubString。
*
* @param sb 参数 {@code sb}({@code String})
* @param key 键/配置项({@code String})
* @param prefix 参数 {@code prefix}({@code String})
* @param suffix 参数 {@code suffix}({@code String})
* @return 字符串结果
*/
private String lastSubString(String sb, String key, String prefix, String suffix) { private String lastSubString(String sb, String key, String prefix, String suffix) {
int keyIndex = sb.indexOf(key); int keyIndex = sb.indexOf(key);
int endIndex = sb.lastIndexOf(",", keyIndex); int endIndex = sb.lastIndexOf(",", keyIndex);
@@ -754,6 +1182,14 @@ public class OtaFile extends BaseFile implements Comparable<OtaFile> {
return startIndex < endIndex ? sb.substring(startIndex, endIndex) : ""; return startIndex < endIndex ? sb.substring(startIndex, endIndex) : "";
} }
/**
* 按业务字段比较两个对象的顺序。
*
* 实现要点:包含 6 个条件分支、0 个循环。
*
* @param other 参数 {@code other}({@code OtaFile})
* @return 数量/长度
*/
public int compareTo(OtaFile other) { public int compareTo(OtaFile other) {
int result = this.getSkuId().compareTo(other.getSkuId()); int result = this.getSkuId().compareTo(other.getSkuId());
if (result == 0) { if (result == 0) {
@@ -2,6 +2,23 @@ package com.midm.model.file;
import java.util.List; import java.util.List;
/**
* 【枚举常量】{@code REPORT_ERROR}
*
* 类职责:
* <ul>
* <li>用有限枚举值表达状态/类型,避免魔法字符串。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code COLLECT_SSN}(List<REPORT_ERROR>):REPORT_ERROR集合</li>
* <li>{@code value}(int):值</li>
* </ul>
*
* 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。
*/
public enum REPORT_ERROR { public enum REPORT_ERROR {
UNKNOWN(1000), UNKNOWN(1000),
FILE_ERROR(1001), FILE_ERROR(1001),
@@ -14,17 +31,40 @@ public enum REPORT_ERROR {
FILE_ALREADY_EXISTS(1009), FILE_ALREADY_EXISTS(1009),
FILE_MISMATCHED(2001); FILE_MISMATCHED(2001);
public static final List COLLECT_SSN = List.of(UNKNOWN, FILE_ERROR, INSUFFICIENT_SPACE, DEVICE_NOT_FOUND, CANNOT_RESUME, FILE_ALREADY_EXISTS); /**
* REPORT_ERROR集合。
*/
public static final List<REPORT_ERROR> COLLECT_SSN = List.of(UNKNOWN, FILE_ERROR, INSUFFICIENT_SPACE, DEVICE_NOT_FOUND, CANNOT_RESUME, FILE_ALREADY_EXISTS);
/**
* 值。
*/
private int value; private int value;
/**
* 构造 {@code REPORT_ERROR} 实例。
*
* @param value 值({@code int})
*/
private REPORT_ERROR(int value) { private REPORT_ERROR(int value) {
this.value = value; this.value = value;
} }
/**
* 获取 {@code value}。
* @return 数量/长度
*/
public int getValue() { public int getValue() {
return this.value; return this.value;
} }
/**
* 处理从值。
*
* 实现要点:包含 1 个条件分支、1 个循环。
*
* @param value 值({@code int})
* @return 处理结果
*/
public static REPORT_ERROR fromValue(int value) { public static REPORT_ERROR fromValue(int value) {
for(REPORT_ERROR e : values()) { for(REPORT_ERROR e : values()) {
if (e.getValue() == value) { if (e.getValue() == value) {
@@ -0,0 +1,17 @@
/**
* 文件领域模型:APK/OTA/报表/图片等文件元数据与上传结果。
*
* <p>本包主要类型:
* <ul>
* <li>{@link AppFile}</li>
* <li>{@link BaseFile}</li>
* <li>{@link DeployOption}</li>
* <li>{@link FILE_TYPE}</li>
* <li>{@link OtaFile}</li>
* <li>{@link REPORT_ERROR}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.model.file;
@@ -12,6 +12,31 @@ import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code MidmLog}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code forWhat}(UUID):用于What</li>
* <li>{@code category}(String):字段 category</li>
* <li>{@code log}(String):日志</li>
* <li>{@code reference}(DbObject):字段 reference</li>
* <li>{@code loggedAt}(Date):时间字段</li>
* </ul>
*
* 协作对象:{@code DbObject、User}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
@CompoundIndexes({@CompoundIndex( @CompoundIndexes({@CompoundIndex(
def = "{'category':1, 'loggedAt':1}" def = "{'category':1, 'loggedAt':1}"
@@ -21,21 +46,62 @@ import org.springframework.data.mongodb.core.mapping.Document;
def = "{'forWhat':1, 'log': 1}" def = "{'forWhat':1, 'log': 1}"
)}) )})
public class MidmLog { public class MidmLog {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid; private UUID uuid;
/**
* 用于What。
*/
private UUID forWhat; private UUID forWhat;
/**
* 字段 category。
*/
private String category; private String category;
/**
* 日志。
*/
private String log; private String log;
/**
* 字段 reference。
*/
private DbObject reference; private DbObject reference;
/**
* 时间字段。
*/
private Date loggedAt; private Date loggedAt;
/**
* 字段 logger;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private User logger; private User logger;
/**
* 构造 {@code MidmLog} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*
* 实现要点:主要调用:new Date。
*/
public MidmLog() { public MidmLog() {
this.setUuid(UUID.randomUUID()); this.setUuid(UUID.randomUUID());
this.setLoggedAt(new Date()); this.setLoggedAt(new Date());
} }
/**
* 构造 {@code MidmLog} 实例。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param user 当前用户({@code User})
* @param forWhat 参数 {@code forWhat}({@code UUID})
* @param category 分类(app/ota/other/report 等)({@code String})
* @param log 参数 {@code log}({@code String})
*/
public MidmLog(User user, UUID forWhat, String category, String log) { public MidmLog(User user, UUID forWhat, String category, String log) {
this(); this();
if (user != null) { if (user != null) {
@@ -47,38 +113,80 @@ public class MidmLog {
this.setLog(log); this.setLog(log);
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code forWhat}。
* @return UUID
*/
public UUID getForWhat() { public UUID getForWhat() {
return this.forWhat; return this.forWhat;
} }
/**
* 设置 {@code forWhat}。
*
* @param forWhat 参数 {@code forWhat}({@code UUID})
*/
public void setForWhat(UUID forWhat) { public void setForWhat(UUID forWhat) {
this.forWhat = forWhat; this.forWhat = forWhat;
} }
/**
* 获取 {@code category}。
* @return 字符串结果
*/
public String getCategory() { public String getCategory() {
return this.category; return this.category;
} }
/**
* 设置 {@code category}。
*
* @param category 分类(app/ota/other/report 等)({@code String})
*/
public void setCategory(String category) { public void setCategory(String category) {
this.category = category; this.category = category;
} }
/**
* 获取 {@code log}。
* @return 字符串结果
*/
public String getLog() { public String getLog() {
return this.log; return this.log;
} }
/**
* 设置 {@code log}。
*
* @param log 参数 {@code log}({@code String})
*/
public void setLog(String log) { public void setLog(String log) {
this.log = log; this.log = log;
} }
/**
* 获取 {@code reference}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getReference() { public DbObject getReference() {
if (this.reference == null) { if (this.reference == null) {
this.reference = new DbObject(); this.reference = new DbObject();
@@ -87,14 +195,32 @@ public class MidmLog {
return this.reference; return this.reference;
} }
/**
* 判断 {@code reference}。
* @return 字段/派生属性 {@code reference} 的值
*/
public boolean hasReference() { public boolean hasReference() {
return this.reference != null && this.reference.size() > 0; return this.reference != null && this.reference.size() > 0;
} }
/**
* 设置 {@code reference}。
*
* @param reference 参数 {@code reference}({@code DbObject})
*/
public void setReference(DbObject reference) { public void setReference(DbObject reference) {
this.reference = reference; this.reference = reference;
} }
/**
* 设置Reference。
*
* 实现要点:包含 3 个条件分支、0 个循环。
*
* @param agent 参数 {@code agent}({@code UserAgent})
* @param sessionId 参数 {@code sessionId}({@code String})
* @param remoteIp 参数 {@code remoteIp}({@code String})
*/
public void setReference(UserAgent agent, String sessionId, String remoteIp) { public void setReference(UserAgent agent, String sessionId, String remoteIp) {
if (agent != null) { if (agent != null) {
this.addReference("browser", agent.agentFamily()); this.addReference("browser", agent.agentFamily());
@@ -112,30 +238,65 @@ public class MidmLog {
} }
/**
* 添加Reference。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void addReference(String key, Object value) { public void addReference(String key, Object value) {
this.getReference().put(key, value); this.getReference().put(key, value);
} }
/**
* 获取 {@code loggerUuid}。
* @return UUID
*/
public UUID getLoggerUuid() { public UUID getLoggerUuid() {
return this.logger != null ? this.logger.getUuid() : null; return this.logger != null ? this.logger.getUuid() : null;
} }
/**
* 获取 {@code loggedAt}。
* @return 字段/派生属性 {@code loggedAt} 的值
*/
public Date getLoggedAt() { public Date getLoggedAt() {
return this.loggedAt; return this.loggedAt;
} }
/**
* 设置 {@code loggedAt}。
*
* @param loggedAt 参数 {@code loggedAt}({@code Date})
*/
public void setLoggedAt(Date loggedAt) { public void setLoggedAt(Date loggedAt) {
this.loggedAt = loggedAt; this.loggedAt = loggedAt;
} }
/**
* 设置 {@code loggedAt}。
*
* 实现要点:主要调用:new Date。
*
* @param loggedAt 参数 {@code loggedAt}({@code long})
*/
public void setLoggedAt(long loggedAt) { public void setLoggedAt(long loggedAt) {
this.loggedAt = new Date(loggedAt); this.loggedAt = new Date(loggedAt);
} }
/**
* 获取 {@code logger}。
* @return 用户对象;未找到时返回 {@code null}
*/
public User getLogger() { public User getLogger() {
return this.logger; return this.logger;
} }
/**
* 设置 {@code logger}。
*
* @param logger 参数 {@code logger}({@code User})
*/
public void setLogger(User logger) { public void setLogger(User logger) {
this.logger = logger; this.logger = logger;
} }
@@ -0,0 +1,12 @@
/**
* 审计与操作日志模型。
*
* <p>本包主要类型:
* <ul>
* <li>{@link MidmLog}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.model.log;
@@ -1,5 +1,22 @@
package com.midm.model.message; package com.midm.model.message;
/**
* 【枚举常量】{@code MIDM_REQUEST}
*
* 类职责:
* <ul>
* <li>用有限枚举值表达状态/类型,避免魔法字符串。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code code}(int):代码</li>
* <li>{@code request}(String):请求</li>
* </ul>
*
* 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。
*/
public enum MIDM_REQUEST { public enum MIDM_REQUEST {
PING(99, "ping"), PING(99, "ping"),
CONNECT(100, "connect"), CONNECT(100, "connect"),
@@ -21,22 +38,50 @@ public enum MIDM_REQUEST {
RTC(400, "rtc"), RTC(400, "rtc"),
UNKNOWN(-1, ""); UNKNOWN(-1, "");
/**
* 代码。
*/
private int code; private int code;
/**
* 请求。
*/
private String request; private String request;
/**
* 构造 {@code MIDM_REQUEST} 实例。
*
* @param code 状态码/业务码({@code int})
* @param request HTTP 请求({@code String})
*/
private MIDM_REQUEST(int code, String request) { private MIDM_REQUEST(int code, String request) {
this.code = code; this.code = code;
this.request = request; this.request = request;
} }
/**
* 获取 {@code code}。
* @return 数量/长度
*/
public int getCode() { public int getCode() {
return this.code; return this.code;
} }
/**
* 获取 {@code request}。
* @return 字符串结果
*/
public String getRequest() { public String getRequest() {
return this.request; return this.request;
} }
/**
* 处理获取。
*
* 实现要点:包含 1 个条件分支、1 个循环。
*
* @param code 状态码/业务码({@code int})
* @return 处理结果
*/
public static MIDM_REQUEST get(int code) { public static MIDM_REQUEST get(int code) {
for(MIDM_REQUEST request : values()) { for(MIDM_REQUEST request : values()) {
if (request.code == code) { if (request.code == code) {
@@ -47,6 +92,14 @@ public enum MIDM_REQUEST {
return UNKNOWN; return UNKNOWN;
} }
/**
* 处理获取。
*
* 实现要点:包含 1 个条件分支、1 个循环。
*
* @param requestText 参数 {@code requestText}({@code String})
* @return 处理结果
*/
public static MIDM_REQUEST get(String requestText) { public static MIDM_REQUEST get(String requestText) {
for(MIDM_REQUEST request : values()) { for(MIDM_REQUEST request : values()) {
if (request.getRequest().equalsIgnoreCase(requestText.trim())) { if (request.getRequest().equalsIgnoreCase(requestText.trim())) {
@@ -14,121 +14,306 @@ import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.web.socket.BinaryMessage; import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.TextMessage;
/**
* 【MongoDB 文档实体】{@code MidmPacket}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code recieverUuid}(UUID):recieverUUID</li>
* <li>{@code queryUuid}(UUID):查询UUID</li>
* <li>{@code query}(MidmQuery):查询</li>
* <li>{@code feedback}(MidmResponse):反馈</li>
* <li>{@code readAt}(Date):读取At</li>
* </ul>
*
* 协作对象:{@code MidmQuery、MidmResponse}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class MidmPacket implements Serializable { public class MidmPacket implements Serializable {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid; private UUID uuid;
/**
* recieverUUID。
*/
private UUID recieverUuid; private UUID recieverUuid;
/**
* 查询UUID。
*/
private UUID queryUuid; private UUID queryUuid;
/**
* 查询;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private MidmQuery query; private MidmQuery query;
/**
* 反馈。
*/
private MidmResponse feedback; private MidmResponse feedback;
/**
* 读取At。
*/
private Date readAt; private Date readAt;
/**
* 构造 {@code MidmPacket} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public MidmPacket() { public MidmPacket() {
this.setUuid(UUID.randomUUID()); this.setUuid(UUID.randomUUID());
} }
/**
* 构造 {@code MidmPacket} 实例。
*
* 实现要点:主要调用:new MidmQuery。
*
* @param code 状态码/业务码({@code int})
*/
public MidmPacket(int code) { public MidmPacket(int code) {
this.init(); this.init();
this.setQuery(new MidmQuery(code)); this.setQuery(new MidmQuery(code));
} }
/**
* 构造 {@code MidmPacket} 实例。
*
* @param request HTTP 请求({@code MIDM_REQUEST})
*/
public MidmPacket(MIDM_REQUEST request) { public MidmPacket(MIDM_REQUEST request) {
this(request.getCode()); this(request.getCode());
} }
/**
* 初始化对象状态(补齐 UUID/时间戳/默认字段)。
*/
private void init() { private void init() {
this.setUuid(UUID.randomUUID()); this.setUuid(UUID.randomUUID());
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code recieverUuid}。
* @return UUID
*/
public UUID getRecieverUuid() { public UUID getRecieverUuid() {
return this.recieverUuid; return this.recieverUuid;
} }
/**
* 设置 {@code recieverUuid}。
*
* @param recieverUuid 参数 {@code recieverUuid}({@code UUID})
*/
public void setRecieverUuid(UUID recieverUuid) { public void setRecieverUuid(UUID recieverUuid) {
this.recieverUuid = recieverUuid; this.recieverUuid = recieverUuid;
} }
/**
* 获取 {@code queryUuid}。
* @return UUID
*/
public UUID getQueryUuid() { public UUID getQueryUuid() {
return this.queryUuid; return this.queryUuid;
} }
/**
* 设置 {@code queryUuid}。
*
* @param queryUuid 参数 {@code queryUuid}({@code UUID})
*/
public void setQueryUuid(UUID queryUuid) { public void setQueryUuid(UUID queryUuid) {
this.queryUuid = queryUuid; this.queryUuid = queryUuid;
} }
/**
* 获取 {@code query}。
* @return 字段/派生属性 {@code query} 的值
*/
public MidmQuery getQuery() { public MidmQuery getQuery() {
return this.query; return this.query;
} }
/**
* 设置 {@code query}。
*
* @param query 查询对象({@code MidmQuery})
*/
public void setQuery(MidmQuery query) { public void setQuery(MidmQuery query) {
this.query = query; this.query = query;
} }
/**
* 获取Param。
*
* @param key 键/配置项({@code String})
* @return 字段/派生属性 {@code param} 的值
*/
public Object getParam(String key) { public Object getParam(String key) {
return this.getQuery().getParam(key); return this.getQuery().getParam(key);
} }
/**
* 设置Param。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setParam(String key, Object value) { public void setParam(String key, Object value) {
this.getQuery().setParam(key, value); this.getQuery().setParam(key, value);
} }
/**
* 获取 {@code feedback}。
* @return 字段/派生属性 {@code feedback} 的值
*/
public MidmResponse getFeedback() { public MidmResponse getFeedback() {
return this.feedback; return this.feedback;
} }
/**
* 设置 {@code feedback}。
*
* @param feedback 参数 {@code feedback}({@code MidmResponse})
*/
public void setFeedback(MidmResponse feedback) { public void setFeedback(MidmResponse feedback) {
this.feedback = feedback; this.feedback = feedback;
} }
/**
* 设置反馈。
*
* 实现要点:主要调用:new MidmResponse。
*
* @param code 状态码/业务码({@code int})
* @param message 消息内容({@code String})
*/
public void setFeedback(int code, String message) { public void setFeedback(int code, String message) {
this.feedback = new MidmResponse(code, message); this.feedback = new MidmResponse(code, message);
} }
/**
* 设置反馈。
*
* 实现要点:主要调用:new MidmResponse。
*
* @param code 状态码/业务码({@code int})
* @param message 消息内容({@code String})
* @param data 参数 {@code data}({@code Object})
*/
public void setFeedback(int code, String message, Object data) { public void setFeedback(int code, String message, Object data) {
this.feedback = new MidmResponse(code, message, data); this.feedback = new MidmResponse(code, message, data);
} }
/**
* 获取 {@code readAt}。
* @return 字段/派生属性 {@code readAt} 的值
*/
public Date getReadAt() { public Date getReadAt() {
return this.readAt; return this.readAt;
} }
/**
* 设置 {@code readAt}。
*
* @param readAt 参数 {@code readAt}({@code Date})
*/
public void setReadAt(Date readAt) { public void setReadAt(Date readAt) {
this.readAt = readAt; this.readAt = readAt;
} }
/**
* 处理转换为消息。
*
* 实现要点:主要调用:new TextMessage。
* @return 处理结果
*/
public TextMessage toMessage() { public TextMessage toMessage() {
return new TextMessage(this.toString()); return new TextMessage(this.toString());
} }
/**
* 处理转换为Binary。
*
* 实现要点:主要调用:new BinaryMessage。
* @return 处理结果
*/
public BinaryMessage toBinary() { public BinaryMessage toBinary() {
byte[] bytes = McCompress.compress(this.toString()); byte[] bytes = McCompress.compress(this.toString());
return new BinaryMessage(bytes); return new BinaryMessage(bytes);
} }
/**
* 返回对象的可读字符串表示。
* @return 字符串结果
*/
public String toString() { public String toString() {
return McJsonUtils.toJson(this); return McJsonUtils.toJson(this);
} }
/**
* 处理转换为报文。
*
* @param message 消息内容({@code TextMessage})
* @return 处理结果
*/
public static MidmPacket toPacket(TextMessage message) { public static MidmPacket toPacket(TextMessage message) {
return (MidmPacket)McJsonUtils.toObject((String)message.getPayload(), MidmPacket.class); return (MidmPacket)McJsonUtils.toObject((String)message.getPayload(), MidmPacket.class);
} }
/**
* 处理topacket。
*
* 实现要点:主要调用:new String。
*
* @param message 消息内容({@code BinaryMessage})
* @return 处理结果
*/
public static MidmPacket topacket(BinaryMessage message) { public static MidmPacket topacket(BinaryMessage message) {
ByteBuffer bytes = (ByteBuffer)message.getPayload(); ByteBuffer bytes = (ByteBuffer)message.getPayload();
byte[] decompressed = McDecompress.decompress(bytes.array()); byte[] decompressed = McDecompress.decompress(bytes.array());
return (MidmPacket)McJsonUtils.toObject(new String(decompressed, Charsets.UTF_8), MidmPacket.class); return (MidmPacket)McJsonUtils.toObject(new String(decompressed, Charsets.UTF_8), MidmPacket.class);
} }
/**
* 处理转换为报文。
*
* @param message 消息内容({@code String})
* @return 处理结果
*/
public static MidmPacket toPacket(String message) { public static MidmPacket toPacket(String message) {
return (MidmPacket)McJsonUtils.toObject(message, MidmPacket.class); return (MidmPacket)McJsonUtils.toObject(message, MidmPacket.class);
} }
@@ -5,54 +5,144 @@ import java.util.Date;
import java.util.UUID; import java.util.UUID;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code MidmQuery}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code senderUuid}(UUID):senderUUID</li>
* <li>{@code code}(int):代码</li>
* <li>{@code query}(DbObject):查询</li>
* <li>{@code isInstant}(boolean):判断是否Instant</li>
* <li>{@code registeredAt}(Date):时间字段</li>
* </ul>
*
* 协作对象:{@code DbObject}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class MidmQuery { public class MidmQuery {
/**
* 对象唯一标识(MongoDB 主键)。
*/
private UUID uuid; private UUID uuid;
/**
* senderUUID。
*/
private UUID senderUuid; private UUID senderUuid;
/**
* 代码。
*/
private int code; private int code;
/**
* 查询。
*/
private DbObject query; private DbObject query;
/**
* 判断是否Instant。
*/
private boolean isInstant; private boolean isInstant;
/**
* 时间字段。
*/
private Date registeredAt; private Date registeredAt;
/**
* 构造 {@code MidmQuery} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public MidmQuery() { public MidmQuery() {
this.init(); this.init();
} }
/**
* 构造 {@code MidmQuery} 实例。
*
* @param code 状态码/业务码({@code int})
*/
public MidmQuery(int code) { public MidmQuery(int code) {
this(); this();
this.setCode(code); this.setCode(code);
} }
/**
* 初始化对象状态(补齐 UUID/时间戳/默认字段)。
*
* 实现要点:主要调用:new Date。
*/
public void init() { public void init() {
this.setUuid(UUID.randomUUID()); this.setUuid(UUID.randomUUID());
this.isInstant = true; this.isInstant = true;
this.setRegisteredAt(new Date()); this.setRegisteredAt(new Date());
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code senderUuid}。
* @return UUID
*/
public UUID getSenderUuid() { public UUID getSenderUuid() {
return this.senderUuid; return this.senderUuid;
} }
/**
* 设置 {@code senderUuid}。
*
* @param senderUuid 参数 {@code senderUuid}({@code UUID})
*/
public void setSenderUuid(UUID senderUuid) { public void setSenderUuid(UUID senderUuid) {
this.senderUuid = senderUuid; this.senderUuid = senderUuid;
} }
/**
* 获取 {@code code}。
* @return 数量/长度
*/
public int getCode() { public int getCode() {
return this.code; return this.code;
} }
/**
* 设置 {@code code}。
*
* @param code 状态码/业务码({@code int})
*/
public void setCode(int code) { public void setCode(int code) {
this.code = code; this.code = code;
} }
/**
* 获取 {@code query}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getQuery() { public DbObject getQuery() {
if (this.query == null) { if (this.query == null) {
this.query = new DbObject(); this.query = new DbObject();
@@ -61,18 +151,38 @@ public class MidmQuery {
return this.query; return this.query;
} }
/**
* 设置 {@code query}。
*
* @param query 查询对象({@code DbObject})
*/
public void setQuery(DbObject query) { public void setQuery(DbObject query) {
this.query = query; this.query = query;
} }
/**
* 获取 {@code request}。
* @return 字符串结果
*/
public String getRequest() { public String getRequest() {
return (String)this.getQuery().get("request"); return (String)this.getQuery().get("request");
} }
/**
* 设置 {@code request}。
*
* @param request HTTP 请求({@code String})
*/
public void setRequest(String request) { public void setRequest(String request) {
this.getQuery().put("request", request); this.getQuery().put("request", request);
} }
/**
* 获取 {@code params}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getParams() { public DbObject getParams() {
DbObject params = this.getQuery().getDbObject(new String[]{"params"}); DbObject params = this.getQuery().getDbObject(new String[]{"params"});
if (params == null) { if (params == null) {
@@ -83,30 +193,64 @@ public class MidmQuery {
return params; return params;
} }
/**
* 获取Param。
*
* @param key 键/配置项({@code String})
* @return 字段/派生属性 {@code param} 的值
*/
public Object getParam(String key) { public Object getParam(String key) {
return this.getParams().get(key); return this.getParams().get(key);
} }
/**
* 获取 {@code command}。
* @return 字符串结果
*/
public String getCommand() { public String getCommand() {
return this.getParam("command").toString(); return this.getParam("command").toString();
} }
/**
* 设置Param。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setParam(String key, Object value) { public void setParam(String key, Object value) {
this.getParams().put(key, value); this.getParams().put(key, value);
} }
/**
* 判断 {@code instant}。
* @return 字段/派生属性 {@code instant} 的值
*/
public boolean isInstant() { public boolean isInstant() {
return this.isInstant; return this.isInstant;
} }
/**
* 设置 {@code instant}。
*
* @param isInstant 参数 {@code isInstant}({@code boolean})
*/
public void setInstant(boolean isInstant) { public void setInstant(boolean isInstant) {
this.isInstant = isInstant; this.isInstant = isInstant;
} }
/**
* 获取 {@code registeredAt}。
* @return 字段/派生属性 {@code registeredAt} 的值
*/
public Date getRegisteredAt() { public Date getRegisteredAt() {
return this.registeredAt; return this.registeredAt;
} }
/**
* 设置 {@code registeredAt}。
*
* @param registeredAt 参数 {@code registeredAt}({@code Date})
*/
public void setRegisteredAt(Date registeredAt) { public void setRegisteredAt(Date registeredAt) {
this.registeredAt = registeredAt; this.registeredAt = registeredAt;
} }
@@ -8,163 +8,584 @@ import java.util.Map;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.TextMessage;
/**
* 【领域模型】{@code MidmResponse}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code MESSAGE_SUCCEED}(String):字段 MESSAGE_SUCCEED</li>
* <li>{@code MESSAGE_FAILED}(String):字段 MESSAGE_FAILED</li>
* <li>{@code CODE_SERVICE_CONNECTED}(int):字段 CODE_SERVICE_CONNECTED</li>
* <li>{@code CODE_SUCCEED}(int):字段 CODE_SUCCEED</li>
* <li>{@code CODE_CHECKEDIN}(int):字段 CODE_CHECKEDIN</li>
* <li>{@code CODE_ENROLLED}(int):字段 CODE_ENROLLED</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class MidmResponse { public class MidmResponse {
/**
* 字段 MESSAGE_SUCCEED。
*/
public static final String MESSAGE_SUCCEED = "succeed"; public static final String MESSAGE_SUCCEED = "succeed";
/**
* 字段 MESSAGE_FAILED。
*/
public static final String MESSAGE_FAILED = "failed"; public static final String MESSAGE_FAILED = "failed";
/**
* 字段 CODE_SERVICE_CONNECTED。
*/
public static final int CODE_SERVICE_CONNECTED = 100; public static final int CODE_SERVICE_CONNECTED = 100;
/**
* 字段 CODE_SUCCEED。
*/
public static final int CODE_SUCCEED = 200; public static final int CODE_SUCCEED = 200;
/**
* 字段 CODE_CHECKEDIN。
*/
public static final int CODE_CHECKEDIN = 110; public static final int CODE_CHECKEDIN = 110;
/**
* 字段 CODE_ENROLLED。
*/
public static final int CODE_ENROLLED = 111; public static final int CODE_ENROLLED = 111;
/**
* 字段 CODE_ENROLL_REJECTED。
*/
public static final int CODE_ENROLL_REJECTED = 112; public static final int CODE_ENROLL_REJECTED = 112;
/**
* 字段 CODE_DEVICE_REGISTERD。
*/
public static final int CODE_DEVICE_REGISTERD = 113; public static final int CODE_DEVICE_REGISTERD = 113;
/**
* 字段 CODE_DEVICE_UPDATED。
*/
public static final int CODE_DEVICE_UPDATED = 114; public static final int CODE_DEVICE_UPDATED = 114;
/**
* 字段 CODE_LICENSE_EXPIRED。
*/
public static final int CODE_LICENSE_EXPIRED = 115; public static final int CODE_LICENSE_EXPIRED = 115;
/**
* 字段 CODE_MESSAGE_NOTIFY。
*/
public static final int CODE_MESSAGE_NOTIFY = 116; public static final int CODE_MESSAGE_NOTIFY = 116;
/**
* 字段 CODE_REPORT_READY。
*/
public static final int CODE_REPORT_READY = 117; public static final int CODE_REPORT_READY = 117;
/**
* 字段 CODE_REPORT_GENERATE_FAIL。
*/
public static final int CODE_REPORT_GENERATE_FAIL = 118; public static final int CODE_REPORT_GENERATE_FAIL = 118;
/**
* 字段 CODE_HOST_LICENSE_READY。
*/
public static final int CODE_HOST_LICENSE_READY = 119; public static final int CODE_HOST_LICENSE_READY = 119;
/**
* 字段 CODE_SITE_LICENSE_READY。
*/
public static final int CODE_SITE_LICENSE_READY = 109; public static final int CODE_SITE_LICENSE_READY = 109;
/**
* 字段 CODE_SITE_LICENSE_REQUESTED。
*/
public static final int CODE_SITE_LICENSE_REQUESTED = 108; public static final int CODE_SITE_LICENSE_REQUESTED = 108;
/**
* 字段 CODE_SITE_UPGRADE_REQUESTED。
*/
public static final int CODE_SITE_UPGRADE_REQUESTED = 107; public static final int CODE_SITE_UPGRADE_REQUESTED = 107;
/**
* 字段 CODE_SITE_UPGRADE_SUCCESS。
*/
public static final int CODE_SITE_UPGRADE_SUCCESS = 106; public static final int CODE_SITE_UPGRADE_SUCCESS = 106;
/**
* 字段 CODE_UPDATE_CIENT_APPS。
*/
public static final int CODE_UPDATE_CIENT_APPS = 121; public static final int CODE_UPDATE_CIENT_APPS = 121;
/**
* 字段 CODE_ONLINE_STATE_CHANGED。
*/
public static final int CODE_ONLINE_STATE_CHANGED = 211; public static final int CODE_ONLINE_STATE_CHANGED = 211;
/**
* 字段 CODE_DEVICE_STATE_CHANGED。
*/
public static final int CODE_DEVICE_STATE_CHANGED = 300; public static final int CODE_DEVICE_STATE_CHANGED = 300;
/**
* 字段 FEEDBACK_APP_LIST。
*/
public static final int FEEDBACK_APP_LIST = 120; public static final int FEEDBACK_APP_LIST = 120;
/**
* 字段 FEEDBACK_APP_INSTALLED。
*/
public static final int FEEDBACK_APP_INSTALLED = 121; public static final int FEEDBACK_APP_INSTALLED = 121;
/**
* 字段 FEEDBACK_APP_UNINSTALLED。
*/
public static final int FEEDBACK_APP_UNINSTALLED = 122; public static final int FEEDBACK_APP_UNINSTALLED = 122;
/**
* 字段 FEEDBACK_APP_ENABLE。
*/
public static final int FEEDBACK_APP_ENABLE = 123; public static final int FEEDBACK_APP_ENABLE = 123;
/**
* 字段 FEEDBACK_APP_DISABLE。
*/
public static final int FEEDBACK_APP_DISABLE = 124; public static final int FEEDBACK_APP_DISABLE = 124;
/**
* 字段 FEEDBACK_APP_SHOW。
*/
public static final int FEEDBACK_APP_SHOW = 125; public static final int FEEDBACK_APP_SHOW = 125;
/**
* 字段 FEEDBACK_APP_HIDE。
*/
public static final int FEEDBACK_APP_HIDE = 126; public static final int FEEDBACK_APP_HIDE = 126;
/**
* 字段 FEEDBACK_APP_INFO。
*/
public static final int FEEDBACK_APP_INFO = 127; public static final int FEEDBACK_APP_INFO = 127;
/**
* 字段 FEEDBACK_FILE_LIST。
*/
public static final int FEEDBACK_FILE_LIST = 130; public static final int FEEDBACK_FILE_LIST = 130;
/**
* 字段 FEEDBACK_FILE_STORAGE。
*/
public static final int FEEDBACK_FILE_STORAGE = 131; public static final int FEEDBACK_FILE_STORAGE = 131;
/**
* 字段 FEEDBACK_FILE_COPY。
*/
public static final int FEEDBACK_FILE_COPY = 132; public static final int FEEDBACK_FILE_COPY = 132;
/**
* 字段 FEEDBACK_FILE_RENAME。
*/
public static final int FEEDBACK_FILE_RENAME = 133; public static final int FEEDBACK_FILE_RENAME = 133;
/**
* 字段 FEEDBACK_FILE_MOVE。
*/
public static final int FEEDBACK_FILE_MOVE = 134; public static final int FEEDBACK_FILE_MOVE = 134;
/**
* 字段 FEEDBACK_FILE_REMOVE。
*/
public static final int FEEDBACK_FILE_REMOVE = 135; public static final int FEEDBACK_FILE_REMOVE = 135;
/**
* 字段 FEEDBACK_FILE_MKDIR。
*/
public static final int FEEDBACK_FILE_MKDIR = 136; public static final int FEEDBACK_FILE_MKDIR = 136;
/**
* 字段 FEEDBACK_FILE_PUSH。
*/
public static final int FEEDBACK_FILE_PUSH = 137; public static final int FEEDBACK_FILE_PUSH = 137;
/**
* 字段 FEEDBACK_FILE_PULL。
*/
public static final int FEEDBACK_FILE_PULL = 138; public static final int FEEDBACK_FILE_PULL = 138;
/**
* 字段 FEEDBACK_FILE_LOGCAT。
*/
public static final int FEEDBACK_FILE_LOGCAT = 139; public static final int FEEDBACK_FILE_LOGCAT = 139;
/**
* 字段 FEEDBACK_EXEC。
*/
public static final int FEEDBACK_EXEC = 140; public static final int FEEDBACK_EXEC = 140;
/**
* 字段 FEEDBACK_EXEC_LOGCAT。
*/
public static final int FEEDBACK_EXEC_LOGCAT = 141; public static final int FEEDBACK_EXEC_LOGCAT = 141;
/**
* 字段 FEEDBACK_HARDWARE_INFO。
*/
public static final int FEEDBACK_HARDWARE_INFO = 170; public static final int FEEDBACK_HARDWARE_INFO = 170;
/**
* 字段 FEEDBACK_SOFTWARE_INFO。
*/
public static final int FEEDBACK_SOFTWARE_INFO = 180; public static final int FEEDBACK_SOFTWARE_INFO = 180;
/**
* 字段 FEEDBACK_MEMORY_USAGE。
*/
public static final int FEEDBACK_MEMORY_USAGE = 190; public static final int FEEDBACK_MEMORY_USAGE = 190;
/**
* 字段 FEEDBACK_BATTERY_INFO。
*/
public static final int FEEDBACK_BATTERY_INFO = 191; public static final int FEEDBACK_BATTERY_INFO = 191;
/**
* 字段 FEEDBACK_DATA_USAGE。
*/
public static final int FEEDBACK_DATA_USAGE = 192; public static final int FEEDBACK_DATA_USAGE = 192;
/**
* 字段 FEEDBACK_ACTIVE_NETWORK。
*/
public static final int FEEDBACK_ACTIVE_NETWORK = 193; public static final int FEEDBACK_ACTIVE_NETWORK = 193;
/**
* 字段 FEEDBACK_NETWORK。
*/
public static final int FEEDBACK_NETWORK = 194; public static final int FEEDBACK_NETWORK = 194;
/**
* 字段 FEEDBACK_LOCATION。
*/
public static final int FEEDBACK_LOCATION = 198; public static final int FEEDBACK_LOCATION = 198;
/**
* 字段 FEEDBACK_SCREEN_CAPTURED。
*/
public static final int FEEDBACK_SCREEN_CAPTURED = 199; public static final int FEEDBACK_SCREEN_CAPTURED = 199;
/**
* 字段 FEEDBACK_ONLINE_STATE。
*/
public static final int FEEDBACK_ONLINE_STATE = 211; public static final int FEEDBACK_ONLINE_STATE = 211;
/**
* 字段 FEEDBACK_CAMERA_STATE。
*/
public static final int FEEDBACK_CAMERA_STATE = 212; public static final int FEEDBACK_CAMERA_STATE = 212;
/**
* 字段 FEEDBACK_DEVICE_STATE。
*/
public static final int FEEDBACK_DEVICE_STATE = 300; public static final int FEEDBACK_DEVICE_STATE = 300;
/**
* 字段 CODE_FAILED。
*/
public static final int CODE_FAILED = 400; public static final int CODE_FAILED = 400;
/**
* 字段 CODE_NOT_FOUND。
*/
public static final int CODE_NOT_FOUND = 404; public static final int CODE_NOT_FOUND = 404;
/**
* 字段 CODE_FAIL_USER_NOT_FOUND。
*/
public static final int CODE_FAIL_USER_NOT_FOUND = 410; public static final int CODE_FAIL_USER_NOT_FOUND = 410;
/**
* 字段 CODE_FAIL_WRONG_PASSWROD。
*/
public static final int CODE_FAIL_WRONG_PASSWROD = 411; public static final int CODE_FAIL_WRONG_PASSWROD = 411;
/**
* 字段 CODE_FAIL_USER_NOT_AVAILABLE。
*/
public static final int CODE_FAIL_USER_NOT_AVAILABLE = 412; public static final int CODE_FAIL_USER_NOT_AVAILABLE = 412;
/**
* 字段 CODE_FAIL_INSUFFICIENT_INFO。
*/
public static final int CODE_FAIL_INSUFFICIENT_INFO = 413; public static final int CODE_FAIL_INSUFFICIENT_INFO = 413;
/**
* 字段 CODE_FAIL_USER_LOGGED_IN。
*/
public static final int CODE_FAIL_USER_LOGGED_IN = 414; public static final int CODE_FAIL_USER_LOGGED_IN = 414;
/**
* 字段 CODE_FAIL_NO_AUTH_INFO。
*/
public static final int CODE_FAIL_NO_AUTH_INFO = 415; public static final int CODE_FAIL_NO_AUTH_INFO = 415;
/**
* 字段 CODE_FAIL_REGISTERED_TO_OTHER。
*/
public static final int CODE_FAIL_REGISTERED_TO_OTHER = 416; public static final int CODE_FAIL_REGISTERED_TO_OTHER = 416;
/**
* 字段 CODE_FAIL_VERSION_DUPLICATE。
*/
public static final int CODE_FAIL_VERSION_DUPLICATE = 417; public static final int CODE_FAIL_VERSION_DUPLICATE = 417;
/**
* 字段 CODE_FAIL_USER_NOT_AGREED。
*/
public static final int CODE_FAIL_USER_NOT_AGREED = 418; public static final int CODE_FAIL_USER_NOT_AGREED = 418;
/**
* 字段 CODE_FAIL_SAME_NAME_NOT_ALLOW。
*/
public static final int CODE_FAIL_SAME_NAME_NOT_ALLOW = 419; public static final int CODE_FAIL_SAME_NAME_NOT_ALLOW = 419;
/**
* 字段 CODE_FAIL_HOST_EXPIRED。
*/
public static final int CODE_FAIL_HOST_EXPIRED = 420; public static final int CODE_FAIL_HOST_EXPIRED = 420;
/**
* 字段 CODE_FAIL_HOST_EXCEED_DEVICE_LIMIT。
*/
public static final int CODE_FAIL_HOST_EXCEED_DEVICE_LIMIT = 421; public static final int CODE_FAIL_HOST_EXCEED_DEVICE_LIMIT = 421;
/**
* 字段 CODE_FAIL_INVALID。
*/
public static final int CODE_FAIL_INVALID = 422; public static final int CODE_FAIL_INVALID = 422;
/**
* 字段 CODE_FAIL_EXISTING_USER。
*/
public static final int CODE_FAIL_EXISTING_USER = 423; public static final int CODE_FAIL_EXISTING_USER = 423;
/**
* 字段 CODE_FAIL_EXCEED_LOGIN_FAILURE。
*/
public static final int CODE_FAIL_EXCEED_LOGIN_FAILURE = 424; public static final int CODE_FAIL_EXCEED_LOGIN_FAILURE = 424;
/**
* 字段 CODE_FAIL_API_ONLY_USER。
*/
public static final int CODE_FAIL_API_ONLY_USER = 425; public static final int CODE_FAIL_API_ONLY_USER = 425;
/**
* 字段 CODE_FAIL_SITE_NOT_FOUND。
*/
public static final int CODE_FAIL_SITE_NOT_FOUND = 450; public static final int CODE_FAIL_SITE_NOT_FOUND = 450;
/**
* 字段 CODE_FAIL_NO_SITE_AVAILABLE。
*/
public static final int CODE_FAIL_NO_SITE_AVAILABLE = 451; public static final int CODE_FAIL_NO_SITE_AVAILABLE = 451;
/**
* 字段 CODE_FAIL_SITE_NO_USER。
*/
public static final int CODE_FAIL_SITE_NO_USER = 452; public static final int CODE_FAIL_SITE_NO_USER = 452;
/**
* 字段 CODE_FAIL_SITE_USER_DISABLED。
*/
public static final int CODE_FAIL_SITE_USER_DISABLED = 453; public static final int CODE_FAIL_SITE_USER_DISABLED = 453;
/**
* 字段 CODE_FAIL_SITE_SAME。
*/
public static final int CODE_FAIL_SITE_SAME = 455; public static final int CODE_FAIL_SITE_SAME = 455;
/**
* 字段 CODE_FAIL_DEVICE_NO_SERIAL。
*/
public static final int CODE_FAIL_DEVICE_NO_SERIAL = 461; public static final int CODE_FAIL_DEVICE_NO_SERIAL = 461;
/**
* 字段 CODE_FAIL_DEVICE_NO_SITE。
*/
public static final int CODE_FAIL_DEVICE_NO_SITE = 462; public static final int CODE_FAIL_DEVICE_NO_SITE = 462;
/**
* 字段 CODE_FAIL_NO_DEVICE_EXISTS。
*/
public static final int CODE_FAIL_NO_DEVICE_EXISTS = 463; public static final int CODE_FAIL_NO_DEVICE_EXISTS = 463;
/**
* 字段 CODE_FAIL_DEVICE_NO_LICENSE。
*/
public static final int CODE_FAIL_DEVICE_NO_LICENSE = 464; public static final int CODE_FAIL_DEVICE_NO_LICENSE = 464;
/**
* 字段 CODE_FAIL_CHILD_EXISTS。
*/
public static final int CODE_FAIL_CHILD_EXISTS = 466; public static final int CODE_FAIL_CHILD_EXISTS = 466;
/**
* 字段 CODE_FAIL_DEVICE_EXISTS。
*/
public static final int CODE_FAIL_DEVICE_EXISTS = 467; public static final int CODE_FAIL_DEVICE_EXISTS = 467;
/**
* 字段 CODE_FAIL_LICENSE_EXPIRED。
*/
public static final int CODE_FAIL_LICENSE_EXPIRED = 115; public static final int CODE_FAIL_LICENSE_EXPIRED = 115;
/**
* 字段 CODE_ERROR_NO_RECORD。
*/
public static final int CODE_ERROR_NO_RECORD = 421; public static final int CODE_ERROR_NO_RECORD = 421;
/**
* 字段 CODE_ERROR_TOKEN_NOT_DEFINED。
*/
public static final int CODE_ERROR_TOKEN_NOT_DEFINED = 461; public static final int CODE_ERROR_TOKEN_NOT_DEFINED = 461;
/**
* 字段 CODE_ERROR_EXPIRED_TOKEN。
*/
public static final int CODE_ERROR_EXPIRED_TOKEN = 462; public static final int CODE_ERROR_EXPIRED_TOKEN = 462;
/**
* 字段 CODE_ERROR_INVALID_TOKEN。
*/
public static final int CODE_ERROR_INVALID_TOKEN = 463; public static final int CODE_ERROR_INVALID_TOKEN = 463;
/**
* 字段 CODE_ERROR_URL_FORMAT。
*/
public static final int CODE_ERROR_URL_FORMAT = 431; public static final int CODE_ERROR_URL_FORMAT = 431;
/**
* 字段 CODE_ERROR_IO_EXEPTION。
*/
public static final int CODE_ERROR_IO_EXEPTION = 432; public static final int CODE_ERROR_IO_EXEPTION = 432;
/**
* 字段 CODE_ERROR_NO_PERMISSION。
*/
public static final int CODE_ERROR_NO_PERMISSION = 433; public static final int CODE_ERROR_NO_PERMISSION = 433;
/**
* 字段 CODE_ERROR_INVALID_SYSTEM_IMAGE。
*/
public static final int CODE_ERROR_INVALID_SYSTEM_IMAGE = 441; public static final int CODE_ERROR_INVALID_SYSTEM_IMAGE = 441;
/**
* 字段 CODE_UNKOWN。
*/
public static final int CODE_UNKOWN = -1; public static final int CODE_UNKOWN = -1;
/**
* 字段 MESSAGE_NOT_ALLOWED。
*/
public static final String MESSAGE_NOT_ALLOWED = "Not allowed."; public static final String MESSAGE_NOT_ALLOWED = "Not allowed.";
/**
* 字段 MESSAGE_NOT_AUTHORIZED。
*/
public static final String MESSAGE_NOT_AUTHORIZED = "Not authorized."; public static final String MESSAGE_NOT_AUTHORIZED = "Not authorized.";
/**
* 字段 MESSAGE_NO_PERMISSION。
*/
public static final String MESSAGE_NO_PERMISSION = "No permission."; public static final String MESSAGE_NO_PERMISSION = "No permission.";
/**
* 字段 MESSAGE_NO_USER_EXISTS。
*/
public static final String MESSAGE_NO_USER_EXISTS = "No user exists."; public static final String MESSAGE_NO_USER_EXISTS = "No user exists.";
/**
* 字段 MESSAGE_NO_SITE_AVAILABLE。
*/
public static final String MESSAGE_NO_SITE_AVAILABLE = "No site available."; public static final String MESSAGE_NO_SITE_AVAILABLE = "No site available.";
/**
* 字段 MESSAGE_NO_DEVICE_EXISTS。
*/
public static final String MESSAGE_NO_DEVICE_EXISTS = "No device exists."; public static final String MESSAGE_NO_DEVICE_EXISTS = "No device exists.";
/**
* 字段 MESSAGE_NO_SERIAL_DEFINED。
*/
public static final String MESSAGE_NO_SERIAL_DEFINED = "No serial no. defined."; public static final String MESSAGE_NO_SERIAL_DEFINED = "No serial no. defined.";
/**
* 字段 MESSAGE_DEVICE_EXISTS。
*/
public static final String MESSAGE_DEVICE_EXISTS = "Existing device."; public static final String MESSAGE_DEVICE_EXISTS = "Existing device.";
/**
* 字段 MESSAGE_NO_GROUP_EXISTS。
*/
public static final String MESSAGE_NO_GROUP_EXISTS = "No group exists."; public static final String MESSAGE_NO_GROUP_EXISTS = "No group exists.";
/**
* 字段 MESSAGE_NO_GROUP。
*/
public static final String MESSAGE_NO_GROUP = "No group: "; public static final String MESSAGE_NO_GROUP = "No group: ";
/**
* 字段 MESSAGE_NO_RECORDS。
*/
public static final String MESSAGE_NO_RECORDS = "No records."; public static final String MESSAGE_NO_RECORDS = "No records.";
/**
* 字段 MESSAGE_NO_REPORTS。
*/
public static final String MESSAGE_NO_REPORTS = "No reports."; public static final String MESSAGE_NO_REPORTS = "No reports.";
/**
* 字段 MESSAGE_NO_LICENSE。
*/
public static final String MESSAGE_NO_LICENSE = "No license."; public static final String MESSAGE_NO_LICENSE = "No license.";
/**
* 字段 MESSAGE_NO_LOCATIONS。
*/
public static final String MESSAGE_NO_LOCATIONS = "No locations."; public static final String MESSAGE_NO_LOCATIONS = "No locations.";
/**
* 字段 MESSAGE_NO_PROFILE_FOUND。
*/
public static final String MESSAGE_NO_PROFILE_FOUND = "No profile found."; public static final String MESSAGE_NO_PROFILE_FOUND = "No profile found.";
/**
* 字段 MESSAGE_NO_APP_FOUND。
*/
public static final String MESSAGE_NO_APP_FOUND = "No apps found."; public static final String MESSAGE_NO_APP_FOUND = "No apps found.";
/**
* 字段 MESSAGE_NO_USER_LOGGED_IN。
*/
public static final String MESSAGE_NO_USER_LOGGED_IN = "No user logged in."; public static final String MESSAGE_NO_USER_LOGGED_IN = "No user logged in.";
/**
* 代码。
*/
private int code; private int code;
/**
* 消息。
*/
private String message; private String message;
/**
* 数据。
*/
private Object data; private Object data;
/**
* 字段 reference。
*/
private Object reference; private Object reference;
/**
* 总数分页。
*/
private Integer totalPage; private Integer totalPage;
/**
* 数量。
*/
private Long size; private Long size;
/**
* 总数数量。
*/
private Long totalSize; private Long totalSize;
/**
* 构造 {@code MidmResponse} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public MidmResponse() { public MidmResponse() {
} }
/**
* 构造 {@code MidmResponse} 实例。
*
* @param code 状态码/业务码({@code int})
* @param msg 参数 {@code msg}({@code String})
*/
public MidmResponse(int code, String msg) { public MidmResponse(int code, String msg) {
this.setCode(code); this.setCode(code);
this.setMessage(msg); this.setMessage(msg);
} }
/**
* 构造 {@code MidmResponse} 实例。
*
* @param code 状态码/业务码({@code int})
* @param msg 参数 {@code msg}({@code String})
* @param data 参数 {@code data}({@code Object})
*/
public MidmResponse(int code, String msg, Object data) { public MidmResponse(int code, String msg, Object data) {
this.setCode(code); this.setCode(code);
this.setMessage(msg); this.setMessage(msg);
this.setData(data); this.setData(data);
} }
/**
* 获取 {@code code}。
* @return 数量/长度
*/
public int getCode() { public int getCode() {
return this.code; return this.code;
} }
/**
* 设置 {@code code}。
*
* @param code 状态码/业务码({@code int})
*/
public void setCode(int code) { public void setCode(int code) {
this.code = code; this.code = code;
} }
/**
* 获取 {@code message}。
* @return 字符串结果
*/
public String getMessage() { public String getMessage() {
return this.message; return this.message;
} }
/**
* 设置 {@code message}。
*
* @param message 消息内容({@code String})
*/
public void setMessage(String message) { public void setMessage(String message) {
this.message = message; this.message = message;
} }
/**
* 获取 {@code data}。
* @return 字段/派生属性 {@code data} 的值
*/
public Object getData() { public Object getData() {
return this.data; return this.data;
} }
/**
* 获取 {@code dataAsDbObject}。
*
* 实现要点:主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getDataAsDbObject() { public DbObject getDataAsDbObject() {
Object data = this.getData(); Object data = this.getData();
return data == null ? new DbObject() : new DbObject((Map)data); return data == null ? new DbObject() : new DbObject((Map)data);
} }
/**
* 设置 {@code data}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
*
* @param data 参数 {@code data}({@code Object})
*/
public void setData(Object data) { public void setData(Object data) {
if (data instanceof UpdateResult) { if (data instanceof UpdateResult) {
UpdateResult result = (UpdateResult)data; UpdateResult result = (UpdateResult)data;
@@ -175,56 +596,120 @@ public class MidmResponse {
} }
/**
* 获取 {@code reference}。
* @return 字段/派生属性 {@code reference} 的值
*/
public Object getReference() { public Object getReference() {
return this.reference; return this.reference;
} }
/**
* 获取 {@code refereceAsDbObject}。
*
* 实现要点:主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getRefereceAsDbObject() { public DbObject getRefereceAsDbObject() {
Object data = this.getReference(); Object data = this.getReference();
return data == null ? new DbObject() : new DbObject((Map)data); return data == null ? new DbObject() : new DbObject((Map)data);
} }
/**
* 设置 {@code reference}。
*
* @param reference 参数 {@code reference}({@code Object})
*/
public void setReference(Object reference) { public void setReference(Object reference) {
this.reference = reference; this.reference = reference;
} }
/**
* 获取 {@code totalPage}。
* @return 数量/长度
*/
public int getTotalPage() { public int getTotalPage() {
return this.totalPage; return this.totalPage;
} }
/**
* 设置 {@code totalPages}。
*
* @param totalPage 参数 {@code totalPage}({@code int})
*/
public void setTotalPages(int totalPage) { public void setTotalPages(int totalPage) {
this.totalPage = totalPage; this.totalPage = totalPage;
} }
/**
* 获取 {@code size}。
* @return 数量/长度
*/
public long getSize() { public long getSize() {
return this.size; return this.size;
} }
/**
* 设置 {@code size}。
*
* @param size 每页数量({@code long})
*/
public void setSize(long size) { public void setSize(long size) {
this.size = size; this.size = size;
} }
/**
* 获取 {@code totalSize}。
* @return 数量/长度
*/
public long getTotalSize() { public long getTotalSize() {
return this.totalSize; return this.totalSize;
} }
/**
* 设置 {@code totalSize}。
*
* @param totalSize 参数 {@code totalSize}({@code long})
*/
public void setTotalSize(long totalSize) { public void setTotalSize(long totalSize) {
this.totalSize = totalSize; this.totalSize = totalSize;
} }
/**
* 返回对象的可读字符串表示。
* @return 字符串结果
*/
public String toString() { public String toString() {
return McJsonUtils.toJson(this); return McJsonUtils.toJson(this);
} }
/**
* 处理转换为Text消息。
*
* 实现要点:主要调用:new TextMessage。
* @return 处理结果
*/
public TextMessage toTextMessage() { public TextMessage toTextMessage() {
return new TextMessage(this.toString()); return new TextMessage(this.toString());
} }
/**
* 获取 {@code succeedResponse}。
* @return 字符串结果
*/
public static String getSucceedResponse() { public static String getSucceedResponse() {
return getResponse(200, "succeed"); return getResponse(200, "succeed");
} }
public static String getSucceedResponse(List list) { /**
* 获取Succeed响应。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new MidmResponse。
*
* @param list 参数 {@code list}({@code List<?>})
* @return 字符串结果
*/
public static String getSucceedResponse(List<?> list) {
MidmResponse response = new MidmResponse(200, "succeed"); MidmResponse response = new MidmResponse(200, "succeed");
if (list != null) { if (list != null) {
response.setData(list); response.setData(list);
@@ -234,7 +719,15 @@ public class MidmResponse {
return response.toString(); return response.toString();
} }
public static String getSucceedResponse(Page page) { /**
* 获取Succeed响应。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new MidmResponse。
*
* @param page 页码(从 0 开始)({@code Page<?>})
* @return 字符串结果
*/
public static String getSucceedResponse(Page<?> page) {
MidmResponse response = new MidmResponse(200, "succeed"); MidmResponse response = new MidmResponse(200, "succeed");
if (page != null) { if (page != null) {
response.setData(page.getContent()); response.setData(page.getContent());
@@ -246,22 +739,57 @@ public class MidmResponse {
return response.toString(); return response.toString();
} }
/**
* 获取Succeed响应。
*
* @param data 参数 {@code data}({@code Object})
* @return 字符串结果
*/
public static String getSucceedResponse(Object data) { public static String getSucceedResponse(Object data) {
return getResponse(200, "succeed", data); return getResponse(200, "succeed", data);
} }
/**
* 获取 {@code failedResponse}。
* @return 字符串结果
*/
public static String getFailedResponse() { public static String getFailedResponse() {
return getResponse(400, "failed"); return getResponse(400, "failed");
} }
/**
* 获取响应。
*
* 实现要点:主要调用:new MidmResponse。
*
* @param code 状态码/业务码({@code int})
* @param msg 参数 {@code msg}({@code String})
* @return 字符串结果
*/
public static String getResponse(int code, String msg) { public static String getResponse(int code, String msg) {
return (new MidmResponse(code, msg)).toString(); return (new MidmResponse(code, msg)).toString();
} }
/**
* 获取响应。
*
* 实现要点:主要调用:new MidmResponse。
*
* @param code 状态码/业务码({@code int})
* @param msg 参数 {@code msg}({@code String})
* @param data 参数 {@code data}({@code Object})
* @return 字符串结果
*/
public static String getResponse(int code, String msg, Object data) { public static String getResponse(int code, String msg, Object data) {
return (new MidmResponse(code, msg, data)).toString(); return (new MidmResponse(code, msg, data)).toString();
} }
/**
* 获取响应。
*
* @param object 参数 {@code object}({@code Object})
* @return 字符串结果
*/
public static String getResponse(Object object) { public static String getResponse(Object object) {
return McJsonUtils.toJson(object); return McJsonUtils.toJson(object);
} }
@@ -0,0 +1,15 @@
/**
* WebSocket 报文模型:请求、响应、反馈、参数与错误码。
*
* <p>本包主要类型:
* <ul>
* <li>{@link MIDM_REQUEST}</li>
* <li>{@link MidmPacket}</li>
* <li>{@link MidmQuery}</li>
* <li>{@link MidmResponse}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.model.message;
@@ -8,30 +8,113 @@ import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code MessageLog}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code message}(NewsMessage):消息</li>
* <li>{@code reader}(User):字段 reader</li>
* <li>{@code siteUuid}(UUID):用户所属站点 UUID</li>
* <li>{@code readDate}(Date):读取日期</li>
* <li>{@code isCheck}(boolean):判断是否检查</li>
* </ul>
*
* 协作对象:{@code NewsMessage、User}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class MessageLog { public class MessageLog {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid; private UUID uuid;
/**
* 消息;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private NewsMessage message; private NewsMessage message;
/**
* 字段 reader;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private User reader; private User reader;
/**
* 用户所属站点 UUID;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private UUID siteUuid; private UUID siteUuid;
/**
* 读取日期;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private Date readDate; private Date readDate;
/**
* 判断是否检查;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private boolean isCheck; private boolean isCheck;
/**
* 判断是否读取;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private boolean isRead; private boolean isRead;
/**
* 检查日期;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private Date checkDate; private Date checkDate;
/**
* 时间字段;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private Date notified; private Date notified;
/**
* 构造 {@code MessageLog} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public MessageLog() { public MessageLog() {
} }
/**
* 构造 {@code MessageLog} 实例。
*
* 实现要点:主要调用:new Date。
*
* @param message 消息内容({@code NewsMessage})
* @param reader 参数 {@code reader}({@code User})
* @param siteUuid 站点 UUID({@code UUID})
*/
public MessageLog(NewsMessage message, User reader, UUID siteUuid) { public MessageLog(NewsMessage message, User reader, UUID siteUuid) {
this.uuid = UUID.randomUUID(); this.uuid = UUID.randomUUID();
this.message = message; this.message = message;
@@ -41,6 +124,15 @@ public class MessageLog {
this.notified = new Date(); this.notified = new Date();
} }
/**
* 构造 {@code MessageLog} 实例。
*
* 实现要点:主要调用:new User、new Date。
*
* @param message 消息内容({@code NewsMessage})
* @param userUuid 用户 UUID({@code UUID})
* @param siteUuid 站点 UUID({@code UUID})
*/
public MessageLog(NewsMessage message, UUID userUuid, UUID siteUuid) { public MessageLog(NewsMessage message, UUID userUuid, UUID siteUuid) {
this.uuid = UUID.randomUUID(); this.uuid = UUID.randomUUID();
this.message = message; this.message = message;
@@ -50,74 +142,155 @@ public class MessageLog {
this.notified = new Date(); this.notified = new Date();
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code message}。
* @return 字段/派生属性 {@code message} 的值
*/
public NewsMessage getMessage() { public NewsMessage getMessage() {
return this.message; return this.message;
} }
/**
* 设置 {@code message}。
*
* @param message 消息内容({@code NewsMessage})
*/
public void setMessage(NewsMessage message) { public void setMessage(NewsMessage message) {
this.message = message; this.message = message;
} }
/**
* 获取 {@code reader}。
* @return 用户对象;未找到时返回 {@code null}
*/
public User getReader() { public User getReader() {
return this.reader; return this.reader;
} }
/**
* 设置 {@code reader}。
*
* @param reader 参数 {@code reader}({@code User})
*/
public void setReader(User reader) { public void setReader(User reader) {
this.reader = reader; this.reader = reader;
} }
/**
* 判断 {@code check}。
* @return 字段/派生属性 {@code check} 的值
*/
public boolean isCheck() { public boolean isCheck() {
return this.isCheck; return this.isCheck;
} }
/**
* 设置 {@code check}。
*
* @param isCheck 参数 {@code isCheck}({@code boolean})
*/
public void setCheck(boolean isCheck) { public void setCheck(boolean isCheck) {
this.isCheck = isCheck; this.isCheck = isCheck;
} }
/**
* 判断 {@code read}。
* @return 字段/派生属性 {@code read} 的值
*/
public boolean isRead() { public boolean isRead() {
return this.isRead; return this.isRead;
} }
/**
* 设置 {@code read}。
*
* @param isRead 参数 {@code isRead}({@code boolean})
*/
public void setRead(boolean isRead) { public void setRead(boolean isRead) {
this.isRead = isRead; this.isRead = isRead;
} }
/**
* 获取 {@code siteUuid}。
* @return UUID
*/
public UUID getSiteUuid() { public UUID getSiteUuid() {
return this.siteUuid; return this.siteUuid;
} }
/**
* 设置 {@code siteUuid}。
*
* @param siteUuid 站点 UUID({@code UUID})
*/
public void setSiteUuid(UUID siteUuid) { public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid; this.siteUuid = siteUuid;
} }
/**
* 获取 {@code notified}。
* @return 字段/派生属性 {@code notified} 的值
*/
public Date getNotified() { public Date getNotified() {
return this.notified; return this.notified;
} }
/**
* 设置 {@code notified}。
*
* @param notified 参数 {@code notified}({@code Date})
*/
public void setNotified(Date notified) { public void setNotified(Date notified) {
this.notified = notified; this.notified = notified;
} }
/**
* 获取 {@code readDate}。
* @return 字段/派生属性 {@code readDate} 的值
*/
public Date getReadDate() { public Date getReadDate() {
return this.readDate; return this.readDate;
} }
/**
* 设置 {@code readDate}。
*
* @param readDate 参数 {@code readDate}({@code Date})
*/
public void setReadDate(Date readDate) { public void setReadDate(Date readDate) {
this.readDate = readDate; this.readDate = readDate;
} }
/**
* 获取 {@code checkDate}。
* @return 字段/派生属性 {@code checkDate} 的值
*/
public Date getCheckDate() { public Date getCheckDate() {
return this.checkDate; return this.checkDate;
} }
/**
* 设置 {@code checkDate}。
*
* @param checkDate 参数 {@code checkDate}({@code Date})
*/
public void setCheckDate(Date checkDate) { public void setCheckDate(Date checkDate) {
this.checkDate = checkDate; this.checkDate = checkDate;
} }
@@ -18,37 +18,124 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
import javax.mail.internet.InternetAddress;
/**
* 【MongoDB 文档实体】{@code NewsMessage}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code writer}(User):字段 writer</li>
* <li>{@code category}(String):字段 category</li>
* <li>{@code forWhat}(String):用于What</li>
* <li>{@code reference}(DbObject):字段 reference</li>
* <li>{@code message}(DbObject):消息</li>
* </ul>
*
* 协作对象:{@code User、DbObject}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class NewsMessage { public class NewsMessage {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid; private UUID uuid;
/**
* 字段 writer;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private User writer; private User writer;
/**
* 字段 category。
*/
private String category; private String category;
/**
* 用于What。
*/
private String forWhat; private String forWhat;
/**
* 字段 reference。
*/
private DbObject reference; private DbObject reference;
/**
* 消息。
*/
private DbObject message; private DbObject message;
/**
* 判断是否Unremovable。
*/
private Boolean isUnremovable; private Boolean isUnremovable;
/**
* 判断是否Enabled。
*/
private Boolean isEnabled; private Boolean isEnabled;
/**
* 发送调度。
*/
private Date sendSchedule; private Date sendSchedule;
/**
* 时间字段。
*/
private Date expiry; private Date expiry;
/**
* 发送Now;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private boolean sendNow; private boolean sendNow;
/**
* 创建时间。
*/
private Date created; private Date created;
/**
* 最后更新时间。
*/
private Date updated; private Date updated;
/**
* 构造 {@code NewsMessage} 实例。
*
* @param device 设备({@code Device})
* @param category 分类(app/ota/other/report 等)({@code String})
*/
public NewsMessage(Device device, String category) { public NewsMessage(Device device, String category) {
this.init(); this.init();
this.category = "device_" + category; this.category = "device_" + category;
this.reference.put("uuid", device.getUuid()); this.reference.put("uuid", device.getUuid());
} }
/**
* 构造 {@code NewsMessage} 实例。
*
* @param device 设备({@code Device})
*/
public NewsMessage(Device device) { public NewsMessage(Device device) {
this.init(); this.init();
this.reference.put("uuid", device.getUuid()); this.reference.put("uuid", device.getUuid());
} }
/**
* 构造 {@code NewsMessage} 实例。
*
* @param packet WebSocket 报文({@code MidmPacket})
*/
public NewsMessage(MidmPacket packet) { public NewsMessage(MidmPacket packet) {
MidmQuery query = packet.getQuery(); MidmQuery query = packet.getQuery();
this.setUuid(query.getUuid()); this.setUuid(query.getUuid());
@@ -62,16 +149,31 @@ public class NewsMessage {
this.getReference().put("query", query.getQuery()); this.getReference().put("query", query.getQuery());
} }
/**
* 构造 {@code NewsMessage} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public NewsMessage() { public NewsMessage() {
this.init(); this.init();
} }
/**
* 初始化对象状态(补齐 UUID/时间戳/默认字段)。
*
* 实现要点:主要调用:new Date。
*/
public void init() { public void init() {
this.uuid = UUID.randomUUID(); this.uuid = UUID.randomUUID();
this.created = new Date(); this.created = new Date();
this.updated = this.created; this.updated = this.created;
} }
/**
* 获取 {@code message}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getMessage() { public DbObject getMessage() {
if (this.message == null) { if (this.message == null) {
this.message = new DbObject(); this.message = new DbObject();
@@ -80,17 +182,32 @@ public class NewsMessage {
return this.message; return this.message;
} }
/**
* 获取消息。
*
* @param locale 参数 {@code locale}({@code Locale})
* @return MongoDB 文档扩展对象
*/
public DbObject getMessage(Locale locale) { public DbObject getMessage(Locale locale) {
return this.getMessage(locale.toLanguageTag()); return this.getMessage(locale.toLanguageTag());
} }
/**
* 获取消息。
*
* 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、2 个循环;主要调用:new DbObject。
*
* @param languageTag 参数 {@code languageTag}({@code String})
* @return MongoDB 文档扩展对象
*/
public DbObject getMessage(String languageTag) { public DbObject getMessage(String languageTag) {
DbObject message = this.getMessage(); DbObject message = this.getMessage();
DbObject localedMessage = new DbObject(); DbObject localedMessage = new DbObject();
if (message.get(languageTag) == null) { if (message.get(languageTag) == null) {
message.put(languageTag, localedMessage); message.put(languageTag, localedMessage);
} else if (message.get(languageTag) instanceof LinkedTreeMap) { } else if (message.get(languageTag) instanceof LinkedTreeMap) {
for(Map.Entry entry : ((LinkedTreeMap)message.get(languageTag)).entrySet()) { for(Object entryObject : ((LinkedTreeMap)message.get(languageTag)).entrySet()) {
Map.Entry entry = (Map.Entry)entryObject;
localedMessage.append((String)entry.getKey(), entry.getValue()); localedMessage.append((String)entry.getKey(), entry.getValue());
} }
@@ -109,83 +226,186 @@ public class NewsMessage {
return localedMessage; return localedMessage;
} }
/**
* 设置 {@code message}。
*
* @param message 消息内容({@code DbObject})
*/
public void setMessage(DbObject message) { public void setMessage(DbObject message) {
this.message = message; this.message = message;
} }
/**
* 设置消息。
*
* @param title 参数 {@code title}({@code String})
* @param content 参数 {@code content}({@code String})
*/
public void setMessage(String title, String content) { public void setMessage(String title, String content) {
this.setTitle(title); this.setTitle(title);
this.setContent(content); this.setContent(content);
} }
/**
* 获取 {@code title}。
* @return 字符串结果
*/
public String getTitle() { public String getTitle() {
return this.getMessage("en-US").getString("title"); return this.getMessage("en-US").getString("title");
} }
/**
* 获取 {@code summary}。
* @return 字符串结果
*/
public String getSummary() { public String getSummary() {
return this.getMessage().getString("summary"); return this.getMessage().getString("summary");
} }
/**
* 判断 {@code content}。
* @return 字段/派生属性 {@code content} 的值
*/
public boolean hasContent() { public boolean hasContent() {
return this.getMessage().containsKey("content"); return this.getMessage().containsKey("content");
} }
/**
* 获取 {@code content}。
* @return 字符串结果
*/
public String getContent() { public String getContent() {
return this.getMessage("en-US").getString("content"); return this.getMessage("en-US").getString("content");
} }
/**
* 获取Title。
*
* @param locale 参数 {@code locale}({@code String})
* @return 字符串结果
*/
public String getTitle(String locale) { public String getTitle(String locale) {
return this.getMessage(locale).getString("title"); return this.getMessage(locale).getString("title");
} }
/**
* 获取Summary。
*
* @param locale 参数 {@code locale}({@code String})
* @return 字符串结果
*/
public String getSummary(String locale) { public String getSummary(String locale) {
return this.getMessage(locale).getString("summary"); return this.getMessage(locale).getString("summary");
} }
/**
* 判断是否Content。
*
* @param locale 参数 {@code locale}({@code String})
* @return 字段/派生属性 {@code content} 的值
*/
public boolean hasContent(String locale) { public boolean hasContent(String locale) {
return this.getMessage(locale).containsKey("content"); return this.getMessage(locale).containsKey("content");
} }
/**
* 获取Content。
*
* @param locale 参数 {@code locale}({@code String})
* @return 字符串结果
*/
public String getContent(String locale) { public String getContent(String locale) {
return this.getMessage(locale).getString("content"); return this.getMessage(locale).getString("content");
} }
public List getMailsTo() { /**
* 获取 {@code mailsTo}。
* @return InternetAddress列表,可能为空
*/
public List<InternetAddress> getMailsTo() {
return McEmailUtils.parseMails(this.getMessage().getString("to")); return McEmailUtils.parseMails(this.getMessage().getString("to"));
} }
/**
* 设置消息。
*
* @param title 参数 {@code title}({@code String})
* @param content 参数 {@code content}({@code String})
* @param summary 参数 {@code summary}({@code String})
*/
public void setMessage(String title, String content, String summary) { public void setMessage(String title, String content, String summary) {
this.setMessage(Locale.US.toLanguageTag(), title, content, summary); this.setMessage(Locale.US.toLanguageTag(), title, content, summary);
} }
/**
* 设置消息。
*
* @param languageTag 参数 {@code languageTag}({@code String})
* @param title 参数 {@code title}({@code String})
* @param content 参数 {@code content}({@code String})
* @param summary 参数 {@code summary}({@code String})
*/
public void setMessage(String languageTag, String title, String content, String summary) { public void setMessage(String languageTag, String title, String content, String summary) {
this.setTitle(languageTag, title); this.setTitle(languageTag, title);
this.setContent(languageTag, content); this.setContent(languageTag, content);
this.setSummary(languageTag, summary); this.setSummary(languageTag, summary);
} }
/**
* 设置 {@code title}。
*
* @param title 参数 {@code title}({@code String})
*/
public void setTitle(String title) { public void setTitle(String title) {
this.setTitle(Locale.US.toLanguageTag(), title); this.setTitle(Locale.US.toLanguageTag(), title);
} }
/**
* 设置 {@code content}。
*
* @param content 参数 {@code content}({@code String})
*/
public void setContent(String content) { public void setContent(String content) {
this.setContent(Locale.US.toLanguageTag(), content); this.setContent(Locale.US.toLanguageTag(), content);
} }
/**
* 设置 {@code summary}。
*
* @param summary 参数 {@code summary}({@code String})
*/
public void setSummary(String summary) { public void setSummary(String summary) {
this.setSummary(Locale.US.toLanguageTag(), summary); this.setSummary(Locale.US.toLanguageTag(), summary);
} }
/**
* 设置Title。
*
* @param languageTag 参数 {@code languageTag}({@code String})
* @param title 参数 {@code title}({@code String})
*/
public void setTitle(String languageTag, String title) { public void setTitle(String languageTag, String title) {
DbObject message = this.getMessage(languageTag); DbObject message = this.getMessage(languageTag);
message.put("title", title); message.put("title", title);
} }
/**
* 设置Content。
*
* @param languageTag 参数 {@code languageTag}({@code String})
* @param content 参数 {@code content}({@code String})
*/
public void setContent(String languageTag, String content) { public void setContent(String languageTag, String content) {
DbObject message = this.getMessage(languageTag); DbObject message = this.getMessage(languageTag);
message.put("content", content); message.put("content", content);
} }
/**
* 获取 {@code reference}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getReference() { public DbObject getReference() {
if (this.reference == null) { if (this.reference == null) {
this.reference = new DbObject(); this.reference = new DbObject();
@@ -194,111 +414,240 @@ public class NewsMessage {
return this.reference; return this.reference;
} }
/**
* 设置 {@code reference}。
*
* @param reference 参数 {@code reference}({@code DbObject})
*/
public void setReference(DbObject reference) { public void setReference(DbObject reference) {
this.reference = reference; this.reference = reference;
} }
/**
* 设置Summary。
*
* @param languageTag 参数 {@code languageTag}({@code String})
* @param summary 参数 {@code summary}({@code String})
*/
public void setSummary(String languageTag, String summary) { public void setSummary(String languageTag, String summary) {
DbObject message = this.getMessage(languageTag); DbObject message = this.getMessage(languageTag);
message.put("summary", summary); message.put("summary", summary);
} }
/**
* 判断 {@code unremovable}。
* @return 字段/派生属性 {@code unremovable} 的值
*/
public Boolean isUnremovable() { public Boolean isUnremovable() {
return this.isUnremovable; return this.isUnremovable;
} }
/**
* 设置 {@code isUnremovable}。
*
* @param isUnremovable 参数 {@code isUnremovable}({@code Boolean})
*/
public void setIsUnremovable(Boolean isUnremovable) { public void setIsUnremovable(Boolean isUnremovable) {
this.isUnremovable = isUnremovable; this.isUnremovable = isUnremovable;
} }
/**
* 获取 {@code forWhat}。
* @return 字符串结果
*/
public String getForWhat() { public String getForWhat() {
return this.forWhat; return this.forWhat;
} }
/**
* 设置 {@code forWhat}。
*
* @param forWhat 参数 {@code forWhat}({@code String})
*/
public void setForWhat(String forWhat) { public void setForWhat(String forWhat) {
this.forWhat = forWhat; this.forWhat = forWhat;
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code writer}。
* @return 用户对象;未找到时返回 {@code null}
*/
public User getWriter() { public User getWriter() {
return this.writer; return this.writer;
} }
/**
* 设置 {@code writer}。
*
* @param writer 参数 {@code writer}({@code User})
*/
public void setWriter(User writer) { public void setWriter(User writer) {
this.writer = writer; this.writer = writer;
} }
/**
* 获取 {@code category}。
* @return 字符串结果
*/
public String getCategory() { public String getCategory() {
return this.category; return this.category;
} }
/**
* 设置 {@code category}。
*
* @param category 分类(app/ota/other/report 等)({@code String})
*/
public void setCategory(String category) { public void setCategory(String category) {
this.category = category; this.category = category;
} }
/**
* 获取 {@code sendSchedule}。
* @return 字段/派生属性 {@code sendSchedule} 的值
*/
public Date getSendSchedule() { public Date getSendSchedule() {
return this.sendSchedule; return this.sendSchedule;
} }
/**
* 设置 {@code sendSchedule}。
*
* @param sendSchedule 参数 {@code sendSchedule}({@code Date})
*/
public void setSendSchedule(Date sendSchedule) { public void setSendSchedule(Date sendSchedule) {
this.sendSchedule = sendSchedule; this.sendSchedule = sendSchedule;
} }
/**
* 发送Now。
*
* 实现要点:主要调用:new DateTime。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean sendNow() { public boolean sendNow() {
return this.sendNow || this.sendSchedule == null || McDateTimeUtils.isSameDate(new DateTime(this.sendSchedule), DateTime.now()); return this.sendNow || this.sendSchedule == null || McDateTimeUtils.isSameDate(new DateTime(this.sendSchedule), DateTime.now());
} }
/**
* 获取 {@code expiry}。
* @return 字段/派生属性 {@code expiry} 的值
*/
public Date getExpiry() { public Date getExpiry() {
return this.expiry; return this.expiry;
} }
/**
* 设置 {@code expiry}。
*
* @param expiry 参数 {@code expiry}({@code Date})
*/
public void setExpiry(Date expiry) { public void setExpiry(Date expiry) {
this.expiry = expiry; this.expiry = expiry;
} }
/**
* 获取 {@code created}。
* @return 字段/派生属性 {@code created} 的值
*/
public Date getCreated() { public Date getCreated() {
return this.created; return this.created;
} }
/**
* 设置 {@code created}。
*
* @param created 参数 {@code created}({@code Date})
*/
public void setCreated(Date created) { public void setCreated(Date created) {
this.created = created; this.created = created;
} }
/**
* 获取 {@code updated}。
* @return 字段/派生属性 {@code updated} 的值
*/
public Date getUpdated() { public Date getUpdated() {
return this.updated; return this.updated;
} }
/**
* 设置 {@code updated}。
*
* @param updated 参数 {@code updated}({@code Date})
*/
public void setUpdated(Date updated) { public void setUpdated(Date updated) {
this.updated = updated; this.updated = updated;
} }
/**
* 获取 {@code isUnremovable}。
* @return 字段/派生属性 {@code isUnremovable} 的值
*/
public Boolean getIsUnremovable() { public Boolean getIsUnremovable() {
return this.isUnremovable; return this.isUnremovable;
} }
/**
* 判断 {@code enabled}。
* @return 字段/派生属性 {@code enabled} 的值
*/
public Boolean isEnabled() { public Boolean isEnabled() {
return this.isEnabled; return this.isEnabled;
} }
/**
* 设置 {@code isEnabled}。
*
* @param isEnabled 参数 {@code isEnabled}({@code Boolean})
*/
public void setIsEnabled(Boolean isEnabled) { public void setIsEnabled(Boolean isEnabled) {
this.isEnabled = isEnabled; this.isEnabled = isEnabled;
} }
/**
* 判断 {@code sendNow}。
* @return 字段/派生属性 {@code sendNow} 的值
*/
public boolean isSendNow() { public boolean isSendNow() {
return this.sendNow; return this.sendNow;
} }
/**
* 设置 {@code sendNow}。
*
* @param sendNow 参数 {@code sendNow}({@code boolean})
*/
public void setSendNow(boolean sendNow) { public void setSendNow(boolean sendNow) {
this.sendNow = sendNow; this.sendNow = sendNow;
} }
/**
* 处理转换为日期String。
*
* 实现要点:主要调用:new DateTime。
*
* @param dateString 参数 {@code dateString}({@code String})
* @param format 参数 {@code format}({@code String})
* @return 字符串结果
*/
public String toDateString(String dateString, String format) { public String toDateString(String dateString, String format) {
DateTime dateTime = new DateTime(dateString); DateTime dateTime = new DateTime(dateString);
return McDateTimeUtils.toString(dateTime, format); return McDateTimeUtils.toString(dateTime, format);
@@ -0,0 +1,13 @@
/**
* 新闻/通知消息模型。
*
* <p>本包主要类型:
* <ul>
* <li>{@link MessageLog}</li>
* <li>{@link NewsMessage}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.model.news;
+373 -2
View File
@@ -13,30 +13,95 @@ import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code Site}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code MODEL_MIDM}(String):字段 MODEL_MIDM</li>
* <li>{@code MODEL_MUST}(String):字段 MODEL_MUST</li>
* <li>{@code reseller}(Site):字段 reseller</li>
* <li>{@code idName}(String):ID名称</li>
* <li>{@code latestVisit}(Date):最新Visit</li>
* <li>{@code report}(DbObject):报表</li>
* </ul>
*
* 协作对象:{@code DbObject}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class Site extends GeneralProfile { public class Site extends GeneralProfile {
/**
* 字段 MODEL_MIDM。
*/
public static final String MODEL_MIDM = "midm"; public static final String MODEL_MIDM = "midm";
/**
* 字段 MODEL_MUST。
*/
public static final String MODEL_MUST = "must"; public static final String MODEL_MUST = "must";
/**
* 字段 reseller;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private Site reseller; private Site reseller;
/**
* ID名称;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed(unique = true)}。
*/
@Indexed( @Indexed(
unique = true unique = true
) )
private String idName; private String idName;
/**
* 最新Visit;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private Date latestVisit; private Date latestVisit;
/**
* 报表;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private DbObject report; private DbObject report;
/**
* 构造 {@code Site} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public Site() { public Site() {
this.setEnabled(false); this.setEnabled(false);
} }
/**
* 构造 {@code Site} 实例。
*
* @param model 参数 {@code model}({@code String})
*/
public Site(String model) { public Site(String model) {
this(); this();
this.setModel(model); this.setModel(model);
} }
/**
* 初始化对象状态(补齐 UUID/时间戳/默认字段)。
*
* 实现要点:主要调用:new DbObject、new Date。
*/
public void init() { public void init() {
this.setUuid(UUID.randomUUID()); this.setUuid(UUID.randomUUID());
DbObject notiSettings = new DbObject("sendEmail", true); DbObject notiSettings = new DbObject("sendEmail", true);
@@ -49,57 +114,115 @@ public class Site extends GeneralProfile {
this.setCreated(new Date()); this.setCreated(new Date());
} }
/**
* 获取 {@code reseller}。
* @return 站点对象;未找到时返回 {@code null}
*/
public Site getReseller() { public Site getReseller() {
return this.reseller; return this.reseller;
} }
/**
* 设置 {@code reseller}。
*
* @param reseller 参数 {@code reseller}({@code Site})
*/
public void setReseller(Site reseller) { public void setReseller(Site reseller) {
this.reseller = reseller; this.reseller = reseller;
} }
/**
* 判断 {@code child}。
* @return 字段/派生属性 {@code child} 的值
*/
public boolean isChild() { public boolean isChild() {
return this.reseller != null; return this.reseller != null;
} }
/**
* 判断 {@code customize}。
* @return 字段/派生属性 {@code customize} 的值
*/
public boolean canCustomize() { public boolean canCustomize() {
return true; return true;
} }
/**
* 获取 {@code domainName}。
* @return 字段/派生属性 {@code domainName} 的值
*/
public Object getDomainName() { public Object getDomainName() {
return this.getSetting("domainName"); return this.getSetting("domainName");
} }
/**
* 获取 {@code idName}。
* @return 字符串结果
*/
public String getIdName() { public String getIdName() {
return this.idName; return this.idName;
} }
/**
* 设置 {@code idName}。
*
* @param idName 参数 {@code idName}({@code String})
*/
public void setIdName(String idName) { public void setIdName(String idName) {
this.idName = idName; this.idName = idName;
} }
/**
* 获取 {@code title}。
* @return 字符串结果
*/
public String getTitle() { public String getTitle() {
String siteName = (String)this.getSetting("theme", "siteName"); String siteName = (String)this.getSetting("theme", "siteName");
return Strings.isNullOrEmpty(siteName) ? this.getName() : siteName; return Strings.isNullOrEmpty(siteName) ? this.getName() : siteName;
} }
/**
* 判断 {@code logo}。
* @return 字段/派生属性 {@code logo} 的值
*/
public boolean hasLogo() { public boolean hasLogo() {
return this.getSettingAsBoolean("theme", "logo", false); return this.getSettingAsBoolean("theme", "logo", false);
} }
/**
* 获取 {@code plan}。
* @return MongoDB 文档扩展对象
*/
public DbObject getPlan() { public DbObject getPlan() {
return this.getProfileCategory(new String[]{"plan"}); return this.getProfileCategory(new String[]{"plan"});
} }
/**
* 获取 {@code planName}。
* @return 字符串结果
*/
public String getPlanName() { public String getPlanName() {
DbObject plan = this.getPlan(); DbObject plan = this.getPlan();
return plan.getString("plan", "standard"); return plan.getString("plan", "standard");
} }
/**
* 获取 {@code showPlanName}。
* @return 字符串结果
*/
public String getShowPlanName() { public String getShowPlanName() {
String planName = this.getPlanName(); String planName = this.getPlanName();
return this.getShowPlanName(planName); return this.getShowPlanName(planName);
} }
/**
* 获取Show计划名称。
*
* 实现要点:包含 3 个条件分支、0 个循环。
*
* @param planName 参数 {@code planName}({@code String})
* @return 字符串结果
*/
public String getShowPlanName(String planName) { public String getShowPlanName(String planName) {
String name = ""; String name = "";
if (planName.equals("lite")) { if (planName.equals("lite")) {
@@ -113,10 +236,22 @@ public class Site extends GeneralProfile {
return name; return name;
} }
/**
* 设置 {@code plan}。
*
* @param plan 参数 {@code plan}({@code DbObject})
*/
public void setPlan(DbObject plan) { public void setPlan(DbObject plan) {
this.setProfile("plan", plan); this.setProfile("plan", plan);
} }
/**
* 设置 {@code plan}。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:remove。
*
* @param plan 参数 {@code plan}({@code String})
*/
public void setPlan(String plan) { public void setPlan(String plan) {
if (!Strings.isNullOrEmpty(plan)) { if (!Strings.isNullOrEmpty(plan)) {
this.setProfile("plan", "plan", plan); this.setProfile("plan", "plan", plan);
@@ -129,64 +264,133 @@ public class Site extends GeneralProfile {
} }
} }
/**
* 获取 {@code upgradeStatus}。
* @return 字符串结果
*/
public String getUpgradeStatus() { public String getUpgradeStatus() {
DbObject plan = this.getPlan(); DbObject plan = this.getPlan();
return plan.getString("upgradeStatus"); return plan.getString("upgradeStatus");
} }
/**
* 判断 {@code upgradeRequested}。
* @return 字段/派生属性 {@code upgradeRequested} 的值
*/
public boolean isUpgradeRequested() { public boolean isUpgradeRequested() {
return "processing".equals(this.getUpgradeStatus()); return "processing".equals(this.getUpgradeStatus());
} }
/**
* 获取 {@code upgradeTargetPlan}。
* @return 字符串结果
*/
public String getUpgradeTargetPlan() { public String getUpgradeTargetPlan() {
DbObject plan = this.getPlan(); DbObject plan = this.getPlan();
return plan.getString("targetPlan"); return plan.getString("targetPlan");
} }
/**
* 获取 {@code model}。
* @return 字符串结果
*/
public String getModel() { public String getModel() {
return (String)this.getProfile("model", "midm"); return (String)this.getProfile("model", "midm");
} }
/**
* 设置 {@code model}。
*
* @param model 参数 {@code model}({@code String})
*/
public void setModel(String model) { public void setModel(String model) {
this.setProfile("model", model); this.setProfile("model", model);
} }
/**
* 获取 {@code phone}。
* @return 字符串结果
*/
public String getPhone() { public String getPhone() {
return (String)this.getProfile("phone"); return (String)this.getProfile("phone");
} }
/**
* 获取 {@code address}。
* @return 字符串结果
*/
public String getAddress() { public String getAddress() {
return (String)this.getProfile("address"); return (String)this.getProfile("address");
} }
/**
* 获取 {@code country}。
*
* 实现要点:包含异常捕获与降级/回滚分支。
* @return 字符串结果
*/
public String getCountry() { public String getCountry() {
return (String)this.getProfile("country"); return (String)this.getProfile("country");
} }
/**
* 判断 {@code reseller}。
* @return 字段/派生属性 {@code reseller} 的值
*/
public boolean isReseller() { public boolean isReseller() {
return (Boolean)this.getProfile("isReseller", false); return (Boolean)this.getProfile("isReseller", false);
} }
/**
* 设置 {@code isReseller}。
*
* @param isReseller 参数 {@code isReseller}({@code boolean})
*/
public void setIsReseller(boolean isReseller) { public void setIsReseller(boolean isReseller) {
this.setProfile("isReseller", isReseller); this.setProfile("isReseller", isReseller);
} }
/**
* 处理limitRegistered设备Only。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean limitRegisteredDeviceOnly() { public boolean limitRegisteredDeviceOnly() {
return this.getSettingAsBoolean("enrollment", "registeredOnly", false); return this.getSettingAsBoolean("enrollment", "registeredOnly", false);
} }
/**
* 获取 {@code latestVisit}。
* @return 字段/派生属性 {@code latestVisit} 的值
*/
public Date getLatestVisit() { public Date getLatestVisit() {
return this.latestVisit; return this.latestVisit;
} }
/**
* 设置 {@code latestVisit}。
*
* @param latestVisit 参数 {@code latestVisit}({@code Date})
*/
public void setLatestVisit(Date latestVisit) { public void setLatestVisit(Date latestVisit) {
this.latestVisit = latestVisit; this.latestVisit = latestVisit;
} }
/**
* 获取 {@code credential}。
* @return MongoDB 文档扩展对象
*/
public DbObject getCredential() { public DbObject getCredential() {
return this.getSettings().getDbObject(new String[]{"credential"}); return this.getSettings().getDbObject(new String[]{"credential"});
} }
/**
* 判断是否CredentialMatched。
*
* 实现要点:包含 2 个条件分支、0 个循环;主要调用:new Date。
*
* @param credential 参数 {@code credential}({@code String})
* @return 字段/派生属性 {@code credentialMatched} 的值
*/
public boolean isCredentialMatched(String credential) { public boolean isCredentialMatched(String credential) {
if (Strings.isNullOrEmpty(credential)) { if (Strings.isNullOrEmpty(credential)) {
return false; return false;
@@ -202,6 +406,13 @@ public class Site extends GeneralProfile {
} }
} }
/**
* 设置 {@code credential}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
*
* @param credential 参数 {@code credential}({@code String})
*/
public void setCredential(String credential) { public void setCredential(String credential) {
if (!Strings.isNullOrEmpty(credential)) { if (!Strings.isNullOrEmpty(credential)) {
DbObject value = new DbObject("credential", credential); DbObject value = new DbObject("credential", credential);
@@ -213,11 +424,20 @@ public class Site extends GeneralProfile {
} }
/**
* 处理renewCredential。
*/
public void renewCredential() { public void renewCredential() {
String credential = McUuidUtils.toBase64String(UUID.randomUUID(), true); String credential = McUuidUtils.toBase64String(UUID.randomUUID(), true);
this.setCredential(credential); this.setCredential(credential);
} }
/**
* 获取 {@code settings}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getSettings() { public DbObject getSettings() {
DbObject settings = super.getSettings(); DbObject settings = super.getSettings();
if (settings.get("theme") == null) { if (settings.get("theme") == null) {
@@ -230,6 +450,12 @@ public class Site extends GeneralProfile {
return settings; return settings;
} }
/**
* 获取 {@code report}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getReport() { public DbObject getReport() {
if (this.report == null) { if (this.report == null) {
this.report = new DbObject(); this.report = new DbObject();
@@ -238,14 +464,33 @@ public class Site extends GeneralProfile {
return this.report; return this.report;
} }
/**
* 设置 {@code report}。
*
* @param report 参数 {@code report}({@code DbObject})
*/
public void setReport(DbObject report) { public void setReport(DbObject report) {
this.report = report; this.report = report;
} }
/**
* 添加报表。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void addReport(String key, Object value) { public void addReport(String key, Object value) {
this.getReport().put(key, value); this.getReport().put(key, value);
} }
/**
* 比较当前对象与另一个对象是否相等。
*
* 实现要点:包含 3 个条件分支、0 个循环。
*
* @param obj 参数 {@code obj}({@code Object})
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj.hashCode() == this.hashCode()) { if (obj.hashCode() == this.hashCode()) {
return true; return true;
@@ -260,63 +505,139 @@ public class Site extends GeneralProfile {
} }
} }
/**
* 判断 {@code lite}。
* @return 字段/派生属性 {@code lite} 的值
*/
public boolean isLite() { public boolean isLite() {
return this.getPlanName().equals("lite"); return this.getPlanName().equals("lite");
} }
/**
* 判断 {@code standard}。
* @return 字段/派生属性 {@code standard} 的值
*/
public boolean isStandard() { public boolean isStandard() {
return this.getPlanName().equals("standard"); return this.getPlanName().equals("standard");
} }
/**
* 判断 {@code standardWithBatteryPro}。
* @return 字段/派生属性 {@code standardWithBatteryPro} 的值
*/
public boolean isStandardWithBatteryPro() { public boolean isStandardWithBatteryPro() {
return this.getPlanName().equals("standardWithBatteryPro"); return this.getPlanName().equals("standardWithBatteryPro");
} }
/**
* 判断 {@code must}。
* @return 字段/派生属性 {@code must} 的值
*/
public boolean isMust() { public boolean isMust() {
return this.getModel().equals("must"); return this.getModel().equals("must");
} }
/**
* 设置 {@code must}。
*
* @param isMust 参数 {@code isMust}({@code boolean})
*/
public void setMust(boolean isMust) { public void setMust(boolean isMust) {
this.setModel("must"); this.setModel("must");
} }
/**
* 判断是否FeatureAllowed。
*
* @param subCategory 参数 {@code subCategory}({@code String})
* @param item 参数 {@code item}({@code String})
* @return 字段/派生属性 {@code featureAllowed} 的值
*/
public boolean isFeatureAllowed(String subCategory, String item) { public boolean isFeatureAllowed(String subCategory, String item) {
return !this.isLite() ? true : this.getProfileAsBoolean("plan", "features", subCategory, item, false); return !this.isLite() ? true : this.getProfileAsBoolean("plan", "features", subCategory, item, false);
} }
/**
* 获取 {@code notificationSettings}。
* @return MongoDB 文档扩展对象
*/
public DbObject getNotificationSettings() { public DbObject getNotificationSettings() {
return this.getSettingsCategory(new String[]{"noti"}); return this.getSettingsCategory(new String[]{"noti"});
} }
/**
* 通知Via邮件。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean notifyViaMail() { public boolean notifyViaMail() {
return this.getNotificationSettings().getBoolean("sendEmail", false); return this.getNotificationSettings().getBoolean("sendEmail", false);
} }
/**
* 设置 {@code notifyViaMail}。
*
* @param viaMail 参数 {@code viaMail}({@code boolean})
*/
public void setNotifyViaMail(boolean viaMail) { public void setNotifyViaMail(boolean viaMail) {
this.getNotificationSettings().put("sendEmail", viaMail); this.getNotificationSettings().put("sendEmail", viaMail);
} }
/**
* 通知设备错误邮件。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean notifyDeviceErrorMail() { public boolean notifyDeviceErrorMail() {
return this.getNotificationSettings().getBoolean("sendDeviceErrorEmail", false); return this.getNotificationSettings().getBoolean("sendDeviceErrorEmail", false);
} }
/**
* 设置 {@code notifyDeviceErrorMail}。
*
* @param enable 参数 {@code enable}({@code boolean})
*/
public void setNotifyDeviceErrorMail(boolean enable) { public void setNotifyDeviceErrorMail(boolean enable) {
this.getNotificationSettings().put("sendDeviceErrorEmail", enable); this.getNotificationSettings().put("sendDeviceErrorEmail", enable);
} }
/**
* 通知电池Condition邮件。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean notifyBatteryConditionMail() { public boolean notifyBatteryConditionMail() {
return this.getNotificationSettings().getBoolean("sendBatteryConditionEmail", false); return this.getNotificationSettings().getBoolean("sendBatteryConditionEmail", false);
} }
/**
* 设置 {@code notifyBatteryConditionMail}。
*
* @param enable 参数 {@code enable}({@code boolean})
*/
public void setNotifyBatteryConditionMail(boolean enable) { public void setNotifyBatteryConditionMail(boolean enable) {
this.getNotificationSettings().put("sendBatteryConditionEmail", enable); this.getNotificationSettings().put("sendBatteryConditionEmail", enable);
} }
/**
* 设置Notification设置列表。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param forWhat 参数 {@code forWhat}({@code String})
* @param isEnabled 参数 {@code isEnabled}({@code boolean})
*/
public void setNotificationSettings(String category, String forWhat, boolean isEnabled) { public void setNotificationSettings(String category, String forWhat, boolean isEnabled) {
this.setNotificationSettings(category, forWhat, isEnabled, (Set)null); this.setNotificationSettings(category, forWhat, isEnabled, (Set)null);
} }
public void setNotificationSettings(String category, String forWhat, boolean isEnabled, Set roles) { /**
* 设置Notification设置列表。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:remove。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param forWhat 参数 {@code forWhat}({@code String})
* @param isEnabled 参数 {@code isEnabled}({@code boolean})
* @param roles 参数 {@code roles}({@code Set<String>})
*/
public void setNotificationSettings(String category, String forWhat, boolean isEnabled, Set<String> roles) {
DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat}); DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat});
settings.put("isEnabled", isEnabled); settings.put("isEnabled", isEnabled);
if (roles == null) { if (roles == null) {
@@ -327,20 +648,45 @@ public class Site extends GeneralProfile {
} }
/**
* 设置Notification设置列表。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param forWhat 参数 {@code forWhat}({@code String})
* @param key 键/配置项({@code String})
* @param value 值({@code String})
*/
public void setNotificationSettings(String category, String forWhat, String key, String value) { public void setNotificationSettings(String category, String forWhat, String key, String value) {
DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat}); DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat});
settings.put(key, value); settings.put(key, value);
} }
/**
* 获取 {@code dataUsage}。
* @return 字符串结果
*/
public String getDataUsage() { public String getDataUsage() {
return this.getSettingsCategory(new String[]{"report"}).getString("dataUsage", "none"); return this.getSettingsCategory(new String[]{"report"}).getString("dataUsage", "none");
} }
/**
* 处理collect数据用量。
* @return 条件成立返回 {@code true},否则返回 {@code false}
*/
public boolean collectDataUsage() { public boolean collectDataUsage() {
return !this.getDataUsage().equals("none"); return !this.getDataUsage().equals("none");
} }
public Set getMessageRoles(String category, String forWhat) { /**
* 获取消息Roles。
*
* 实现要点:包含 2 个条件分支、0 个循环。
*
* @param category 分类(app/ota/other/report 等)({@code String})
* @param forWhat 参数 {@code forWhat}({@code String})
* @return String列表,可能为空
*/
public Set<String> getMessageRoles(String category, String forWhat) {
DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat}); DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat});
if (settings.getBoolean("enabled")) { if (settings.getBoolean("enabled")) {
Object value = settings.get("roles"); Object value = settings.get("roles");
@@ -355,28 +701,53 @@ public class Site extends GeneralProfile {
} }
} }
/**
* 判断 {@code timeZone}。
* @return 字段/派生属性 {@code timeZone} 的值
*/
public boolean hasTimeZone() { public boolean hasTimeZone() {
return this.getSetting("general", "timeZone") != null; return this.getSetting("general", "timeZone") != null;
} }
/**
* 设置 {@code timeZone}。
*
* @param timeZone 参数 {@code timeZone}({@code TimeZone})
*/
public void setTimeZone(TimeZone timeZone) { public void setTimeZone(TimeZone timeZone) {
this.setSetting("general", "timeZone", timeZone.getID()); this.setSetting("general", "timeZone", timeZone.getID());
} }
/**
* 获取 {@code timeZone}。
* @return 字段/派生属性 {@code timeZone} 的值
*/
public TimeZone getTimeZone() { public TimeZone getTimeZone() {
Object timeZone = this.getSetting("general", "timeZone"); Object timeZone = this.getSetting("general", "timeZone");
return timeZone != null ? TimeZone.getTimeZone((String)timeZone) : TimeZone.getDefault(); return timeZone != null ? TimeZone.getTimeZone((String)timeZone) : TimeZone.getDefault();
} }
/**
* 获取 {@code includeApps}。
* @return 字段/派生属性 {@code includeApps} 的值
*/
public String[] getIncludeApps() { public String[] getIncludeApps() {
String installApps = this.getSettingsCategory(new String[]{"report"}).getString("installApps"); String installApps = this.getSettingsCategory(new String[]{"report"}).getString("installApps");
return Strings.isNullOrEmpty(installApps) ? null : installApps.split("[,;\\s]+"); return Strings.isNullOrEmpty(installApps) ? null : installApps.split("[,;\\s]+");
} }
/**
* 获取 {@code callbackSetting}。
* @return MongoDB 文档扩展对象
*/
public DbObject getCallbackSetting() { public DbObject getCallbackSetting() {
return this.getSettingsCategory(new String[]{"callback"}); return this.getSettingsCategory(new String[]{"callback"});
} }
/**
* 返回对象的可读字符串表示。
* @return 字符串结果
*/
public String toString() { public String toString() {
return String.format("%s(%s):%s", this.getName(), this.getIdName(), this.getUuid()); return String.format("%s(%s):%s", this.getName(), this.getIdName(), this.getUuid());
} }
@@ -7,69 +7,179 @@ import java.util.UUID;
import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code SiteFile}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code category}(String):字段 category</li>
* <li>{@code forWhat}(String):用于What</li>
* <li>{@code requested}(Date):时间字段</li>
* <li>{@code expiry}(Date):时间字段</li>
* <li>{@code siteName}(String):站点名称</li>
* <li>{@code requestedFrom}(User):requested从</li>
* </ul>
*
* 协作对象:{@code User}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class SiteFile extends BaseFile { public class SiteFile extends BaseFile {
/**
* 字段 category。
*/
private String category; private String category;
/**
* 用于What。
*/
private String forWhat; private String forWhat;
/**
* 时间字段。
*/
private Date requested; private Date requested;
/**
* 时间字段。
*/
private Date expiry; private Date expiry;
/**
* 站点名称。
*/
private String siteName; private String siteName;
/**
* requested从;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private User requestedFrom; private User requestedFrom;
/**
* 构造 {@code SiteFile} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public SiteFile() { public SiteFile() {
} }
/**
* 构造 {@code SiteFile} 实例。
*
* @param requestedFrom 参数 {@code requestedFrom}({@code User})
* @param fileUuid 文件 UUID({@code UUID})
* @param file 文件({@code McFile})
*/
public SiteFile(User requestedFrom, UUID fileUuid, McFile file) { public SiteFile(User requestedFrom, UUID fileUuid, McFile file) {
this.setUserUuid(requestedFrom); this.setUserUuid(requestedFrom);
this.setFileUuid(fileUuid); this.setFileUuid(fileUuid);
this.setFileInfo(file); this.setFileInfo(file);
} }
/**
* 获取 {@code category}。
* @return 字符串结果
*/
public String getCategory() { public String getCategory() {
return this.category; return this.category;
} }
/**
* 设置 {@code category}。
*
* @param category 分类(app/ota/other/report 等)({@code String})
*/
public void setCategory(String category) { public void setCategory(String category) {
this.category = category; this.category = category;
} }
/**
* 获取 {@code requestedFrom}。
* @return 用户对象;未找到时返回 {@code null}
*/
public User getRequestedFrom() { public User getRequestedFrom() {
return this.requestedFrom; return this.requestedFrom;
} }
/**
* 设置 {@code requestedFrom}。
*
* @param requestedFrom 参数 {@code requestedFrom}({@code User})
*/
public void setRequestedFrom(User requestedFrom) { public void setRequestedFrom(User requestedFrom) {
this.requestedFrom = requestedFrom; this.requestedFrom = requestedFrom;
} }
/**
* 获取 {@code requested}。
* @return 字段/派生属性 {@code requested} 的值
*/
public Date getRequested() { public Date getRequested() {
return this.requested; return this.requested;
} }
/**
* 设置 {@code requested}。
*
* @param requested 参数 {@code requested}({@code Date})
*/
public void setRequested(Date requested) { public void setRequested(Date requested) {
this.requested = requested; this.requested = requested;
} }
/**
* 获取 {@code expiry}。
* @return 字段/派生属性 {@code expiry} 的值
*/
public Date getExpiry() { public Date getExpiry() {
return this.expiry; return this.expiry;
} }
/**
* 设置 {@code expiry}。
*
* @param expiry 参数 {@code expiry}({@code Date})
*/
public void setExpiry(Date expiry) { public void setExpiry(Date expiry) {
this.expiry = expiry; this.expiry = expiry;
} }
/**
* 获取 {@code siteName}。
* @return 字符串结果
*/
public String getSiteName() { public String getSiteName() {
return this.siteName; return this.siteName;
} }
/**
* 设置 {@code siteName}。
*
* @param siteName 参数 {@code siteName}({@code String})
*/
public void setSiteName(String siteName) { public void setSiteName(String siteName) {
this.siteName = siteName; this.siteName = siteName;
} }
/**
* 获取 {@code forWhat}。
* @return 字符串结果
*/
public String getForWhat() { public String getForWhat() {
return this.forWhat; return this.forWhat;
} }
/**
* 设置 {@code forWhat}。
*
* @param forWhat 参数 {@code forWhat}({@code String})
*/
public void setForWhat(String forWhat) { public void setForWhat(String forWhat) {
this.forWhat = forWhat; this.forWhat = forWhat;
} }
+195 -2
View File
@@ -9,17 +9,72 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.index.Indexed;
/**
* 【领域模型】{@code SiteInfo}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code siteUuid}(UUID):用户所属站点 UUID</li>
* <li>{@code roles}(Set<String>):String集合</li>
* <li>{@code groupUuid}(UUID):分组UUID</li>
* <li>{@code settings}(DbObject):设置列表</li>
* <li>{@code apiOnly}(Boolean):APIOnly</li>
* <li>{@code created}(Date):创建时间</li>
* </ul>
*
* 协作对象:{@code DbObject}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class SiteInfo { public class SiteInfo {
/**
* 用户所属站点 UUID;建有索引,常用于查询条件。
*
* 注解:{@code @Indexed}。
*/
@Indexed @Indexed
private UUID siteUuid; private UUID siteUuid;
private Set roles; /**
* String集合。
*/
private Set<String> roles;
/**
* 分组UUID。
*/
private UUID groupUuid; private UUID groupUuid;
/**
* 设置列表。
*/
protected DbObject settings; protected DbObject settings;
/**
* APIOnly。
*/
private Boolean apiOnly; private Boolean apiOnly;
/**
* 创建时间。
*/
private Date created; private Date created;
/**
* 最后更新时间。
*/
private Date updated; private Date updated;
/**
* 是否启用。
*/
private boolean enabled; private boolean enabled;
/**
* 构造 {@code SiteInfo} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*
* 实现要点:主要调用:new HashSet、new Date。
*/
public SiteInfo() { public SiteInfo() {
this.setRoles(new HashSet()); this.setRoles(new HashSet());
this.setCreated(new Date()); this.setCreated(new Date());
@@ -27,20 +82,40 @@ public class SiteInfo {
this.setEnabled(false); this.setEnabled(false);
} }
/**
* 构造 {@code SiteInfo} 实例。
*
* @param siteUuid 站点 UUID({@code UUID})
*/
public SiteInfo(UUID siteUuid) { public SiteInfo(UUID siteUuid) {
this(); this();
this.setSiteUuid(siteUuid); this.setSiteUuid(siteUuid);
} }
/**
* 获取 {@code siteUuid}。
* @return UUID
*/
public UUID getSiteUuid() { public UUID getSiteUuid() {
return this.siteUuid; return this.siteUuid;
} }
/**
* 设置 {@code siteUuid}。
*
* @param siteUuid 站点 UUID({@code UUID})
*/
public void setSiteUuid(UUID siteUuid) { public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid; this.siteUuid = siteUuid;
} }
public Set getRoles() { /**
* 获取 {@code roles}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new HashSet。
* @return String列表,可能为空
*/
public Set<String> getRoles() {
if (this.roles == null) { if (this.roles == null) {
this.roles = new HashSet(); this.roles = new HashSet();
} }
@@ -48,10 +123,24 @@ public class SiteInfo {
return this.roles; return this.roles;
} }
/**
* 判断是否Role。
*
* @param role 参数 {@code role}({@code String})
* @return 字段/派生属性 {@code role} 的值
*/
public boolean hasRole(String role) { public boolean hasRole(String role) {
return this.isEnabled() && !this.getRoles().isEmpty() && this.getRoles().contains(role); return this.isEnabled() && !this.getRoles().isEmpty() && this.getRoles().contains(role);
} }
/**
* 判断是否Role。
*
* 实现要点:包含 2 个条件分支、1 个循环。
*
* @param roles 参数 {@code roles}({@code Collection<String>})
* @return 字段/派生属性 {@code role} 的值
*/
public boolean hasRole(Collection<String> roles) { public boolean hasRole(Collection<String> roles) {
if (this.isEnabled() && !this.getRoles().isEmpty()) { if (this.isEnabled() && !this.getRoles().isEmpty()) {
for(String role : roles) { for(String role : roles) {
@@ -64,6 +153,13 @@ public class SiteInfo {
return false; return false;
} }
/**
* 添加Role。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param role 参数 {@code role}({@code String})
*/
public void addRole(String role) { public void addRole(String role) {
role = UserRole.toRole(role); role = UserRole.toRole(role);
if (!Strings.isNullOrEmpty(role)) { if (!Strings.isNullOrEmpty(role)) {
@@ -72,6 +168,13 @@ public class SiteInfo {
} }
/**
* 设置 {@code roles}。
*
* 实现要点:包含 3 个条件分支、1 个循环。
*
* @param roles 参数 {@code roles}({@code Set<String>})
*/
public void setRoles(Set<String> roles) { public void setRoles(Set<String> roles) {
if (roles != null && !roles.isEmpty()) { if (roles != null && !roles.isEmpty()) {
for(String role : roles) { for(String role : roles) {
@@ -91,26 +194,53 @@ public class SiteInfo {
} }
/**
* 清理Roles。
*/
public void clearRoles() { public void clearRoles() {
this.getRoles().clear(); this.getRoles().clear();
} }
/**
* 获取 {@code groupUuid}。
* @return UUID
*/
public UUID getGroupUuid() { public UUID getGroupUuid() {
return this.groupUuid; return this.groupUuid;
} }
/**
* 设置 {@code groupUuid}。
*
* @param groupUuid 分组 UUID({@code UUID})
*/
public void setGroupUuid(UUID groupUuid) { public void setGroupUuid(UUID groupUuid) {
this.groupUuid = groupUuid; this.groupUuid = groupUuid;
} }
/**
* 判断 {@code apiOnly}。
* @return 字段/派生属性 {@code apiOnly} 的值
*/
public boolean isApiOnly() { public boolean isApiOnly() {
return this.apiOnly != null && this.apiOnly; return this.apiOnly != null && this.apiOnly;
} }
/**
* 设置 {@code apiOnly}。
*
* @param apiOnly 参数 {@code apiOnly}({@code boolean})
*/
public void setApiOnly(boolean apiOnly) { public void setApiOnly(boolean apiOnly) {
this.apiOnly = apiOnly; this.apiOnly = apiOnly;
} }
/**
* 获取 {@code settings}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getSettings() { public DbObject getSettings() {
if (this.settings == null) { if (this.settings == null) {
this.settings = new DbObject(); this.settings = new DbObject();
@@ -119,50 +249,113 @@ public class SiteInfo {
return this.settings; return this.settings;
} }
/**
* 设置 {@code settings}。
*
* @param settings 参数 {@code settings}({@code DbObject})
*/
public void setSettings(DbObject settings) { public void setSettings(DbObject settings) {
this.settings = settings; this.settings = settings;
} }
/**
* 设置设置。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setSetting(String key, Object value) { public void setSetting(String key, Object value) {
this.getSettings().put(key, value); this.getSettings().put(key, value);
} }
/**
* 获取设置。
*
* @param key 键/配置项({@code String})
* @return 字段/派生属性 {@code setting} 的值
*/
public Object getSetting(String key) { public Object getSetting(String key) {
return this.getSettings().get(key); return this.getSettings().get(key);
} }
/**
* 获取设置AsString。
*
* @param key 键/配置项({@code String})
* @return 字符串结果
*/
public String getSettingAsString(String key) { public String getSettingAsString(String key) {
return this.getSettings().getString(key, (String)null); return this.getSettings().getString(key, (String)null);
} }
/**
* 获取分页设置。
*
* @param url 参数 {@code url}({@code String})
* @return MongoDB 文档扩展对象
*/
public DbObject getPageSetting(String url) { public DbObject getPageSetting(String url) {
return this.getSettings().getDbObject(new String[]{"page", url}); return this.getSettings().getDbObject(new String[]{"page", url});
} }
/**
* 设置分页设置。
*
* @param url 参数 {@code url}({@code String})
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setPageSetting(String url, String key, Object value) { public void setPageSetting(String url, String key, Object value) {
this.getPageSetting(url).put(key, value); this.getPageSetting(url).put(key, value);
} }
/**
* 获取 {@code created}。
* @return 字段/派生属性 {@code created} 的值
*/
public Date getCreated() { public Date getCreated() {
return this.created; return this.created;
} }
/**
* 设置 {@code created}。
*
* @param created 参数 {@code created}({@code Date})
*/
public void setCreated(Date created) { public void setCreated(Date created) {
this.created = created; this.created = created;
} }
/**
* 获取 {@code updated}。
* @return 字段/派生属性 {@code updated} 的值
*/
public Date getUpdated() { public Date getUpdated() {
return this.updated; return this.updated;
} }
/**
* 设置 {@code updated}。
*
* @param updated 参数 {@code updated}({@code Date})
*/
public void setUpdated(Date updated) { public void setUpdated(Date updated) {
this.updated = updated; this.updated = updated;
} }
/**
* 判断 {@code enabled}。
* @return 字段/派生属性 {@code enabled} 的值
*/
public boolean isEnabled() { public boolean isEnabled() {
return this.enabled; return this.enabled;
} }
/**
* 设置 {@code enabled}。
*
* @param enabled 参数 {@code enabled}({@code boolean})
*/
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
this.enabled = enabled; this.enabled = enabled;
} }
@@ -12,28 +12,110 @@ import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code SiteLicense}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code site}(Site):站点</li>
* <li>{@code childSite}(Site):子站点</li>
* <li>{@code writer}(User):字段 writer</li>
* <li>{@code licenseModel}(LicenseModel):许可证模型</li>
* <li>{@code amount}(int):字段 amount</li>
* </ul>
*
* 协作对象:{@code Site、User、LicenseModel、DbObject、STATUS}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class SiteLicense { public class SiteLicense {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid; private UUID uuid;
/**
* 站点;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private Site site; private Site site;
/**
* 子站点;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private Site childSite; private Site childSite;
/**
* 字段 writer;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private User writer; private User writer;
/**
* 许可证模型;以 DBRef 引用其他文档。
*
* 注解:{@code @DBRef}。
*/
@DBRef @DBRef
private LicenseModel licenseModel; private LicenseModel licenseModel;
/**
* 字段 amount。
*/
private int amount; private int amount;
/**
* 字段 reference。
*/
private DbObject reference; private DbObject reference;
/**
* 计划。
*/
private String plan; private String plan;
/**
* 报表;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private DbObject report; private DbObject report;
/**
* 状态。
*/
private STATUS status; private STATUS status;
/**
* 是否启用。
*/
private boolean enabled; private boolean enabled;
/**
* 最后更新时间。
*/
private Date updated; private Date updated;
/**
* 创建时间。
*/
private Date created; private Date created;
/**
* 构造 {@code SiteLicense} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*
* 实现要点:主要调用:new Date。
*/
public SiteLicense() { public SiteLicense() {
this.plan = "standard"; this.plan = "standard";
this.status = SiteLicense.STATUS.UNKNOWN; this.status = SiteLicense.STATUS.UNKNOWN;
@@ -42,23 +124,48 @@ public class SiteLicense {
this.setCreated(new Date()); this.setCreated(new Date());
} }
/**
* 构造 {@code SiteLicense} 实例。
*
* @param site 站点/企业({@code Site})
*/
public SiteLicense(Site site) { public SiteLicense(Site site) {
this(); this();
this.setSite(site); this.setSite(site);
} }
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code site}。
* @return 站点对象;未找到时返回 {@code null}
*/
public Site getSite() { public Site getSite() {
return this.site; return this.site;
} }
/**
* 设置 {@code site}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param site 站点/企业({@code Site})
*/
public void setSite(Site site) { public void setSite(Site site) {
if (site.isChild()) { if (site.isChild()) {
this.site = site.getReseller(); this.site = site.getReseller();
@@ -69,42 +176,88 @@ public class SiteLicense {
} }
/**
* 获取 {@code childSite}。
* @return 站点对象;未找到时返回 {@code null}
*/
public Site getChildSite() { public Site getChildSite() {
return this.childSite; return this.childSite;
} }
/**
* 判断 {@code forChildSite}。
* @return 字段/派生属性 {@code forChildSite} 的值
*/
public boolean isForChildSite() { public boolean isForChildSite() {
return this.childSite != null; return this.childSite != null;
} }
/**
* 设置 {@code childSite}。
*
* @param reseller 参数 {@code reseller}({@code Site})
*/
public void setChildSite(Site reseller) { public void setChildSite(Site reseller) {
this.childSite = reseller; this.childSite = reseller;
} }
/**
* 获取 {@code writer}。
* @return 用户对象;未找到时返回 {@code null}
*/
public User getWriter() { public User getWriter() {
return this.writer; return this.writer;
} }
/**
* 设置 {@code writer}。
*
* @param user 当前用户({@code User})
*/
public void setWriter(User user) { public void setWriter(User user) {
this.writer = user; this.writer = user;
} }
/**
* 获取 {@code plan}。
* @return 字符串结果
*/
public String getPlan() { public String getPlan() {
return this.plan; return this.plan;
} }
/**
* 设置 {@code plan}。
*
* @param plan 参数 {@code plan}({@code String})
*/
public void setPlan(String plan) { public void setPlan(String plan) {
this.plan = plan; this.plan = plan;
} }
/**
* 判断 {@code lite}。
* @return 字段/派生属性 {@code lite} 的值
*/
public boolean isLite() { public boolean isLite() {
return "lite".equals(this.getPlan()); return "lite".equals(this.getPlan());
} }
/**
* 获取 {@code licenseModel}。
* @return 字段/派生属性 {@code licenseModel} 的值
*/
public LicenseModel getLicenseModel() { public LicenseModel getLicenseModel() {
return this.licenseModel; return this.licenseModel;
} }
/**
* 设置 {@code licenseModel}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param licenseModel 参数 {@code licenseModel}({@code LicenseModel})
*/
public void setLicenseModel(LicenseModel licenseModel) { public void setLicenseModel(LicenseModel licenseModel) {
if (this.isUpdated() && !this.licenseModel.getUuid().equals(licenseModel.getUuid())) { if (this.isUpdated() && !this.licenseModel.getUuid().equals(licenseModel.getUuid())) {
this.addNote("License model changed: " + licenseModel.getName()); this.addNote("License model changed: " + licenseModel.getName());
@@ -113,18 +266,37 @@ public class SiteLicense {
this.licenseModel = licenseModel; this.licenseModel = licenseModel;
} }
/**
* 获取 {@code type}。
* @return 字段/派生属性 {@code type} 的值
*/
public Character getType() { public Character getType() {
return this.licenseModel.getType(); return this.licenseModel.getType();
} }
/**
* 获取 {@code period}。
* @return 数量/长度
*/
public Integer getPeriod() { public Integer getPeriod() {
return this.licenseModel.getPeriod(); return this.licenseModel.getPeriod();
} }
/**
* 获取 {@code amount}。
* @return 数量/长度
*/
public int getAmount() { public int getAmount() {
return this.amount; return this.amount;
} }
/**
* 设置 {@code amount}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param amount 参数 {@code amount}({@code int})
*/
public void setAmount(int amount) { public void setAmount(int amount) {
if (this.isUpdated() && this.amount != amount) { if (this.isUpdated() && this.amount != amount) {
this.addNote("Amount changed: " + amount); this.addNote("Amount changed: " + amount);
@@ -133,6 +305,12 @@ public class SiteLicense {
this.amount = amount; this.amount = amount;
} }
/**
* 获取 {@code reference}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getReference() { public DbObject getReference() {
if (this.reference == null) { if (this.reference == null) {
this.reference = new DbObject(); this.reference = new DbObject();
@@ -141,14 +319,30 @@ public class SiteLicense {
return this.reference; return this.reference;
} }
/**
* 设置 {@code reference}。
*
* @param reference 参数 {@code reference}({@code DbObject})
*/
public void setReference(DbObject reference) { public void setReference(DbObject reference) {
this.reference = reference; this.reference = reference;
} }
/**
* 获取 {@code po}。
* @return 字符串结果
*/
public String getPo() { public String getPo() {
return this.getReference().getString("po", ""); return this.getReference().getString("po", "");
} }
/**
* 设置 {@code po}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param po 参数 {@code po}({@code String})
*/
public void setPo(String po) { public void setPo(String po) {
if (this.isUpdated() && !this.getPo().equals(po)) { if (this.isUpdated() && !this.getPo().equals(po)) {
this.addNote(Strings.isNullOrEmpty(po) ? "PO has unset" : "PO changed: " + po); this.addNote(Strings.isNullOrEmpty(po) ? "PO has unset" : "PO changed: " + po);
@@ -157,18 +351,38 @@ public class SiteLicense {
this.getReference().put("po", po); this.getReference().put("po", po);
} }
/**
* 获取 {@code desc}。
* @return 字符串结果
*/
public String getDesc() { public String getDesc() {
return this.getReference().getString("desc", ""); return this.getReference().getString("desc", "");
} }
/**
* 设置 {@code desc}。
*
* @param desc 参数 {@code desc}({@code String})
*/
public void setDesc(String desc) { public void setDesc(String desc) {
this.getReference().put("desc", desc); this.getReference().put("desc", desc);
} }
public List getNotes() { /**
* 获取 {@code notes}。
* @return 数据库Object列表,可能为空
*/
public List<DbObject> getNotes() {
return this.getReference().getList("notes", DbObject.class); return this.getReference().getList("notes", DbObject.class);
} }
/**
* 添加备注。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param status 状态({@code STATUS})
*/
public void addNote(STATUS status) { public void addNote(STATUS status) {
if (this.isUpdated()) { if (this.isUpdated()) {
this.addNote("Status changed: " + status); this.addNote("Status changed: " + status);
@@ -178,6 +392,13 @@ public class SiteLicense {
} }
/**
* 添加备注。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject、new ArrayList。
*
* @param note 参数 {@code note}({@code String})
*/
public void addNote(String note) { public void addNote(String note) {
DbObject noteObj = new DbObject("name", this.writer.getName()); DbObject noteObj = new DbObject("name", this.writer.getName());
noteObj.append("email", this.writer.getEmail()).append("note", note).append("updated", this.updated); noteObj.append("email", this.writer.getEmail()).append("note", note).append("updated", this.updated);
@@ -190,39 +411,81 @@ public class SiteLicense {
notes.add(noteObj); notes.add(noteObj);
} }
/**
* 获取 {@code enabled}。
* @return 字段/派生属性 {@code enabled} 的值
*/
public boolean getEnabled() { public boolean getEnabled() {
return this.enabled; return this.enabled;
} }
/**
* 设置 {@code enabled}。
*
* @param enabled 参数 {@code enabled}({@code boolean})
*/
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
this.enabled = enabled; this.enabled = enabled;
} }
/**
* 获取 {@code updated}。
* @return 字段/派生属性 {@code updated} 的值
*/
public Date getUpdated() { public Date getUpdated() {
return this.updated; return this.updated;
} }
/**
* 设置 {@code updated}。
*
* @param updated 参数 {@code updated}({@code Date})
*/
public void setUpdated(Date updated) { public void setUpdated(Date updated) {
this.updated = updated; this.updated = updated;
} }
/**
* 判断 {@code updated}。
* @return 字段/派生属性 {@code updated} 的值
*/
private boolean isUpdated() { private boolean isUpdated() {
return !this.created.equals(this.updated); return !this.created.equals(this.updated);
} }
/**
* 处理updated。
*
* 实现要点:主要调用:new Date。
*/
public void updated() { public void updated() {
this.updated = new Date(); this.updated = new Date();
} }
/**
* 获取 {@code created}。
* @return 字段/派生属性 {@code created} 的值
*/
public Date getCreated() { public Date getCreated() {
return this.created; return this.created;
} }
/**
* 设置 {@code created}。
*
* @param created 参数 {@code created}({@code Date})
*/
public void setCreated(Date created) { public void setCreated(Date created) {
this.created = created; this.created = created;
this.updated = created; this.updated = created;
} }
/**
* 获取 {@code report}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getReport() { public DbObject getReport() {
if (this.report == null) { if (this.report == null) {
this.report = new DbObject(); this.report = new DbObject();
@@ -231,31 +494,74 @@ public class SiteLicense {
return this.report; return this.report;
} }
/**
* 设置 {@code report}。
*
* @param report 参数 {@code report}({@code DbObject})
*/
public void setReport(DbObject report) { public void setReport(DbObject report) {
this.report = report; this.report = report;
} }
/**
* 设置报表。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setReport(String key, Object value) { public void setReport(String key, Object value) {
this.getReport().put(key, value); this.getReport().put(key, value);
} }
/**
* 判断 {@code trial}。
* @return 字段/派生属性 {@code trial} 的值
*/
public boolean isTrial() { public boolean isTrial() {
return this.getLicenseModel().isTrial(); return this.getLicenseModel().isTrial();
} }
/**
* 判断 {@code perpetual}。
* @return 字段/派生属性 {@code perpetual} 的值
*/
public boolean isPerpetual() { public boolean isPerpetual() {
return this.getLicenseModel().isPerpetual(); return this.getLicenseModel().isPerpetual();
} }
/**
* 获取 {@code status}。
* @return 字段/派生属性 {@code status} 的值
*/
public STATUS getStatus() { public STATUS getStatus() {
return this.status; return this.status;
} }
/**
* 设置 {@code status}。
*
* @param status 状态({@code STATUS})
*/
public void setStatus(STATUS status) { public void setStatus(STATUS status) {
this.addNote(status); this.addNote(status);
this.status = status; this.status = status;
} }
/**
* 【枚举常量】{@code STATUS}
*
* 类职责:
* <ul>
* <li>用有限枚举值表达状态/类型,避免魔法字符串。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* </ul>
*
* 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。
*/
public static enum STATUS { public static enum STATUS {
ORDERED, ORDERED,
PROCESSING, PROCESSING,
@@ -5,42 +5,115 @@ import java.util.UUID;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code SitePlan}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code model}(String):模型</li>
* <li>{@code plan}(DbObject):计划</li>
* <li>{@code isReseller}(boolean):判断是否Reseller</li>
* </ul>
*
* 协作对象:{@code DbObject}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class SitePlan { public class SitePlan {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid; private UUID uuid;
/**
* 模型。
*/
private String model = "midm"; private String model = "midm";
/**
* 计划。
*/
private DbObject plan; private DbObject plan;
/**
* 判断是否Reseller。
*/
private boolean isReseller = false; private boolean isReseller = false;
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code model}。
* @return 字符串结果
*/
public String getModel() { public String getModel() {
return this.model; return this.model;
} }
/**
* 设置 {@code model}。
*
* @param model 参数 {@code model}({@code String})
*/
public void setModel(String model) { public void setModel(String model) {
this.model = model; this.model = model;
} }
/**
* 获取 {@code plan}。
* @return MongoDB 文档扩展对象
*/
public DbObject getPlan() { public DbObject getPlan() {
return this.plan; return this.plan;
} }
/**
* 设置 {@code plan}。
*
* @param plan 参数 {@code plan}({@code DbObject})
*/
public void setPlan(DbObject plan) { public void setPlan(DbObject plan) {
this.plan = plan; this.plan = plan;
} }
/**
* 判断 {@code reseller}。
* @return 字段/派生属性 {@code reseller} 的值
*/
public boolean isReseller() { public boolean isReseller() {
return this.isReseller; return this.isReseller;
} }
/**
* 设置 {@code reseller}。
*
* @param isReseller 参数 {@code isReseller}({@code boolean})
*/
public void setReseller(boolean isReseller) { public void setReseller(boolean isReseller) {
this.isReseller = isReseller; this.isReseller = isReseller;
} }
@@ -5,87 +5,228 @@ import java.util.UUID;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code SiteRequest}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code uuid}(UUID):对象唯一标识(MongoDB 主键)</li>
* <li>{@code name}(String):名称</li>
* <li>{@code email}(String):用户邮箱(登录名,建立索引)</li>
* <li>{@code company}(String):字段 company</li>
* <li>{@code title}(String):字段 title</li>
* <li>{@code phone}(String):字段 phone</li>
* </ul>
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class SiteRequest { public class SiteRequest {
/**
* 对象唯一标识(MongoDB 主键);MongoDB 主键。
*
* 注解:{@code @Id}。
*/
@Id @Id
private UUID uuid; private UUID uuid;
/**
* 名称。
*/
private String name; private String name;
/**
* 用户邮箱(登录名,建立索引)。
*/
private String email; private String email;
/**
* 字段 company。
*/
private String company; private String company;
/**
* 字段 title。
*/
private String title; private String title;
/**
* 字段 phone。
*/
private String phone; private String phone;
/**
* 字段 country。
*/
private String country; private String country;
/**
* 字段 industry。
*/
private String industry; private String industry;
/**
* 时间字段。
*/
private Date requestedAt; private Date requestedAt;
/**
* 获取 {@code uuid}。
* @return UUID
*/
public UUID getUuid() { public UUID getUuid() {
return this.uuid; return this.uuid;
} }
/**
* 设置 {@code uuid}。
*
* @param uuid 对象 UUID({@code UUID})
*/
public void setUuid(UUID uuid) { public void setUuid(UUID uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
/**
* 获取 {@code name}。
* @return 字符串结果
*/
public String getName() { public String getName() {
return this.name; return this.name;
} }
/**
* 设置 {@code name}。
*
* @param name 参数 {@code name}({@code String})
*/
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/**
* 获取 {@code email}。
* @return 字符串结果
*/
public String getEmail() { public String getEmail() {
return this.email; return this.email;
} }
/**
* 设置 {@code email}。
*
* @param email 邮箱({@code String})
*/
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
/**
* 获取 {@code company}。
* @return 字符串结果
*/
public String getCompany() { public String getCompany() {
return this.company; return this.company;
} }
/**
* 设置 {@code company}。
*
* @param company 参数 {@code company}({@code String})
*/
public void setCompany(String company) { public void setCompany(String company) {
this.company = company; this.company = company;
} }
/**
* 获取 {@code title}。
* @return 字符串结果
*/
public String getTitle() { public String getTitle() {
return this.title; return this.title;
} }
/**
* 设置 {@code title}。
*
* @param title 参数 {@code title}({@code String})
*/
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
/**
* 获取 {@code phone}。
* @return 字符串结果
*/
public String getPhone() { public String getPhone() {
return this.phone; return this.phone;
} }
/**
* 设置 {@code phone}。
*
* @param phone 参数 {@code phone}({@code String})
*/
public void setPhone(String phone) { public void setPhone(String phone) {
this.phone = phone; this.phone = phone;
} }
/**
* 获取 {@code country}。
*
* 实现要点:包含异常捕获与降级/回滚分支。
* @return 字符串结果
*/
public String getCountry() { public String getCountry() {
return this.country; return this.country;
} }
/**
* 设置 {@code country}。
*
* 实现要点:包含异常捕获与降级/回滚分支。
*
* @param country 参数 {@code country}({@code String})
*/
public void setCountry(String country) { public void setCountry(String country) {
this.country = country; this.country = country;
} }
/**
* 获取 {@code industry}。
*
* 实现要点:包含异常捕获与降级/回滚分支。
* @return 字符串结果
*/
public String getIndustry() { public String getIndustry() {
return this.industry; return this.industry;
} }
/**
* 设置 {@code industry}。
*
* 实现要点:包含异常捕获与降级/回滚分支。
*
* @param industry 参数 {@code industry}({@code String})
*/
public void setIndustry(String industry) { public void setIndustry(String industry) {
this.industry = industry; this.industry = industry;
} }
/**
* 获取 {@code requestedAt}。
* @return 字段/派生属性 {@code requestedAt} 的值
*/
public Date getRequestedAt() { public Date getRequestedAt() {
return this.requestedAt; return this.requestedAt;
} }
/**
* 设置 {@code requestedAt}。
*
* @param requestedAt 参数 {@code requestedAt}({@code Date})
*/
public void setRequestedAt(Date requestedAt) { public void setRequestedAt(Date requestedAt) {
this.requestedAt = requestedAt; this.requestedAt = requestedAt;
} }
@@ -1,5 +1,20 @@
package com.midm.model.org; package com.midm.model.org;
/**
* 【枚举常量】{@code USER_PROPERTY}
*
* 类职责:
* <ul>
* <li>用有限枚举值表达状态/类型,避免魔法字符串。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* </ul>
*
* 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。
*/
public enum USER_PROPERTY { public enum USER_PROPERTY {
email, email,
email_addr, email_addr,
@@ -21,6 +36,14 @@ public enum USER_PROPERTY {
mobile_phone, mobile_phone,
unknown; unknown;
/**
* 处理获取。
*
* 实现要点:包含异常捕获与降级/回滚分支。
*
* @param key 键/配置项({@code String})
* @return 处理结果
*/
public static USER_PROPERTY get(String key) { public static USER_PROPERTY get(String key) {
try { try {
return valueOf(key.trim().toLowerCase()); return valueOf(key.trim().toLowerCase());
File diff suppressed because it is too large. Load diff
@@ -3,11 +3,50 @@ package com.midm.model.org;
import java.util.Date; import java.util.Date;
import java.util.UUID; import java.util.UUID;
/**
* 【领域模型】{@code UserAccess}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code sessionId}(String):会话ID</li>
* <li>{@code userUuid}(UUID):用户UUID</li>
* <li>{@code browser}(String):字段 browser</li>
* <li>{@code os}(String):操作系统</li>
* <li>{@code device}(String):设备</li>
* <li>{@code lastAccess}(Date):最后Access</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class UserAccess { public class UserAccess {
/**
* 会话ID。
*/
private String sessionId; private String sessionId;
/**
* 用户UUID。
*/
private UUID userUuid; private UUID userUuid;
/**
* 字段 browser。
*/
private String browser; private String browser;
/**
* 操作系统。
*/
private String os; private String os;
/**
* 设备。
*/
private String device; private String device;
/**
* 最后Access。
*/
private Date lastAccess; private Date lastAccess;
} }
@@ -4,16 +4,62 @@ import com.midm.model.GeneralProfile;
import java.util.UUID; import java.util.UUID;
import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.Transient;
/**
* 【领域模型】{@code UserGroup}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code siteUuid}(UUID):用户所属站点 UUID</li>
* <li>{@code parentUuid}(UUID):父级UUID</li>
* <li>{@code order}(Integer):字段 order</li>
* <li>{@code userNumbers}(Long):用户Numbers</li>
* </ul>
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class UserGroup extends GeneralProfile { public class UserGroup extends GeneralProfile {
/**
* 用户所属站点 UUID。
*/
private UUID siteUuid; private UUID siteUuid;
/**
* 父级UUID。
*/
private UUID parentUuid; private UUID parentUuid;
/**
* 字段 order。
*/
private Integer order; private Integer order;
/**
* 用户Numbers;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private Long userNumbers; private Long userNumbers;
/**
* 构造 {@code UserGroup} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public UserGroup() { public UserGroup() {
} }
/**
* 构造 {@code UserGroup} 实例。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param siteUuid 站点 UUID({@code UUID})
* @param parentGroup 参数 {@code parentGroup}({@code UserGroup})
* @param name 参数 {@code name}({@code String})
*/
public UserGroup(UUID siteUuid, UserGroup parentGroup, String name) { public UserGroup(UUID siteUuid, UserGroup parentGroup, String name) {
this.setSiteUuid(siteUuid); this.setSiteUuid(siteUuid);
if (parentGroup != null) { if (parentGroup != null) {
@@ -23,34 +69,70 @@ public class UserGroup extends GeneralProfile {
this.setName(name); this.setName(name);
} }
/**
* 获取 {@code siteUuid}。
* @return UUID
*/
public UUID getSiteUuid() { public UUID getSiteUuid() {
return this.siteUuid; return this.siteUuid;
} }
/**
* 设置 {@code siteUuid}。
*
* @param siteUuid 站点 UUID({@code UUID})
*/
public void setSiteUuid(UUID siteUuid) { public void setSiteUuid(UUID siteUuid) {
this.siteUuid = siteUuid; this.siteUuid = siteUuid;
} }
/**
* 获取 {@code parentUuid}。
* @return UUID
*/
public UUID getParentUuid() { public UUID getParentUuid() {
return this.parentUuid; return this.parentUuid;
} }
/**
* 设置 {@code parentUuid}。
*
* @param parentUuid 参数 {@code parentUuid}({@code UUID})
*/
public void setParentUuid(UUID parentUuid) { public void setParentUuid(UUID parentUuid) {
this.parentUuid = parentUuid; this.parentUuid = parentUuid;
} }
/**
* 获取 {@code order}。
* @return 数量/长度
*/
public Integer getOrder() { public Integer getOrder() {
return this.order; return this.order;
} }
/**
* 设置 {@code order}。
*
* @param order 参数 {@code order}({@code Integer})
*/
public void setOrder(Integer order) { public void setOrder(Integer order) {
this.order = order; this.order = order;
} }
/**
* 获取 {@code userNumbers}。
* @return 数量/长度
*/
public Long getUserNumbers() { public Long getUserNumbers() {
return this.userNumbers; return this.userNumbers;
} }
/**
* 设置 {@code userNumbers}。
*
* @param numbers 参数 {@code numbers}({@code Long})
*/
public void setUserNumbers(Long numbers) { public void setUserNumbers(Long numbers) {
this.userNumbers = numbers; this.userNumbers = numbers;
} }
+104 -2
View File
@@ -5,28 +5,114 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.GrantedAuthority;
/**
* 【领域模型】{@code UserRole}
*
* 类职责:
* <ul>
* <li>表达领域对象的数据结构、字段约束与派生属性。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code ROLES}(String):字段 ROLES</li>
* <li>{@code SYSTEM_ROLES}(String):字段 SYSTEM_ROLES</li>
* <li>{@code ROLE_SUPER_USER}(String):字段 ROLE_SUPER_USER</li>
* <li>{@code ROLE_SUPERVISOR}(String):字段 ROLE_SUPERVISOR</li>
* <li>{@code ROLE_SYSTEM_ADMIN}(String):字段 ROLE_SYSTEM_ADMIN</li>
* <li>{@code ROLE_SITE_MANAGER}(String):字段 ROLE_SITE_MANAGER</li>
* </ul>
*
* 协作对象:{@code String[]}。
*
* 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。
*/
public class UserRole { public class UserRole {
/**
* 字段 ROLES。
*/
public static final String ROLES = "roles"; public static final String ROLES = "roles";
/**
* 字段 SYSTEM_ROLES。
*/
public static final String SYSTEM_ROLES = "systemRoles"; public static final String SYSTEM_ROLES = "systemRoles";
/**
* 字段 ROLE_SUPER_USER。
*/
public static final String ROLE_SUPER_USER = "SUPER_USER"; public static final String ROLE_SUPER_USER = "SUPER_USER";
/**
* 字段 ROLE_SUPERVISOR。
*/
public static final String ROLE_SUPERVISOR = "SUPERVISOR"; public static final String ROLE_SUPERVISOR = "SUPERVISOR";
/**
* 字段 ROLE_SYSTEM_ADMIN。
*/
public static final String ROLE_SYSTEM_ADMIN = "SYSTEM_ADMIN"; public static final String ROLE_SYSTEM_ADMIN = "SYSTEM_ADMIN";
/**
* 字段 ROLE_SITE_MANAGER。
*/
public static final String ROLE_SITE_MANAGER = "SITE_MANAGER"; public static final String ROLE_SITE_MANAGER = "SITE_MANAGER";
/**
* 字段 ROLE_SALES。
*/
public static final String ROLE_SALES = "SALES"; public static final String ROLE_SALES = "SALES";
/**
* 字段 ROLE_RESELLER。
*/
public static final String ROLE_RESELLER = "RESELLER"; public static final String ROLE_RESELLER = "RESELLER";
/**
* 字段 ROLE_FINANCE。
*/
public static final String ROLE_FINANCE = "FINANCE"; public static final String ROLE_FINANCE = "FINANCE";
/**
* 字段 ROLE_USER。
*/
public static final String ROLE_USER = "USER"; public static final String ROLE_USER = "USER";
/**
* 字段 ROLE_USER_MANAGER。
*/
public static final String ROLE_USER_MANAGER = "USER_MANAGER"; public static final String ROLE_USER_MANAGER = "USER_MANAGER";
/**
* 字段 ROLE_DEVICE_MANAGER。
*/
public static final String ROLE_DEVICE_MANAGER = "DEVICE_MANAGER"; public static final String ROLE_DEVICE_MANAGER = "DEVICE_MANAGER";
/**
* 字段 ROLE_PROFILE_MANAGER。
*/
public static final String ROLE_PROFILE_MANAGER = "PROFILE_MANAGER"; public static final String ROLE_PROFILE_MANAGER = "PROFILE_MANAGER";
/**
* 字段 ROLE_DEVIE_OWNER。
*/
public static final String ROLE_DEVIE_OWNER = "DEVICE_OWNER"; public static final String ROLE_DEVIE_OWNER = "DEVICE_OWNER";
/**
* 字段 ROLE_GUEST。
*/
public static final String ROLE_GUEST = "ROLE_GUEST"; public static final String ROLE_GUEST = "ROLE_GUEST";
/**
* 字段 USER_MANAGE_ROLES。
*/
public static final String[] USER_MANAGE_ROLES = new String[]{"SUPERVISOR", "USER_MANAGER"}; public static final String[] USER_MANAGE_ROLES = new String[]{"SUPERVISOR", "USER_MANAGER"};
/**
* 字段 DEVICE_MANAGE_ROLES。
*/
public static final String[] DEVICE_MANAGE_ROLES = new String[]{"SUPERVISOR", "DEVICE_MANAGER"}; public static final String[] DEVICE_MANAGE_ROLES = new String[]{"SUPERVISOR", "DEVICE_MANAGER"};
/**
* 字段 PROFILE_MANAGE_ROLES。
*/
public static final String[] PROFILE_MANAGE_ROLES = new String[]{"SUPERVISOR", "PROFILE_MANAGER"}; public static final String[] PROFILE_MANAGE_ROLES = new String[]{"SUPERVISOR", "PROFILE_MANAGER"};
public static List getAuthorities(final String role) { /**
* 获取Authorities。
*
* 实现要点:主要调用:new ArrayList、new SimpleGrantedAuthority。
*
* @param role 参数 {@code role}({@code String})
* @return GrantedAuthority列表,可能为空
*/
public static List<GrantedAuthority> getAuthorities(final String role) {
return new ArrayList() { return new ArrayList() {
{ {
this.add(new SimpleGrantedAuthority(role)); this.add(new SimpleGrantedAuthority(role));
@@ -34,7 +120,15 @@ public class UserRole {
}; };
} }
public static List getAuthorities(final Set roles) { /**
* 获取Authorities。
*
* 实现要点:包含 1 个条件分支、1 个循环;主要调用:new ArrayList、new SimpleGrantedAuthority。
*
* @param roles 参数 {@code roles}({@code Set<String>})
* @return GrantedAuthority列表,可能为空
*/
public static List<GrantedAuthority> getAuthorities(final Set<String> roles) {
return new ArrayList() { return new ArrayList() {
{ {
if (roles != null && !roles.isEmpty()) { if (roles != null && !roles.isEmpty()) {
@@ -49,6 +143,14 @@ public class UserRole {
}; };
} }
/**
* 处理转换为Role。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param role 参数 {@code role}({@code String})
* @return 字符串结果
*/
public static String toRole(String role) { public static String toRole(String role) {
if (Strings.isNullOrEmpty(role)) { if (Strings.isNullOrEmpty(role)) {
return null; return null;
+206 -2
View File
@@ -14,43 +14,135 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
/**
* 【MongoDB 文档实体】{@code UserToken}
*
* 类职责:
* <ul>
* <li>作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。</li>
* <li>通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。</li>
* </ul>
*
* 核心字段(按声明顺序):
* <ul>
* <li>{@code TOKEN_CONFIRMATION}(char):字段 TOKEN_CONFIRMATION</li>
* <li>{@code TOKEN_ACTIVATION}(char):字段 TOKEN_ACTIVATION</li>
* <li>{@code TOKEN_LOGIN}(char):字段 TOKEN_LOGIN</li>
* <li>{@code TOKEN_REMEMBER_LOGIN}(char):字段 TOKEN_REMEMBER_LOGIN</li>
* <li>{@code TOKEN_RESET_PASSWORD}(char):字段 TOKEN_RESET_PASSWORD</li>
* <li>{@code TOKEN_MFA_AUTH}(char):字段 TOKEN_MFA_AUTH</li>
* </ul>
*
* 协作对象:{@code DbObject}。
*
* 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。
*
* 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。
*/
@Document @Document
public class UserToken implements Serializable { public class UserToken implements Serializable {
/**
* 字段 TOKEN_CONFIRMATION。
*/
public static final char TOKEN_CONFIRMATION = 'C'; public static final char TOKEN_CONFIRMATION = 'C';
/**
* 字段 TOKEN_ACTIVATION。
*/
public static final char TOKEN_ACTIVATION = 'A'; public static final char TOKEN_ACTIVATION = 'A';
/**
* 字段 TOKEN_LOGIN。
*/
public static final char TOKEN_LOGIN = 'L'; public static final char TOKEN_LOGIN = 'L';
/**
* 字段 TOKEN_REMEMBER_LOGIN。
*/
public static final char TOKEN_REMEMBER_LOGIN = 'R'; public static final char TOKEN_REMEMBER_LOGIN = 'R';
/**
* 字段 TOKEN_RESET_PASSWORD。
*/
public static final char TOKEN_RESET_PASSWORD = 'P'; public static final char TOKEN_RESET_PASSWORD = 'P';
/**
* 字段 TOKEN_MFA_AUTH。
*/
public static final char TOKEN_MFA_AUTH = 'M'; public static final char TOKEN_MFA_AUTH = 'M';
/**
* 字段 TOKEN_DEVICE_ACCESS。
*/
public static final char TOKEN_DEVICE_ACCESS = 'D'; public static final char TOKEN_DEVICE_ACCESS = 'D';
/**
* 令牌UUID;MongoDB 主键;Gson 序列化控制。
*
* 注解:{@code @Id @Expose(serialize = false)}。
*/
@Id @Id
@Expose( @Expose(
serialize = false serialize = false
) )
private UUID tokenUuid; private UUID tokenUuid;
/**
* access令牌;不持久化到 MongoDB,仅运行时使用。
*
* 注解:{@code @Transient}。
*/
@Transient @Transient
private String accessToken; private String accessToken;
/**
* 用户UUID;Gson 序列化控制。
*
* 注解:{@code @Expose(serialize = false)}。
*/
@Expose( @Expose(
serialize = false serialize = false
) )
private UUID userUuid; private UUID userUuid;
/**
* 令牌类型;Gson 序列化控制。
*
* 注解:{@code @Expose(serialize = false)}。
*/
@Expose( @Expose(
serialize = false serialize = false
) )
private char tokenType; private char tokenType;
/**
* 创建时间;Gson 序列化控制。
*
* 注解:{@code @Expose(serialize = false)}。
*/
@Expose( @Expose(
serialize = false serialize = false
) )
private Date created; private Date created;
/**
* 时间字段;Gson 序列化控制。
*
* 注解:{@code @Expose(serialize = false)}。
*/
@Expose( @Expose(
serialize = false serialize = false
) )
private Date expired; private Date expired;
/**
* 字段 reference。
*/
private DbObject reference; private DbObject reference;
/**
* 构造 {@code UserToken} 实例。
* 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。
*/
public UserToken() { public UserToken() {
} }
/**
* 构造 {@code UserToken} 实例。
*
* 实现要点:主要调用:new Date、new DateTime。
*
* @param user 当前用户({@code User})
* @param tokenType 参数 {@code tokenType}({@code char})
* @param validPeriod 参数 {@code validPeriod}({@code long})
*/
public UserToken(User user, char tokenType, long validPeriod) { public UserToken(User user, char tokenType, long validPeriod) {
this.tokenUuid = UUID.randomUUID(); this.tokenUuid = UUID.randomUUID();
this.userUuid = user.getUuid(); this.userUuid = user.getUuid();
@@ -60,6 +152,11 @@ public class UserToken implements Serializable {
this.expired = date.plus(validPeriod).toDate(); this.expired = date.plus(validPeriod).toDate();
} }
/**
* 处理renew。
*
* 实现要点:主要调用:new Date、new DateTime。
*/
public void renew() { public void renew() {
this.tokenUuid = UUID.randomUUID(); this.tokenUuid = UUID.randomUUID();
this.encryptToken(); this.encryptToken();
@@ -69,10 +166,19 @@ public class UserToken implements Serializable {
this.expired = date.plus(validPeriod).toDate(); this.expired = date.plus(validPeriod).toDate();
} }
/**
* 加密令牌。
*/
public void encryptToken() { public void encryptToken() {
this.accessToken = McUuidUtils.toBase64String(this.tokenUuid); this.accessToken = McUuidUtils.toBase64String(this.tokenUuid);
} }
/**
* 获取 {@code accessToken}。
*
* 实现要点:包含 1 个条件分支、0 个循环。
* @return 字符串结果
*/
public String getAccessToken() { public String getAccessToken() {
if (Strings.isNullOrEmpty(this.accessToken)) { if (Strings.isNullOrEmpty(this.accessToken)) {
this.encryptToken(); this.encryptToken();
@@ -81,38 +187,81 @@ public class UserToken implements Serializable {
return this.accessToken; return this.accessToken;
} }
/**
* 获取 {@code tokenUuid}。
* @return UUID
*/
public UUID getTokenUuid() { public UUID getTokenUuid() {
return this.tokenUuid; return this.tokenUuid;
} }
/**
* 设置 {@code tokenUuid}。
*
* @param uid 参数 {@code uid}({@code UUID})
*/
public void setTokenUuid(UUID uid) { public void setTokenUuid(UUID uid) {
this.tokenUuid = uid; this.tokenUuid = uid;
} }
/**
* 获取 {@code userUuid}。
* @return UUID
*/
public UUID getUserUuid() { public UUID getUserUuid() {
return this.userUuid; return this.userUuid;
} }
/**
* 设置 {@code userUuid}。
*
* @param userUuid 用户 UUID({@code UUID})
*/
public void setUserUuid(UUID userUuid) { public void setUserUuid(UUID userUuid) {
this.userUuid = userUuid; this.userUuid = userUuid;
} }
/**
* 获取 {@code tokenType}。
* @return 字段/派生属性 {@code tokenType} 的值
*/
public char getTokenType() { public char getTokenType() {
return this.tokenType; return this.tokenType;
} }
/**
* 设置 {@code tokenType}。
*
* @param tokenType 参数 {@code tokenType}({@code char})
*/
public void setTokenType(char tokenType) { public void setTokenType(char tokenType) {
this.tokenType = tokenType; this.tokenType = tokenType;
} }
/**
* 获取Mfa令牌。
*
* @param length 参数 {@code length}({@code int})
* @return 字符串结果
*/
public String getMfaToken(int length) { public String getMfaToken(int length) {
return this.getMfaToken().substring(0, length); return this.getMfaToken().substring(0, length);
} }
/**
* 获取 {@code mfaToken}。
* @return 字符串结果
*/
public String getMfaToken() { public String getMfaToken() {
return String.valueOf(this.tokenUuid.getMostSignificantBits() * this.tokenUuid.getLeastSignificantBits()); return String.valueOf(this.tokenUuid.getMostSignificantBits() * this.tokenUuid.getLeastSignificantBits());
} }
/**
* 获取 {@code reference}。
*
* 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。
* @return MongoDB 文档扩展对象
*/
public DbObject getReference() { public DbObject getReference() {
if (this.reference == null) { if (this.reference == null) {
this.reference = new DbObject(); this.reference = new DbObject();
@@ -121,10 +270,23 @@ public class UserToken implements Serializable {
return this.reference; return this.reference;
} }
/**
* 设置 {@code reference}。
*
* @param reference 参数 {@code reference}({@code DbObject})
*/
public void setReference(DbObject reference) { public void setReference(DbObject reference) {
this.reference = reference; this.reference = reference;
} }
/**
* 设置Reference。
*
* 实现要点:包含 1 个条件分支、0 个循环。
*
* @param key 键/配置项({@code String})
* @param value 值({@code Object})
*/
public void setReference(String key, Object value) { public void setReference(String key, Object value) {
if (value == null) { if (value == null) {
this.getReference().remove(key); this.getReference().remove(key);
@@ -134,38 +296,80 @@ public class UserToken implements Serializable {
} }
/**
* 获取 {@code deviceUuid}。
* @return UUID
*/
public UUID getDeviceUuid() { public UUID getDeviceUuid() {
return this.getReference().getUuid("deviceUuid"); return this.getReference().getUuid("deviceUuid");
} }
/**
* 获取 {@code created}。
* @return 字段/派生属性 {@code created} 的值
*/
public Date getCreated() { public Date getCreated() {
return this.created; return this.created;
} }
/**
* 设置 {@code created}。
*
* @param registered 参数 {@code registered}({@code Date})
*/
public void setCreated(Date registered) { public void setCreated(Date registered) {
this.created = registered; this.created = registered;
} }
/**
* 获取 {@code expired}。
* @return 字段/派生属性 {@code expired} 的值
*/
public Date getExpired() { public Date getExpired() {
return this.expired; return this.expired;
} }
/**
* 设置 {@code expired}。
*
* @param expired 参数 {@code expired}({@code Date})
*/
public void setExpired(Date expired) { public void setExpired(Date expired) {
this.expired = expired; this.expired = expired;
} }
/**
* 处理plusExpired。
*
* 实现要点:主要调用:new DateTime。
*
* @param time 参数 {@code time}({@code long})
*/
public void plusExpired(long time) { public void plusExpired(long time) {
DateTime expiredDate = new DateTime(this.getExpired()); DateTime expiredDate = new DateTime(this.getExpired());
expiredDate.plus(time); expiredDate.plus(time);
} }
/**
* 判断 {@code expired}。
*
* 实现要点:主要调用:new Date。
* @return 字段/派生属性 {@code expired} 的值
*/
public boolean isExpired() { public boolean isExpired() {
return this.getExpired().getTime() < (new Date()).getTime(); return this.getExpired().getTime() < (new Date()).getTime();
} }
/**
* 处理转换为设备Access。
*
* 实现要点:主要调用:new DbObject。
*
* @param request HTTP 请求({@code HttpServletRequest})
* @return MongoDB 文档扩展对象
*/
public DbObject toDeviceAccess(HttpServletRequest request) { public DbObject toDeviceAccess(HttpServletRequest request) {
String var10000 = McUrlUtils.getHostUrl(request); String accessUrl = McUrlUtils.getHostUrl(request) + "/device/" + McUuidUtils.toBase64String(this.tokenUuid, true);
String accessUrl = var10000 + "/device/" + McUuidUtils.toBase64String(this.tokenUuid, true);
DbObject deviceAccess = new DbObject("accessUrl", accessUrl); DbObject deviceAccess = new DbObject("accessUrl", accessUrl);
deviceAccess.append("expiry", this.getExpired()); deviceAccess.append("expiry", this.getExpired());
return deviceAccess; return deviceAccess;
@@ -0,0 +1,23 @@
/**
* 组织架构模型:站点、用户、用户组、License、令牌。
*
* <p>本包主要类型:
* <ul>
* <li>{@link Site}</li>
* <li>{@link SiteFile}</li>
* <li>{@link SiteInfo}</li>
* <li>{@link SiteLicense}</li>
* <li>{@link SitePlan}</li>
* <li>{@link SiteRequest}</li>
* <li>{@link USER_PROPERTY}</li>
* <li>{@link User}</li>
* <li>{@link UserAccess}</li>
* <li>{@link UserGroup}</li>
* <li>{@link UserRole}</li>
* <li>{@link UserToken}</li>
* </ul>
*
* <p>阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看,
* 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。
*/
package com.midm.model.org;
Loaded 100 of 346 files, more files were not shown because too many files have changed in this diff. Show more